├── .github └── pull_request_template.md ├── .gitignore ├── LICENSE ├── README.md ├── contributors.md └── leetcode └── problems ├── c ├── a-number-after-a-double-reversal.c ├── a.c ├── add-binary.c ├── add-digits.c ├── add-strings.c ├── add-to-array-form-of-intege.c ├── add-two-numbers.c ├── average-salary-excluding-the-minimum-and-maximum-salary.c ├── backspace-string-compare.c ├── balanced-binary-tree.c ├── best-time-to-buy-and-sell-stock.c ├── binary-search.c ├── binary-tree-inorder-traversal.c ├── binary-tree-postorder-traversa.c ├── binary-tree-preorder-traversal.c ├── bulls-and-cows.c ├── can-make-arithmetic-progression-from-sequence.c ├── can-place-flowers.c ├── capitalize-the-title.c ├── check-if-it-is-a-straight-line.c ├── check-if-number-has-equal-digit-count-and-digit-value.c ├── climbing-stairs.c ├── complement-of-base-10-integer.c ├── concatenation-of-array.c ├── convert-sorted-array-to-binary-search-tree.c ├── count-odd-numbers-in-an-interval-range.c ├── count-primes.c ├── counting-bits.c ├── decode-xored-array.c ├── detect-capital.c ├── eplace-all-digits-with-characters.c ├── excel-sheet-column-title.c ├── fibonacci-number.c ├── find-all-anagrams-in-a-string.c ├── find-all-numbers-disappeared-in-an-array.1.c ├── find-first-palindromic-string-in-the-array.c ├── find-greatest-common-divisor-of-array.c ├── find-n-unique-integers-sum-up-to-zero.c ├── find-pivot-index.c ├── find-the-difference.c ├── find-the-highest-altitude.c ├── find-the-middle-index-in-array.c ├── first-bad-version.c ├── first-letter-to-appear-twice.c ├── first-unique-character-in-a-string.c ├── flood-fill.c ├── greatest-english-letter-in-upper-and-lower-case.c ├── guess-number-higher-or-lower.c ├── happy-number.c ├── hello-world.c ├── house-robber.c ├── implement-queue-using-stacks.c ├── implement-stack-using-queues.c ├── implement-strstr.c ├── increasing-triplet-subsequence.c ├── insert-into-a-binary-search-tree.c ├── integer-to-roman.c ├── intersection-of-two-arrays-ii.c ├── intersection-of-two-linked-lists.c ├── invert-binary-tree.c ├── is-subsequence.c ├── isomorphic-strings.c ├── largest-perimeter-triangle.c ├── last-stone-weight.c ├── last-stone-weight.cpp ├── lemonade-change.c ├── length-of-last-word.c ├── linked-list-cycle.c ├── longest-common-prefix.c ├── longest-palindrome.c ├── longest-repeating-character-replacement.c ├── longest-subarray-of-1s-after-deleting-one-element.c ├── longest-substring-without-repeating-characters.c ├── lowest-common-ancestor-of-a-binary-search-tree.c ├── majority-element.c ├── make-array-zero-by-subtracting-equal-amounts.cpp ├── make-two-arrays-equal-by-reversing-sub-arrays.c ├── matrix-diagonal-sum.c ├── max-area-of-island.c ├── max-consecutive-ones-iii.c ├── max-number-of-k-sum-pairs.c ├── maximum-average-subarray-i.c ├── maximum-depth-of-binary-tree.c ├── maximum-subarray.c ├── median-of-two-sorted-arrays.c ├── merge-sorted-array.c ├── merge-two-binary-trees.c ├── merge-two-sorted-lists.c ├── middle-of-the-linked-list.c ├── min-cost-climbing-stairs.c ├── minimum-depth-of-binary-tree.c ├── missing-number.c ├── monotonic-array.c ├── move-zeroes.c ├── n-ary-tree-preorder-traversal.c ├── nim-game.c ├── number-complement.c ├── number-of-1-bits.c ├── number-of-good-pairs.c ├── number-of-islands.c ├── number-of-segments-in-a-string.c ├── number-of-steps-to-reduce-a-number-to-zero.c ├── palindrome-linked-list.c ├── palindrome-number.c ├── pascals-triangle-ii.c ├── pascals-triangle.c ├── path-sum.c ├── perfect-number.c ├── permutation-in-string.c ├── plus-one.c ├── poor-pigs.c ├── populating-next-right-pointers-in-each-node.c ├── power-of-four.c ├── power-of-two.c ├── powx-n.c ├── ransom-note.c ├── relative-ranks.cpp ├── remove-duplicates-from-sorted-array.c ├── remove-duplicates-from-sorted-list.c ├── remove-element.c ├── remove-linked-list-elements.c ├── remove-nth-node-from-end-of-list.c ├── remove-outermost-parentheses.c ├── removing-stars-from-a-string.c ├── reverse-bits.c ├── reverse-integer.c ├── reverse-linked-list.c ├── reverse-only-letters.c ├── reverse-prefix-of-word.c ├── reverse-string-ii.c ├── reverse-string.c ├── reverse-vowels-of-a-string.c ├── reverse-words-in-a-string-iii.c ├── richest-customer-wealth.c ├── roman-to-integer.c ├── rotate-array.c ├── rotting-oranges.c ├── running-sum-of-1d-array.c ├── same-tree.c ├── search-a-2d-matrix.c ├── search-in-a-binary-search-tree.c ├── search-insert-position.c ├── self-dividing-numbers.c ├── shuffle-string.c ├── sign-of-the-product-of-an-array.c ├── single-number-ii.c ├── single-number.c ├── smallest-even-multiple.c ├── sqrtx.c ├── squares-of-a-sorted-array.c ├── student-attendance-record.c ├── sum-of-left-leaves.c ├── super-pow.c ├── symmetric-tree.c ├── take-gifts-from-the-richest-pile.cpp ├── the-k-weakest-rows-in-a-matrix.c ├── three-divisors.c ├── to-lower-case.c ├── two-sum-ii-input-array-is-sorted.c ├── two-sum-iv-input-is-a-bst.c ├── two-sum.c ├── ugly-number.c ├── unique-paths.c ├── valid-anagram.c ├── valid-palindrome.c ├── valid-parentheses.c ├── valid-perfect-square.c ├── valid-sudoku.c ├── validate-binary-search-tree.c └── xor-operation-in-an-array.c ├── cpp ├── .clang-format ├── add-binary.cpp ├── add-one-row-to-tree.cpp ├── add-two-integers.cpp ├── add-two-numbers-ii.cpp ├── add-two-numbers.cpp ├── all-elements-in-two-binary-search-trees.cpp ├── all-possible-full-binary-trees.cpp ├── amount-of-time-for-binary-tree-to-be-infected.cpp ├── arranging-coins.cpp ├── array-partition.cpp ├── asteroid-collision.cpp ├── average-of-levels-in-binary-tree.cpp ├── average-salary-excluding-the-minimum-and-maximum-salary.cpp ├── backspace-string-compare.cpp ├── balance-a-binary-search-tree.cpp ├── balanced-binary-tree.cpp ├── baseball-game.cpp ├── best-time-to-buy-and-sell-stock-ii.cpp ├── best-time-to-buy-and-sell-stock.cpp ├── binary-search-tree-iterator.cpp ├── binary-search-tree-to-greater-sum-tree.cpp ├── binary-tree-inorder-traversal.cpp ├── binary-tree-level-order-traversal-ii.cpp ├── binary-tree-level-order-traversal.cpp ├── binary-tree-paths.cpp ├── binary-tree-postorder-traversal.cpp ├── binary-tree-preorder-traversal.cpp ├── binary-tree-pruning.cpp ├── binary-tree-right-side-view.cpp ├── binary-tree-tilt.cpp ├── binary-tree-zigzag-level-order-traversal.cpp ├── bit-manipulation.cpp ├── build-an-array-with-stack-operations.cpp ├── build-array-from-permutation.1.cpp ├── build-array-from-permutation.cpp ├── can-make-arithmetic-progression-from-sequence.1.cpp ├── can-place-flowers.cpp ├── check-completeness-of-a-binary-tree.cpp ├── check-if-all-as-appears-before-all-bs.cpp ├── check-if-it-is-a-straight-line.cpp ├── check-if-n-and-its-double-exist.cpp ├── climbing-stairs.CPP ├── complete-binary-tree-inserter.cpp ├── concatenation-of-array.cpp ├── construct-binary-search-tree-from-preorder-traversal.cpp ├── construct-binary-tree-from-inorder-and-postorder-traversal.cpp ├── construct-binary-tree-from-preorder-and-inorder-traversal.cpp ├── construct-binary-tree-from-preorder-and-postorder-traversal.CPP ├── construct-smallest-number-from-di-string.cpp ├── construct-string-from-binary-tree.cpp ├── container-with-most-water.cpp ├── contains-duplicate-ii.cpp ├── contains-duplicate.cpp ├── convert-a-number-to-hexadecimal.cpp ├── convert-binary-number-in-a-linked-list-to-integer.cpp ├── convert-bst-to-greater-tree.cpp ├── convert-sorted-array-to-binary-search-tree.cpp ├── convert-sorted-list-to-binary-search-tree.cpp ├── convert-the-temperature.cpp ├── count-complete-tree-nodes.cpp ├── count-good-nodes-in-binary-tree.cpp ├── count-negative-numbers-in-a-sorted-matrix.cpp ├── count-nodes-equal-to-average-of-subtree.cpp ├── count-odd-numbers-in-an-interval-range.cpp ├── count-operations-to-obtain-zero.cpp ├── count-prefixes-of-a-given-string.cpp ├── count-primes.cpp ├── count-the-number-of-consistent-strings.cpp ├── counting-bits.cpp ├── cousins-in-binary-tree-ii.cpp ├── cousins-in-binary-tree.cpp ├── crawler-log-folde.cpp ├── crawler-log-folder.cpp ├── create-binary-tree-from-descriptions.cpp ├── daily-temperatures.cpp ├── decode-string.cpp ├── decode-xored-array.cpp ├── deepest-leaves-sum.cpp ├── defanging-an-ip-address.cpp ├── delete-greatest-value-in-each-row.cpp ├── delete-leaves-with-a-given-value.cpp ├── delete-node-in-a-bst.cpp ├── delete-node-in-a-linked-list.cpp ├── delete-nodes-and-return-forest.cpp ├── delete-the-middle-node-of-a-linked-list.cpp ├── design-a-stack-with-increment-operation.cpp ├── design-browser-history.cpp ├── design-circular-queue.cpp ├── determine-if-two-strings-are-close.cpp ├── determine-whether-matrix-can-be-obtained-by-rotation.cpp ├── di-string-match.cpp ├── diameter-of-binary-tree.cpp ├── divisible-and-non-divisible-sums-difference.cpp ├── dota2-senate.cpp ├── duplicate-zeros.cpp ├── encode-and-decode-strings.cpp ├── equal-row-and-column-pairs.cpp ├── evaluate-boolean-binary-tree.cpp ├── even-odd-tree.cpp ├── excel-sheet-column-number.cpp ├── final-prices-with-a-special-discount-in-a-shop.cpp ├── final-value-of-variable-after-performing-operations.cpp ├── find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree.cpp ├── find-all-numbers-disappeared-in-an-array.cpp ├── find-bottom-left-tree-value.cpp ├── find-common-characters.cpp ├── find-duplicate-subtrees.cpp ├── find-elements-in-a-contaminated-binary-tree.cpp ├── find-first-and-last-position-of-element-in-sorted-array.cpp ├── find-largest-value-in-each-tree-row.cpp ├── find-mode-in-binary-search-tree.cpp ├── find-numbers-with-even-number-of-digits.cpp ├── find-peak-element.cpp ├── find-pivot-index.cpp ├── find-subsequence-of-length-k-with-the-largest-sum.cpp ├── find-the-difference-of-two-arrays.cpp ├── find-the-difference.cpp ├── find-the-highest-altitude.cpp ├── find-the-index-of-the-first-occurrence-in-a-string.cpp ├── find-the-maximum-achievable-number.cpp ├── find-the-middle-index-in-array.cpp ├── find-the-original-array-of-prefix-xor.cpp ├── find-winner-on-a-tic-tac-toe-game.cpp ├── first-bad-version.cpp ├── first-unique-character-in-a-string.cpp ├── fizz-buzz.cpp ├── flatten-binary-tree-to-linked-list.cpp ├── flip-equivalent-binary-trees.cpp ├── flipping-an-image.cpp ├── flood-fill.cpp ├── generate-parentheses.cpp ├── goal-parser-interpretation.cpp ├── greatest-common-divisor-of-strings.cpp ├── group-anagrams.cpp ├── guess-number-higher-or-lower.cpp ├── hamming-distance.cpp ├── height-checker.cpp ├── hello-world.cpp ├── house-robber.cpp ├── how-many-numbers-are-smaller-than-the-current-number.cpp ├── implement-queue-using-stacks.cpp ├── implement-stack-using-queues.cpp ├── implement-trie-prefix-tree.cpp ├── increasing-order-search-tree.cpp ├── increasing-triplet-subsequence.cpp ├── insert-greatest-common-divisors-in-linked-list.cpp ├── insert-into-a-binary-search-tree.cpp ├── integer-to-roman.cpp ├── intersection-of-two-arrays.cpp ├── invert-binary-tree.cpp ├── is-subsequence.cpp ├── island-perimeter.cpp ├── isomorphic-strings.cpp ├── jewels-and-stones.cpp ├── k-closest-points-to-origin.cpp ├── kids-with-the-greatest-number-of-candies.cpp ├── kth-largest-element-in-a-stream.cpp ├── kth-largest-element-in-an-array.cpp ├── kth-smallest-element-in-a-bst.cpp ├── kth-smallest-element-in-a-sorted-matrix.cpp ├── largest-local-values-in-a-matrix.cpp ├── largest-number-after-digit-swaps-by-parity.cpp ├── largest-perimeter-triangle.cpp ├── leaf-similar-trees.cpp ├── left-and-right-sum-differences.cpp ├── lemonade-change.cpp ├── length-of-last-word.cpp ├── linked-list-cycle.cpp ├── longest-common-prefix.cpp ├── longest-consecutive-sequence.cpp ├── longest-palindromic-substring.cpp ├── longest-subarray-of-1s-after-deleting-one-element.cpp ├── longest-substring-without-repeating-characters.cpp ├── longest-zigzag-path-in-a-binary-tree.cpp ├── lowest-common-ancestor-of-a-binary-search-tree.cpp ├── lowest-common-ancestor-of-a-binary-tree.cpp ├── lowest-common-ancestor-of-deepest-leaves.cpp ├── make-costs-of-paths-equal-in-a-binary-tree.cpp ├── make-the-string-great.cpp ├── matrix-diagonal-sum.cpp ├── max-consecutive-ones-iii.cpp ├── max-consecutive-ones.cpp ├── max-number-of-k-sum-pairs.cpp ├── maximum-69-number.cpp ├── maximum-average-subarray-i.cpp ├── maximum-binary-tree-ii.cpp ├── maximum-binary-tree.cpp ├── maximum-depth-of-binary-tree.cpp ├── maximum-depth-of-n-ary-tree.cpp ├── maximum-difference-between-node-and-ancestor.cpp ├── maximum-level-sum-of-a-binary-tree.cpp ├── maximum-nesting-depth-of-the-parentheses.cpp ├── maximum-nesting-depth-of-two-valid-parentheses-strings.cpp ├── maximum-number-of-pairs-in-array.cpp ├── maximum-number-of-vowels-in-a-substring-of-given-length.cpp ├── maximum-number-of-words-found-in-sentences.cpp ├── maximum-number-of-words-you-can-type.cpp ├── maximum-product-of-two-elements-in-an-array.cpp ├── maximum-score-from-removing-stones.cpp ├── maximum-subarray.cpp ├── maximum-subsequence-score.cpp ├── maximum-twin-sum-of-a-linked-list.cpp ├── merge-in-between-linked-lists.cpp ├── merge-nodes-in-between-zeros.cpp ├── merge-similar-items.cpp ├── merge-sorted-array.cpp ├── merge-strings-alternately.cpp ├── merge-two-binary-trees.cpp ├── merge-two-sorted-lists.cpp ├── middle-of-the-linked-list.cpp ├── min-cost-climbing-stairs.cpp ├── min-stack.cpp ├── minimum-absolute-difference-in-bst.cpp ├── minimum-add-to-make-parentheses-valid.cpp ├── minimum-amount-of-time-to-fill-cups.cpp ├── minimum-changes-to-make-alternating-binary-string.cpp ├── minimum-depth-of-binary-tree.cpp ├── minimum-distance-between-bst-nodes.cpp ├── minimum-lines-to-represent-a-line-chart.cpp ├── minimum-number-game.cpp ├── minimum-number-of-operations-to-sort-a-binary-tree-by-level.cpp ├── minimum-number-of-swaps-to-make-the-string-balanced.cpp ├── minimum-remove-to-make-valid-parentheses.cpp ├── minimum-string-length-after-removing-substrings.cpp ├── minimum-time-to-type-word-using-special-typewriter.cpp ├── missing-number.cpp ├── monotonic-array.cpp ├── most-frequent-subtree-sum.cpp ├── move-zeroes.cpp ├── multiply-strings.cpp ├── n-ary-tree-postorder-traversal.cpp ├── n-ary-tree-preorder-traversal.cpp ├── n-th-tribonacci-number.cpp ├── next-greater-element-i.cpp ├── next-greater-element-ii.cpp ├── number-of-1-bits.cpp ├── number-of-even-and-odd-bits..cpp ├── number-of-good-leaf-nodes-pairs.cpp ├── number-of-good-pairs.cpp ├── number-of-islands.cpp ├── number-of-recent-calls.cpp ├── number-of-steps-to-reduce-a-number-in-binary-representation-to-one.cpp ├── number-of-steps-to-reduce-a-number-to-zero.cpp ├── number-of-students-doing-homework-at-a-given-time.cpp ├── number-of-students-unable-to-eat-lunch.cpp ├── odd-even-linked-lis.cpp ├── pacific-atlantic-water-flow.cpp ├── palindrome-linked-list.cpp ├── palindrome-number.cpp ├── partitioning-into-minimum-number-of-deci-binary-numbers.cpp ├── pascals-triangle.cpp ├── path-in-zigzag-labelled-binary-tree.cpp ├── path-sum-ii.cpp ├── path-sum-iii.cpp ├── path-sum.cpp ├── percentage-of-letter-in-string.cpp ├── perfect-number.cpp ├── plus-one.cpp ├── populating-next-right-pointers-in-each-node-ii.cpp ├── populating-next-right-pointers-in-each-node.cpp ├── power-of-three.cpp ├── power-of-two.cpp ├── powx-n.cpp ├── print-binary-tree.cpp ├── product-of-array-except-self.cpp ├── pseudo-palindromic-paths-in-a-binary-tree.cpp ├── range-sum-of-bst.cpp ├── range-sum-query-immutable.cpp ├── ransom-note.cpp ├── recover-a-tree-from-preorder-traversal.cpp ├── reduce-array-size-to-the-half.cpp ├── reduction-operations-to-make-the-array-elements-equal.cpp ├── redundant-connection.cpp ├── remove-all-adjacent-duplicates-in-string.cpp ├── remove-duplicates-from-sorted-array.cpp ├── remove-duplicates-from-sorted-lis.cpp ├── remove-element.cpp ├── remove-nodes-from-linked-list.cpp ├── remove-nth-node-from-end-of-list.cpp ├── remove-outermost-parentheses.cpp ├── removing-stars-from-a-string.cpp ├── repeated-substring-pattern.cpp ├── replace-elements-with-greatest-element-on-right-side.cpp ├── replace-words.cpp ├── reshape-the-matrix.1.cpp ├── reverse-bits.cpp ├── reverse-integer.cpp ├── reverse-linked-list.cpp ├── reverse-odd-levels-of-binary-tree.cpp ├── reverse-string.cpp ├── reverse-substrings-between-each-pair-of-parentheses.cpp ├── reverse-vowels-of-a-string.cpp ├── reverse-words-in-a-string.cpp ├── richest-customer-wealth.cpp ├── robot-bounded-in-circle.cpp ├── robot-return-to-origin.cpp ├── roman-to-integer.cpp ├── roman-to-nteger.cpp ├── root-equals-sum-of-children.cpp ├── rotate-array.cpp ├── rotate-image.cpp ├── running-sum-of-1d-array.cpp ├── same-tree.cpp ├── score-of-parentheses.cpp ├── search-in-a-binary-search-tree.cpp ├── search-insert-position.cpp ├── search-suggestions-system.cpp ├── seat-reservation-manager.cpp ├── second-minimum-node-in-a-binary-tree.cpp ├── serialize-and-deserialize-binary-tree.cpp ├── serialize-and-deserialize-bst.cpp ├── set-matrix-zeroes.cpp ├── shuffle-an-array.cpp ├── shuffle-the-array.cpp ├── sign-of-the-product-of-an-array.cpp ├── single-number-ii.cpp ├── single-number.cpp ├── smallest-index-with-equal-value.cpp ├── smallest-number-in-infinite-set.cpp ├── smallest-string-starting-from-leaf.cpp ├── smallest-subtree-with-all-the-deepest-nodes.cpp ├── sort-array-by-increasing-frequency.cpp ├── sort-array-by-parity.cpp ├── sort-characters-by-frequency.cpp ├── sort-colors.cpp ├── special-array-with-x-elements-greater-than-or-equal-x.cpp ├── spiral-matrix-iv.cpp ├── spiral-matrix.cpp ├── sqrtx.cpp ├── squares-of-a-sorted-array.cpp ├── string-compression.cpp ├── string-to-integer-atoi.cpp ├── student-attendance-record.cpp ├── subsets.cpp ├── subtree-of-another-tree.cpp ├── sum-of-all-odd-length-subarray.cpp ├── sum-of-left-leaves.cpp ├── sum-of-nodes-with-even-valued-grandparent.cpp ├── sum-of-root-to-leaf-binary-numbers.cpp ├── sum-of-unique-elements.cpp ├── sum-root-to-leaf-numbers.cpp ├── super-pow.cpp ├── swapping-nodes-in-a-linked-list.cpp ├── symmetric-tree.cpp ├── the-k-weakest-rows-in-a-matrix.cpp ├── third-maximum-number.cpp ├── time-needed-to-buy-tickets.cpp ├── to-lower-case.cpp ├── top-k-frequent-elements.cpp ├── trim-a-binary-search-tree.cpp ├── truncate-sentence.cpp ├── two-out-of-three.cpp ├── two-sum-ii-input-array-is-sorted.cpp ├── two-sum-iv-input-is-a-bst.cpp ├── two-sum.cpp ├── unique-binary-search-trees.cpp ├── unique-number-of-occurrences.cpp ├── univalued-binary-tree.cpp ├── valid-anagram.cpp ├── valid-mountain-array.cpp ├── valid-palindrome.cpp ├── valid-parentheses.cpp ├── valid-sudoku.cpp ├── validate-binary-search-tree.cpp ├── validate-stack-sequences.cpp ├── word-pattern.cpp ├── word-search.cpp ├── xor-operation-in-an-array.cpp └── zigzag-conversion.cpp ├── java ├── TreeNode.java ├── add-strings.java ├── add-two-numbers.java ├── all-ancestors-of-a-node-in-a-directed-acyclic-graph.java ├── append-characters-to-string-to-make-subsequence.java ├── average-waiting-time.java ├── balanced-binary-tree.java ├── binary-tree-level-order-traversal.java ├── binary-tree-maximum-path-sum.java ├── binary-tree-right-side-view.java ├── build-a-matrix-with-conditions.java ├── check-if-array-pairs-are-divisible-by-k.java ├── climbing-stairs.java ├── clone-graph.java ├── coin-change.java ├── combination-sum-ii.java ├── combination-sum.java ├── construct-binary-tree-from-preorder-and-inorder-traversal.java ├── continuous-subarray-sum.java ├── copy-list-with-random-pointer.java ├── count-good-nodes-in-binary-tree.java ├── count-number-of-nice-subarrays.java ├── count-number-of-teams.java ├── count-the-number-of-consistent-strings.java ├── count-the-number-of-fair-pairs.java ├── count-triplets-that-can-form-two-arrays-of-equal-xor.java ├── counting-bits.java ├── course-schedule-ii.java ├── course-schedule.java ├── crawler-log-folder.java ├── create-binary-tree-from-descriptions.java ├── decode-ways.java ├── decode-xored-array.java ├── delete-leaves-with-a-given-value.java ├── delete-nodes-and-return-forest.java ├── design-add-and-search-words-data-structure.java ├── design-twitter.java ├── detect-squares.java ├── diameter-of-binary-tree.java ├── evaluate-boolean-binary-tree.java ├── filling-bookcase-shelves.java ├── find-center-of-star-graph.java ├── find-k-th-smallest-pair-distance.java ├── find-median-from-data-stream.java ├── find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance.java ├── find-the-duplicate-number.java ├── find-the-highest-altitude.java ├── find-the-maximum-sum-of-node-values.java ├── find-the-minimum-and-maximum-number-of-nodes-between-critical-points.java ├── find-the-winner-of-the-circular-game.java ├── group-anagram.java ├── grumpy-bookstore-owner.java ├── happy-number.java ├── height-checker.java ├── hello-world.java ├── house-robber-ii.java ├── house-robber.java ├── implement-trie-prefix-tree.java ├── intersection-of-two-arrays-ii.java ├── invert-binary-tree.java ├── ipo.java ├── k-closest-points-to-origin.java ├── kth-largest-element-in-a-stream.java ├── kth-largest-element-in-an-array.java ├── kth-smallest-element-in-a-bst.java ├── last-stone-weight.java ├── letter-case-permutation.java ├── letter-combinations-of-a-phone-number.java ├── linked-list-cycle.java ├── longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.java ├── longest-increasing-subsequence.java ├── longest-palindrome.java ├── longest-palindromic-substring.java ├── lowest-common-ancestor-of-a-binary-search-tree.java ├── lru-cache.java ├── lucky-numbers-in-a-matrix.java ├── magnetic-force-between-two-balls.java ├── max-area-of-island.java ├── maximize-happiness-of-selected-children.java ├── maximum-depth-of-binary-tree.java ├── maximum-product-subarray.java ├── maximum-score-from-removing-substrings.java ├── maximum-sum-of-distinct-subarrays-with-length-k.java ├── maximum-total-importance-of-roads.java ├── merge-k-sorted-lists.java ├── merge-nodes-in-between-zeros.java ├── min-cost-climbing-stairs.java ├── minimum-deletions-to-make-string-balanced.java ├── minimum-difference-between-largest-and-smallest-value-in-three-moves.java ├── minimum-increment-to-make-array-unique.java ├── minimum-number-of-days-to-make-m-bouquets.java ├── minimum-number-of-k-consecutive-bit-flips.java ├── minimum-number-of-moves-to-seat-everyone.java ├── minimum-swaps-to-group-all-1s-together-ii.java ├── missing-number.java ├── most-profit-assigning-work.java ├── multiply-strings.java ├── n-queens.java ├── number-of-1-bits.java ├── number-of-atoms.java ├── number-of-islands.java ├── number-of-senior-citizens.java ├── pacific-atlantic-water-flow.java ├── palindrome-partitioning.java ├── palindromic-substrings.java ├── partition-equal-subset-sum.java ├── pass-the-pillow.java ├── patching-array.java ├── permutations.java ├── plus-one.java ├── power-of-two.java ├── powx-n.java ├── range-sum-of-bst.java ├── relative-ranks.java ├── relative-sort-array.java ├── remove-max-number-of-edges-to-keep-graph-fully-traversable.java ├── remove-nodes-from-linked-list.java ├── reorder-list.java ├── reverse-bits.java ├── reverse-integer.java ├── reverse-linked-list.java ├── reverse-nodes-in-k-group.java ├── reverse-string.java ├── reverse-substrings-between-each-pair-of-parentheses.java ├── robot-collision.java ├── rotate-image.java ├── rotting-orange.java ├── same-tree.java ├── score-of-a-string.java ├── second-minimum-time-to-reach-destination.java ├── set-matrix-zeroes.java ├── single-number-iii.java ├── single-number.java ├── sort-an-array.java ├── sort-array-by-increasing-frequency.java ├── sort-colors.java ├── sort-the-jumbled-numbers.java ├── spiral-matrix.java ├── step-by-step-directions-from-a-binary-tree-node-to-another.java ├── subarray-sums-divisible-by-k.java ├── subsets-ii.java ├── subsets.java ├── subtree-of-another-tree.java ├── sum-of-all-subset-xor-totals.java ├── sum-of-square-numbers.java ├── sum-of-two-integers.java ├── surrounded-regions.java ├── task-scheduler.java ├── three-consecutive-odds.java ├── validate-binary-search-tree.java ├── water-bottles.java ├── word-break.java ├── word-ladder.java ├── word-search-ii.java ├── word-search.java └── xor-operation-in-an-array.java ├── js ├── 01-matrix.js ├── add-two-promises.js ├── allow-one-function-call.js ├── apply-transform-over-each-element-in-array.js ├── array-prototype-last.js ├── array-reduce-transformation.js ├── array-wrapper.js ├── cache-with-time-limit.js ├── calculator-with-method-chaining.js ├── call-function-with-custom-context.js ├── check-if-object-instance-of-class.js ├── chunk-array.js ├── compact-object.js ├── concatenation-of-array.js ├── counter-ii.js ├── counter.js ├── create-hello-world-function.js ├── curry.js ├── debounce.js ├── decode-string.js ├── decode-xored-array.js ├── design-cancellable-function.js ├── event-emitter.js ├── execute-asynchronous-functions-in-parallel.js ├── execute-cancellable-function-with-delay.js ├── filter-elements-from-array.js ├── find-the-difference-of-two-arrays.js ├── find-the-highest-altitude.js ├── fizz-buzz.js ├── flatten-deeply-nested-array.js ├── flipping-an-image.js ├── function-composition.js ├── generate-fibonacci-sequence.js ├── group-by.js ├── guess-number-higher-or-lower.js ├── hello-world.js ├── interval-cancellation.js ├── is-object-empty.js ├── is-subsequence.js ├── join-two-arrays-by-id.js ├── json-deep-equal.js ├── linked-list-cycle-ii.js ├── memoize-ii.js ├── memoize.js ├── nested-array-generator.js ├── number-of-1-bits.js ├── power-of-two.js ├── promise-time-limit.js ├── return-length-of-arguments-passed.js ├── rotate-image.js ├── running-sum-of-1d-array.js ├── single-number.js ├── sleep.js ├── smallest-even-multiple.js ├── snail-traversal.js ├── sort-by.js ├── sort-characters-by-frequency.js ├── student-attendance-record.js ├── summary-ranges.js ├── to-be-or-not-to-be.js ├── top-k-frequent-words.js ├── truncate-sentence.js ├── word-pattern.js └── xor-operation-in-an-array.js ├── py ├── binary-tree-level-order-traversal.py ├── check-if-it-is-a-straight-line.py ├── combinations.py ├── decode-string.py ├── decode-xored-array.py ├── find-the-highest-altitude.py ├── hello-world.py ├── left-and-right-sum-differences.py ├── permutations.py ├── power-of-two.py ├── range-sum-of-bst.py ├── single-number.py ├── triangle.py ├── two-sum.py └── xor-operation-in-an-array.py ├── rs ├── 3sum.rs ├── add-two-integers.rs ├── best-time-to-buy-and-sell-stock.rs ├── binary-search.rs ├── binary-tree-inorder-traversal.rs ├── car-fleet.rs ├── container-with-most-water.rs ├── contains-duplicate.rs ├── daily-temperatures.rs ├── evaluate-reverse-polish-notation.rs ├── find-minimum-in-rotated-sorted-array.rs ├── find-the-highest-altitude.rs ├── find-the-maximum-achievable-number.rs ├── generate-parentheses.rs ├── group-anagram.rs ├── hello-world.rs ├── isomorphic-strings.rs ├── jewels-and-stones.rs ├── koko-eating-bananas.rs ├── largest-rectangle-in-histogram.rs ├── longest-repeating-character-replacement.rs ├── longest-substring-without-repeating-characters.rs ├── median-of-two-sorted-arrays.rs ├── min-stack.rs ├── minimum-sum-of-four-digit-number-after-splitting-digits.rs ├── minimum-window-substring.rs ├── number-of-even-and-odd-bits.rs ├── permutation-in-string.rs ├── product-of-array-except-self.rs ├── reverse-linked-list.rs ├── running-sum-of-1d-array.rs ├── search-a-2d-matrix.rs ├── search-in-rotated-sorted-array.rs ├── sliding-window-maximum.rs ├── smallest-even-multiple.rs ├── subtract-the-product-and-sum-of-digits-of-an-integer.rs ├── time-based-key-value-store.rs ├── top-k-frequent-elements.rs ├── trapping-rain-water.rs ├── two-sum-ii-input-array-is-sorted.rs ├── two-sum.rs ├── valid-anagram.rs ├── valid-palindrome.rs └── valid-parentheses.rs ├── sql └── combine-two-tables.sql ├── ts ├── add-two-promises.ts ├── allow-one-function-call.ts ├── apply-transform-over-each-element-in-array.ts ├── array-prototype-last.ts ├── array-reduce-transformation.ts ├── array-wrapper.ts ├── average-of-levels-in-binary-tree.ts ├── binary-tree-preorder-traversal.ts ├── cache-with-time-limit.ts ├── calculator-with-method-chaining.ts ├── call-function-with-custom-context.ts ├── check-if-object-instance-of-class.ts ├── chunk-array.ts ├── compact-object.ts ├── counter-ii.ts ├── counter.ts ├── create-hello-world-function.ts ├── debounce.ts ├── decode-xored-array.ts ├── deepest-leaves-sum.ts ├── event-emitter.ts ├── execute-asynchronous-functions-in-parallel.ts ├── execute-cancellable-function-with-delay.ts ├── filter-elements-from-array.ts ├── find-the-highest-altitude.ts ├── flatten-deeply-nested-array.ts ├── function-composition.ts ├── generate-fibonacci-sequence.ts ├── group-anagrams.ts ├── group-by.ts ├── hello-world.ts ├── interval-cancellation.ts ├── is-object-empty.ts ├── join-two-arrays-by-id.ts ├── maximum-depth-of-n-ary-tree.ts ├── memoize.ts ├── minimum-absolute-difference-in-bst.ts ├── nested-array-generator.ts ├── number-of-1-bits.ts ├── power-of-two.ts ├── promise-time-limit.ts ├── return-length-of-arguments-passed.ts ├── running-sum-of-1d-array.ts ├── single-number.ts ├── sleep.ts ├── snail-traversal.ts ├── sort-by.ts ├── sum-of-root-to-leaf-binary-numbers.ts ├── to-be-or-not-to-be.ts ├── two-sum-iv-input-is-a-bst.ts ├── univalued-binary-tree.ts └── xor-operation-in-an-array.ts └── txt └── hello-world.txt /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | [//]: # "Please Write File names and submission URLs." 2 | 3 | Modified Files & Submission URL 4 | - 5 | - 6 | - 7 | - 8 | 9 | [//]: # "For Example " 10 | 11 | [//]: # "- valid-palindrome.c https://leetcode.com/submissions/detail/767702059/" 12 | 13 | 14 | [//]: # "Go to submission tab in leetcode and click the Accepted submission then copy the link from nav bar and paste here 😁" 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | **.exe 2 | **/.vscode 3 | **/current 4 | desktop.ini 5 | **/later 6 | **/test 7 | test.* -------------------------------------------------------------------------------- /contributors.md: -------------------------------------------------------------------------------- 1 | ## OWNER 2 | [@Abinash Karmamar](https://www.linkedin.com/in/codeabinash/) 3 | 4 | --- 5 | 6 | ## OUR CONTRIBUTORS 7 | 8 | * [@ArshErgon](https://github.com/ArshErgon) 9 | * [@Anushka-bot](https://github.com/Anushka-bot) 10 | * [@Vansitha](https://github.com/Vansitha) 11 | * [@abhie16](https://github.com/abhie16) 12 | * [@aakash172](https://github.com/aakash172) 13 | * [@codeAntu](https://github.com/codeAntu) -------------------------------------------------------------------------------- /leetcode/problems/c/a-number-after-a-double-reversal.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(1) 3 | // Space Complexity : O(1) 4 | 5 | bool isSameAfterReversals(int num){ 6 | return num == 0 || num % 10; 7 | } -------------------------------------------------------------------------------- /leetcode/problems/c/a.c: -------------------------------------------------------------------------------- 1 | #include "stdio.h" 2 | 3 | 4 | int main(){ 5 | 6 | return 0; 7 | } -------------------------------------------------------------------------------- /leetcode/problems/c/add-binary.c: -------------------------------------------------------------------------------- 1 | char *addBinary(char *a, char *b) { 2 | int len1 = strlen(a); 3 | int len2 = strlen(b); 4 | int sLen = (len1 > len2 ? len1 : len2) + 1; 5 | 6 | char *str = (char *)malloc((sLen + 1) * sizeof(char)); 7 | str[sLen] = '\0'; 8 | 9 | int sum = 0; 10 | 11 | while (len1 > 0 || len2 > 0 || sum > 0) { 12 | if (len1 > 0) sum += a[--len1] - '0'; 13 | if (len2 > 0) sum += b[--len2] - '0'; 14 | str[--sLen] = sum % 2 + '0'; 15 | sum /= 2; 16 | } 17 | return str + sLen; 18 | } -------------------------------------------------------------------------------- /leetcode/problems/c/add-digits.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Using recursion 3 | int addDigits(int num) { 4 | if (num < 10) return num; 5 | 6 | int sum = 0; 7 | 8 | while (num) { 9 | sum += num % 10; 10 | num /= 10; 11 | } 12 | return addDigits(sum); 13 | } 14 | 15 | // Better Solution 16 | // O(1) Time and space complexity 17 | int addDigits(int num) { 18 | if(num%9 == 0 && num/9 >= 1) 19 | return 9; 20 | return num % 9; 21 | } -------------------------------------------------------------------------------- /leetcode/problems/c/average-salary-excluding-the-minimum-and-maximum-salary.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | double average(int* salary, int salarySize) { 6 | int min = salary[0], max = salary[0]; 7 | 8 | for (int i = 0; i < salarySize; i++) { 9 | if (salary[i] < min) min = salary[i]; 10 | if (salary[i] > max) max = salary[i]; 11 | } 12 | 13 | double sum = 0; 14 | for (int i = 0; i < salarySize; i++) 15 | sum += salary[i]; 16 | 17 | return (double)(sum - min - max) / (salarySize - 2); 18 | } -------------------------------------------------------------------------------- /leetcode/problems/c/backspace-string-compare.c: -------------------------------------------------------------------------------- 1 | void processString(char *s){ 2 | int start = 0; 3 | for(int i = 0; s[i] != '\0'; i++) 4 | { 5 | if(s[i] != '#') 6 | s[start++] = s[i]; 7 | else if(s[i] == '#' && start > 0) 8 | start--; 9 | } 10 | s[start] = '\0'; 11 | } 12 | 13 | bool backspaceCompare(char* S, char* T) { 14 | processString(S); 15 | processString(T); 16 | 17 | return (strcmp(S, T) == 0); 18 | } 19 | -------------------------------------------------------------------------------- /leetcode/problems/c/balanced-binary-tree.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | inline int max(int a, int b) { return a > b ? a : b; } 6 | 7 | int height(struct TreeNode* root) { 8 | if (!root) return 0; 9 | return 1 + max(height(root->left), height(root->right)); 10 | } 11 | 12 | bool isBalanced(struct TreeNode* root) { 13 | if (!root) return 1; 14 | int left = height(root->left); 15 | int right = height(root->right); 16 | return abs(left - right) <= 1 && isBalanced(root->left) && 17 | isBalanced(root->right); 18 | } -------------------------------------------------------------------------------- /leetcode/problems/c/best-time-to-buy-and-sell-stock.c: -------------------------------------------------------------------------------- 1 | int maxProfit(int* prices, int pricesSize) { 2 | int min = prices[0], profit = 0, max = 0; 3 | 4 | for (int i = 1; i < pricesSize; i++) { 5 | if (prices[i] < min) 6 | min = prices[i]; 7 | profit = prices[i] - min; 8 | if (max < profit) 9 | max = profit; 10 | } 11 | return max; 12 | } -------------------------------------------------------------------------------- /leetcode/problems/c/binary-search.c: -------------------------------------------------------------------------------- 1 | int search(int* nums, int numsSize, int target){ 2 | int low = 0, 3 | high = numsSize - 1, 4 | mid; 5 | 6 | while (low <= high) { 7 | mid = (low + high) / 2; 8 | if(nums[mid] == target) 9 | return mid; 10 | if(target > nums[mid]) 11 | low = mid + 1; 12 | else 13 | high = mid - 1; 14 | } 15 | return -1; 16 | } -------------------------------------------------------------------------------- /leetcode/problems/c/binary-tree-inorder-traversal.c: -------------------------------------------------------------------------------- 1 | void inOrder(struct TreeNode* root, int* index, int* arr) { 2 | if (root != NULL) { 3 | inOrder(root->left, index, arr); 4 | arr[(*index)++] = root->val; 5 | inOrder(root->right, index, arr); 6 | } 7 | } 8 | 9 | int* inorderTraversal(struct TreeNode* root, int* returnSize){ 10 | 11 | int *arr = (int *)malloc(sizeof(int) * 100); 12 | *returnSize = 0; 13 | inOrder(root, returnSize, arr); 14 | return arr; 15 | } -------------------------------------------------------------------------------- /leetcode/problems/c/binary-tree-postorder-traversa.c: -------------------------------------------------------------------------------- 1 | void inOrder(struct TreeNode* root, int* index, int* arr) { 2 | if (root != NULL) { 3 | inOrder(root->left, index, arr); 4 | inOrder(root->right, index, arr); 5 | arr[(*index)++] = root->val; 6 | } 7 | } 8 | int* postorderTraversal(struct TreeNode* root, int* returnSize){ 9 | int *arr = (int *)malloc(sizeof(int) * 100); 10 | *returnSize = 0; 11 | inOrder(root, returnSize, arr); 12 | return arr; 13 | } -------------------------------------------------------------------------------- /leetcode/problems/c/binary-tree-preorder-traversal.c: -------------------------------------------------------------------------------- 1 | void preOrder(struct TreeNode* root, int* index, int* arr) { 2 | if (root != NULL) { 3 | arr[(*index)++] = root->val; 4 | preOrder(root->left, index, arr); 5 | preOrder(root->right, index, arr); 6 | } 7 | } 8 | 9 | int* preorderTraversal(struct TreeNode* root, int* returnSize) { 10 | int *arr = (int *)malloc(sizeof(int) * 100); 11 | *returnSize = 0; 12 | preOrder(root, returnSize, arr); 13 | return arr; 14 | } -------------------------------------------------------------------------------- /leetcode/problems/c/can-make-arithmetic-progression-from-sequence.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | int compare(const void* a, const void* b) { 6 | return (*(int*)a - *(int*)b); 7 | } 8 | 9 | bool canMakeArithmeticProgression(int* arr, int arrSize) { 10 | int i, diff; 11 | qsort(arr, arrSize, sizeof(int), compare); 12 | diff = arr[1] - arr[0]; 13 | for (i = 2; i < arrSize; i++) { 14 | if (arr[i] - arr[i - 1] != diff) { 15 | return false; 16 | } 17 | } 18 | return true; 19 | } -------------------------------------------------------------------------------- /leetcode/problems/c/can-place-flowers.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | bool canPlaceFlowers(int* flowerbed, int flowerbedSize, int n) { 6 | for (int i = 0;i < flowerbedSize;i++) { 7 | if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) && (i == flowerbedSize - 1 || flowerbed[i + 1] == 0)) { 8 | flowerbed[i] = 1; 9 | n--; 10 | } 11 | } 12 | return n <= 0; 13 | } -------------------------------------------------------------------------------- /leetcode/problems/c/check-if-it-is-a-straight-line.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | bool checkStraightLine(int** coordinates, int coordinatesSize, int* coordinatesColSize) { 6 | int dx = coordinates[1][0] - coordinates[0][0], 7 | dy = coordinates[1][1] - coordinates[0][1]; 8 | for (size_t i = 2; i < coordinatesSize ; i++) { 9 | int c_dy = coordinates[i][1] - coordinates[i - 1][1]; 10 | int c_dx = coordinates[i][0] - coordinates[i - 1][0]; 11 | if (dy * c_dx != dx * c_dy) return false; 12 | } 13 | return true; 14 | } -------------------------------------------------------------------------------- /leetcode/problems/c/check-if-number-has-equal-digit-count-and-digit-value.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | bool digitCount(char* num) { 6 | int i = 0, hash[10] = {0}; 7 | while (num[i]) hash[num[i++] - '0']++; 8 | 9 | i = 0; 10 | while (num[i]) 11 | if (num[i] - '0' != hash[i++]) 12 | return false; 13 | return true; 14 | } -------------------------------------------------------------------------------- /leetcode/problems/c/climbing-stairs.c: -------------------------------------------------------------------------------- 1 | int count(int n, int *memory){ 2 | if(n <= 1) return 1; 3 | if(memory[n] > 0) return memory[n]; 4 | return memory[n] = count(n - 1, memory) + count(n - 2, memory); 5 | } 6 | 7 | int climbStairs(int n){ 8 | int memory[46] = {0}; 9 | return count(n, memory); 10 | } -------------------------------------------------------------------------------- /leetcode/problems/c/complement-of-base-10-integer.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(log n) 3 | // Space Complexity : O(1) 4 | 5 | int bitwiseComplement(int num) { 6 | int tmp = num, n = 0; 7 | if (num == 0) return 1; 8 | while (tmp > 0) { 9 | n = (n << 1) | 1; 10 | tmp >>= 1; 11 | } 12 | return num ^ n; 13 | } -------------------------------------------------------------------------------- /leetcode/problems/c/concatenation-of-array.c: -------------------------------------------------------------------------------- 1 | //// by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | int *getConcatenation(int *nums, int numsSize, int *returnSize) { 6 | int *newArr = (int *)malloc(numsSize * 2 * sizeof(int)); 7 | *returnSize = numsSize * 2; 8 | for (int i = 0; i < numsSize; i++) 9 | newArr[i + numsSize] = newArr[i] = nums[i % numsSize]; 10 | return newArr; 11 | } -------------------------------------------------------------------------------- /leetcode/problems/c/count-odd-numbers-in-an-interval-range.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | int countOdds(int low, int high) { 6 | return (high + 1) / 2 - low / 2; 7 | } 8 | 9 | // A bit faster 10 | 11 | int countOdds(int low, int high) { 12 | if (!(high & 1) && !(low & 1)) 13 | return (high - low) / 2; 14 | return (high - low) / 2 + 1; 15 | } -------------------------------------------------------------------------------- /leetcode/problems/c/count-primes.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | #include "stdio.h" 4 | 5 | int countPrimes(int n) { 6 | if (n <= 2) return 0; 7 | bool isPrime[n]; 8 | for (int i = 0; i < n;i++) 9 | isPrime[i] = true; 10 | isPrime[0] = isPrime[1] = false; 11 | 12 | for (int i = 2; i * i < n; i++) 13 | if (isPrime[i]) 14 | for (int j = 2 * i; j < n; j += i) 15 | isPrime[j] = false; 16 | 17 | // Count primes 18 | int count = 0; 19 | for (int i = 2; i < n;i++) 20 | if (isPrime[i]) 21 | count++; 22 | 23 | return count; 24 | } -------------------------------------------------------------------------------- /leetcode/problems/c/decode-xored-array.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | int* decode(int* encoded, int encodedSize, int first, int* returnSize) { 6 | int* arr = (int*)malloc(sizeof(int) * (encodedSize + 1)); 7 | *returnSize = encodedSize + 1; 8 | arr[0] = first; 9 | for (int i = 0; i < encodedSize; i++) 10 | arr[i + 1] = arr[i] ^ encoded[i]; 11 | return arr; 12 | } -------------------------------------------------------------------------------- /leetcode/problems/c/eplace-all-digits-with-characters.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | char* replaceDigits(char* s) { 6 | int index = 0; 7 | while (s[index]) { 8 | if (index % 2 != 0) s[index] = s[index - 1] + (s[index] - '0'); 9 | index++; 10 | } 11 | return s; 12 | } -------------------------------------------------------------------------------- /leetcode/problems/c/fibonacci-number.c: -------------------------------------------------------------------------------- 1 | int count(int n, int *memory){ 2 | if(n == 1) return 1; 3 | if(n <= 0) return 0; 4 | if(memory[n] > 0) return memory[n]; 5 | return memory[n] = count(n - 1, memory) + count(n - 2, memory); 6 | } 7 | int fib(int n){ 8 | int memory[31] = {0}; 9 | return count(n, memory); 10 | } -------------------------------------------------------------------------------- /leetcode/problems/c/find-greatest-common-divisor-of-array.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | int gcd(int a,int b){ 4 | if(b == 0) 5 | return a; 6 | return gcd(b, a%b); 7 | } 8 | 9 | int findGCD(int* nums, int numsSize) { 10 | int min = nums[0], max = nums[0]; 11 | int i; 12 | for(i = 0; i < numsSize; i++){ 13 | if(min < nums[i]) min = nums[i]; 14 | else if(max > nums[i]) max = nums[i]; 15 | } 16 | return gcd(min,max); 17 | } -------------------------------------------------------------------------------- /leetcode/problems/c/find-n-unique-integers-sum-up-to-zero.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(n) 4 | 5 | int* sumZero(int n, int* returnSize) { 6 | int* arr = (int*)calloc(n, sizeof(int)); 7 | int start = n % 2 ? 1 : 0; 8 | int num = 1; 9 | *returnSize = n; 10 | for (int i = start; i < n; i += 2) { 11 | arr[i] = num; 12 | arr[i + 1] = -num; 13 | num++; 14 | } 15 | return arr; 16 | } -------------------------------------------------------------------------------- /leetcode/problems/c/find-pivot-index.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | inline int sum(int* arr, int len) { 6 | int sum = 0; 7 | for (int i = 0; i < len; i++) 8 | sum += arr[i]; 9 | return sum; 10 | } 11 | 12 | int pivotIndex(int* nums, int numsSize) { 13 | int leftSum = 0, rightSum = sum(nums, numsSize); 14 | for (int i = 0; i < numsSize; i++) { 15 | leftSum += nums[i]; 16 | if (leftSum == rightSum) 17 | return i; 18 | rightSum -= nums[i]; 19 | } 20 | return -1; 21 | } -------------------------------------------------------------------------------- /leetcode/problems/c/find-the-difference.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | char findTheDifference(char* s, char* t) { 6 | int xor = 0; 7 | int index = 0; 8 | while (s[index] && t[index]) { 9 | xor ^= s[index]; 10 | xor ^= t[index]; 11 | index++; 12 | } 13 | xor ^= t[index]; 14 | return xor; 15 | } -------------------------------------------------------------------------------- /leetcode/problems/c/find-the-highest-altitude.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | int largestAltitude(int* gain, int gainSize) { 6 | int currentAlt = 0, maxAlt = 0; 7 | 8 | for (int i = 0; i < gainSize; i++) { 9 | currentAlt += gain[i]; 10 | if (currentAlt > maxAlt) 11 | maxAlt = currentAlt; 12 | } 13 | 14 | return maxAlt; 15 | } -------------------------------------------------------------------------------- /leetcode/problems/c/find-the-middle-index-in-array.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | inline int sum(int* arr, int len) { 6 | int sum = 0; 7 | for (int i = 0; i < len; i++) 8 | sum += arr[i]; 9 | return sum; 10 | } 11 | 12 | int findMiddleIndex(int* nums, int numsSize) { 13 | int leftSum = 0, rightSum = sum(nums, numsSize); 14 | for (int i = 0; i < numsSize; i++) { 15 | leftSum += nums[i]; 16 | if (leftSum == rightSum) 17 | return i; 18 | rightSum -= nums[i]; 19 | } 20 | return -1; 21 | } -------------------------------------------------------------------------------- /leetcode/problems/c/first-bad-version.c: -------------------------------------------------------------------------------- 1 | int firstBadVersion(int n) { 2 | long low = 1; 3 | long mid; 4 | while (low <= n) { 5 | mid = (low + n) / 2; 6 | if (isBadVersion(mid)) 7 | n = mid - 1; 8 | else 9 | low = mid + 1; 10 | } 11 | return low; 12 | } -------------------------------------------------------------------------------- /leetcode/problems/c/first-letter-to-appear-twice.c: -------------------------------------------------------------------------------- 1 | char repeatedCharacter(char* s) { 2 | int chars[26] = {0}; 3 | int i = 0; 4 | 5 | while (s[i]) { 6 | chars[s[i] - 'a']++; 7 | if(chars[s[i] - 'a'] == 2) 8 | return s[i]; 9 | i++; 10 | } 11 | return NULL; 12 | } -------------------------------------------------------------------------------- /leetcode/problems/c/first-unique-character-in-a-string.c: -------------------------------------------------------------------------------- 1 | int firstUniqChar(char* s) { 2 | int chars[26] = {0}; 3 | int i = 0; 4 | 5 | while (s[i]) { 6 | chars[s[i] - 'a']++; 7 | i++; 8 | } 9 | i = 0; 10 | 11 | while (s[i]) { 12 | if (chars[s[i] - 'a'] == 1) 13 | return i; 14 | i++; 15 | } 16 | return -1; 17 | } -------------------------------------------------------------------------------- /leetcode/problems/c/guess-number-higher-or-lower.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(log n) 3 | // Space : O(1) 4 | 5 | int guess(int); 6 | int guessNumber(int n) { 7 | int start = 1, end = n; 8 | while (start < end) { 9 | int mid = start + (end - start) / 2; 10 | int result = guess(mid); 11 | 12 | if (result == -1) 13 | end = mid - 1; 14 | else if (result == 1) 15 | start = mid + 1; 16 | else return mid; 17 | } 18 | return start; 19 | } -------------------------------------------------------------------------------- /leetcode/problems/c/happy-number.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | bool isHappy(int n) { 6 | int digit, sum = 0; 7 | if (n == 1 || n == 7) return true; 8 | if (n < 10 && n != 1) return false; 9 | 10 | while (n > 0) { 11 | sum = sum + (n % 10) * (n % 10); 12 | n /= 10; 13 | } 14 | 15 | digit = isHappy(sum); 16 | 17 | if (digit == 1 || digit == 7) return true; 18 | return false; 19 | } -------------------------------------------------------------------------------- /leetcode/problems/c/hello-world.c: -------------------------------------------------------------------------------- 1 | // A simple hello world program in C 2 | 3 | #include "stdio.h" 4 | 5 | int main(){ 6 | printf("Hello World"); 7 | return 0; 8 | } 9 | 10 | 11 | // Search for Leetcode Solutions 12 | // Paste the link or the name of the problem 13 | // 👆🏻 in the Search Bar 14 | // Hit enter or click the search button 15 | // The solution will be displayed in this section -------------------------------------------------------------------------------- /leetcode/problems/c/house-robber.c: -------------------------------------------------------------------------------- 1 | int max(int a, int b){ 2 | return a > b ? a : b; 3 | } 4 | 5 | int rob(int* nums, int numsSize){ 6 | int rob1 = 0 , rob2 = 0, tmp; 7 | for(int i = 0; i < numsSize; i++) { 8 | tmp = max(nums[i] + rob1, rob2); 9 | rob1 = rob2; 10 | rob2 = tmp; 11 | } 12 | return rob2; 13 | } -------------------------------------------------------------------------------- /leetcode/problems/c/implement-strstr.c: -------------------------------------------------------------------------------- 1 | int match(char *haystack, char *needle, int a, int n) { 2 | for (int i = 0; i < n; i++) { 3 | if (haystack[a] != needle[i]) 4 | return 0; 5 | a++; 6 | } 7 | return 1; 8 | } 9 | 10 | int strStr(char *haystack, char *needle) { 11 | int n = strlen(haystack), m = strlen(needle); 12 | for (int i = 0; i < n; i++) 13 | if (haystack[i] == needle[0]) 14 | if (match(haystack, needle, i, m)) 15 | return i; 16 | return -1; 17 | } -------------------------------------------------------------------------------- /leetcode/problems/c/increasing-triplet-subsequence.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "limits.h" 6 | 7 | bool increasingTriplet(int* nums, int numsSize) { 8 | int i, min = INT_MAX, mid = INT_MAX; 9 | for (i = 0; i < numsSize; i++) { 10 | if (nums[i] <= min) min = nums[i]; 11 | else if (nums[i] <= mid) mid = nums[i]; 12 | else return true; 13 | } 14 | return false; 15 | } -------------------------------------------------------------------------------- /leetcode/problems/c/integer-to-roman.c: -------------------------------------------------------------------------------- 1 | char *intToRoman(int num) { 2 | int numbers[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 3 | char *romans[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; 4 | char *ans= calloc(16, sizeof(char)); 5 | int i, j; 6 | 7 | for (i = 0; i <= 12; i++) { 8 | while (num >= numbers[i]) { 9 | strcat(ans, romans[i]); 10 | num -= numbers[i]; 11 | } 12 | } 13 | return ans; 14 | } 15 | -------------------------------------------------------------------------------- /leetcode/problems/c/intersection-of-two-linked-lists.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) { 4 | if (!headA || !headB) 5 | return NULL; 6 | 7 | struct ListNode *tmp1 = headA, *tmp2 = headB; 8 | 9 | while (tmp1 != tmp2) { 10 | tmp1 = tmp1 ? tmp1->next : headB; 11 | tmp2 = tmp2 ? tmp2->next : headA; 12 | } 13 | 14 | return tmp1; 15 | } -------------------------------------------------------------------------------- /leetcode/problems/c/invert-binary-tree.c: -------------------------------------------------------------------------------- 1 | struct TreeNode* invertTree(struct TreeNode* root) { 2 | struct TreeNode* tmp; 3 | 4 | if (root == NULL) return NULL; 5 | 6 | tmp = root->left; 7 | root->left = root->right; 8 | root->right = tmp; 9 | 10 | invertTree(root->left); 11 | invertTree(root->right); 12 | 13 | return root; 14 | } -------------------------------------------------------------------------------- /leetcode/problems/c/is-subsequence.c: -------------------------------------------------------------------------------- 1 | int isSubsequence(char* s, char* t) { 2 | while(*s && *t) { 3 | if (*s == *t) 4 | s++; 5 | t++; 6 | } 7 | return !(*s); 8 | } -------------------------------------------------------------------------------- /leetcode/problems/c/isomorphic-strings.c: -------------------------------------------------------------------------------- 1 | int isIsomorphic(char* s, char* t) { 2 | int S[128] = {0}; 3 | int T[128] = {0}; 4 | int index = 1; 5 | int i = 0; 6 | 7 | while (s[i]) { 8 | if (S[s[i]] == T[t[i]]) { 9 | if (S[s[i]] == 0) { 10 | S[s[i]] = index; 11 | T[t[i]] = index; 12 | index++; 13 | } 14 | } else 15 | return 0; 16 | i++; 17 | } 18 | return 1; 19 | } -------------------------------------------------------------------------------- /leetcode/problems/c/largest-perimeter-triangle.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n * lon(n)) 3 | // Space : O(1) 4 | 5 | int compare(const void* a, const void* b) { 6 | return (*(int*)a - *(int*)b); 7 | } 8 | 9 | int largestPerimeter(int* nums, int numsSize) { 10 | qsort(nums, numsSize, sizeof(int), compare); 11 | 12 | for (int i = numsSize - 1; i >= 2; i--) 13 | if (nums[i] < nums[i - 1] + nums[i - 2]) 14 | return nums[i] + nums[i - 1] + nums[i - 2]; 15 | 16 | return 0; 17 | } -------------------------------------------------------------------------------- /leetcode/problems/c/lemonade-change.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | bool lemonadeChange(int* bills, int billsSize) { 6 | int ten = 0, five = 0; 7 | for (int i = 0; i < billsSize; i++) { 8 | if (bills[i] == 5) five++; 9 | else if (bills[i] == 10) five--, ten++; 10 | else if (ten > 0) ten--, five--; 11 | else five -= 3; 12 | if (five < 0) return false; 13 | } 14 | return true; 15 | } -------------------------------------------------------------------------------- /leetcode/problems/c/length-of-last-word.c: -------------------------------------------------------------------------------- 1 | int lengthOfLastWord(char* s) { 2 | int len = 1, i = 1; 3 | 4 | if(s[0] == ' ') len = 0; 5 | 6 | while (s[i]) { 7 | if(s[i] != ' ' && s[i - 1] == ' ') 8 | len = 1; 9 | else if(s[i] != ' ') 10 | len++; 11 | i++; 12 | } 13 | return len; 14 | } -------------------------------------------------------------------------------- /leetcode/problems/c/linked-list-cycle.c: -------------------------------------------------------------------------------- 1 | bool hasCycle(struct ListNode *head) { 2 | struct ListNode *slow = head; 3 | struct ListNode *fast = head; 4 | 5 | while(fast != NULL && fast->next != NULL) { 6 | slow = slow->next; 7 | fast = fast->next->next; 8 | if(slow == fast) 9 | return true; 10 | } 11 | return false; 12 | } -------------------------------------------------------------------------------- /leetcode/problems/c/longest-repeating-character-replacement.c: -------------------------------------------------------------------------------- 1 | int characterReplacement(char *s, int k) { 2 | int max = 0, i, diff = 0, l = 0; 3 | int hash[26] = {0}; 4 | // int *hash = calloc(26, 4); 5 | if (s[0] == 0) return 0; 6 | 7 | while(s[i]){ 8 | if (++hash[s[i] - 'A'] <= max) { 9 | if (diff == k) 10 | hash[s[l++] - 'A']--; 11 | else 12 | diff++; 13 | } 14 | else 15 | max++; 16 | i++; 17 | } 18 | return max + diff; 19 | } -------------------------------------------------------------------------------- /leetcode/problems/c/longest-subarray-of-1s-after-deleting-one-element.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | int longestSubarray(int* nums, int numsSize) { 6 | int left = 0, i, right = 1; 7 | 8 | for (i = 0; i < numsSize; i++) { 9 | if (nums[i] == 0) right--; 10 | if (right < 0 && nums[left++] == 0) right++; 11 | } 12 | 13 | return i - left - 1; 14 | } -------------------------------------------------------------------------------- /leetcode/problems/c/longest-substring-without-repeating-characters.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | int lengthOfLongestSubstring(char* s) { 6 | bool set[128] = { 0 }; 7 | int left = 0, maxLen = 0, i = 0; 8 | 9 | while (s[i++]) { 10 | while (set[s[i - 1]]) 11 | set[s[left++]] = 0; 12 | 13 | set[s[i - 1]] = 1; 14 | if (i - left > maxLen) maxLen = i - left; 15 | } 16 | return maxLen; 17 | } 18 | -------------------------------------------------------------------------------- /leetcode/problems/c/lowest-common-ancestor-of-a-binary-search-tree.c: -------------------------------------------------------------------------------- 1 | struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p,struct TreeNode* q) { 2 | if (root == NULL) return NULL; 3 | 4 | if (q->val > root->val && p->val > root->val) 5 | root = lowestCommonAncestor(root->right, p, q); 6 | 7 | if (q->val < root->val && p->val < root->val) 8 | root = lowestCommonAncestor(root->left, p, q); 9 | return root; 10 | } -------------------------------------------------------------------------------- /leetcode/problems/c/majority-element.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | int majorityElement(int num[], int n) { 6 | int count = 0, elem; 7 | for (int i = 0; i < n; i++) { 8 | if (count == 0) elem = num[i]; 9 | if (elem == num[i]) count++; 10 | else count--; 11 | } 12 | return elem; 13 | } -------------------------------------------------------------------------------- /leetcode/problems/c/make-array-zero-by-subtracting-equal-amounts.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(n) 4 | 5 | #include "unordered_set" 6 | #include "vector" 7 | 8 | using namespace std; 9 | 10 | class Solution { 11 | public: 12 | int minimumOperations(vector& nums) { 13 | unordered_set s; 14 | for (int num : nums) 15 | if (num != 0) s.insert(num); 16 | return s.size(); 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /leetcode/problems/c/make-two-arrays-equal-by-reversing-sub-arrays.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | bool canBeEqual(int* target, int targetSize, int* arr, int arrSize) { 6 | int i = 0; 7 | int hash[1001] = {0}; 8 | while (i < arrSize) hash[arr[i++]]++; 9 | i = 0; 10 | while (i < arrSize) hash[target[i++]]--; 11 | for (i = 0; i <= 1000; i++) 12 | if (hash[i] != 0) return false; 13 | return true; 14 | } -------------------------------------------------------------------------------- /leetcode/problems/c/max-consecutive-ones-iii.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | int longestOnes(int* nums, int numsSize, int k) { 6 | int i = 0, j; 7 | for (j = 0; j < numsSize; ++j) { 8 | if (nums[j] == 0) k--; 9 | if (k < 0 && nums[i++] == 0) k++; 10 | } 11 | return j - i; 12 | } -------------------------------------------------------------------------------- /leetcode/problems/c/max-number-of-k-sum-pairs.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | int cmp(const void* a, const void* b) { 6 | return *(int*)a - *(int*)b; 7 | } 8 | 9 | int maxOperations(int* nums, int numsSize, int k) { 10 | int i, j, count = 0; 11 | qsort(nums, numsSize, sizeof(int), cmp); 12 | for (i = 0, j = numsSize - 1; i < j;) { 13 | if (nums[i] + nums[j] == k) count++, i++, j--; 14 | else if (nums[i] + nums[j] < k) i++; 15 | else j--; 16 | } 17 | return count; 18 | } -------------------------------------------------------------------------------- /leetcode/problems/c/maximum-average-subarray-i.c: -------------------------------------------------------------------------------- 1 | #include "limits.h" 2 | 3 | // by @codeAbinash 4 | // Time : O(n) 5 | // Space : O(1) 6 | 7 | inline double max(double a, double b) { 8 | return a > b ? a : b; 9 | } 10 | 11 | double findMaxAverage(int* nums, int numsSize, int k) { 12 | double sum = 0, result = INT_MIN; 13 | for (int i = 0; i < numsSize; i++) { 14 | if (i < k) sum += nums[i]; 15 | else { 16 | result = max(sum, result); 17 | sum += nums[i] - nums[i - k]; 18 | } 19 | } 20 | result = max(sum, result); 21 | return result / k; 22 | } 23 | -------------------------------------------------------------------------------- /leetcode/problems/c/maximum-depth-of-binary-tree.c: -------------------------------------------------------------------------------- 1 | int maxDepth(struct TreeNode* root){ 2 | if(root == NULL) 3 | return 0; 4 | int leftDepth = maxDepth(root->left); 5 | int rigthDepth = maxDepth(root->right); 6 | return (leftDepth > rigthDepth ? leftDepth : rigthDepth) + 1; 7 | } -------------------------------------------------------------------------------- /leetcode/problems/c/maximum-subarray.c: -------------------------------------------------------------------------------- 1 | int maxSubArray(int* nums, int numsSize){ 2 | int max = nums[0]; 3 | int sum = 0; 4 | 5 | for(int i = 0; i < numsSize; i++) { 6 | if(sum < 0) 7 | sum = 0; 8 | sum += nums[i]; 9 | if(sum > max) 10 | max = sum; 11 | } 12 | return max; 13 | } -------------------------------------------------------------------------------- /leetcode/problems/c/merge-sorted-array.c: -------------------------------------------------------------------------------- 1 | void merge(int* nums1, int nums1Size, int m, int* nums2, int nums2Size, int n) { 2 | int i = nums1Size - 1, i1 = m - 1, i2 = n - 1; 3 | while (i1 >=0 && i2 >= 0) { 4 | if(nums1[i1] > nums2[i2]) 5 | nums1[i--] = nums1[i1--]; 6 | else 7 | nums1[i--] = nums2[i2--]; 8 | } 9 | while (i2 >= 0) 10 | nums1[i--] = nums2[i2--]; 11 | } 12 | 13 | int main() { return 0; } -------------------------------------------------------------------------------- /leetcode/problems/c/middle-of-the-linked-list.c: -------------------------------------------------------------------------------- 1 | struct ListNode* middleNode(struct ListNode* head) { 2 | struct ListNode* tmp = head; 3 | int len = 0; 4 | 5 | while (tmp) { 6 | len++; 7 | tmp = tmp->next; 8 | } 9 | 10 | tmp = head; 11 | len = len / 2; 12 | while (len) { 13 | tmp = tmp->next; 14 | len--; 15 | } 16 | return tmp; 17 | } -------------------------------------------------------------------------------- /leetcode/problems/c/min-cost-climbing-stairs.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | inline int min(int a, int b) { return a > b ? b : a; } 6 | 7 | int minCostClimbingStairs(int* cost, int costSize) { 8 | int i = costSize - 3; 9 | while (i >= 0) { 10 | int m = cost[i] + cost[i + 1]; 11 | int n = cost[i] + cost[i + 2]; 12 | cost[i] = m < n ? m : n; 13 | i--; 14 | } 15 | return cost[0] > cost[1] ? cost[1] : cost[0]; 16 | } -------------------------------------------------------------------------------- /leetcode/problems/c/minimum-depth-of-binary-tree.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | inline int min(int a, int b) { return a > b ? b : a; } 6 | 7 | int minDepth(struct TreeNode* root) { 8 | if (root == NULL) return 0; 9 | if (root->left == NULL) return 1 + minDepth(root->right); 10 | if (root->right == NULL) return 1 + minDepth(root->left); 11 | return 1 + min(minDepth(root->left), minDepth(root->right)); 12 | } -------------------------------------------------------------------------------- /leetcode/problems/c/missing-number.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | // The missing number is (seriesSum - arraySum) 6 | int missingNumber(int* nums, int numsSize){ 7 | int sum = 0; 8 | for(int i = 0; i < numsSize; i++) 9 | sum+=nums[i]; 10 | int seriesSum = (numsSize * (numsSize + 1) / 2); 11 | return seriesSum - sum; 12 | } -------------------------------------------------------------------------------- /leetcode/problems/c/monotonic-array.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | bool isMonotonic(int* nums, int numsSize) { 6 | bool isIncreasing = false, isDecreasing = false; 7 | 8 | for (int i = 0; i < numsSize - 1; i++) { 9 | if (nums[i] > nums[i + 1]) 10 | isDecreasing = true; 11 | else if (nums[i] < nums[i + 1]) 12 | isIncreasing = true; 13 | if (isIncreasing & isDecreasing) 14 | return false; 15 | } 16 | return true; 17 | } -------------------------------------------------------------------------------- /leetcode/problems/c/move-zeroes.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | void moveZeroes(int* nums, int numsSize) { 6 | int index = 0; 7 | for (int i = 0; i < numsSize; i++) 8 | if (nums[i]) 9 | nums[index++] = nums[i]; 10 | 11 | while (numsSize > index) 12 | nums[index++] = 0; 13 | } -------------------------------------------------------------------------------- /leetcode/problems/c/n-ary-tree-preorder-traversal.c: -------------------------------------------------------------------------------- 1 | void order(struct Node *root, int *arr, int *index){ 2 | if(root == NULL) 3 | return; 4 | arr[*index] = root->val; 5 | *index = *index + 1; 6 | 7 | for(int i = 0; i < root->numChildren; i++) 8 | order(root->children[i], arr, index); 9 | } 10 | int* preorder(struct Node* root, int* returnSize) { 11 | int index = 0; 12 | int *resArr = (int *)malloc(10000 * sizeof(int)); 13 | order(root, resArr, &index); 14 | *returnSize = index; 15 | return resArr; 16 | } -------------------------------------------------------------------------------- /leetcode/problems/c/nim-game.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complesity O(1) 3 | // Space Complesity O(1) 4 | 5 | bool canWinNim(int n){ 6 | return n % 4; 7 | } -------------------------------------------------------------------------------- /leetcode/problems/c/number-complement.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(log n) 3 | // Space Complexity : O(1) 4 | 5 | int findComplement(int num) { 6 | int tmp = num, n = 0; 7 | while (tmp > 0) { 8 | n = (n << 1) | 1; 9 | tmp >>= 1; 10 | } 11 | return num ^ n; 12 | } -------------------------------------------------------------------------------- /leetcode/problems/c/number-of-1-bits.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | int hammingWeight(uint32_t n) { 6 | int count = 0; 7 | for (int i = 0; i < 32; i++) { 8 | if (n & 1) 9 | count++; 10 | n = n >> 1; 11 | } 12 | return count; 13 | } -------------------------------------------------------------------------------- /leetcode/problems/c/number-of-good-pairs.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | int numIdenticalPairs(int* nums, int numsSize) { 6 | int count = 0, hash[101] = {0}; 7 | for (int i = 0; i < numsSize; i++) 8 | count += hash[nums[i]]++; 9 | return count; 10 | } -------------------------------------------------------------------------------- /leetcode/problems/c/number-of-segments-in-a-string.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | int countSegments(char * s){ 6 | int i = 0, count = 0; 7 | while (s[i]){ 8 | if(s[i] != ' ' && (s[i + 1] == ' ' || s[i+1] == '\0' )) 9 | count++; 10 | i++; 11 | } 12 | return count; 13 | } -------------------------------------------------------------------------------- /leetcode/problems/c/number-of-steps-to-reduce-a-number-to-zero.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | int numberOfSteps(int num) { 4 | int steps = 0; 5 | while (num != 0) { 6 | if (num % 2 == 0) 7 | num /= 2; 8 | else 9 | num--; 10 | steps++; 11 | } 12 | return steps; 13 | } -------------------------------------------------------------------------------- /leetcode/problems/c/palindrome-number.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(log(n)) 3 | // Space : O(1) 4 | 5 | bool isPalindrome(int x) { 6 | if (x < 0) return false; 7 | unsigned int reversed = 0; 8 | int num = x; 9 | while (num) { 10 | reversed = reversed * 10 + num % 10; 11 | num /= 10; 12 | } 13 | return reversed == x; 14 | } -------------------------------------------------------------------------------- /leetcode/problems/c/pascals-triangle-ii.c: -------------------------------------------------------------------------------- 1 | // By @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | int* getRow(int rowIndex, int* returnSize){ 6 | int *row = (int *)malloc((rowIndex + 1) * sizeof(int)); 7 | *returnSize = rowIndex + 1; 8 | row[0] = row[rowIndex] = 1; 9 | 10 | for(int i = 1; i < rowIndex / 2 + 1; i++) 11 | row[rowIndex - i] = row[i] = (long) row[i - 1] * (rowIndex + 1 - i) / i; 12 | 13 | return row; 14 | } -------------------------------------------------------------------------------- /leetcode/problems/c/path-sum.c: -------------------------------------------------------------------------------- 1 | bool hasPathSum(struct TreeNode* root, int sum) { 2 | if (root == NULL) return 0; 3 | if (!root->left && !root->right && sum - root->val == 0) return 1; 4 | return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val); 5 | } -------------------------------------------------------------------------------- /leetcode/problems/c/perfect-number.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(1) 3 | // Space Complexity : O(1) 4 | 5 | 6 | bool checkPerfectNumber(int num) { 7 | return num == 6 || num == 28 || num == 496 || num == 8128 || num == 33550336; 8 | } -------------------------------------------------------------------------------- /leetcode/problems/c/plus-one.c: -------------------------------------------------------------------------------- 1 | int* plusOne(int* digits, int digitsSize, int* returnSize) { 2 | int carry = 1, i = digitsSize; 3 | int* arr = (int*)malloc(sizeof(int) * (digitsSize + 1)); 4 | while (i > 0) { 5 | arr[i] = (digits[i - 1] + carry) % 10; 6 | carry = (digits[i - 1] + carry) / 10; 7 | i--; 8 | } 9 | if (!arr[1]) { 10 | arr[0] = 1; 11 | *returnSize = digitsSize + 1; 12 | return arr; 13 | } 14 | *returnSize = digitsSize; 15 | return arr + 1; 16 | } -------------------------------------------------------------------------------- /leetcode/problems/c/poor-pigs.c: -------------------------------------------------------------------------------- 1 | int poorPigs(int b, int d, int t) { 2 | return ceil(log(b) / log(t / d + 1)); 3 | } -------------------------------------------------------------------------------- /leetcode/problems/c/populating-next-right-pointers-in-each-node.c: -------------------------------------------------------------------------------- 1 | struct Node *connect(struct Node *root) { 2 | struct Node *check = root, *node; 3 | while (check != NULL && check->left !=NULL) { 4 | node = check; 5 | while (1) { 6 | node->left->next = node->right; 7 | if (node->next == NULL) break; 8 | node->right->next = node->next->left; 9 | node = node->next; 10 | } 11 | check = check->left; 12 | } 13 | return root; 14 | } -------------------------------------------------------------------------------- /leetcode/problems/c/power-of-four.c: -------------------------------------------------------------------------------- 1 | // By @codeAbinash 2 | bool isPowerOfFour(int n) { 3 | if (n < 0 || (n && n - 1)) return false; 4 | while (n > 0) { 5 | if (n & 1) return true; 6 | n = n >> 2; 7 | } 8 | return false; 9 | } 10 | 11 | // Better Solution 12 | // by @codeAbinash 13 | // Time complexity O(1) 14 | // Logic : (4^n-1) % 3 == 0, always 15 | bool isPowerOfFour(int num) { 16 | return num > 0 && (num & (num - 1)) == 0 && (num - 1) % 3 == 0; 17 | } -------------------------------------------------------------------------------- /leetcode/problems/c/power-of-two.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | bool isPowerOfTwo(int n) { 6 | return n > 0 && (n & n - 1) == 0; 7 | } -------------------------------------------------------------------------------- /leetcode/problems/c/ransom-note.c: -------------------------------------------------------------------------------- 1 | bool canConstruct(char * ransomNote, char * magazine){ 2 | int counter[26] = {0}; 3 | int i = 0; 4 | 5 | while (magazine[i]){ 6 | counter[magazine[i] - 'a']++; 7 | i++; 8 | } 9 | 10 | i = 0; 11 | while (ransomNote[i]) { 12 | if(counter[ransomNote[i] - 'a'] == 0) 13 | return false; 14 | counter[ransomNote[i] - 'a']--; 15 | i++; 16 | } 17 | return true; 18 | } -------------------------------------------------------------------------------- /leetcode/problems/c/remove-duplicates-from-sorted-array.c: -------------------------------------------------------------------------------- 1 | int removeDuplicates(int* nums, int numsSize){ 2 | int i, j = 0; 3 | for (i = 0; i < numsSize; i++) 4 | if (nums[i] != nums[j]) 5 | nums[++j] = nums[i]; 6 | return j + 1; 7 | } -------------------------------------------------------------------------------- /leetcode/problems/c/remove-duplicates-from-sorted-list.c: -------------------------------------------------------------------------------- 1 | struct ListNode* deleteDuplicates(struct ListNode* head) { 2 | struct ListNode* tmp = head , *last = head; 3 | 4 | if(head == NULL) return NULL; 5 | 6 | while(tmp!=NULL) { 7 | if(tmp->val != last->val) { 8 | last->next = tmp; 9 | last = tmp; 10 | } 11 | tmp = tmp->next; 12 | } 13 | 14 | last->next = tmp; 15 | return head; 16 | } -------------------------------------------------------------------------------- /leetcode/problems/c/remove-element.c: -------------------------------------------------------------------------------- 1 | // by @codeAntu 2 | // timecomplexity: O(n) 3 | // spacecomplexity: O(1) 4 | 5 | 6 | int removeElement(int* nums, int numsSize, int val){ 7 | int j = 0; 8 | for (int i = 0; i < numsSize; i++) 9 | { 10 | if( nums[i] != val){ 11 | nums[j] = nums[i]; 12 | j++; 13 | } 14 | } 15 | return j; 16 | } -------------------------------------------------------------------------------- /leetcode/problems/c/remove-outermost-parentheses.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | char* removeOuterParentheses(char* s) { 6 | char *slow, *fast; 7 | slow = fast = s; 8 | int stack = 0; 9 | 10 | while (*fast) { 11 | *slow = *fast; 12 | if (*fast == '(') { 13 | if (stack != 0) slow++; 14 | stack++; 15 | } else { 16 | stack--; 17 | if (stack != 0) slow++; 18 | } 19 | fast++; 20 | } 21 | *slow = '\0'; 22 | return s; 23 | } -------------------------------------------------------------------------------- /leetcode/problems/c/removing-stars-from-a-string.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | char* removeStars(char* s) { 6 | int i = 0, j = 0; 7 | while (s[i] != '\0') { 8 | if (s[i] == '*') 9 | j--; 10 | else 11 | s[j++] = s[i]; 12 | i++; 13 | } 14 | s[j] = '\0'; 15 | return s; 16 | } -------------------------------------------------------------------------------- /leetcode/problems/c/reverse-bits.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | uint32_t reverseBits(uint32_t n) { 6 | uint32_t res = 0; 7 | for (int i = 0; i < 32; i++) { 8 | res = (res << 1) + (n & 1); 9 | n >>= 1; 10 | } 11 | return res; 12 | } -------------------------------------------------------------------------------- /leetcode/problems/c/reverse-integer.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | #include "limits.h" 6 | 7 | int reverse(int x) { 8 | long reversed = 0; 9 | while (x) { 10 | reversed = reversed * 10 + x % 10; 11 | x /= 10; 12 | } 13 | if (reversed > INT_MAX || reversed < INT_MIN) 14 | return 0; 15 | return x < 0 ? -reversed : reversed; 16 | } -------------------------------------------------------------------------------- /leetcode/problems/c/reverse-linked-list.c: -------------------------------------------------------------------------------- 1 | struct ListNode* reverseList(struct ListNode* head){ 2 | struct ListNode *prev = NULL, *curr, *next; 3 | curr = next = head; 4 | 5 | while (next != NULL) { 6 | next = next->next; 7 | curr->next = prev; 8 | prev = curr; 9 | curr = next; 10 | } 11 | return prev; 12 | } -------------------------------------------------------------------------------- /leetcode/problems/c/reverse-string.c: -------------------------------------------------------------------------------- 1 | void reverseString(char* s, int sSize){ 2 | int start = 0; 3 | char tmp; 4 | sSize--; 5 | while (start < sSize) { 6 | tmp = s[start]; 7 | s[start] = s[sSize]; 8 | s[sSize] = tmp; 9 | start++;sSize--; 10 | } 11 | } -------------------------------------------------------------------------------- /leetcode/problems/c/richest-customer-wealth.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | int maximumWealth(int** accounts, int accountsSize, int* accountsColSize) { 4 | int max = 0, sum; 5 | for (int i = 0; i < accountsSize; i++) { 6 | sum = 0; 7 | for (int j = 0; j < accountsColSize[i]; j++) 8 | sum += accounts[i][j]; 9 | if (sum > max) max = sum; 10 | } 11 | return max; 12 | } -------------------------------------------------------------------------------- /leetcode/problems/c/running-sum-of-1d-array.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | int* runningSum(int* nums, int numsSize, int* returnSize) { 6 | *returnSize = numsSize; 7 | for (int i = 1; i < numsSize; i++) nums[i] += nums[i - 1]; 8 | return nums; 9 | } -------------------------------------------------------------------------------- /leetcode/problems/c/same-tree.c: -------------------------------------------------------------------------------- 1 | bool isSameTree(struct TreeNode* p, struct TreeNode* q){ 2 | if(!p && !q) 3 | return true; 4 | else if(!p || !q) 5 | return false; 6 | 7 | if(p->val == q->val) 8 | return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); 9 | return false; 10 | } -------------------------------------------------------------------------------- /leetcode/problems/c/search-in-a-binary-search-tree.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(log n) 3 | // Space : O(1) 4 | 5 | struct TreeNode { 6 | int val; 7 | struct TreeNode* left; 8 | struct TreeNode* right; 9 | }; 10 | 11 | struct TreeNode* searchBST(struct TreeNode* root, int val) { 12 | if (!root) return root; 13 | if (root->val == val) return root; 14 | if (root->val < val) return searchBST(root->right, val); 15 | return searchBST(root->left, val); 16 | } 17 | -------------------------------------------------------------------------------- /leetcode/problems/c/search-insert-position.c: -------------------------------------------------------------------------------- 1 | int searchInsert(int* nums, int numsSize, int target){ 2 | int low = 0, mid, 3 | high = numsSize - 1; 4 | 5 | while (low <= high){ 6 | mid = (low + high) / 2; 7 | if (nums[mid] == target) 8 | return mid; 9 | if(target > nums[mid]) 10 | low = mid + 1; 11 | else 12 | high = mid - 1; 13 | } 14 | return low; 15 | } -------------------------------------------------------------------------------- /leetcode/problems/c/self-dividing-numbers.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | bool checkSelfDiv(int num) { 4 | int tmp = num; 5 | while (tmp) { 6 | if (tmp % 10 == 0 || num % (tmp % 10) != 0) 7 | return false; 8 | tmp /= 10; 9 | } 10 | return true; 11 | } 12 | int *selfDividingNumbers(int left, int right, int *returnSize) { 13 | int *arr = (int *)malloc(sizeof(int) * (right - left + 1)); 14 | *returnSize = 0; 15 | for (int i = left; i <= right; i++) 16 | if (checkSelfDiv(i)) 17 | arr[(*returnSize)++] = i; 18 | return arr; 19 | } -------------------------------------------------------------------------------- /leetcode/problems/c/shuffle-string.c: -------------------------------------------------------------------------------- 1 | char* restoreString(char* s, int* indices, int indicesSize) { 2 | int i; 3 | char newStr[indicesSize]; 4 | for (i = 0; i < indicesSize; i++) 5 | newStr[indices[i]] = s[i]; 6 | for (i = 0; i < indicesSize; i++) 7 | s[i] = newStr[i]; 8 | return s; 9 | } -------------------------------------------------------------------------------- /leetcode/problems/c/sign-of-the-product-of-an-array.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | 6 | int arraySign(int* nums, int numsSize) { 7 | int minus = 0; 8 | for (int i = 0; i < numsSize; i++) { 9 | if (nums[i] == 0) return 0; 10 | if (nums[i] < 0) minus++; 11 | } 12 | return minus & 1 ? -1 : 1; 13 | } -------------------------------------------------------------------------------- /leetcode/problems/c/single-number-ii.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | int singleNumber(int* nums, int numsSize) { 6 | int ones = 0, tows = 0; 7 | for (int i = 0;i < numsSize; i++) { 8 | ones = (ones ^ nums[i]) & (~tows); 9 | tows = (tows ^ nums[i]) & (~ones); 10 | } 11 | return ones; 12 | } -------------------------------------------------------------------------------- /leetcode/problems/c/single-number.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | int singleNumber(int* nums, int numsSize) { 6 | int singleNumber = nums[0]; 7 | for (int i = 1; i < numsSize; i++) 8 | singleNumber ^= nums[i]; 9 | return singleNumber; 10 | } -------------------------------------------------------------------------------- /leetcode/problems/c/smallest-even-multiple.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(1) 3 | // Space Complexity : O(1) 4 | 5 | int smallestEvenMultiple(int n){ 6 | return n % 2 == 0 ? n : 2 * n; 7 | } -------------------------------------------------------------------------------- /leetcode/problems/c/sqrtx.c: -------------------------------------------------------------------------------- 1 | int mySqrt(int x){ 2 | int low = 0; 3 | int high = x/2 + 1; 4 | long mid,square; 5 | 6 | while (low <= high){ 7 | mid = low + (high - low) / 2; 8 | square = mid * mid; 9 | 10 | if(square == x) 11 | return mid; 12 | else if(square > x) 13 | high = mid - 1; 14 | else 15 | low = mid + 1; 16 | } 17 | return high; 18 | } -------------------------------------------------------------------------------- /leetcode/problems/c/student-attendance-record.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | bool checkRecord(char* s) { 6 | int absentCount = 0; 7 | int lateCount = 0; 8 | for (int i = 0; s[i] != '\0';i++) { 9 | if (lateCount >= 3) return 0; 10 | if (s[i] == 'A') { 11 | absentCount++; 12 | lateCount = 0; 13 | } else if (s[i] == 'L') 14 | lateCount++; 15 | else 16 | lateCount = 0; 17 | } 18 | return absentCount < 2 && lateCount < 3; 19 | } -------------------------------------------------------------------------------- /leetcode/problems/c/sum-of-left-leaves.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | void sumLeft(struct TreeNode *node, int *sum, bool left) { 6 | if (node == NULL) return; 7 | if (node->left == NULL && node->right == NULL && left) { 8 | *sum = *sum + node->val; 9 | return; 10 | } 11 | sumLeft(node->left, sum, 1); 12 | sumLeft(node->right, sum, 0); 13 | } 14 | 15 | int sumOfLeftLeaves(struct TreeNode *root) { 16 | int sum = 0; 17 | sumLeft(root, &sum, 0); 18 | return sum; 19 | } -------------------------------------------------------------------------------- /leetcode/problems/c/super-pow.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #define m 1337 6 | #define phi_m 1140 7 | 8 | int binExp(int a, int b) { 9 | int ans = 1; 10 | while (b) { 11 | if (b & 1) ans = (ans * a) % m; 12 | a = (a * 1LL * a) % m; 13 | b >>= 1; 14 | } 15 | return ans; 16 | } 17 | 18 | int superPow(int a, int* b, int bSize) { 19 | int bmod = 0; 20 | for (int i = 0; i < bSize; i++) 21 | bmod = (bmod * 10 + b[i]) % phi_m; 22 | return binExp(a, bmod); 23 | } -------------------------------------------------------------------------------- /leetcode/problems/c/symmetric-tree.c: -------------------------------------------------------------------------------- 1 | bool traverse(struct TreeNode* leftNode, struct TreeNode* rightNode){ 2 | if(!leftNode && !rightNode) return true; 3 | if(!(leftNode && rightNode)) return false; 4 | if(leftNode->val != rightNode->val) return false; 5 | return traverse(leftNode->left, rightNode->right) && traverse(leftNode->right, rightNode->left); 6 | } 7 | 8 | bool isSymmetric(struct TreeNode* root) { 9 | if (!root) return true; 10 | return traverse(root->left, root->right); 11 | } -------------------------------------------------------------------------------- /leetcode/problems/c/three-divisors.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | bool isThree(int n) { 6 | int count = 0; 7 | for (int i = 1; i <= n; i++) { 8 | if (n % i == 0) count++; 9 | if (count > 3) return false; 10 | } 11 | return count == 3; 12 | } -------------------------------------------------------------------------------- /leetcode/problems/c/to-lower-case.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | char* toLowerCase(char* s) { 6 | int i = 0; 7 | while(s[i]){ 8 | if(s[i] >= 'A' && s[i] <= 'Z') 9 | s[i] = s[i] - 'A' + 'a'; 10 | i++; 11 | } 12 | return s; 13 | } -------------------------------------------------------------------------------- /leetcode/problems/c/two-sum.c: -------------------------------------------------------------------------------- 1 | int* twoSum(int* nums, int numsSize, int target, int* returnSize) { 2 | int diff, i, j; 3 | int *newArr = (int*)malloc(sizeof(int) * 2); 4 | for (i = 0; i < numsSize; i++) { 5 | diff = target - nums[i]; 6 | for (j = i + 1; j < numsSize; j++) { 7 | if (diff == nums[j]) { 8 | newArr[0] = i; 9 | newArr[1] = j; 10 | return newArr; 11 | } 12 | } 13 | } 14 | return NULL; 15 | } -------------------------------------------------------------------------------- /leetcode/problems/c/ugly-number.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinah 2 | // O(n) time complexity 3 | // O(1) space complexity 4 | 5 | bool isUgly(int n){ 6 | int i = 2; 7 | while(i < 6 && n){ 8 | if(n % i == 0) 9 | n /= i; 10 | else 11 | i++; 12 | } 13 | return n == 1; 14 | } -------------------------------------------------------------------------------- /leetcode/problems/c/unique-paths.c: -------------------------------------------------------------------------------- 1 | int uniquePaths(int m, int n) { 2 | int row[n], newRow[n]; 3 | int i, j; 4 | for (i = 0; i < n; i++) row[i] = 1; 5 | 6 | for (i = 0; i < m - 1; i++) { 7 | for (j = 0; j < n; j++) newRow[j] = 1; 8 | for (j = n - 2; j >= 0; j--) 9 | row[j] = newRow[j] = newRow[j + 1] + row[j]; 10 | } 11 | return row[0]; 12 | } -------------------------------------------------------------------------------- /leetcode/problems/c/valid-anagram.c: -------------------------------------------------------------------------------- 1 | bool isAnagram(char* s, char* t) { 2 | int hash[26] = {0}; 3 | int i = 0; 4 | 5 | while (s[i]) hash[s[i++] - 'a']++; 6 | i = 0; 7 | while (t[i]) hash[t[i++] - 'a']--; 8 | 9 | for (i = 0; i < 26; i++) 10 | if (hash[i] != 0) return false; 11 | return true; 12 | } -------------------------------------------------------------------------------- /leetcode/problems/c/valid-perfect-square.c: -------------------------------------------------------------------------------- 1 | int isPerfectSquare(int num){ 2 | int high = num / 2 + 1; 3 | int low = 0; 4 | int mid, square; 5 | 6 | while(low <= high){ 7 | mid = low + (high - low) / 2; 8 | square = mid * mid; 9 | if(square == num) 10 | return 1; 11 | else if(square > num) 12 | high = mid - 1; 13 | else 14 | low = mid + 1; 15 | } 16 | return 0; 17 | } -------------------------------------------------------------------------------- /leetcode/problems/c/validate-binary-search-tree.c: -------------------------------------------------------------------------------- 1 | bool check(struct TreeNode* root, long low, long high) { 2 | if (!root) return true; 3 | 4 | if (!(low < root->val && root->val < high)) return false; 5 | 6 | return check(root->left, low, root->val) && check(root->right, root->val, high); 7 | } 8 | 9 | bool isValidBST(struct TreeNode* root) { 10 | if (!root) return true; 11 | return check(root->left, LONG_MIN, root->val) && check(root->right, root->val, LONG_MAX); 12 | } -------------------------------------------------------------------------------- /leetcode/problems/c/xor-operation-in-an-array.c: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | int xorOperation(int n, int start) { 6 | int i, res = start; 7 | for (i = 1; i < n; i++) 8 | start += 2, res ^= start; 9 | return res; 10 | } -------------------------------------------------------------------------------- /leetcode/problems/cpp/.clang-format: -------------------------------------------------------------------------------- 1 | BasedOnStyle: Google 2 | IndentWidth: 3 3 | ColumnLimit: 100 4 | AccessModifierOffset: -2 5 | AlignTrailingComments: true 6 | AllowShortIfStatementsOnASingleLine: true 7 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/add-two-integers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int sum(int num1, int num2) { 4 | return num1 + num2; 5 | } 6 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/array-partition.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | class Solution { 6 | public: 7 | int arrayPairSum(vector& nums) { 8 | sort(nums.begin(), nums.end()); 9 | int len = nums.size(), sum = 0; 10 | for (int i = 0; i < len; i += 2) sum += nums[i]; 11 | return sum; 12 | } 13 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/best-time-to-buy-and-sell-stock-ii.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "vector" 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | int maxProfit(vector& prices) { 11 | int profit = 0; 12 | for (int i = 1; i < prices.size(); i++) 13 | if (prices[i] > prices[i - 1]) 14 | profit += prices[i] - prices[i - 1]; 15 | return profit; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/best-time-to-buy-and-sell-stock.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "vector" 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | int maxProfit(vector& prices) { 11 | int min = prices[0], profit = 0, max = 0; 12 | 13 | for (int i = 1; i < prices.size(); i++) { 14 | if (prices[i] < min) 15 | min = prices[i]; 16 | profit = prices[i] - min; 17 | if (max < profit) 18 | max = profit; 19 | } 20 | return max; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/bit-manipulation.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | class Solution { 6 | public: 7 | vector decode(vector& encoded, int first) { 8 | for(auto &num : encoded){ 9 | swap(num, first); 10 | first ^= num; 11 | } 12 | encoded.push_back(first); 13 | return encoded; 14 | } 15 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/build-array-from-permutation.1.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(n) 4 | 5 | #include "vector" 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | vector buildArray(vector& nums) { 11 | int len = nums.size(); 12 | vector ans(len); 13 | for (int i = 0;i < len; i++) { 14 | ans[i] = nums[nums[i]]; 15 | } 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/build-array-from-permutation.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | class Solution { 4 | public: 5 | vector buildArray(vector& nums) { 6 | vector result; 7 | for (int i = 0; i < nums.size(); i++) 8 | result.push_back(nums[nums[i]]); 9 | return result; 10 | } 11 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/check-if-all-as-appears-before-all-bs.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | class Solution { 6 | public: 7 | bool checkString(string s) { 8 | int len = s.length(), i; 9 | for (i = 0; i < len; i++) 10 | if (s[i] == 'b') break; 11 | 12 | while (i < len) { 13 | if (s[i] == 'a') return false; 14 | i++; 15 | } 16 | return true; 17 | } 18 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/check-if-n-and-its-double-exist.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(n) 4 | 5 | #include "unordered_set" 6 | #include "vector" 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | bool checkIfExist(vector& arr) { 12 | unordered_set s; 13 | for (auto num : arr) { 14 | if 15 | (s.find(num * 2) != s.end() || 16 | (num % 2 == 0 && s.find(num / 2) != s.end())) 17 | return true; 18 | s.insert(num); 19 | } 20 | return false; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/concatenation-of-array.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(n) 4 | 5 | #include "vector" 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | vector getConcatenation(vector& nums) { 11 | int len = nums.size(); 12 | vector ans(2 * len); 13 | for (int i = 0; i < len; i++) { 14 | ans[i] = nums[i]; 15 | ans[i + len] = nums[i]; 16 | } 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/contains-duplicate-ii.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | class Solution { 4 | public: 5 | bool containsNearbyDuplicate(vector& nums, int k) { 6 | int len = nums.size(); 7 | unordered_set set; 8 | for (int i = 0; i < len; i++) { 9 | if (set.count(nums[i])) return true; 10 | set.insert(nums[i]); 11 | if (set.size() > k) set.erase(nums[i - k]); 12 | } 13 | return false; 14 | } 15 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/contains-duplicate.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | #include "vector" 4 | #include "unordered_set" 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | bool containsDuplicate(vector& nums) { 10 | unordered_set set; 11 | for (auto num : nums) { 12 | if (set.find(num) == set.end()) 13 | set.insert(num); 14 | else return true; 15 | } 16 | return false; 17 | } 18 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/convert-a-number-to-hexadecimal.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | class Solution { 4 | public: 5 | string toHex(int num) { 6 | if (num == 0) return "0"; 7 | const string chars = "0123456789abcdef"; 8 | unsigned int n = num; 9 | string result; 10 | 11 | while (n > 0) { 12 | result = chars[n % 16] + result; 13 | n /= 16; 14 | } 15 | return result; 16 | } 17 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/convert-the-temperature.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | #include "vector" 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | vector convertTemperature(double celsius) { 11 | return { celsius + 273.15, celsius * 1.80 + 32.00 }; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/count-negative-numbers-in-a-sorted-matrix.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | class Solution { 6 | public: 7 | int countNegatives(vector>& grid) { 8 | int row = grid.size(), col = grid[0].size(); 9 | int count = 0; 10 | for (int i = 0; i < row; i++) 11 | for (int j = 0; j < col; j++) 12 | if (grid[i][j] < 0) { 13 | count += col - j; 14 | break; 15 | } 16 | 17 | return count; 18 | } 19 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/count-odd-numbers-in-an-interval-range.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | class Solution { 6 | public: 7 | int countOdds(int low, int high) { 8 | return (high + 1) / 2 - low / 2; 9 | } 10 | }; 11 | 12 | // A bit faster 13 | class Solution { 14 | public: 15 | int countOdds(int low, int high) { 16 | if (!(high & 1) && !(low & 1)) 17 | return (high - low) / 2; 18 | return (high - low) / 2 + 1; 19 | } 20 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/count-operations-to-obtain-zero.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | class Solution { 4 | public: 5 | int countOperations(int num1, int num2) { 6 | unsigned int count = 1; 7 | if (num1 == 0 || num2 == 0) return 0; 8 | while (abs(num1 - num2)) { 9 | if (num1 > num2) 10 | num1 = num1 - num2; 11 | else 12 | num2 = num2 - num1; 13 | count++; 14 | } 15 | return count; 16 | } 17 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/counting-bits.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(n) 4 | 5 | #include "vector" 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | vector countBits(int n) { 11 | vector ans(n + 1); 12 | ans[0] = 0; 13 | for (int i = 0; i <= n; i++) 14 | ans[i] = ans[i / 2] + i % 2; 15 | return ans; 16 | } 17 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/crawler-log-folde.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "string" 6 | #include "vector" 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int minOperations(vector& logs) { 12 | int depth = 0; 13 | for (auto& log : logs) { 14 | if (log == "./") continue; 15 | if (log == "../") { 16 | if (depth) depth--; 17 | } else 18 | depth++; 19 | } 20 | return depth; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/crawler-log-folder.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | class Solution { 6 | public: 7 | int minOperations(vector& logs) { 8 | int len = logs.size(); 9 | int state = 0; 10 | for (auto &log : logs) 11 | if (log== "../") { 12 | if (state != 0) state -= 1; 13 | } else if (log == "./") { 14 | // Same directory 15 | } else 16 | state++; 17 | return state; 18 | } 19 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/decode-xored-array.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "vector" 6 | #include "iostream" 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | vector decode(vector& encoded, int first) { 12 | int size = encoded.size(); 13 | vector result(size + 1); 14 | result[0] = first; 15 | for (int i = 0; i < size; i++) 16 | result[i + 1] = result[i] ^ encoded[i]; 17 | return result; 18 | } 19 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/defanging-an-ip-address.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(n) 4 | 5 | #include "string" 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | string defangIPaddr(string address) { 11 | string ans; 12 | int len = address.size(); 13 | for (int i = 0; i < len; i++) { 14 | if (address[i] == '.') 15 | ans.push_back('['), ans.push_back('.'), ans.push_back(']'); 16 | else 17 | ans.push_back(address[i]); 18 | } 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/delete-node-in-a-linked-list.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | #include "cstddef" 6 | 7 | struct ListNode { 8 | int val; 9 | ListNode* next; 10 | ListNode(int x) : val(x), next(NULL) {} 11 | }; 12 | 13 | class Solution { 14 | public: 15 | void deleteNode(ListNode* node) { 16 | node->val = node->next->val; 17 | node->next = node->next->next; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/divisible-and-non-divisible-sums-difference.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | class Solution { 6 | public: 7 | int differenceOfSums(int n, int m) { 8 | int sum1 = 0, sum2 = 0; 9 | for (int i = 1; i <= n; i++) { 10 | if (i % m == 0) 11 | sum1 += i; 12 | else 13 | sum2 += i; 14 | } 15 | return sum2 - sum1; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/excel-sheet-column-number.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | class Solution { 4 | public: 5 | int titleToNumber(string columnTitle) { 6 | int len = columnTitle.length(), result = 0; 7 | for (int i = 0; i < len; i++) 8 | result = result * 26 + (columnTitle[i] - 'A' + 1); 9 | return result; 10 | } 11 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/final-prices-with-a-special-discount-in-a-shop.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(n) 4 | 5 | class Solution { 6 | public: 7 | vector finalPrices(vector& prices) { 8 | stack s; 9 | int size = prices.size(); 10 | for (int i = size - 1; i >= 0; i--) { 11 | while (s.size() && prices[i] < s.top()) s.pop(); 12 | int tmp = prices[i]; 13 | if (s.size()) prices[i] -= s.top(); 14 | s.push(tmp); 15 | } 16 | return prices; 17 | } 18 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/final-value-of-variable-after-performing-operations.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "vector" 6 | #include "string" 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int finalValueAfterOperations(vector& operations) { 12 | int result = 0; 13 | for (auto& op : operations) { 14 | result += (op[1] == '+') ? 1 : -1; 15 | } 16 | return result; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/find-peak-element.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(log n) 3 | // Space : O(1) 4 | 5 | #include "iostream" 6 | #include "vector" 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int findPeakElement(vector& nums) { 12 | int size = nums.size(), low = 0, high = size - 1; 13 | while (low < high) { 14 | int m = (low + high) >> 1; 15 | if (nums[m + 1] > nums[m]) 16 | low = m + 1; 17 | else high = m; 18 | } 19 | return low; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/find-the-difference.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "iostream" 6 | #include "vector" 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | char findTheDifference(string s, string t) { 12 | int len = s.length(); 13 | int x = 0, index; 14 | for (index = 0; index < len; index++) { 15 | x ^= s[index]; 16 | x ^= t[index]; 17 | } 18 | x ^= t[index]; 19 | 20 | return x; 21 | } 22 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/find-the-highest-altitude.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "vector" 6 | #include "algorithm" 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int largestAltitude(vector& gain) { 12 | int size = gain.size(); 13 | int currentAlt = 0, maxAlt = 0; 14 | 15 | for (int i = 0; i < size; i++) { 16 | currentAlt += gain[i]; 17 | maxAlt = max(currentAlt, maxAlt); 18 | } 19 | 20 | return maxAlt; 21 | } 22 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/find-the-maximum-achievable-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int theMaximumAchievableX(int num, int t) { 4 | return num + t * 2; 5 | } 6 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/find-the-original-array-of-prefix-xor.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "vector" 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | vector findArray(vector& pref) { 11 | int n = pref.size(); 12 | vector ans(n); 13 | ans[0] = pref[0]; 14 | for (int i = 1; i < n; i++) 15 | ans[i] = pref[i] ^ pref[i - 1]; 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/first-unique-character-in-a-string.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(n) 4 | 5 | #include "string" 6 | #include "unordered_map" 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int firstUniqChar(string s) { 12 | unordered_map m; 13 | for (auto c : s) 14 | m[c]++; 15 | for (int i = 0; i < s.size(); i++) 16 | if (m[s[i]] == 1) 17 | return i; 18 | return -1; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/flipping-an-image.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | class Solution { 4 | public: 5 | vector> flipAndInvertImage(vector>& image) { 6 | for (auto& im : image) { 7 | reverse(im.begin(), im.end()); 8 | for(auto &pixel : im){ 9 | pixel = !pixel; 10 | } 11 | } 12 | return image; 13 | } 14 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/greatest-common-divisor-of-strings.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "iostream" 6 | #include "numeric" 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | string gcdOfStrings(string str1, string str2) { 12 | int l1 = str1.length(), l2 = str2.length(); 13 | if (str1 + str2 == str2 + str1) 14 | return str1.substr(0, gcd(l1, l2)); 15 | return ""; 16 | } 17 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/guess-number-higher-or-lower.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | int guess(int); 6 | 7 | class Solution { 8 | public: 9 | int guessNumber(int n) { 10 | int start = 1, end = n; 11 | while (start < end) { 12 | int mid = start + (end - start) / 2; 13 | int result = guess(mid); 14 | 15 | if (result == -1) 16 | end = mid - 1; 17 | else if (result == 1) 18 | start = mid + 1; 19 | else return mid; 20 | } 21 | return start; 22 | } 23 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/hamming-distance.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(1) 3 | // Space Complexity : O(1) 4 | 5 | class Solution { 6 | public: 7 | int hammingDistance(int x, int y) { 8 | bitset<32> xbit(x), ybit(y); 9 | int result = 0; 10 | for (int i = 0; i < 32; i++) 11 | result += xbit[i] != ybit[i]; 12 | return result; 13 | } 14 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/height-checker.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(n) 4 | 5 | #include "vector" 6 | #include "algorithm" 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int heightChecker(vector& heights) { 12 | vectorarr = heights; 13 | int ans = 0; 14 | sort(arr.begin(), arr.end()); 15 | for (int i = 0;i < heights.size();i++) 16 | if (arr[i] != heights[i]) 17 | ans++; 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/hello-world.cpp: -------------------------------------------------------------------------------- 1 | // A simple hello world program in C++ 2 | 3 | #include "iostream" 4 | 5 | int main() { 6 | std::cout << "Hello World"; 7 | return 0; 8 | } 9 | 10 | 11 | // Search for Leetcode Solutions 12 | // Paste the link or the name of the problem 13 | // 👆🏻 in the Search Bar 14 | // Hit enter or click the search button 15 | // The solution will be displayed in this section -------------------------------------------------------------------------------- /leetcode/problems/cpp/house-robber.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "vector" 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | int rob(vector& nums) { 11 | int rob1 = 0, rob2 = 0, tmp = 0; 12 | for (int i = 0; i < nums.size(); i++) { 13 | tmp = max(rob1 + nums[i], rob2); 14 | rob1 = rob2; 15 | rob2 = tmp; 16 | } 17 | return rob2; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/how-many-numbers-are-smaller-than-the-current-number.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | class Solution { 4 | public: 5 | vector smallerNumbersThanCurrent(vector& nums) { 6 | unordered_map mp; 7 | vector v = nums; 8 | sort(v.begin(), v.end()); 9 | int n = nums.size(), i; 10 | for (i = n - 1; i >= 0; i--) mp[v[i]] = i; 11 | for (i = 0; i < n; i++) nums[i] = mp[nums[i]]; 12 | return nums; 13 | } 14 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/increasing-triplet-subsequence.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "vector" 6 | #include "climits" 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | bool increasingTriplet(vector& nums) { 12 | int n = nums.size(); 13 | if (n < 3) return false; 14 | int min1 = INT_MAX, min2 = INT_MAX; 15 | for (auto num : nums) { 16 | if (num <= min1) min1 = num; 17 | else if (num <= min2) min2 = num; 18 | else return true; 19 | } 20 | return false; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/is-subsequence.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "string" 6 | #include "vector" 7 | using namespace std; 8 | 9 | 10 | class Solution { 11 | public: 12 | bool isSubsequence(string s, string t) { 13 | int i = 0, j = 0; 14 | int s_len = s.length(), t_len = t.length(); 15 | 16 | while (i < s_len && j < t_len) 17 | (s[i] == t[j++]) && i++; 18 | 19 | return i == s_len; 20 | } 21 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/jewels-and-stones.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(n) 4 | 5 | #include "string" 6 | #include "unordered_set" 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int numJewelsInStones(string jewels, string stones) { 12 | int count = 0; 13 | unordered_set s; 14 | for (auto ch : jewels) 15 | s.insert(ch); 16 | for (auto ch : stones) 17 | if (s.find(ch) != s.end()) 18 | count++; 19 | return count; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/kth-smallest-element-in-a-sorted-matrix.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(nlogk) 3 | // Space : O(k) 4 | 5 | #include "queue" 6 | #include "vector" 7 | 8 | using namespace std; 9 | 10 | class Solution { 11 | public: 12 | int kthSmallest(vector>& matrix, int k) { 13 | priority_queue pq; 14 | for (auto row : matrix) { 15 | for (auto num : row) { 16 | pq.push(num); 17 | if (pq.size() > k) pq.pop(); 18 | } 19 | } 20 | return pq.top(); 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/largest-perimeter-triangle.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n * lon(n)) 3 | // Space : O(1) 4 | 5 | #include "algorithm" 6 | #include "vector" 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int largestPerimeter(vector& nums) { 12 | size_t len = nums.size(); 13 | sort(nums.begin(), nums.end()); 14 | 15 | for (int i = len - 1; i > 1; i--) 16 | if (nums[i] < nums[i - 1] + nums[i - 2]) 17 | return nums[i] + nums[i - 1] + nums[i - 2]; 18 | 19 | return 0; 20 | } 21 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/lemonade-change.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "vector" 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | bool lemonadeChange(vector& bills) { 11 | int ten = 0, five = 0; 12 | for (auto bill : bills) { 13 | if (bill == 5) five++; 14 | else if (bill == 10) five--, ten++; 15 | else if (ten > 0) ten--, five --; 16 | else five -= 3; 17 | if (five < 0) return false; 18 | } 19 | return true; 20 | } 21 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/length-of-last-word.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAntu 2 | // time complexity: O(n) 3 | // space complexity: O(1) 4 | 5 | class Solution { 6 | public: 7 | int lengthOfLastWord(string s) { 8 | int max = 0; 9 | int count = 0; 10 | for (int i = s.length() - 1; i >= 0; i--){ 11 | if (s[i] == ' ' && count == 0){ 12 | continue; 13 | } 14 | if (s[i] == ' ') 15 | return count; 16 | count++; 17 | } 18 | return count; 19 | } 20 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/longest-subarray-of-1s-after-deleting-one-element.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "vector" 6 | #include "algorithm" 7 | using namespace std; 8 | 9 | 10 | class Solution { 11 | public: 12 | int longestSubarray(vector& nums) { 13 | int left = 0, i, right = 1; 14 | int size = nums.size(); 15 | 16 | for (i = 0; i < size; i++) { 17 | if (nums[i] == 0) right--; 18 | if (right < 0 && nums[left++] == 0) right++; 19 | } 20 | 21 | return i - left - 1; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/matrix-diagonal-sum.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "vector" 6 | 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int diagonalSum(vector>& mat) { 12 | int n = mat.size(), sum = 0; 13 | int mid = n >> 1; 14 | 15 | for (int i = 0; i < n; i++) { 16 | sum += mat[i][i]; 17 | sum += mat[n - i - 1][i]; 18 | } 19 | 20 | if (n & 1) sum -= mat[mid][mid]; 21 | return sum; 22 | } 23 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/max-consecutive-ones-iii.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "vector" 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | int longestOnes(vector& nums, int k) { 11 | int i = 0, j; 12 | for (j = 0; j < nums.size(); ++j) { 13 | if (nums[j] == 0) k--; 14 | if (k < 0 && nums[i++] == 0) k++; 15 | } 16 | return j - i; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/max-consecutive-ones.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "vector" 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | int findMaxConsecutiveOnes(vector& nums) { 11 | int count = 0, max = 0; 12 | for (auto num : nums) { 13 | if (num == 1) { count++; continue; } 14 | if (count > max) max = count; 15 | count = 0; 16 | } 17 | return count > max ? count : max; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/maximum-69-number.cpp: -------------------------------------------------------------------------------- 1 | #include "algorithm" 2 | #include "iostream" 3 | #include "vector" 4 | using namespace std; 5 | 6 | int main() { 7 | Solution s; 8 | return 0; 9 | } 10 | class Solution { 11 | public: 12 | int maximum69Number(int num) { 13 | string number = to_string(num); 14 | for (int i = 0; i < number.length(); i++) 15 | 16 | if (number[i] == '6') { 17 | number[i] = 9; 18 | break; 19 | } 20 | return stoi(number); 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/maximum-nesting-depth-of-the-parentheses.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(n) 4 | 5 | #include "string" 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | int maxDepth(string s) { 11 | int max = 0, count = 0; 12 | int len = s.length(); 13 | for (int i = 0; i < len; i++) { 14 | if (s[i] == '(') { 15 | count++; 16 | if (count > max) max = count; 17 | } else if (s[i] == ')') 18 | count--; 19 | } 20 | return max; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/maximum-number-of-words-found-in-sentences.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | class Solution { 4 | public: 5 | int mostWordsFound(vector& sentences) { 6 | int maxWordCount = 0; 7 | for (auto& s : sentences) { 8 | int wordCount = count(s.begin(), s.end(), ' ') + 1; 9 | if(wordCount > maxWordCount) 10 | maxWordCount = wordCount; 11 | } 12 | return maxWordCount; 13 | } 14 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/maximum-subarray.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "iostream" 6 | #include "vector" 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int maxSubArray(vector& nums) { 12 | int max = nums[0], sum = 0; 13 | for (int i = 0; i < nums.size(); i++) { 14 | sum += nums[i]; 15 | if (max < sum) max = sum; 16 | if (sum < 0) sum = 0; 17 | } 18 | return max; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/merge-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | #include "vector" 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | void merge(vector& nums1, int m, vector& nums2, int n) { 7 | int i = m - 1, j = n - 1, k = m + n - 1; 8 | while (i >= 0 && j >= 0) { 9 | if (nums1[i] > nums2[j]) nums1[k--] = nums1[i--]; 10 | else nums1[k--] = nums2[j--]; 11 | } 12 | while (j >= 0) nums1[k--] = nums2[j--]; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/merge-strings-alternately.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "iostream" 6 | #include "vector" 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | string mergeAlternately(string word1, string word2) { 12 | string ans = ""; 13 | int i = 0, l1 = word1.length(), l2 = word2.length(); 14 | while (i < l1 || i < l2) { 15 | if (i < l1) ans += word1[i]; 16 | if (i < l2) ans += word2[i]; 17 | i++; 18 | } 19 | return ans; 20 | } 21 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/min-cost-climbing-stairs.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "vector" 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | int minCostClimbingStairs(vector& cost) { 11 | int i = cost.size() - 3; 12 | while (i >= 0) { 13 | int m = cost[i] + cost[i + 1]; 14 | int n = cost[i] + cost[i + 2]; 15 | cost[i] = m < n ? m : n; 16 | i--; 17 | } 18 | return cost[0] > cost[1] ? cost[1] : cost[0]; 19 | } 20 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/minimum-changes-to-make-alternating-binary-string.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "string" 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | int minOperations(string s) { 11 | int n = s.size(); 12 | int cnt1 = 0; 13 | for (int i = 0; i < n; i++) 14 | if ((s[i] - '0') ^ (i & 1)) cnt1++; 15 | return min(cnt1, n - cnt1); 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/minimum-time-to-type-word-using-special-typewriter.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | class Solution { 6 | public: 7 | int minTimeToType(string word) { 8 | char currWord = 'a'; 9 | int diff = 0, time = 0; 10 | for (auto &ch : word) { 11 | diff = abs(currWord - ch); 12 | time += min(diff, 26 - diff) + 1; // +1 for writing 13 | currWord = ch; 14 | } 15 | return time; 16 | } 17 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/missing-number.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "vector" 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | int missingNumber(vector& nums) { 11 | int xor1 = 0, xor2 = 0; 12 | for (int i = 0; i < nums.size(); i++) { 13 | xor1 ^= nums[i]; 14 | xor2 ^= i; 15 | } 16 | xor2 ^= nums.size(); 17 | return xor1 ^ xor2; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/move-zeroes.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "iostream" 6 | #include "vector" 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | void moveZeroes(vector& nums) { 12 | int index = 0; 13 | int size = nums.size(); 14 | 15 | for (auto num : nums) 16 | if (num) 17 | nums[index++] = num; 18 | 19 | while (size > index) 20 | nums[index++] = 0; 21 | } 22 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/n-th-tribonacci-number.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | using namespace std; 6 | class Solution { 7 | public: 8 | int tribonacci(int n) { 9 | if (n == 0) return 0; 10 | int t0 = 0, t1 = 1, t2 = 1; 11 | for (int i = 2; i < n;i++) { 12 | int tmp = t2; 13 | t2 = t0 + t1 + t2; 14 | t0 = t1; 15 | t1 = tmp; 16 | } 17 | return t2; 18 | } 19 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/number-of-1-bits.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | #include "iostream" 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | int hammingWeight(uint32_t n) { 11 | uint32_t count = 0; 12 | for (int i = 0; i < 32; i++) { 13 | if (n & 1) 14 | count++; 15 | n >>= 1; 16 | } 17 | return count; 18 | } 19 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/number-of-even-and-odd-bits..cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | vector evenOddBit(int n) { 11 | vector ans(2, 0); 12 | int i = 0; 13 | while (n) { 14 | ans[i] += n & 1; 15 | n >>= 1; 16 | i ^= 1; 17 | } 18 | return ans; 19 | } 20 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/number-of-recent-calls.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(n) 4 | 5 | #include "queue" 6 | using namespace std; 7 | 8 | class RecentCounter { 9 | private: queue q; 10 | public: 11 | RecentCounter() {} 12 | 13 | int ping(int t) { 14 | q.push(t); 15 | while (q.front() < t - 3000) 16 | q.pop(); 17 | return q.size(); 18 | } 19 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/number-of-steps-to-reduce-a-number-to-zero.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | class Solution { 6 | public: 7 | int numberOfSteps(int num) { 8 | int count = 0; 9 | while (num) { 10 | if (num & 1) 11 | num--; 12 | else 13 | num = num >> 1; 14 | count++; 15 | } 16 | return count; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/number-of-students-doing-homework-at-a-given-time.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | class Solution { 4 | public: 5 | int findContentChildren(vector& g, vector& s) { 6 | int count = 0, calc = -1; 7 | sort(s.begin(), s.end()); 8 | sort(g.begin(), g.end()); 9 | 10 | for (int i = 0; i < g.size(); i++) 11 | while (++calc < s.size()) 12 | if(s[calc] >= g[i]){ 13 | count ++; 14 | break; 15 | } 16 | return count; 17 | } 18 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/palindrome-number.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(log(n)) 3 | // Space : O(1) 4 | 5 | class Solution { 6 | public: 7 | bool isPalindrome(int x) { 8 | if (x < 0) return false; 9 | long int reversed = 0; 10 | int num = x; 11 | while (x) { 12 | reversed = reversed * 10 + x % 10; 13 | x /= 10; 14 | } 15 | return num == reversed; 16 | } 17 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/partitioning-into-minimum-number-of-deci-binary-numbers.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "string" 6 | #include "algorithm" 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int minPartitions(string n) { 12 | int ans = 0; 13 | for (auto ch : n) 14 | ans = max(ans, ch - '0'); 15 | return ans; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/percentage-of-letter-in-string.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | class Solution { 6 | public: 7 | int percentageLetter(string s, char letter) { 8 | int len = s.length(); 9 | float count = 0; 10 | for (int i = 0; i < len; i++) 11 | if (s[i] == letter) count++; 12 | return (double(count) / len ) * 100; 13 | } 14 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/perfect-number.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(1) 3 | // Space Complexity : O(1) 4 | 5 | class Solution { 6 | public: 7 | bool checkPerfectNumber(int num) { 8 | return num == 6 || num == 28 || num == 496 || num == 8128 || 9 | num == 33550336; 10 | } 11 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/plus-one.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "vector" 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | vector plusOne(vector& digits) { 11 | int len = digits.size(); 12 | for (int i = len - 1; i >= 0; i--) { 13 | if (digits[i] != 9) { 14 | digits[i]++; 15 | return digits; 16 | } 17 | digits[i] = 0; 18 | } 19 | digits[0] = 1; 20 | digits.push_back(0); 21 | return digits; 22 | } 23 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/power-of-two.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | class Solution { 6 | public: 7 | bool isPowerOfTwo(int n) { 8 | return n > 0 && (n & n - 1) == 0; 9 | } 10 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/range-sum-query-immutable.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | using namespace std; 4 | class NumArray { 5 | vector nums; 6 | public: 7 | NumArray(vector& nums) { this->nums = nums; } 8 | int sumRange(int left, int right) { 9 | return accumulate(this->nums.begin() + left, this->nums.begin() + right + 1, 0); 10 | } 11 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/ransom-note.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "string" 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | bool canConstruct(string ransomNote, string magazine) { 11 | int map[127] = { false }; 12 | for (auto ch : magazine) 13 | map[ch]++; 14 | for (auto ch : ransomNote) { 15 | map[ch]--; 16 | if (map[ch] < 0) 17 | return false; 18 | } 19 | return true; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/reduction-operations-to-make-the-array-elements-equal.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | class Solution { 4 | public: 5 | int reductionOperations(vector& nums) { 6 | sort(nums.begin(), nums.end()); 7 | int count = 0, c = 0, len = nums.size(); 8 | for (int i = 1; i < len; i++) { 9 | if (nums[i] != nums[i - 1]) c++; 10 | count += c; 11 | } 12 | return count; 13 | } 14 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/remove-all-adjacent-duplicates-in-string.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(n) 4 | 5 | #include "string" 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | string removeDuplicates(string s) { 11 | string res; 12 | for (char c : s) { 13 | if (res.empty() || res.back() != c) 14 | res.push_back(c); 15 | else 16 | res.pop_back(); 17 | } 18 | return res; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/remove-duplicates-from-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "vector" 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | int removeDuplicates(vector& nums) { 11 | int i, j = 0; 12 | for (i = 0; i < nums.size(); i++) 13 | if (nums[i] != nums[j]) 14 | nums[++j] = nums[i]; 15 | return j + 1; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/remove-duplicates-from-sorted-lis.cpp: -------------------------------------------------------------------------------- 1 | 2 | // by @CodeAntu 3 | // time complexity o(n) 4 | // space complexity o(1) 5 | 6 | 7 | 8 | class Solution { 9 | public: 10 | ListNode* deleteDuplicates(ListNode* head) { 11 | ListNode * temp = head; 12 | 13 | while (temp && temp->next) 14 | { 15 | if (temp->val == temp-> next -> val) 16 | { 17 | temp -> next = temp-> next -> next; 18 | continue; 19 | } 20 | temp = temp -> next; 21 | } 22 | return head; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/remove-element.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "vector" 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | int removeElement(vector& nums, int val) { 11 | int left = 0; 12 | int right = nums.size() - 1; 13 | while (left <= right) { 14 | if (nums[left] == val) { 15 | nums[left] = nums[right]; 16 | right--; 17 | } else { 18 | left++; 19 | } 20 | } 21 | return left; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/repeated-substring-pattern.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | #include "vector" 4 | #include "string" 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | bool repeatedSubstringPattern(string s) { 10 | int n = s.length(); 11 | for (int i = n / 2; i >= 1; i--) 12 | if (n % i == 0) 13 | if (s.substr(0, n - i) == s.substr(i)) 14 | return true; 15 | return false; 16 | } 17 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/reshape-the-matrix.1.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> matrixReshape(vector>& mat, int r, int c) { 4 | int row = size(mat), col = size(mat[0]); 5 | int cells = row * col; 6 | 7 | if (r * c != cells || r == row) return mat; 8 | vector> answer(r, vector(c)); 9 | for (int i = 0; i < cells; i++) 10 | answer[i / c][i % c] = mat[i / col][i % col]; 11 | return answer; 12 | } 13 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/reverse-bits.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | #include "iostream" 6 | #include "vector" 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | uint32_t reverseBits(uint32_t n) { 12 | uint32_t res = 0; 13 | for (int i = 0; i < 32; ++i) { 14 | res = (res << 1) + (n & 1); 15 | n >>= 1; 16 | } 17 | return res; 18 | } 19 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/reverse-integer.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | #include "climits" 6 | #include "bits/std_abs.h" 7 | 8 | using namespace std; 9 | class Solution { 10 | public: 11 | int reverse(int x) { 12 | bool isNegative = x < 0; 13 | long int reversed = 0; 14 | x = abs(x); 15 | while (x) { 16 | reversed = reversed * 10 + x % 10; 17 | x /= 10; 18 | } 19 | if (reversed > INT_MAX || reversed < INT_MIN) 20 | return 0; 21 | return isNegative ? -reversed : reversed; 22 | } 23 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/reverse-string.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "algorithm" 6 | #include "vector" 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | void reverseString(vector& s) { 12 | reverse(s.begin(), s.end()); 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/robot-return-to-origin.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "iostream" 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | bool judgeCircle(string moves) { 11 | int x = 0, y = 0; 12 | for (auto mv : moves) { 13 | switch (mv) { 14 | case 'R': x++;break; 15 | case 'L': x--;break; 16 | case 'U': y++;break; 17 | case 'D': y--;break; 18 | } 19 | } 20 | return x == 0 && y == 0; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/root-equals-sum-of-children.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | struct TreeNode { 6 | int val; 7 | TreeNode* left; 8 | TreeNode* right; 9 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 10 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 11 | TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {} 12 | }; 13 | 14 | class Solution { 15 | public: 16 | bool checkTree(TreeNode* root) { 17 | return root->val == root->left->val + root->right->val; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/rotate-array.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "algorithm" 6 | #include "vector" 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | void rotate(vector& nums, int k) { 12 | int n = nums.size(); 13 | k %= n; 14 | reverse(nums.begin(), nums.end()); 15 | reverse(nums.begin(), nums.begin() + k); 16 | reverse(nums.begin() + k, nums.end()); 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/running-sum-of-1d-array.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "vector" 6 | using namespace std; 7 | 8 | 9 | class Solution { 10 | public: 11 | vector runningSum(vector& nums) { 12 | int len = nums.size(); 13 | for (int i = 1; i < len;i++) 14 | nums[i] += nums[i - 1]; 15 | return nums; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/shuffle-the-array.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(n) 4 | 5 | 6 | #include "iostream" 7 | #include "vector" 8 | using namespace std; 9 | 10 | 11 | class Solution { 12 | public: 13 | vector shuffle(vector& nums, int n) { 14 | vector ans(n * 2); 15 | for (int i = 0, j = 0; i < n; i++, j += 2) { 16 | ans[j] = nums[i]; 17 | ans[j + 1] = nums[i + n]; 18 | } 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/sign-of-the-product-of-an-array.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | 6 | #include "vector" 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int arraySign(vector& nums) { 12 | int minus = 0, numsSize = nums.size(); 13 | for (int i = 0; i < numsSize; i++) { 14 | if (nums[i] == 0) return 0; 15 | if (nums[i] < 0) minus++; 16 | } 17 | return minus & 1 ? -1 : 1; 18 | } 19 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/single-number-ii.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "vector" 6 | using namespace std; 7 | class Solution { 8 | public: 9 | int singleNumber(vector& nums) { 10 | int ones = 0, tows = 0; 11 | for (auto num : nums) { 12 | ones = (ones ^ num) & (~tows); 13 | tows = (tows ^ num) & (~ones); 14 | } 15 | return ones; 16 | } 17 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/single-number.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "vector" 6 | #include "iostream" 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int singleNumber(vector& nums) { 12 | ios_base::sync_with_stdio(false); 13 | cin.tie(NULL); 14 | int singleNumber = 0; 15 | for (auto num : nums) 16 | singleNumber ^= num; 17 | return singleNumber; 18 | } 19 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/smallest-index-with-equal-value.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | class Solution { 6 | public: 7 | int smallestEqual(vector& nums) { 8 | int i, len = nums.size(); 9 | for (i = 0; i < len; i++) 10 | if (i % 10 == nums[i]) return i; 11 | return -1; 12 | } 13 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/sort-array-by-parity.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "vector" 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | vector sortArrayByParity(vector& nums) { 11 | int i = 0, j = nums.size() - 1; 12 | while (i < j) { 13 | if (nums[i] % 2 > nums[j] % 2) 14 | swap(nums[i], nums[j]); 15 | if (nums[i] % 2 == 0) 16 | i++; 17 | if (nums[j] % 2 == 1) 18 | j--; 19 | } 20 | return nums; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/sqrtx.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(log n) 3 | // Space : O(1) 4 | 5 | #include "climits" 6 | 7 | class Solution { 8 | public: 9 | int mySqrt(int x) { 10 | long root = x; 11 | while (root * root > x) 12 | root = (root + x / root) / 2; 13 | return root; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/subsets.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "vector" 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | vector> subsets(vector& nums) { 11 | int size = nums.size(); 12 | int mask = 1 << size; 13 | vector> subsets(mask); 14 | for (int i = 1; i < mask; i++) 15 | for (int j = 0;j < size; j++) 16 | if (i & (1 << j)) 17 | subsets[i].push_back(nums[j]); 18 | return subsets; 19 | } 20 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/sum-of-unique-elements.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | class Solution { 6 | public: 7 | int sumOfUnique(vector& nums) { 8 | int hash[101] = {0}, len = nums.size(); 9 | for (int i = 0; i < len; i++) hash[nums[i]]++; 10 | 11 | int sum = 0; 12 | for (int i = 0; i < len; i++) 13 | if (hash[nums[i]] == 1) sum += nums[i]; 14 | return sum; 15 | } 16 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/truncate-sentence.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | class Solution { 6 | public: 7 | string truncateSentence(string s, int k) { 8 | int count = 0, n = s.size(); 9 | for (int i = 0; i < n; i++) { 10 | if (s[i] == ' ') count++; 11 | if (count == k) { 12 | s.erase(s.begin() + i, s.end()); 13 | return s; 14 | } 15 | } 16 | return s; 17 | } 18 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/two-sum-ii-input-array-is-sorted.cpp: -------------------------------------------------------------------------------- 1 | #include "vector" 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | vector twoSum(vector& numbers, int target) { 7 | int left = 0, right = numbers.size() - 1; 8 | while (left < right) { 9 | int sum = numbers[left] + numbers[right]; 10 | if (sum == target) { 11 | return {left + 1, right + 1}; 12 | } else if (sum < target) { 13 | left++; 14 | } else { 15 | right--; 16 | } 17 | } 18 | return {}; 19 | } 20 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/unique-binary-search-trees.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(n) 4 | 5 | #include "iostream" 6 | #include "vector" 7 | using namespace std; 8 | 9 | 10 | class Solution { 11 | public: 12 | int numTrees(int n) { 13 | vectornumbers(n + 1, 0); 14 | numbers[1] = numbers[0] = 1; 15 | for (int i = 2;i <= n;i++) 16 | for (int j = 0;j < i;j++) 17 | numbers[i] += numbers[j] * numbers[i - j - 1]; 18 | return numbers[n]; 19 | } 20 | }; -------------------------------------------------------------------------------- /leetcode/problems/cpp/valid-mountain-array.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | #include "vector" 6 | using namespace std; 7 | 8 | class Solution { 9 | public: 10 | bool validMountainArray(vector& arr) { 11 | int i = 1; 12 | int n = arr.size(); 13 | while (i < n && arr[i] > arr[i - 1]) i++; 14 | if (i == 1 || i == n) return false; 15 | while (i < n && arr[i] < arr[i - 1]) i++; 16 | return i == n; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /leetcode/problems/cpp/xor-operation-in-an-array.cpp: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | class Solution { 6 | public: 7 | int xorOperation(int n, int start) { 8 | int i, res = start; 9 | for (i = 1; i < n; i++) 10 | start += 2, res ^= start; 11 | return res; 12 | } 13 | }; -------------------------------------------------------------------------------- /leetcode/problems/java/TreeNode.java: -------------------------------------------------------------------------------- 1 | public class TreeNode { 2 | int val; 3 | TreeNode left; 4 | TreeNode right; 5 | 6 | TreeNode() { 7 | } 8 | 9 | TreeNode(int val) { 10 | this.val = val; 11 | } 12 | 13 | TreeNode(int val, TreeNode left, TreeNode right) { 14 | this.val = val; 15 | this.left = left; 16 | this.right = right; 17 | } 18 | } -------------------------------------------------------------------------------- /leetcode/problems/java/append-characters-to-string-to-make-subsequence.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int appendCharacters(String s, String t) { 3 | int si = 0, ti = 0; 4 | int sLen = s.length(), tLen = t.length(); 5 | 6 | while (si < sLen && ti < tLen) { 7 | if (s.charAt(si) == t.charAt(ti)) 8 | ti++; 9 | si++; 10 | } 11 | return tLen - ti; 12 | } 13 | } -------------------------------------------------------------------------------- /leetcode/problems/java/average-waiting-time.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public double averageWaitingTime(int[][] customers) { 3 | int n = customers.length; 4 | long time = 0; 5 | long wait = 0; 6 | for (int i = 0; i < n; i++) { 7 | time = Math.max(time, (long) customers[i][0]) + customers[i][1]; 8 | wait += time - customers[i][0]; 9 | } 10 | return (double) wait / n; 11 | } 12 | } -------------------------------------------------------------------------------- /leetcode/problems/java/balanced-binary-tree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isBalanced(TreeNode root) { 3 | return dfs(root) != -1; 4 | } 5 | 6 | int dfs(TreeNode root) { 7 | if (root == null) 8 | return 0; 9 | int left = dfs(root.left); 10 | if (left == -1) 11 | return -1; 12 | int right = dfs(root.right); 13 | if (right == -1) 14 | return -1; 15 | if (Math.abs(left - right) > 1) 16 | return -1; 17 | return 1 + Math.max(left, right); 18 | } 19 | } -------------------------------------------------------------------------------- /leetcode/problems/java/check-if-array-pairs-are-divisible-by-k.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean canArrange(int[] arr, int k) { 3 | int freq[] = new int[k]; 4 | for (int n : arr) 5 | freq[(n % k + k) % k]++; 6 | 7 | if (freq[0] % 2 != 0) // k - 0 = k and it does not exist in the array 8 | return false; 9 | 10 | for (int i = 1; i <= k / 2; i++) 11 | if (freq[i] != freq[k - i]) 12 | return false; 13 | 14 | return true; 15 | } 16 | } -------------------------------------------------------------------------------- /leetcode/problems/java/climbing-stairs.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int climbStairs(int n) { 3 | if (n <= 2) 4 | return n; 5 | int a = 1, b = 2, c = 0; 6 | for (int i = 3; i <= n; i++) { 7 | c = a + b; 8 | a = b; 9 | b = c; 10 | } 11 | return c; 12 | } 13 | } -------------------------------------------------------------------------------- /leetcode/problems/java/coin-change.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class Solution { 4 | public int coinChange(int[] coins, int amount) { 5 | int[] dp = new int[amount + 1]; 6 | Arrays.fill(dp, amount + 1); 7 | dp[0] = 0; 8 | for (int i = 1; i <= amount; i++) { 9 | for (int j = 0; j < coins.length; j++) { 10 | if (coins[j] <= i) { 11 | dp[i] = Math.min(dp[i], dp[i - coins[j]] + 1); 12 | } 13 | } 14 | } 15 | return dp[amount] > amount ? -1 : dp[amount]; 16 | } 17 | } -------------------------------------------------------------------------------- /leetcode/problems/java/count-good-nodes-in-binary-tree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int count = 0; 3 | 4 | public int goodNodes(TreeNode root) { 5 | dfs(root, root.val); 6 | return count; 7 | } 8 | 9 | void dfs(TreeNode root, int max) { 10 | if (root == null) 11 | return; 12 | if (root.val >= max) { 13 | count++; 14 | max = root.val; 15 | } 16 | dfs(root.left, max); 17 | dfs(root.right, max); 18 | } 19 | } -------------------------------------------------------------------------------- /leetcode/problems/java/count-number-of-nice-subarrays.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numberOfSubarrays(int[] nums, int k) { 3 | int n = nums.length; 4 | int[] odd = new int[n + 2]; 5 | int ans = 0; 6 | int count = 0; 7 | odd[0] = 1; 8 | for (int i = 0; i < n; i++) { 9 | if (nums[i] % 2 == 1) { 10 | count++; 11 | } 12 | odd[count]++; 13 | if (count >= k) { 14 | ans += odd[count - k]; 15 | } 16 | } 17 | return ans; 18 | } 19 | } -------------------------------------------------------------------------------- /leetcode/problems/java/count-triplets-that-can-form-two-arrays-of-equal-xor.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countTriplets(int[] nums) { 3 | int count = 0; 4 | for (int i = 0; i < nums.length; i++) { 5 | int xor = 0; 6 | for (int j = i; j < nums.length; j++) { 7 | xor ^= nums[j]; 8 | if (xor == 0) 9 | count += (j - i); 10 | } 11 | } 12 | return count; 13 | } 14 | } -------------------------------------------------------------------------------- /leetcode/problems/java/counting-bits.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] countBits(int n) { 3 | int[] result = new int[n + 1]; 4 | for (int i = 1; i <= n; i++) { 5 | result[i] = result[i & (i - 1)] + 1; 6 | } 7 | return result; 8 | } 9 | } -------------------------------------------------------------------------------- /leetcode/problems/java/crawler-log-folder.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minOperations(String[] logs) { 3 | int depth = 0; 4 | for (String log : logs) { 5 | if (log.equals("../")) { 6 | if (depth > 0) { 7 | depth--; 8 | } 9 | } else if (log.equals("./")) { 10 | continue; 11 | } else { 12 | depth++; 13 | } 14 | } 15 | return depth; 16 | } 17 | } -------------------------------------------------------------------------------- /leetcode/problems/java/decode-xored-array.java: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | class Solution { 6 | public int[] decode(int[] encoded, int first) { 7 | int size = encoded.length; 8 | int[] result = new int[size + 1]; 9 | result[0] = first; 10 | for (int i = 0; i < size; i++) 11 | result[i + 1] = result[i] ^ encoded[i]; 12 | return result; 13 | } 14 | } -------------------------------------------------------------------------------- /leetcode/problems/java/delete-leaves-with-a-given-value.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public TreeNode removeLeafNodes(TreeNode root, int target) { 3 | if (root == null) 4 | return null; 5 | root.left = removeLeafNodes(root.left, target); 6 | root.right = removeLeafNodes(root.right, target); 7 | if (root.val == target && root.left == null && root.right == null) 8 | return null; 9 | return root; 10 | } 11 | } -------------------------------------------------------------------------------- /leetcode/problems/java/diameter-of-binary-tree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int ans = 0; 3 | 4 | public int diameterOfBinaryTree(TreeNode root) { 5 | dfs(root); 6 | return ans; 7 | } 8 | 9 | int dfs(TreeNode root) { 10 | if (root == null) 11 | return 0; 12 | int left = dfs(root.left); 13 | int right = dfs(root.right); 14 | ans = Math.max(ans, left + right); 15 | return 1 + Math.max(left, right); 16 | } 17 | } -------------------------------------------------------------------------------- /leetcode/problems/java/find-center-of-star-graph.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findCenter(int[][] edges) { 3 | int a = edges[0][0]; 4 | int b = edges[0][1]; 5 | 6 | if (a == edges[1][0] || a == edges[1][1]) 7 | return a; 8 | else 9 | return b; 10 | } 11 | } -------------------------------------------------------------------------------- /leetcode/problems/java/find-the-highest-altitude.java: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | class Solution { 6 | public int largestAltitude(int[] gain) { 7 | int altitude = 0, maxAltitude = 0; 8 | for (int i = 0; i < gain.length; i++) { 9 | altitude += gain[i]; 10 | maxAltitude = Math.max(maxAltitude, altitude); 11 | } 12 | return maxAltitude; 13 | } 14 | } -------------------------------------------------------------------------------- /leetcode/problems/java/find-the-winner-of-the-circular-game.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int findTheWinner(int n, int k) { 3 | int winner = 0; 4 | for (int i = 1; i <= n; i++) { 5 | winner = (winner + k) % i; 6 | } 7 | return winner + 1; 8 | } 9 | } -------------------------------------------------------------------------------- /leetcode/problems/java/happy-number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isHappy(int n) { 3 | int digit = 0, sum = 0; 4 | if (n == 1 || n == 7) 5 | return true; 6 | if (n < 10) 7 | return false; 8 | 9 | while (n > 0) { 10 | digit = n % 10; 11 | sum += digit * digit; 12 | n /= 10; 13 | } 14 | 15 | return isHappy(sum); 16 | 17 | } 18 | 19 | } -------------------------------------------------------------------------------- /leetcode/problems/java/height-checker.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class Solution { 4 | public int heightChecker(int[] heights) { 5 | int[] sorted = heights.clone(); 6 | Arrays.sort(sorted); 7 | int count = 0; 8 | for (int i = 0; i < heights.length; i++) { 9 | if (heights[i] != sorted[i]) { 10 | count++; 11 | } 12 | } 13 | return count; 14 | } 15 | } -------------------------------------------------------------------------------- /leetcode/problems/java/hello-world.java: -------------------------------------------------------------------------------- 1 | // A simple hello world program in Java 2 | 3 | 4 | class HelloWorld { 5 | public static void main(String[] args) { 6 | System.out.println("Hello, World!"); 7 | } 8 | } 9 | 10 | 11 | // Search for Leetcode Solutions 12 | // Paste the link or the name of the problem 13 | // 👆🏻 in the Search Bar 14 | // Hit enter or click the search button 15 | // The solution will be displayed in this section -------------------------------------------------------------------------------- /leetcode/problems/java/house-robber.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int rob(int[] nums) { 3 | int rob1 = 0, rob2 = 0; 4 | for (int i = 0; i < nums.length; i++) { 5 | int temp = Math.max(rob1 + nums[i], rob2); 6 | rob1 = rob2; 7 | rob2 = temp; 8 | } 9 | return rob2; 10 | } 11 | } -------------------------------------------------------------------------------- /leetcode/problems/java/invert-binary-tree.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public TreeNode invertTree(TreeNode root) { 4 | if (root == null) 5 | return null; 6 | TreeNode left = invertTree(root.left); 7 | TreeNode right = invertTree(root.right); 8 | root.left = right; 9 | root.right = left; 10 | return root; 11 | } 12 | } -------------------------------------------------------------------------------- /leetcode/problems/java/k-closest-points-to-origin.java: -------------------------------------------------------------------------------- 1 | import java.util.PriorityQueue; 2 | 3 | class Solution { 4 | public int[][] kClosest(int[][] points, int k) { 5 | PriorityQueue maxHeap = new PriorityQueue<>((a, b) -> b[0] * b[0] + b[1] * b[1] - a[0] * a[0] - a[1] * a[1]); 6 | for (int[] point : points) { 7 | maxHeap.add(point); 8 | if (maxHeap.size() > k) { 9 | maxHeap.poll(); 10 | } 11 | } 12 | int[][] result = new int[k][2]; 13 | while (k-- > 0) { 14 | result[k] = maxHeap.poll(); 15 | } 16 | return result; 17 | } 18 | } -------------------------------------------------------------------------------- /leetcode/problems/java/kth-largest-element-in-an-array.java: -------------------------------------------------------------------------------- 1 | import java.util.PriorityQueue; 2 | 3 | class Solution { 4 | public int findKthLargest(int[] nums, int k) { 5 | PriorityQueue minHeap = new PriorityQueue<>(); 6 | for (int num : nums) { 7 | minHeap.add(num); 8 | if (minHeap.size() > k) { 9 | minHeap.remove(); 10 | } 11 | } 12 | return minHeap.remove(); 13 | } 14 | } -------------------------------------------------------------------------------- /leetcode/problems/java/kth-smallest-element-in-a-bst.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int n, ans = 0; 3 | 4 | public int kthSmallest(TreeNode root, int k) { 5 | n = k; 6 | dfs(root); 7 | return ans; 8 | } 9 | 10 | void dfs(TreeNode root) { 11 | if (root == null || n == 0) 12 | return; 13 | dfs(root.left); 14 | if (n == 1) { 15 | ans = root.val; 16 | n--; 17 | return; 18 | } else { 19 | n--; 20 | } 21 | dfs(root.right); 22 | } 23 | } -------------------------------------------------------------------------------- /leetcode/problems/java/linked-list-cycle.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean hasCycle(ListNode head) { 3 | ListNode slow = head; 4 | ListNode fast = head; 5 | 6 | while (fast != null && fast.next != null) { 7 | slow = slow.next; 8 | fast = fast.next.next; 9 | 10 | if (slow == fast) 11 | return true; 12 | } 13 | 14 | return false; 15 | 16 | } 17 | } -------------------------------------------------------------------------------- /leetcode/problems/java/longest-increasing-subsequence.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Solution { 4 | public int lengthOfLIS(int[] nums) { 5 | int n = nums.length; 6 | int[] dp = new int[n]; 7 | Arrays.fill(dp, 1); 8 | int max = 1; 9 | for (int i = 1; i < n; i++) { 10 | for (int j = 0; j < i; j++) { 11 | if (nums[i] > nums[j]) { 12 | dp[i] = Math.max(dp[i], dp[j] + 1); 13 | } 14 | } 15 | max = Math.max(max, dp[i]); 16 | } 17 | return max; 18 | } 19 | } -------------------------------------------------------------------------------- /leetcode/problems/java/lowest-common-ancestor-of-a-binary-search-tree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { 3 | TreeNode curr = root; 4 | while (curr != null) { 5 | if (p.val < curr.val && q.val < curr.val) { 6 | curr = curr.left; 7 | } else if (p.val > curr.val && q.val > curr.val) { 8 | curr = curr.right; 9 | } else { 10 | return curr; 11 | } 12 | } 13 | return null; 14 | } 15 | } -------------------------------------------------------------------------------- /leetcode/problems/java/maximize-happiness-of-selected-children.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class Solution { 4 | public long maximumHappinessSum(int[] happiness, int k) { 5 | Arrays.sort(happiness); 6 | long res = 0; 7 | int n = happiness.length, j = 0; 8 | for (int i = n - 1; i >= n - k; --i) { 9 | happiness[i] = Math.max(happiness[i] - j++, 0); 10 | res += happiness[i]; 11 | } 12 | return res; 13 | } 14 | } -------------------------------------------------------------------------------- /leetcode/problems/java/maximum-depth-of-binary-tree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxDepth(TreeNode root) { 3 | if (root == null) 4 | return 0; 5 | return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); 6 | } 7 | } -------------------------------------------------------------------------------- /leetcode/problems/java/maximum-product-subarray.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxProduct(int[] nums) { 3 | int res = nums[0]; 4 | int curMax = 1, curMin = 1; 5 | 6 | for (int num : nums) { 7 | if (num < 0) { 8 | int temp = curMax; 9 | curMax = curMin; 10 | curMin = temp; 11 | } 12 | 13 | curMax = Math.max(curMax * num, num); 14 | curMin = Math.min(curMin * num, num); 15 | 16 | res = Math.max(res, curMax); 17 | } 18 | 19 | return res; 20 | } 21 | } -------------------------------------------------------------------------------- /leetcode/problems/java/merge-nodes-in-between-zeros.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public ListNode mergeNodes(ListNode head) { 3 | ListNode modify = head.next; 4 | ListNode nextSum = modify; 5 | 6 | while (nextSum != null) { 7 | int sum = 0; 8 | while (nextSum.val != 0) { 9 | sum += nextSum.val; 10 | nextSum = nextSum.next; 11 | } 12 | modify.val = sum; 13 | nextSum = nextSum.next; 14 | modify.next = nextSum; 15 | modify = modify.next; 16 | } 17 | return head.next; 18 | } 19 | } -------------------------------------------------------------------------------- /leetcode/problems/java/min-cost-climbing-stairs.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minCostClimbingStairs(int[] cost) { 3 | int i = cost.length - 3; 4 | while (i >= 0) { 5 | int m = cost[i] + cost[i + 1]; 6 | int n = cost[i] + cost[i + 2]; 7 | cost[i] = Math.min(m, n); 8 | i--; 9 | } 10 | return Math.min(cost[0], cost[1]); 11 | } 12 | } -------------------------------------------------------------------------------- /leetcode/problems/java/minimum-deletions-to-make-string-balanced.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minimumDeletions(String s) { 3 | int n = s.length(); 4 | int[] f = new int[n + 1]; 5 | int b = 0; 6 | for (int i = 1; i <= n; ++i) { 7 | if (s.charAt(i - 1) == 'b') { 8 | f[i] = f[i - 1]; 9 | ++b; 10 | } else { 11 | f[i] = Math.min(f[i - 1] + 1, b); 12 | } 13 | } 14 | return f[n]; 15 | } 16 | } -------------------------------------------------------------------------------- /leetcode/problems/java/minimum-difference-between-largest-and-smallest-value-in-three-moves.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class Solution { 4 | public int minDifference(int[] nums) { 5 | int n = nums.length; 6 | if (n <= 4) 7 | return 0; 8 | if (n == 5) 9 | return 1; 10 | Arrays.sort(nums); 11 | int x1 = nums[n - 4] - nums[0]; 12 | int x2 = nums[n - 3] - nums[1]; 13 | int x3 = nums[n - 2] - nums[2]; 14 | int x4 = nums[n - 1] - nums[3]; 15 | 16 | return Math.min(x4, Math.min(x1, Math.min(x2, x3))); 17 | } 18 | } -------------------------------------------------------------------------------- /leetcode/problems/java/minimum-increment-to-make-array-unique.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class Solution { 4 | public int minIncrementForUnique(int[] nums) { 5 | Arrays.sort(nums); 6 | int ans = 0; 7 | for (int i = 1; i < nums.length; i++) { 8 | if (nums[i] <= nums[i - 1]) { 9 | ans += nums[i - 1] - nums[i] + 1; 10 | nums[i] = nums[i - 1] + 1; 11 | } 12 | } 13 | return ans; 14 | } 15 | } -------------------------------------------------------------------------------- /leetcode/problems/java/minimum-number-of-k-consecutive-bit-flips.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minKBitFlips(int[] nums, int k) { 3 | int n = nums.length, flipped = 0, res = 0; 4 | int[] isFlipped = new int[n]; 5 | for (int i = 0; i < nums.length; ++i) { 6 | if (i >= k) 7 | flipped ^= isFlipped[i - k]; 8 | if (flipped == nums[i]) { 9 | if (i + k > nums.length) 10 | return -1; 11 | isFlipped[i] = 1; 12 | flipped ^= 1; 13 | res++; 14 | } 15 | } 16 | return res; 17 | } 18 | } -------------------------------------------------------------------------------- /leetcode/problems/java/minimum-number-of-moves-to-seat-everyone.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class Solution { 4 | public int minMovesToSeat(int[] seats, int[] students) { 5 | Arrays.sort(seats); 6 | Arrays.sort(students); 7 | int n = seats.length; 8 | int ans = 0; 9 | for (int i = 0; i < n; i++) { 10 | ans += Math.abs(seats[i] - students[i]); 11 | } 12 | return ans; 13 | } 14 | } -------------------------------------------------------------------------------- /leetcode/problems/java/minimum-swaps-to-group-all-1s-together-ii.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class Solution { 4 | public int minSwaps(int[] nums) { 5 | int k = Arrays.stream(nums).sum(); 6 | int n = nums.length; 7 | int count = 0; 8 | for (int i = 0; i < k; ++i) 9 | count += nums[i]; 10 | int max = count; 11 | for (int i = k; i < n + k; ++i) { 12 | count += nums[i % n] - nums[(i - k + n) % n]; 13 | max = Math.max(max, count); 14 | } 15 | return k - max; 16 | } 17 | } -------------------------------------------------------------------------------- /leetcode/problems/java/missing-number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int missingNumber(int[] nums) { 3 | int n = nums.length; 4 | int xor1 = 0, xor2 = 0; 5 | for (int i = 0; i < n; i++) { 6 | xor1 ^= nums[i]; 7 | xor2 ^= i; 8 | } 9 | xor2 ^= n; 10 | return xor1 ^ xor2; 11 | } 12 | } -------------------------------------------------------------------------------- /leetcode/problems/java/number-of-1-bits.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int hammingWeight(int n) { 3 | int count = 0; 4 | while (n != 0) { 5 | count++; 6 | n &= (n - 1); 7 | } 8 | return count; 9 | } 10 | } -------------------------------------------------------------------------------- /leetcode/problems/java/number-of-senior-citizens.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int countSeniors(String[] details) { 3 | int ans = 0; 4 | for (var x : details) { 5 | int age = Integer.parseInt(x.substring(11, 13)); 6 | if (age > 60) 7 | ++ans; 8 | } 9 | return ans; 10 | } 11 | } -------------------------------------------------------------------------------- /leetcode/problems/java/pass-the-pillow.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int passThePillow(int n, int time) { 3 | int chunks = time / (n - 1); 4 | return chunks % 2 == 0 ? (time % (n - 1) + 1) : (n - time % (n - 1)); 5 | } 6 | } -------------------------------------------------------------------------------- /leetcode/problems/java/patching-array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minPatches(int[] nums, int n) { 3 | long miss = 1; 4 | int patches = 0; 5 | int i = 0; 6 | while (miss <= n) { 7 | if (i < nums.length && nums[i] <= miss) { 8 | miss += nums[i++]; 9 | } else { 10 | miss += miss; 11 | patches++; 12 | } 13 | } 14 | return patches; 15 | } 16 | } -------------------------------------------------------------------------------- /leetcode/problems/java/plus-one.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] plusOne(int[] digits) { 3 | int n = digits.length; 4 | for (int i = n - 1; i >= 0; i--) { 5 | if (digits[i] < 9) { 6 | digits[i]++; 7 | return digits; 8 | } 9 | digits[i] = 0; 10 | } 11 | int[] newNumber = new int[n + 1]; 12 | newNumber[0] = 1; 13 | return newNumber; 14 | } 15 | } -------------------------------------------------------------------------------- /leetcode/problems/java/power-of-two.java: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | class Solution { 6 | public boolean isPowerOfTwo(int n) { 7 | return n > 0 && (n & n - 1) == 0; 8 | } 9 | } -------------------------------------------------------------------------------- /leetcode/problems/java/powx-n.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public double myPow(double x, int n) { 3 | if (n == 0) 4 | return 1; 5 | if (n == 1) 6 | return x; 7 | if (n == -1) 8 | return 1 / x; 9 | 10 | double half = myPow(x, n / 2); 11 | double rest = myPow(x, n % 2); 12 | 13 | return half * half * rest; 14 | } 15 | } -------------------------------------------------------------------------------- /leetcode/problems/java/range-sum-of-bst.java: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(n) 4 | 5 | class Solution { 6 | public int rangeSumBST(TreeNode root, int low, int high) { 7 | if (root == null) 8 | return 0; 9 | if (root.val < low) 10 | return rangeSumBST(root.right, low, high); 11 | if (root.val > high) 12 | return rangeSumBST(root.left, low, high); 13 | return root.val + rangeSumBST(root.left, low, high) + rangeSumBST(root.right, low, high); 14 | } 15 | } -------------------------------------------------------------------------------- /leetcode/problems/java/relative-sort-array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] relativeSortArray(int[] arr1, int[] arr2) { 3 | int[] count = new int[1001]; 4 | for (int num : arr1) { 5 | count[num]++; 6 | } 7 | int i = 0; 8 | for (int num : arr2) { 9 | while (count[num]-- > 0) { 10 | arr1[i++] = num; 11 | } 12 | } 13 | for (int num = 0; num < count.length; num++) { 14 | while (count[num]-- > 0) { 15 | arr1[i++] = num; 16 | } 17 | } 18 | return arr1; 19 | } 20 | } -------------------------------------------------------------------------------- /leetcode/problems/java/remove-nodes-from-linked-list.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public ListNode removeNodes(ListNode head) { 3 | if (head == null) 4 | return null; 5 | 6 | head.next = removeNodes(head.next); 7 | return head.next != null && head.val < head.next.val ? head.next : head; 8 | } 9 | } -------------------------------------------------------------------------------- /leetcode/problems/java/reverse-bits.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int reverseBits(int n) { 3 | int result = 0; 4 | for (int i = 0; i < 32; i++) { 5 | result = (result << 1) + (n & 1); 6 | n >>= 1; 7 | } 8 | return result; 9 | } 10 | } -------------------------------------------------------------------------------- /leetcode/problems/java/reverse-linked-list.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String reversePrefix(String word, char ch) { 3 | int index = word.indexOf(ch); 4 | if (index == -1) { 5 | return word; 6 | } 7 | char[] arr = word.toCharArray(); 8 | int left = 0; 9 | int right = index; 10 | while (left < right) { 11 | char temp = arr[left]; 12 | arr[left] = arr[right]; 13 | arr[right] = temp; 14 | left++; 15 | right--; 16 | } 17 | return new String(arr); 18 | } 19 | }/ -------------------------------------------------------------------------------- /leetcode/problems/java/reverse-string.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void reverseString(char[] s) { 3 | int n = s.length; 4 | for (int i = 0; i < n / 2; i++) { 5 | char temp = s[i]; 6 | s[i] = s[n - i - 1]; 7 | s[n - i - 1] = temp; 8 | } 9 | } 10 | } -------------------------------------------------------------------------------- /leetcode/problems/java/same-tree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isSameTree(TreeNode p, TreeNode q) { 3 | if (p == null && q == null) 4 | return true; 5 | if (p == null || q == null) 6 | return false; 7 | if (p.val != q.val) 8 | return false; 9 | return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); 10 | } 11 | } -------------------------------------------------------------------------------- /leetcode/problems/java/score-of-a-string.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int scoreOfString(String s) { 3 | int score = 0; 4 | int n = s.length(); 5 | for (int i = 0; i < n - 1; i++) { 6 | int diff = Math.abs(s.charAt(i + 1) - s.charAt(i)); 7 | score += diff; 8 | } 9 | return score; 10 | } 11 | } -------------------------------------------------------------------------------- /leetcode/problems/java/single-number-iii.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] singleNumber(int[] nums) { 3 | int xor = 0; 4 | for (int num : nums) { 5 | xor ^= num; 6 | } 7 | int mask = 1; 8 | while ((xor & mask) == 0) { 9 | mask <<= 1; 10 | } 11 | int a = 0; 12 | int b = 0; 13 | for (int num : nums) { 14 | if ((num & mask) == 0) { 15 | a ^= num; 16 | } else { 17 | b ^= num; 18 | } 19 | } 20 | return new int[] { a, b }; 21 | } 22 | } -------------------------------------------------------------------------------- /leetcode/problems/java/single-number.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int singleNumber(int[] nums) { 3 | int result = 0; 4 | for (int num : nums) { 5 | result ^= num; 6 | } 7 | return result; 8 | } 9 | } -------------------------------------------------------------------------------- /leetcode/problems/java/sort-an-array.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] sortArray(int[] nums) { 3 | Arrays.sort(nums); 4 | return nums; 5 | } 6 | } -------------------------------------------------------------------------------- /leetcode/problems/java/sort-array-by-increasing-frequency.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] frequencySort(int[] nums) { 3 | int count[] = new int[201]; 4 | for (int n : nums) 5 | count[n + 100]++; 6 | for (int i = nums.length - 1; i >= 0;) { 7 | int m = 0, ind = -1; 8 | for (int j = 0; j < 201; j++) { 9 | if (count[j] > m) { 10 | m = count[j]; 11 | ind = j; 12 | } 13 | } 14 | for (int j = 0; j < m; j++) 15 | nums[i--] = ind - 100; 16 | count[ind] = 0; 17 | } 18 | return nums; 19 | } 20 | } -------------------------------------------------------------------------------- /leetcode/problems/java/sort-colors.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void sortColors(int[] nums) { 3 | int zero = 0, one = 0; 4 | for (int i = 0; i < nums.length; i++) { 5 | if (nums[i] == 0) { 6 | zero++; 7 | } else if (nums[i] == 1) { 8 | one++; 9 | } 10 | } 11 | for (int i = 0; i < nums.length; i++) { 12 | if (zero > 0) { 13 | nums[i] = 0; 14 | zero--; 15 | } else if (one > 0) { 16 | nums[i] = 1; 17 | one--; 18 | } else { 19 | nums[i] = 2; 20 | } 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /leetcode/problems/java/subarray-sums-divisible-by-k.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int subarraysDivByK(int[] nums, int k) { 3 | int[] fre = new int[k]; 4 | int sum = 0; 5 | for (int i = 0; i < nums.length; i++) { 6 | sum += ((nums[i] % k) + k) % k; 7 | fre[sum % k]++; 8 | } 9 | int res = fre[0]; 10 | for (int i : fre) { 11 | res += (i * (i - 1)) / 2; 12 | } 13 | return res; 14 | } 15 | } -------------------------------------------------------------------------------- /leetcode/problems/java/sum-of-square-numbers.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean judgeSquareSum(int c) { 3 | for (int d = 2; d * d <= c; d++) { 4 | if (c % d == 0) { 5 | int e = 0; 6 | while (c % d == 0) { 7 | e++; 8 | c /= d; 9 | } 10 | if (d % 4 == 3 && e % 2 != 0) 11 | return false; 12 | } 13 | } 14 | return c % 4 != 3; 15 | } 16 | } -------------------------------------------------------------------------------- /leetcode/problems/java/sum-of-two-integers.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int getSum(int a, int b) { 3 | while (b != 0) { 4 | int carry = a & b; 5 | a = a ^ b; 6 | b = carry << 1; 7 | } 8 | return a; 9 | } 10 | } -------------------------------------------------------------------------------- /leetcode/problems/java/task-scheduler.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class Solution { 4 | public int leastInterval(char[] tasks, int n) { 5 | int[] freq = new int[26]; 6 | for (char task : tasks) { 7 | freq[task - 'A']++; 8 | } 9 | Arrays.sort(freq); 10 | int maxFreq = freq[25] - 1; 11 | int idleSlots = maxFreq * n; 12 | for (int i = 24; i >= 0; i--) { 13 | idleSlots -= Math.min(maxFreq, freq[i]); 14 | } 15 | return idleSlots > 0 ? idleSlots + tasks.length : tasks.length; 16 | } 17 | } -------------------------------------------------------------------------------- /leetcode/problems/java/three-consecutive-odds.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean threeConsecutiveOdds(int[] arr) { 3 | int count = 0; 4 | for (int i = 0; i < arr.length; i++) { 5 | if (arr[i] % 2 != 0) { 6 | count++; 7 | } else { 8 | count = 0; 9 | } 10 | 11 | if (count == 3) { 12 | return true; 13 | } 14 | } 15 | return false; 16 | } 17 | } -------------------------------------------------------------------------------- /leetcode/problems/java/validate-binary-search-tree.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | TreeNode prev = null; 3 | 4 | public boolean isValidBST(TreeNode root) { 5 | if (root == null) 6 | return true; 7 | if (!isValidBST(root.left)) 8 | return false; 9 | if (prev != null && prev.val >= root.val) 10 | return false; 11 | prev = root; 12 | return isValidBST(root.right); 13 | } 14 | } -------------------------------------------------------------------------------- /leetcode/problems/java/water-bottles.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int numWaterBottles(int numBottles, int numExchange) { 3 | return numBottles + (numBottles - 1) / (numExchange - 1); 4 | } 5 | } -------------------------------------------------------------------------------- /leetcode/problems/java/xor-operation-in-an-array.java: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | 6 | class Solution { 7 | public int xorOperation(int n, int start) { 8 | int i, res = start; 9 | for (i = 1; i < n; i++){ 10 | start += 2; res ^= start; 11 | } 12 | return res; 13 | } 14 | } -------------------------------------------------------------------------------- /leetcode/problems/js/add-two-promises.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | /** 6 | * @param {Promise} promise1 7 | * @param {Promise} promise2 8 | * @return {Promise} 9 | */ 10 | 11 | var addTwoPromises = async function (promise1, promise2) { 12 | const [num1, num2] = await Promise.all([promise1, promise2]) 13 | return num1 + num2 14 | }; -------------------------------------------------------------------------------- /leetcode/problems/js/allow-one-function-call.js: -------------------------------------------------------------------------------- 1 | //// by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | /** 6 | * @param {Function} fn 7 | * @return {Function} 8 | */ 9 | var once = function (fn) { 10 | let called = false; 11 | return (...args) => { 12 | if (!called) { 13 | called = true; 14 | return fn(...args); 15 | } 16 | } 17 | }; -------------------------------------------------------------------------------- /leetcode/problems/js/apply-transform-over-each-element-in-array.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space: O(n) 4 | 5 | /** 6 | * @param {number[]} arr 7 | * @param {Function} fn 8 | * @return {number[]} 9 | */ 10 | var map = function (arr, fn) { 11 | const len = arr.length 12 | const tArr = [] 13 | for (let i = 0; i < len; i++) 14 | tArr[i] = fn(arr[i], i) 15 | return tArr 16 | }; -------------------------------------------------------------------------------- /leetcode/problems/js/array-prototype-last.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | Array.prototype.last = function () { 6 | const len = this.length 7 | if(len) 8 | return this[len - 1] 9 | return -1 10 | }; 11 | 12 | /** 13 | * const arr = [1, 2, 3]; 14 | * arr.last(); // 3 15 | */ -------------------------------------------------------------------------------- /leetcode/problems/js/array-reduce-transformation.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @param {Function} fn 8 | * @param {number} init 9 | * @return {number} 10 | */ 11 | var reduce = function (nums, fn, init) { 12 | let val = init 13 | nums.forEach((num) => { 14 | val = fn(val, num) 15 | }) 16 | return val 17 | }; -------------------------------------------------------------------------------- /leetcode/problems/js/call-function-with-custom-context.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | /** 6 | * @param {Object} context 7 | * @param {any[]} args 8 | * @return {any} 9 | */ 10 | Function.prototype.callPolyfill = function (context, ...args) { 11 | const fn = this 12 | Object.defineProperty(context, '_fn', { 13 | value: fn, 14 | enumerable: false 15 | }); 16 | return context._fn(...args); 17 | } 18 | 19 | /** 20 | * function increment() { this.count++; return this.count; } 21 | * increment.callPolyfill({count: 1}); // 2 22 | */ -------------------------------------------------------------------------------- /leetcode/problems/js/chunk-array.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | 4 | /** 5 | * @param {Array} arr 6 | * @param {number} size 7 | * @return {Array[]} 8 | */ 9 | var chunk = function (arr, size) { 10 | const len = arr.length 11 | const result = [] 12 | for (let i = 0; i < len; i += size) 13 | result.push(arr.slice(i, size + i)) 14 | return result 15 | } -------------------------------------------------------------------------------- /leetcode/problems/js/concatenation-of-array.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | const getConcatenation = nums => [...nums, ...nums] 4 | 5 | // or 6 | 7 | const getConcatenation2 = nums => nums.concat(nums) -------------------------------------------------------------------------------- /leetcode/problems/js/counter-ii.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | /** 6 | * @param {integer} init 7 | * @return { increment: Function, decrement: Function, reset: Function } 8 | */ 9 | var createCounter = function (init) { 10 | const initial = init 11 | return { 12 | increment: () => ++init, 13 | decrement: () => --init, 14 | reset: () => init = initial 15 | } 16 | }; 17 | 18 | /** 19 | * const counter = createCounter(5) 20 | * counter.increment(); // 6 21 | * counter.reset(); // 5 22 | * counter.decrement(); // 4 23 | */ -------------------------------------------------------------------------------- /leetcode/problems/js/counter.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(1) 3 | // Space Complexity : O(1) 4 | 5 | /** 6 | * @param {number} n 7 | * @return {Function} counter 8 | */ 9 | var createCounter = function (n) { 10 | return function () { 11 | return n++; 12 | }; 13 | } -------------------------------------------------------------------------------- /leetcode/problems/js/create-hello-world-function.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | /** 6 | * @return {Function} 7 | */ 8 | const createHelloWorld = () => 9 | () => "Hello World" 10 | 11 | /** 12 | * const f = createHelloWorld(); 13 | * f(); // "Hello World" 14 | */ -------------------------------------------------------------------------------- /leetcode/problems/js/curry.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | var curry = function (fn) { 4 | return function curried(...args) { 5 | if (fn.length === args.length) return fn(...args) 6 | return function (...args2) { 7 | return curried(...args, ...args2); 8 | } 9 | }; 10 | }; -------------------------------------------------------------------------------- /leetcode/problems/js/debounce.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | /** 6 | * @param {Function} fn 7 | * @param {number} t milliseconds 8 | * @return {Function} 9 | */ 10 | var debounce = function (fn, t) { 11 | let timer 12 | return function (...args) { 13 | timer && clearTimeout(timer) 14 | timer = setTimeout(() => fn(...args), t) 15 | } 16 | } 17 | 18 | /** 19 | * const log = debounce(console.log, 100); 20 | * log('Hello'); // cancelled 21 | * log('Hello'); // cancelled 22 | * log('Hello'); // Logged at t=100ms 23 | */ -------------------------------------------------------------------------------- /leetcode/problems/js/decode-xored-array.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | /** 6 | * @param {number[]} encoded 7 | * @param {number} first 8 | * @return {number[]} 9 | */ 10 | var decode = function (encoded, first) { 11 | let result = [first] 12 | let size = encoded.length 13 | for (let i = 0; i < size; i++) 14 | result.push(result[i] ^ encoded[i]) 15 | return result 16 | } -------------------------------------------------------------------------------- /leetcode/problems/js/event-emitter.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | class EventEmitter { 4 | map = new Map() 5 | EventEmitter() { 6 | this.map = map 7 | } 8 | subscribe(event, cb) { 9 | if (!this.map.has(event)) 10 | this.map.set(event, []) 11 | 12 | const arr = this.map.get(event) || [] 13 | arr.push(cb) 14 | return { unsubscribe: () => arr.splice(arr.indexOf(cb), 1) } 15 | } 16 | 17 | emit(event, args = []) { 18 | return this.map.get(event)?.map(fn => fn(...args)) ?? [] 19 | } 20 | } -------------------------------------------------------------------------------- /leetcode/problems/js/execute-cancellable-function-with-delay.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | /** 6 | * @param {Function} fn 7 | * @param {Array} args 8 | * @param {number} t 9 | * @return {Function} 10 | */ 11 | 12 | var cancellable = function (fn, args, t) { 13 | const timer = setTimeout(() => fn(...args), t); 14 | return () => clearTimeout(timer) 15 | }; -------------------------------------------------------------------------------- /leetcode/problems/js/filter-elements-from-array.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(n) 4 | 5 | /** 6 | * @param {number[]} arr 7 | * @param {Function} fn 8 | * @return {number[]} 9 | */ 10 | var filter = function (arr, fn) { 11 | const len = arr.length 12 | const tArr = [] 13 | for (let i = 0; i < len; i++) 14 | if (fn(arr[i], i)) 15 | tArr.push(arr[i]) 16 | return tArr 17 | }; -------------------------------------------------------------------------------- /leetcode/problems/js/find-the-difference-of-two-arrays.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | var findDifference = function (nums1, nums2) { 4 | nums1 = new Set(nums1) 5 | nums2 = new Set(nums2) 6 | const arr1 = [...nums1].filter(elem => !nums2.has(elem)) 7 | const arr2 = [...nums2].filter(elem => !nums1.has(elem)) 8 | return [arr1, arr2] 9 | }; -------------------------------------------------------------------------------- /leetcode/problems/js/find-the-highest-altitude.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | function largestAltitude(gain) { 6 | let altitude = 0 7 | let max = 0 8 | for (let g of gain) { 9 | altitude += g 10 | max = Math.max(max, altitude) 11 | } 12 | return max 13 | } -------------------------------------------------------------------------------- /leetcode/problems/js/fizz-buzz.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | var fizzBuzz = function (n) { 6 | arr = [] 7 | for (let i = 1; i <= n; i++) { 8 | if (i % 3 == 0 && i % 5 == 0) 9 | arr.push("FizzBuzz") 10 | else if (i % 3 == 0) 11 | arr.push("Fizz") 12 | else if (i % 5 == 0) 13 | arr.push("Buzz") 14 | else 15 | arr.push(i + "") 16 | } 17 | return arr 18 | }; 19 | -------------------------------------------------------------------------------- /leetcode/problems/js/flatten-deeply-nested-array.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(n) 4 | 5 | /** 6 | * @param {any[]} arr 7 | * @param {number} depth 8 | * @return {any[]} 9 | */ 10 | var flat = function (arr, n) { 11 | const result = []; 12 | function helper(arr, depth) { 13 | for (elem of arr) { 14 | if (Array.isArray(elem) && depth < n) 15 | helper(elem, depth + 1) 16 | else 17 | result.push(elem) 18 | } 19 | } 20 | helper(arr, 0) 21 | return result 22 | } -------------------------------------------------------------------------------- /leetcode/problems/js/flipping-an-image.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | const flipAndInvertImage = image => image.map(elem => elem.reverse().map(b => b ? 0 : 1)) -------------------------------------------------------------------------------- /leetcode/problems/js/function-composition.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | var compose = function (functions) { 6 | return function (x) { 7 | let val = x 8 | let len = functions.length 9 | while (len--) { 10 | val = functions[len](val) 11 | } 12 | return val 13 | } 14 | } -------------------------------------------------------------------------------- /leetcode/problems/js/generate-fibonacci-sequence.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | /** 4 | * @return {Generator} 5 | */ 6 | var fibGenerator = function* () { 7 | let a = 0; 8 | let b = 1; 9 | while (true) { 10 | yield a; 11 | const tmp = a; 12 | a = b; 13 | b += tmp; 14 | } 15 | }; -------------------------------------------------------------------------------- /leetcode/problems/js/group-by.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(n) 4 | 5 | /** 6 | * @param {Function} fn 7 | * @return {Array} 8 | */ 9 | Array.prototype.groupBy = function (fn) { 10 | const answer = {}; 11 | for (const item of this) { 12 | const key = fn(item) 13 | if (key in answer) 14 | answer[key].push(item) 15 | else 16 | answer[key] = [item] 17 | } 18 | return answer 19 | } -------------------------------------------------------------------------------- /leetcode/problems/js/guess-number-higher-or-lower.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(log n) 3 | // Space Complexity : O(1) 4 | 5 | var guessNumber = function (n) { 6 | let start = 1, end = n, mid; 7 | while (start < end) { 8 | mid = Math.floor((start + end) / 2); 9 | if (guess(mid) == 0) return mid; 10 | if (guess(mid) == -1) end = mid - 1; 11 | else start = mid + 1; 12 | } 13 | return start; 14 | }; -------------------------------------------------------------------------------- /leetcode/problems/js/hello-world.js: -------------------------------------------------------------------------------- 1 | // A simple hello world program in JavaScript 2 | 3 | 4 | console.log("Hello World") 5 | 6 | 7 | // Search for Leetcode Solutions 8 | // Paste the link or the name of the problem 9 | // 👆🏻 in the Search Bar 10 | // Hit enter or click the search button 11 | // The solution will be displayed in this section -------------------------------------------------------------------------------- /leetcode/problems/js/interval-cancellation.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | /** 6 | * @param {Function} fn 7 | * @param {Array} args 8 | * @param {number} t 9 | * @return {Function} 10 | */ 11 | 12 | var cancellable = function (fn, args, t) { 13 | const executable = () => fn(...args) 14 | const timer = setInterval(executable, t) 15 | const cancel = () => clearInterval(timer) 16 | executable() 17 | return cancel 18 | }; -------------------------------------------------------------------------------- /leetcode/problems/js/is-object-empty.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | /** 6 | * @param {Object | Array} obj 7 | * @return {boolean} 8 | */ 9 | var isEmpty = function (obj) { 10 | return Object.keys(obj).length === 0 11 | }; -------------------------------------------------------------------------------- /leetcode/problems/js/is-subsequence.js: -------------------------------------------------------------------------------- 1 | var isSubsequence = function (s, t) { 2 | s = s.split("") 3 | let j = 0 4 | 5 | for (let i = 0; i < t.length; i++) { 6 | if (s[j] === t[i]) { 7 | j++; 8 | } 9 | } 10 | return j === s.length 11 | } -------------------------------------------------------------------------------- /leetcode/problems/js/linked-list-cycle-ii.js: -------------------------------------------------------------------------------- 1 | var detectCycle = function (head) { 2 | while (head && head.next) { 3 | head.val = null; 4 | head = head.next; 5 | if (head.val == null) 6 | return head; 7 | } 8 | return null; 9 | }; -------------------------------------------------------------------------------- /leetcode/problems/js/memoize.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(n) 4 | 5 | /** 6 | * @param {Function} fn 7 | */ 8 | function memoize(fn) { 9 | const cache = new Map() 10 | return function (...args) { 11 | let key = args.toString() 12 | if (cache.has(key)) 13 | return cache.get(key) 14 | 15 | const val = fn(...args) 16 | cache.set(key, val) 17 | return val 18 | } 19 | } -------------------------------------------------------------------------------- /leetcode/problems/js/nested-array-generator.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(n) 4 | 5 | /** 6 | * @param {Array} arr 7 | * @return {Generator} 8 | */ 9 | var inorderTraversal = function* (arr) { 10 | for (const item of arr) { 11 | if (Array.isArray(item)) 12 | yield* inorderTraversal(item); 13 | else 14 | yield item; 15 | } 16 | }; 17 | 18 | /** 19 | * const gen = inorderTraversal([1, [2, 3]]); 20 | * gen.next().value; // 1 21 | * gen.next().value; // 2 22 | * gen.next().value; // 3 23 | */ -------------------------------------------------------------------------------- /leetcode/problems/js/number-of-1-bits.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | /** 6 | * @param {number} n - a positive integer 7 | * @return {number} 8 | */ 9 | var hammingWeight = function (n) { 10 | let count = 0; 11 | for (let i = 0; i < 32; i++) { 12 | if (n & 1) 13 | count++; 14 | n = n >> 1; 15 | } 16 | return count; 17 | }; -------------------------------------------------------------------------------- /leetcode/problems/js/power-of-two.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | /** 6 | * @param {number} n 7 | * @return {boolean} 8 | */ 9 | var isPowerOfTwo = function (n) { 10 | return n > 0 && (n & n - 1) === 0 11 | }; -------------------------------------------------------------------------------- /leetcode/problems/js/promise-time-limit.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | var timeLimit = function (fn, t) { 6 | return async function (...args) { 7 | return new Promise((res, rej) => { 8 | fn(...args).then(res).catch(rej); 9 | setTimeout(() => rej("Time Limit Exceeded"), t); 10 | }); 11 | } 12 | }; -------------------------------------------------------------------------------- /leetcode/problems/js/return-length-of-arguments-passed.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | /** 6 | * @return {number} 7 | */ 8 | var argumentsLength = function () { 9 | return arguments.length 10 | }; -------------------------------------------------------------------------------- /leetcode/problems/js/rotate-image.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n^2) 3 | // Space Complexity : O(1) 4 | 5 | var rotate = function (matrix) { 6 | let rowLen = matrix[0].length 7 | let colLen = matrix.length 8 | for (let i = 0; i < colLen - 1; i++) 9 | for (let j = i + 1; j < rowLen; j++) 10 | [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]] 11 | for (row of matrix) row.reverse() 12 | }; -------------------------------------------------------------------------------- /leetcode/problems/js/running-sum-of-1d-array.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | function runningSum(nums) { 6 | for (let i = 1; i < nums.length; i++) 7 | nums[i] = nums[i - 1] + nums[i] 8 | return nums 9 | } 10 | -------------------------------------------------------------------------------- /leetcode/problems/js/single-number.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | /** 6 | * @param {number[]} nums 7 | * @return {number} 8 | */ 9 | var singleNumber = function (nums) { 10 | let singleNumber = nums[0] 11 | const len = nums.length 12 | for (let i = 1; i < len; i++) 13 | singleNumber ^= nums[i] 14 | return singleNumber 15 | }; -------------------------------------------------------------------------------- /leetcode/problems/js/sleep.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | /** 6 | * @param {number} millis 7 | */ 8 | async function sleep(millis) { 9 | return new Promise(resolve => setTimeout(resolve, millis)) 10 | } -------------------------------------------------------------------------------- /leetcode/problems/js/smallest-even-multiple.js: -------------------------------------------------------------------------------- 1 | // by codeAbinash 2 | // Time complexity : O(1) 3 | // Space complexity : O(1) 4 | 5 | const smallestEvenMultiple = n => n % 2 === 0 ? n : 2 * n -------------------------------------------------------------------------------- /leetcode/problems/js/sort-by.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(log n) 3 | // Space : O(n) 4 | 5 | /** 6 | * @param {Array} arr 7 | * @param {Function} fn 8 | * @return {Array} 9 | */ 10 | var sortBy = function (arr, fn) { 11 | return arr.sort((a, b) => fn(a) - fn(b)) 12 | } -------------------------------------------------------------------------------- /leetcode/problems/js/sort-characters-by-frequency.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | const frequencySort = s => { 4 | let map = new Map() 5 | for (ch of s) 6 | map.get(ch) === undefined ? map.set(ch, 1) : map.set(ch, map.get(ch) + 1) 7 | map = [...map.entries()].sort((a, b) => b[1] - a[1]) 8 | 9 | let result = '' 10 | map.forEach(elem => { 11 | result += elem[0].repeat(elem[1]) 12 | }) 13 | return result; 14 | }; 15 | -------------------------------------------------------------------------------- /leetcode/problems/js/student-attendance-record.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | const checkRecord = s => { 6 | let countAbsent = 0 7 | for (let ch of s) if (ch === 'A') countAbsent++; 8 | return !s.includes('LLL') && countAbsent < 2; 9 | }; -------------------------------------------------------------------------------- /leetcode/problems/js/summary-ranges.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time Complexity : O(n) 3 | // Space Complexity : O(1) 4 | 5 | var summaryRanges = function (nums) { 6 | let arr = [], index 7 | for (let i = 0; i < nums.length; i++) { 8 | index = i 9 | while ((nums[i] + 1 == nums[i + 1]) && i < nums.length - 1) i++; 10 | arr.push(nums[index] == nums[i] ? `${nums[index]}` : `${nums[index]}->${nums[i]}`) 11 | } 12 | return arr; 13 | }; -------------------------------------------------------------------------------- /leetcode/problems/js/top-k-frequent-words.js: -------------------------------------------------------------------------------- 1 | var topKFrequent = function (words, k) { 2 | let map = new Map(); 3 | 4 | for (let i = 0; i < words.length; i++) 5 | map.set(words[i], (map.get(words[i]) || 0) + 1); 6 | 7 | let ext = [...new Map(map)]; 8 | 9 | ext.sort((map, ext) => { 10 | if (map[1] === ext[1]) 11 | return map[0] > ext[0] ? 1 : -1; 12 | return map[1] < ext[1] ? 1 : -1; 13 | }); 14 | 15 | return ext.slice(0, k).map((x) => x[0]); 16 | }; -------------------------------------------------------------------------------- /leetcode/problems/js/truncate-sentence.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | const truncateSentence = (s, k) => s = s.trim().split(' ').slice(0, k).join(' ') -------------------------------------------------------------------------------- /leetcode/problems/js/xor-operation-in-an-array.js: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | /** 6 | * @param {number} n 7 | * @param {number} start 8 | * @return {number} 9 | */ 10 | var xorOperation = function (n, start) { 11 | let i, res = start 12 | for (i = 1; i < n; i++) 13 | start += 2, res ^= start 14 | return res 15 | } -------------------------------------------------------------------------------- /leetcode/problems/py/check-if-it-is-a-straight-line.py: -------------------------------------------------------------------------------- 1 | # by @codeAbinash 2 | # Time : O(n) 3 | # Space : O(1) 4 | 5 | class Solution(object): 6 | def checkStraightLine(self, coordinates): 7 | 8 | dx = coordinates[1][0] - coordinates[0][0] 9 | dy = coordinates[1][1] - coordinates[0][1] 10 | 11 | for i in range(2, len(coordinates)): 12 | c_dx = coordinates[i][0] - coordinates[i-1][0] 13 | c_dy = coordinates[i][1] - coordinates[i-1][1] 14 | 15 | if dy * c_dx != dx * c_dy: 16 | return False 17 | 18 | return True -------------------------------------------------------------------------------- /leetcode/problems/py/combinations.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def combine(self, n: int, k: int) -> List[List[int]]: 3 | result = [] 4 | 5 | def rec(start, comb): 6 | if len(comb) == k: 7 | result.append(comb.copy()) 8 | return 9 | for i in range(start, n + 1): 10 | comb.append(i) 11 | rec(i + 1, comb) 12 | comb.pop() 13 | 14 | rec(1,[]) 15 | return result -------------------------------------------------------------------------------- /leetcode/problems/py/decode-xored-array.py: -------------------------------------------------------------------------------- 1 | # by @codeAbinash 2 | # Time : O(n) 3 | # Space : O(1) 4 | 5 | class Solution: 6 | def decode(self, encoded: List[int], first: int) -> List[int]: 7 | decoded = [first] 8 | for i in range(len(encoded)): 9 | decoded.append(encoded[i] ^ decoded[i]) 10 | return decoded 11 | -------------------------------------------------------------------------------- /leetcode/problems/py/find-the-highest-altitude.py: -------------------------------------------------------------------------------- 1 | # by @codeAbinash 2 | # Time : O(n) 3 | # Space : O(1) 4 | 5 | class Solution: 6 | def largestAltitude(self, gain: List[int]) -> int: 7 | altitude, max_altitude = 0, 0 8 | for g in gain: 9 | altitude += g 10 | max_altitude = max(max_altitude, altitude) 11 | return max_altitude 12 | -------------------------------------------------------------------------------- /leetcode/problems/py/hello-world.py: -------------------------------------------------------------------------------- 1 | # A simple hello world program in Python 2 | 3 | 4 | print("Hello World") 5 | 6 | 7 | # Search for Leetcode Solutions 8 | # Paste the link or the name of the problem 9 | # 👆🏻 in the Search Bar 10 | # Hit enter or click the search button 11 | # The solution will be displayed in this section -------------------------------------------------------------------------------- /leetcode/problems/py/left-and-right-sum-differences.py: -------------------------------------------------------------------------------- 1 | # by @codeAbinash 2 | # Time : O(n) 3 | # Space : O(n) 4 | 5 | import functools 6 | 7 | 8 | class Solution: 9 | def leftRightDifference(self, nums: List[int]) -> List[int]: 10 | r_sum = functools.reduce(lambda a, b: a + b, nums) 11 | l_sum = 0 12 | result = [] 13 | for i in range(len(nums)): 14 | r_sum -= nums[i] 15 | result.append(abs(l_sum - r_sum)) 16 | l_sum += nums[i] 17 | return result 18 | -------------------------------------------------------------------------------- /leetcode/problems/py/permutations.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def permute(self, nums): 3 | returnArr = [] 4 | 5 | if len(nums) == 1: 6 | return nums[:] 7 | 8 | for i in range(len(nums)): 9 | num = nums.pop(0) 10 | perms = self.permute(nums) 11 | 12 | for perm in perms: 13 | perm.append(num) 14 | returnArr.extend(perms) 15 | nums.append(num) 16 | return returnArr; -------------------------------------------------------------------------------- /leetcode/problems/py/power-of-two.py: -------------------------------------------------------------------------------- 1 | # by @codeAbinash 2 | # Time : O(1) 3 | # Space : O(1) 4 | 5 | class Solution: 6 | def isPowerOfTwo(self, n: int) -> bool: 7 | return n > 0 and (n & n - 1) === 0 -------------------------------------------------------------------------------- /leetcode/problems/py/single-number.py: -------------------------------------------------------------------------------- 1 | # by @codeAbinash 2 | # Time : O(n) 3 | # Space : O(1) 4 | 5 | class Solution(object): 6 | def singleNumber(self, nums): 7 | for i in range(1, len(nums)): 8 | nums[0] ^= nums[i] 9 | return nums[0] -------------------------------------------------------------------------------- /leetcode/problems/py/triangle.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minimumTotal(self, triangle: List[List[int]]) -> int: 3 | arr = [0] * (len(triangle) + 1) 4 | 5 | for row in triangle[::-1]: 6 | for i, n in enumerate(row): 7 | arr[i] = n + min(arr[i], arr[i+1]) 8 | return arr[0] -------------------------------------------------------------------------------- /leetcode/problems/py/two-sum.py: -------------------------------------------------------------------------------- 1 | def twoSum(self, nums, target): 2 | values = {} 3 | for idx, value in enumerate(nums): 4 | if target - value in values: 5 | return [values[target - value], idx] 6 | else: 7 | values[value] = idx -------------------------------------------------------------------------------- /leetcode/problems/py/xor-operation-in-an-array.py: -------------------------------------------------------------------------------- 1 | # by @codeAbinash 2 | # Time : O(n) 3 | # Space : O(1) 4 | 5 | class Solution: 6 | def xorOperation(self, n: int, start: int) -> int: 7 | res = start; 8 | for i in range(1,n): 9 | res ^= start + 2*i 10 | return res -------------------------------------------------------------------------------- /leetcode/problems/rs/add-two-integers.rs: -------------------------------------------------------------------------------- 1 | pub struct Solution; 2 | 3 | impl Solution { 4 | pub fn sum(num1: i32, num2: i32) -> i32 { 5 | num1 + num2 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /leetcode/problems/rs/binary-search.rs: -------------------------------------------------------------------------------- 1 | pub struct Solution; 2 | 3 | impl Solution { 4 | pub fn search(nums: Vec, target: i32) -> i32 { 5 | let mut left = 0; 6 | let mut right = nums.len() as i32 - 1; 7 | while left <= right { 8 | let mid = (right + left) / 2; 9 | if nums[mid as usize] == target { 10 | return mid; 11 | } else if nums[mid as usize] < target { 12 | left = mid + 1; 13 | } else { 14 | right = mid - 1; 15 | } 16 | } 17 | -1 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /leetcode/problems/rs/find-the-highest-altitude.rs: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | impl Solution { 6 | pub fn largest_altitude(gain: Vec) -> i32 { 7 | let mut altitude = 0; 8 | let mut max_altitude = 0; 9 | for i in gain { 10 | altitude += i; 11 | max_altitude = max_altitude.max(altitude); 12 | } 13 | max_altitude 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /leetcode/problems/rs/find-the-maximum-achievable-number.rs: -------------------------------------------------------------------------------- 1 | pub struct Solution; 2 | 3 | impl Solution { 4 | pub fn the_maximum_achievable_x(num: i32, t: i32) -> i32 { 5 | t * 2 + num 6 | } 7 | } -------------------------------------------------------------------------------- /leetcode/problems/rs/group-anagram.rs: -------------------------------------------------------------------------------- 1 | pub struct Solution; 2 | 3 | impl Solution { 4 | pub fn group_anagrams(strs: Vec) -> Vec> { 5 | use std::collections::HashMap; 6 | let mut map: HashMap, Vec> = HashMap::new(); 7 | for s in strs { 8 | let mut key = s.as_bytes().to_vec(); 9 | key.sort(); 10 | map.entry(key).or_insert(Vec::new()).push(s); 11 | } 12 | map.into_iter().map(|(_, v)| v).collect() 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /leetcode/problems/rs/hello-world.rs: -------------------------------------------------------------------------------- 1 | // A simple hello world program in Rust 2 | 3 | 4 | fn main() { 5 | println!("Hello, world!"); 6 | } 7 | 8 | 9 | // Search for Leetcode Solutions 10 | // Paste the link or the name of the problem 11 | // 👆🏻 in the Search Bar 12 | // Hit enter or click the search button 13 | // The solution will be displayed in this section -------------------------------------------------------------------------------- /leetcode/problems/rs/jewels-and-stones.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | impl Solution { 4 | pub fn num_jewels_in_stones(jewels: String, stones: String) -> i32 { 5 | let mut map = HashMap::new(); 6 | let mut count = 0; 7 | for c in jewels.chars() { 8 | map.insert(c, 0); 9 | } 10 | for c in stones.chars() { 11 | if map.contains_key(&c) { 12 | count += 1; 13 | } 14 | } 15 | count 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /leetcode/problems/rs/minimum-sum-of-four-digit-number-after-splitting-digits.rs: -------------------------------------------------------------------------------- 1 | pub struct Solution; 2 | 3 | impl Solution { 4 | pub fn minimum_sum(num: i32) -> i32 { 5 | let d = num % 10; 6 | let c = ((num - d) % 100) / 10; 7 | let b = ((num - c - d) % 1000) / 100; 8 | let a = (num - b - c - d) / 1000; 9 | 10 | ((a + c) * 10 + b + d) 11 | .min((a + b) * 10 + c + d) 12 | .min((a + d) * 10 + b + c) 13 | .min((b + c) * 10 + a + d) 14 | .min((b + d) * 10 + a + c) 15 | .min((c + d) * 10 + a + b) 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /leetcode/problems/rs/number-of-even-and-odd-bits.rs: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | impl Solution { 6 | pub fn even_odd_bit(n: i32) -> Vec { 7 | let mut ans = vec![0; 2]; 8 | let mut n = n; 9 | let mut i = 0; 10 | while n > 0 { 11 | ans[i] += n & 1; 12 | n >>= 1; 13 | i ^= 1; 14 | } 15 | ans 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /leetcode/problems/rs/product-of-array-except-self.rs: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | impl Solution { 6 | pub fn product_except_self(nums: Vec) -> Vec { 7 | let n = nums.len(); 8 | let mut left = 1; 9 | let mut right = 1; 10 | let mut result = vec![1; n]; 11 | 12 | for i in 0..n { 13 | result[i] *= left; 14 | left *= nums[i]; 15 | result[n - 1 - i] *= right; 16 | right *= nums[n - 1 - i]; 17 | } 18 | result 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /leetcode/problems/rs/running-sum-of-1d-array.rs: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(n) 4 | 5 | impl Solution { 6 | pub fn running_sum(nums: Vec) -> Vec { 7 | let mut result = Vec::with_capacity(nums.len()); 8 | let mut sum = 0; 9 | for num in nums { 10 | sum += num; 11 | result.push(sum); 12 | } 13 | result 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /leetcode/problems/rs/smallest-even-multiple.rs: -------------------------------------------------------------------------------- 1 | pub struct Solution; 2 | 3 | impl Solution { 4 | pub fn smallest_even_multiple(n: i32) -> i32 { 5 | if n % 2 == 0 { 6 | n 7 | } else { 8 | n * 2 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /leetcode/problems/rs/subtract-the-product-and-sum-of-digits-of-an-integer.rs: -------------------------------------------------------------------------------- 1 | pub struct Solution; 2 | 3 | impl Solution { 4 | pub fn subtract_product_and_sum(n: i32) -> i32 { 5 | let mut product = 1; 6 | let mut sum = 0; 7 | let mut num = n; 8 | 9 | while num > 0 { 10 | let digit = num % 10; 11 | product *= digit; 12 | sum += digit; 13 | num /= 10; 14 | } 15 | 16 | product - sum 17 | 18 | } 19 | } -------------------------------------------------------------------------------- /leetcode/problems/rs/two-sum-ii-input-array-is-sorted.rs: -------------------------------------------------------------------------------- 1 | pub struct Solution; 2 | 3 | impl Solution { 4 | pub fn two_sum(numbers: Vec, target: i32) -> Vec { 5 | let mut l = 0; 6 | let mut r = numbers.len() - 1; 7 | 8 | while l < r { 9 | let num = numbers[l] + numbers[r]; 10 | if num > target { 11 | r -= 1; 12 | } else if num < target { 13 | l += 1; 14 | } else { 15 | return vec![(l + 1) as i32, (r + 1) as i32]; 16 | } 17 | } 18 | 19 | unreachable!(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /leetcode/problems/rs/two-sum.rs: -------------------------------------------------------------------------------- 1 | pub struct Solution; 2 | 3 | use std::collections::HashMap; 4 | 5 | 6 | impl Solution { 7 | pub fn two_sum(nums: Vec, target: i32) -> Vec { 8 | let mut map = HashMap::new(); 9 | 10 | for (i, num) in nums.into_iter().enumerate() { 11 | let diff = target - num; 12 | 13 | if let Some(&j) = map.get(&diff) { 14 | return vec![i as i32, j as i32]; 15 | } else { 16 | map.insert(num, i); 17 | } 18 | } 19 | 20 | unreachable!() 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /leetcode/problems/rs/valid-anagram.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | pub struct Solution; 3 | 4 | 5 | impl Solution { 6 | pub fn is_anagram(s: String, t: String) -> bool { 7 | if s.len() != t.len() { 8 | return false; 9 | }; 10 | 11 | let mut map: HashMap = HashMap::new(); 12 | 13 | for (a, b) in s.chars().zip(t.chars()) { 14 | *map.entry(a).or_default() += 1; 15 | *map.entry(b).or_default() -= 1; 16 | } 17 | 18 | map.into_values().all(|count| count == 0) 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /leetcode/problems/sql/combine-two-tables.sql: -------------------------------------------------------------------------------- 1 | SELECT 2 | p.firstName, 3 | p.lastName, 4 | a.city, 5 | a.state 6 | FROM 7 | Person p 8 | LEFT JOIN 9 | Address a ON p.personId = a.personId; -------------------------------------------------------------------------------- /leetcode/problems/ts/add-two-promises.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | async function addTwoPromises(promise1: Promise, promise2: Promise): Promise { 6 | const [num1, num2] = await Promise.all([promise1, promise2]); 7 | return num1 + num2; 8 | }; -------------------------------------------------------------------------------- /leetcode/problems/ts/allow-one-function-call.ts: -------------------------------------------------------------------------------- 1 | //by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | type Fn = (...args: any[]) => any 6 | 7 | function once(fn: Fn): Fn { 8 | let called = false 9 | return function (...args) { 10 | if(!called){ 11 | called = true 12 | return fn(...args) 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /leetcode/problems/ts/apply-transform-over-each-element-in-array.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(n) 4 | 5 | function map(arr: number[], fn: (n: number, i: number) => number): number[] { 6 | const len = arr.length 7 | const transformedArray: number[] = [] 8 | for (let i = 0; i < len; i++) 9 | transformedArray[i] = fn(arr[i], i) 10 | return transformedArray 11 | }; -------------------------------------------------------------------------------- /leetcode/problems/ts/array-prototype-last.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | declare global { 6 | interface Array { 7 | last(): T | -1; 8 | } 9 | } 10 | 11 | Array.prototype.last = function () { 12 | const len = this.length 13 | if (len) 14 | return this[len - 1] 15 | return -1 16 | }; 17 | 18 | /** 19 | * const arr = [1, 2, 3]; 20 | * arr.last(); // 3 21 | */ 22 | 23 | export { }; 24 | -------------------------------------------------------------------------------- /leetcode/problems/ts/array-reduce-transformation.ts: -------------------------------------------------------------------------------- 1 | //// by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | type Fn = (accum: number, curr: number) => number 6 | 7 | function reduce(nums: number[], fn: Fn, init: number): number { 8 | let val = init 9 | nums.forEach(num => { val = fn(val, num) }) 10 | return val 11 | }; -------------------------------------------------------------------------------- /leetcode/problems/ts/array-wrapper.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | class ArrayWrapper { 6 | nums: number[] 7 | constructor(nums: number[]) { 8 | this.nums = nums 9 | } 10 | 11 | valueOf() { 12 | return this.nums.reduce((acc, curr) => acc + curr, 0) 13 | } 14 | 15 | toString() { 16 | return JSON.stringify(this.nums) 17 | } 18 | }; -------------------------------------------------------------------------------- /leetcode/problems/ts/call-function-with-custom-context.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | declare global { 4 | interface Function { 5 | callPolyfill(context: Record, ...args: any[]): any; 6 | } 7 | } 8 | 9 | Function.prototype.callPolyfill = function (context, ...args): any { 10 | const fn = this 11 | Object.defineProperty(context, '_fn', { 12 | value: fn, 13 | enumerable: false 14 | }); 15 | return context._fn(...args); 16 | } 17 | 18 | /** 19 | * function increment() { this.count++; return this.count; } 20 | * increment.callPolyfill({count: 1}); // 2 21 | */ -------------------------------------------------------------------------------- /leetcode/problems/ts/chunk-array.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | function chunk(arr: any[], size: number): any[][] { 4 | const result: any[][] = [] 5 | const len = arr.length 6 | 7 | for (let i = 0; i < len; i += size) 8 | result.push(arr.slice(i, i + size)) 9 | 10 | return result 11 | }; -------------------------------------------------------------------------------- /leetcode/problems/ts/counter-ii.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | type ReturnObj = { 6 | increment: () => number, 7 | decrement: () => number, 8 | reset: () => number, 9 | } 10 | 11 | function createCounter(init: number): ReturnObj { 12 | const count = init 13 | return { 14 | increment: () => ++init, 15 | decrement: () => --init, 16 | reset: () => init = count 17 | } 18 | }; 19 | 20 | /** 21 | * const counter = createCounter(5) 22 | * counter.increment(); // 6 23 | * counter.reset(); // 5 24 | * counter.decrement(); // 4 25 | */ -------------------------------------------------------------------------------- /leetcode/problems/ts/counter.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | function createCounter(n: number): () => number { 6 | return () => n++ 7 | } 8 | 9 | 10 | /** 11 | * const counter = createCounter(10) 12 | * counter() // 10 13 | * counter() // 11 14 | * counter() // 12 15 | */ -------------------------------------------------------------------------------- /leetcode/problems/ts/create-hello-world-function.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | function createHelloWorld(): Function { 6 | return (): string => "Hello World" 7 | }; 8 | 9 | /** 10 | * const f = createHelloWorld(); 11 | * f(); // "Hello World" 12 | */ -------------------------------------------------------------------------------- /leetcode/problems/ts/debounce.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | type F = (...p: any[]) => any 4 | 5 | function debounce(fn: F, t: number): F { 6 | let timer 7 | return function (...args) { 8 | clearTimeout(timer) 9 | timer = setTimeout(() => fn(...args), t) 10 | } 11 | } -------------------------------------------------------------------------------- /leetcode/problems/ts/decode-xored-array.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | function decode(encoded: number[], first: number): number[] { 6 | let arr = [first]; 7 | let size = encoded.length 8 | for (let i = 0; i < size; i++) 9 | arr.push(encoded[i] ^ arr[i]) 10 | return arr 11 | } -------------------------------------------------------------------------------- /leetcode/problems/ts/execute-cancellable-function-with-delay.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | function cancellable(fn: Function, args: any[], t: number): Function { 6 | const timer = setTimeout(() => fn(...args), t) 7 | return () => clearTimeout(timer) 8 | } -------------------------------------------------------------------------------- /leetcode/problems/ts/filter-elements-from-array.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(n) 4 | 5 | function filter(arr: number[], fn: (n: number, i: number) => any): number[] { 6 | const len = arr.length 7 | const filtered: number[] = [] 8 | 9 | for (let i = 0; i < len; i++) 10 | if (fn(arr[i], i)) 11 | filtered.push(arr[i]) 12 | return filtered 13 | }; -------------------------------------------------------------------------------- /leetcode/problems/ts/find-the-highest-altitude.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | function largestAltitude(gain: number[]): number { 6 | let altitude = 0 7 | let max = 0 8 | for (let g of gain) { 9 | altitude += g 10 | max = Math.max(max, altitude) 11 | } 12 | return max 13 | } 14 | -------------------------------------------------------------------------------- /leetcode/problems/ts/function-composition.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | type F = (x: number) => number; 6 | 7 | function compose(functions: F[]): F { 8 | return function (x) { 9 | let val = x 10 | let len = functions.length 11 | while (len--) { 12 | val = functions[len](val) 13 | } 14 | return val 15 | } 16 | } -------------------------------------------------------------------------------- /leetcode/problems/ts/generate-fibonacci-sequence.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | 3 | function* fibGenerator(): Generator { 4 | let a = 0; 5 | let b = 1; 6 | while (true) { 7 | yield a; 8 | const tmp = a; 9 | a = b; 10 | b += tmp; 11 | } 12 | }; -------------------------------------------------------------------------------- /leetcode/problems/ts/group-anagrams.ts: -------------------------------------------------------------------------------- 1 | function groupAnagrams(strs: string[]): string[][] { 2 | let map = new Map(); 3 | for (let str of strs) { 4 | let sortedStr = str.split('').sort().join(''); 5 | if (!map.has(sortedStr)) { 6 | map.set(sortedStr, []); 7 | } 8 | map.get(sortedStr)?.push(str); 9 | } 10 | return Array.from(map.values()); 11 | }; -------------------------------------------------------------------------------- /leetcode/problems/ts/group-by.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(n) 4 | 5 | declare global { 6 | interface Array { 7 | groupBy(fn: (item: T) => string): Record 8 | } 9 | } 10 | 11 | Array.prototype.groupBy = function (fn) { 12 | const answer = {}; 13 | for (const item of this) { 14 | const key = fn(item) 15 | if (key in answer) 16 | answer[key].push(item) 17 | else 18 | answer[key] = [item] 19 | } 20 | return answer 21 | } 22 | 23 | /** 24 | * [1,2,3].groupBy(String) // {"1":[1],"2":[2],"3":[3]} 25 | */ -------------------------------------------------------------------------------- /leetcode/problems/ts/hello-world.ts: -------------------------------------------------------------------------------- 1 | // A simple hello world program in TypeScript 2 | 3 | 4 | console.log("Hello World") 5 | 6 | 7 | // Search for Leetcode Solutions 8 | // Paste the link or the name of the problem 9 | // 👆🏻 in the Search Bar 10 | // Hit enter or click the search button 11 | // The solution will be displayed in this section -------------------------------------------------------------------------------- /leetcode/problems/ts/interval-cancellation.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | function cancellable(fn: Function, args: any[], t: number): Function { 6 | const executable = () => fn(...args) 7 | const timer = setInterval(executable, t) 8 | const cancel = () => clearInterval(timer) 9 | executable() 10 | return cancel 11 | } -------------------------------------------------------------------------------- /leetcode/problems/ts/is-object-empty.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | function isEmpty(obj: Record | any[]): boolean { 6 | return Object.keys(obj).length === 0; 7 | }; -------------------------------------------------------------------------------- /leetcode/problems/ts/join-two-arrays-by-id.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(n) 4 | 5 | function join(arr1: any[], arr2: any[]): any[] { 6 | const result: any[] = [] 7 | for (let i = 0; i < arr1.length; i++) 8 | result[arr1[i].id] = arr1[i] 9 | 10 | for (let i = 0; i < arr2.length; i++) { 11 | if (result[arr2[i].id]) 12 | for (const key in arr2[i]) 13 | result[arr2[i].id][key] = arr2[i][key] 14 | else 15 | result[arr2[i].id] = arr2[i] 16 | } 17 | 18 | return Object.values(result) 19 | } -------------------------------------------------------------------------------- /leetcode/problems/ts/maximum-depth-of-n-ary-tree.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(n) 4 | 5 | class Node { 6 | val: number; 7 | children: Node[]; 8 | constructor(val?: number, children?: Node[]) { 9 | this.val = val === undefined ? 0 : val; 10 | this.children = children === undefined ? [] : children; 11 | } 12 | } 13 | 14 | function maxDepth(root: Node | null): number { 15 | if (!root) return 0; 16 | let max = 0; 17 | for (let child of root.children) max = Math.max(max, maxDepth(child)); 18 | return max + 1; 19 | } 20 | -------------------------------------------------------------------------------- /leetcode/problems/ts/memoize.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(n) 4 | 5 | type Fn = (...params: any) => any 6 | 7 | function memoize(fn: Fn): Fn { 8 | const cache = new Map() 9 | return function (...args) { 10 | const key = args.toString() 11 | if (cache.has(key)) 12 | return cache.get(key) 13 | 14 | const result = fn(...args) 15 | cache.set(key, result) 16 | return result 17 | } 18 | } -------------------------------------------------------------------------------- /leetcode/problems/ts/nested-array-generator.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(n) 4 | 5 | type MultidimensionalArray = (MultidimensionalArray | number)[] 6 | 7 | function* inorderTraversal(arr: MultidimensionalArray): Generator { 8 | for (const item of arr) { 9 | if (Array.isArray(item)) 10 | yield* inorderTraversal(item) 11 | else 12 | yield item 13 | } 14 | }; -------------------------------------------------------------------------------- /leetcode/problems/ts/number-of-1-bits.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | function hammingWeight(n: number): number { 6 | let count = 0; 7 | for (let i = 0; i < 32; i++) { 8 | if (n & 1) 9 | count++; 10 | n = n >> 1; 11 | } 12 | return count; 13 | }; -------------------------------------------------------------------------------- /leetcode/problems/ts/power-of-two.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | function isPowerOfTwo(n: number): boolean { 6 | return n > 0 && (n & n - 1) === 0 7 | }; -------------------------------------------------------------------------------- /leetcode/problems/ts/promise-time-limit.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | type Fn = (...params: any[]) => Promise; 6 | 7 | function timeLimit(fn: Fn, t: number): Fn { 8 | return async (...args) => new Promise((res, rej) => { 9 | setTimeout(() => rej("Time Limit Exceeded"), t); 10 | fn(...args).then(res).catch(rej) 11 | }) 12 | }; -------------------------------------------------------------------------------- /leetcode/problems/ts/return-length-of-arguments-passed.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | 6 | function argumentsLength(...args: any[]): number { 7 | return arguments.length 8 | } -------------------------------------------------------------------------------- /leetcode/problems/ts/running-sum-of-1d-array.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | function runningSum(nums: number[]): number[] { 6 | for (let i = 1; i < nums.length; i++) 7 | nums[i] = nums[i] + nums[i - 1] 8 | return nums 9 | } 10 | -------------------------------------------------------------------------------- /leetcode/problems/ts/single-number.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | function singleNumber(nums: number[]): number { 6 | let result = nums[0] 7 | let len = nums.length; 8 | for (let i = 1; i < len; i++) 9 | result ^= nums[i] 10 | return result 11 | } -------------------------------------------------------------------------------- /leetcode/problems/ts/sleep.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(1) 3 | // Space : O(1) 4 | 5 | async function sleep(millis: number): Promise { 6 | return new Promise(res => setTimeout(res, millis)) 7 | } -------------------------------------------------------------------------------- /leetcode/problems/ts/sort-by.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(log n) 3 | // Space : O(n) 4 | 5 | function sortBy(arr: any[], fn: Function): any[] { 6 | return arr.sort((a, b) => fn(a) - fn(b)); 7 | }; -------------------------------------------------------------------------------- /leetcode/problems/ts/xor-operation-in-an-array.ts: -------------------------------------------------------------------------------- 1 | // by @codeAbinash 2 | // Time : O(n) 3 | // Space : O(1) 4 | 5 | function xorOperation(n: number, start: number): number { 6 | let res = start 7 | for (let i = 1; i < n; i++) 8 | start += 2, res ^= start 9 | return res 10 | } -------------------------------------------------------------------------------- /leetcode/problems/txt/hello-world.txt: -------------------------------------------------------------------------------- 1 | A Simple Hello World Program --------------------------------------------------------------------------------