├── .gitignore ├── 002. Add Two Numbers ├── add-two-numbers-1.cpp ├── add-two-numbers-2.cpp ├── add-two-numbers-3.cpp ├── add-two-numbers-4.cpp ├── add-two-numbers-5.cpp ├── add-two-numbers-6.cpp ├── add-two-numbers-7.cpp ├── add-two-numbers-8.cpp └── add-two-numbers-9.cpp ├── 01-matrix-1.cpp ├── 015. 3Sum ├── 3sum-1.cpp ├── 3sum-2.cpp ├── 3sum-3.cpp ├── 3sum-4.cpp ├── 3sum-5.cpp └── 3sum-6.cpp ├── 046. Permutations ├── permutations-1.cpp ├── permutations-2.cpp ├── permutations-3.cpp ├── permutations-4.cpp └── permutations-recur.cpp ├── 047. Permutations II ├── Missing Case Finding.ipynb ├── permutations-ii-1.cpp ├── permutations-ii-2.cpp ├── permutations-ii-3.cpp └── permutations-ii-4.cpp ├── 056. Merge Intervals ├── merge-intervals-1.cpp ├── merge-intervals-2.cpp ├── merge-intervals-3.cpp ├── merge-intervals-4.cpp ├── merge-intervals-5.cpp ├── merge-intervals-6.cpp └── merge-intervals.cpp ├── 067. Add Binary ├── add-binary-1.cpp ├── add-binary-2.cpp ├── add-binary-3.cpp ├── add-binary-4.cpp ├── add-binary-5.cpp └── add-binary.cpp ├── 098. Validate Binary Search Tree ├── validate-binary-search-tree-1.cpp ├── validate-binary-search-tree-10.cpp ├── validate-binary-search-tree-2.cpp ├── validate-binary-search-tree-3.cpp ├── validate-binary-search-tree-4.cpp ├── validate-binary-search-tree-5.cpp ├── validate-binary-search-tree-6.cpp ├── validate-binary-search-tree-7.cpp ├── validate-binary-search-tree-8.cpp └── validate-binary-search-tree-9.cpp ├── 126. Word Ladder II ├── word-ladder-ii-1.cpp ├── word-ladder-ii-2.cpp └── word-ladder-ii-3.cpp ├── 127. Word Ladder ├── word-ladder-1.cpp ├── word-ladder-2.cpp ├── word-ladder-3.cpp ├── word-ladder-4.cpp └── word-ladder-5.cpp ├── 139. Word Break ├── word-break-0.cpp ├── word-break-1.cpp ├── word-break-2.cpp ├── word-break-3.cpp ├── word-break-4.cpp └── word-break-6.cpp ├── 141. Linked List Cycle ├── linked-list-cycle-1.cpp ├── linked-list-cycle-2.cpp ├── linked-list-cycle-3.cpp ├── linked-list-cycle-4.cpp ├── linked-list-cycle-5.cpp ├── linked-list-cycle-6.cpp └── linked-list-cycle.cpp ├── 146. LRU Cache ├── lru-cache-1.cpp ├── lru-cache-2.cpp ├── lru-cache-3.cpp ├── lru-cache-4.cpp ├── lru-cache-5.cpp └── lru-cache-6.cpp ├── 2-keys-keyboard-1.cpp ├── 2-keys-keyboard.cpp ├── 200. Number of Islands ├── number-of-islands-1.cpp ├── number-of-islands-2.cpp ├── number-of-islands-3.cpp ├── number-of-islands-4.cpp ├── number-of-islands-5.cpp ├── number-of-islands-6.cpp ├── number-of-islands-7.cpp ├── number-of-islands-8.cpp └── number-of-islands-9.cpp ├── 286. Walls and Gates ├── walls-and-gates-1.cpp └── walls-and-gates-2.cpp ├── 297. Serialize and Deserialize Binary Tree ├── serialize-and-deserialize-binary-tree-2.cpp ├── serialize-and-deserialize-binary-tree-3.cpp ├── serialize-and-deserialize-binary-tree-4.cpp ├── serialize-and-deserialize-binary-tree-5.cpp └── serialize-and-deserialize-binary-tree.cpp ├── 301. Remove Invalid Parantheses ├── remove-invalid-parentheses-1.cpp ├── remove-invalid-parentheses-2.cpp ├── remove-invalid-parentheses-3.cpp └── remove-invalid-parentheses-4.cpp ├── 353. Design Snake Game └── design-snake-game-1.cpp ├── 3sum-closest-1.cpp ├── 3sum-closest.cpp ├── 3sum.cpp ├── 4Sum.cpp ├── 4sum-1.cpp ├── 4sum-ii.cpp ├── 652. Find Duplicate Subtrees └── find-duplicate-subtrees-1.cpp ├── 655. Print Binary Tree ├── print-binary-tree-1.cpp └── print-binary-tree-2.cpp ├── 679. 24 Game └── 24-game-1.cpp ├── 934. Shortest Bridge └── shortest-bridge-1.cpp ├── README.md ├── accounts-merge-1.cpp ├── add-and-search-word-data-structure-design-1.cpp ├── add-digits-1.cpp ├── add-digits-2.cpp ├── add-one-row-to-tree-1.cpp ├── add-strings.cpp ├── add-two-numbers-ii-1.cpp ├── add-two-numbers-ii-2.cpp ├── add-two-numbers-ii-3.cpp ├── add-two-numbers-ii-4.cpp ├── add-two-numbers-ii.cpp ├── add-two-numbers.cpp ├── alien-dictionary-1.cpp ├── alien-dictionary-2.cpp ├── all-nodes-distance-k-in-binary-tree-1.cpp ├── all-nodes-distance-k-in-binary-tree-2.cpp ├── all-paths-from-source-to-target-1.cpp ├── arithmetic-slices-1.cpp ├── arithmetic-slices.cpp ├── arranging-coins-2.cpp ├── array-nesting-1.cpp ├── array-nesting.cpp ├── average-of-levels-in-binary-tree-1.cpp ├── average-of-levels-in-binary-tree-2.cpp ├── balanced-binary-tree-1.cpp ├── balanced-binary-tree-2.cpp ├── balanced-binary-tree.cpp ├── basic-calculator-1.cpp ├── basic-calculator-ii-1.cpp ├── basic-calculator-ii-2.cpp ├── battleships-in-a-board.cpp ├── beautiful-arrangement-ii-1.cpp ├── beautiful-arrangement-ii-2.cpp ├── beautiful-arrangement.cpp ├── best-time-to-buy-and-sell-stock-1.cpp ├── best-time-to-buy-and-sell-stock-2.cpp ├── best-time-to-buy-and-sell-stock-3.cpp ├── best-time-to-buy-and-sell-stock-4.cpp ├── best-time-to-buy-and-sell-stock-5.cpp ├── best-time-to-buy-and-sell-stock-6.cpp ├── best-time-to-buy-and-sell-stock-ii-1.cpp ├── best-time-to-buy-and-sell-stock-ii.cpp ├── best-time-to-buy-and-sell-stock-with-cooldown-1.cpp ├── best-time-to-buy-and-sell-stock-with-cooldown.cpp ├── best-time-to-buy-and-sell-stock-with-transaction-fee-1.cpp ├── best-time-to-buy-and-sell-stock-with-transaction-fee-2.cpp ├── best-time-to-buy-and-sell-stock-with-transaction-fee-3.cpp ├── best-time-to-buy-and-sell-stock-with-transaction-fee.cpp ├── best-time-to-buy-and-sell-stock.cpp ├── binary-gap-1.cpp ├── binary-number-with-alternating-bits.cpp ├── binary-search-tree-iterator-1.cpp ├── binary-search-tree-iterator-2.cpp ├── binary-tree-inorder-traversal-1.cpp ├── binary-tree-inorder-traversal-2.cpp ├── binary-tree-inorder-traversal.cpp ├── binary-tree-level-order-traversal-1.cpp ├── binary-tree-level-order-traversal-2.cpp ├── binary-tree-level-order-traversal-3.cpp ├── binary-tree-level-order-traversal-4.cpp ├── binary-tree-level-order-traversal-6.cpp ├── binary-tree-level-order-traversal-ii-1.cpp ├── binary-tree-level-order-traversal-ii-2.cpp ├── binary-tree-level-order-traversal-ii-3.cpp ├── binary-tree-level-order-traversal-ii-4.cpp ├── binary-tree-level-order-traversal.cpp ├── binary-tree-maximum-path-sum-1.cpp ├── binary-tree-paths-1.cpp ├── binary-tree-paths-2.cpp ├── binary-tree-paths-3.cpp ├── binary-tree-paths-4.cpp ├── binary-tree-postorder-traversal-1.cpp ├── binary-tree-postorder-traversal-2.cpp ├── binary-tree-postorder-traversal-3.cpp ├── binary-tree-postorder-traversal-4.cpp ├── binary-tree-postorder-traversal-5.cpp ├── binary-tree-preorder-traversal-1.cpp ├── binary-tree-preorder-traversal-2.cpp ├── binary-tree-preorder-traversal.cpp ├── binary-tree-pruning-1.cpp ├── binary-tree-right-side-view-1.cpp ├── binary-tree-right-side-view-2.cpp ├── binary-tree-right-side-view-3.cpp ├── binary-tree-right-side-view-4.cpp ├── binary-tree-right-side-view-5.cpp ├── binary-tree-tilt-1.cpp ├── binary-tree-vertical-order-traversal-1.cpp ├── binary-tree-vertical-order-traversal-2.cpp ├── binary-tree-vertical-order-traversal-3.cpp ├── binary-tree-vertical-order-traversal-4.cpp ├── binary-tree-zigzag-level-order-traversal-1.cpp ├── binary-tree-zigzag-level-order-traversal-2.cpp ├── binary-tree-zigzag-level-order-traversal-3.cpp ├── binary-tree-zigzag-level-order-traversal.cpp ├── bomb-enemy.cpp ├── burst-balloons.cpp ├── bus-routes-1.cpp ├── can-place-flowers.cpp ├── cheapest-flights-within-k-stops-1.cpp ├── cheapest-flights-within-k-stops-2.cpp ├── climbing-stairs-1.cpp ├── climbing-stairs-2.cpp ├── climbing-stairs-3.cpp ├── climbing-stairs-4.cpp ├── climbing-stairs.cpp ├── clone-graph-1.cpp ├── clone-graph-2.cpp ├── clone-graph-3.cpp ├── closest-binary-search-tree-value.cpp ├── closest-leaf-in-a-binary-tree.cpp ├── coin-change-1.cpp ├── coin-change.cpp ├── combination-sum-ii.cpp ├── combination-sum-iii.cpp ├── combination-sum-iv-1.cpp ├── combination-sum-iv-2.cpp ├── combination-sum-iv-3.cpp ├── combination-sum.cpp ├── compare-version-numbers-1.cpp ├── compare-version-numbers-2.cpp ├── complex-number-multiplication.cpp ├── construct-binary-tree-from-inorder-and-postorder-traversal-1.cpp ├── construct-binary-tree-from-preorder-and-inorder-traversal-1.cpp ├── construct-string-from-binary-tree-1.cpp ├── construct-string-from-binary-tree-2.cpp ├── container-with-most-water-1.cpp ├── container-with-most-water-2.cpp ├── container-with-most-water.cpp ├── contains-duplicate-1.cpp ├── contains-duplicate-ii.cpp ├── contiguous-array-1.cpp ├── contiguous-array-2.cpp ├── contiguous-array-3.cpp ├── continuous-subarray-sum-1.cpp ├── continuous-subarray-sum.cpp ├── convert-binary-search-tree-to-sorted-doubly-linked-list-1.cpp ├── convert-binary-search-tree-to-sorted-doubly-linked-list-2.cpp ├── convert-bst-to-greater-tree-1.cpp ├── convert-bst-to-greater-tree-2.cpp ├── convert-sorted-array-to-binary-search-tree-1.cpp ├── convert-sorted-array-to-binary-search-tree-2.cpp ├── convert-sorted-array-to-binary-search-tree-3.cpp ├── convert-sorted-array-to-binary-search-tree.cpp ├── convert-sorted-list-to-binary-search-tree.cpp ├── copy-list-with-random-pointer-1.cpp ├── copy-list-with-random-pointer-2.cpp ├── copy-list-with-random-pointer-3.cpp ├── copy-list-with-random-pointer-4.cpp ├── count-and-say-1.cpp ├── count-and-say.cpp ├── count-binary-strings.cpp ├── count-complete-tree-nodes-1.cpp ├── count-complete-tree-nodes-2.cpp ├── count-complete-tree-nodes.cpp ├── count-numbers-with-unique-digits-1.cpp ├── count-primes-1.cpp ├── counting-bits-1.cpp ├── counting-bits.cpp ├── couples-holding-hands.cpp ├── course-schedule-1.cpp ├── course-schedule-2.cpp ├── course-schedule-3.cpp ├── course-schedule-4.cpp ├── course-schedule-5.cpp ├── course-schedule-ii-1.cpp ├── course-schedule-ii-2.cpp ├── course-schedule-ii-3.cpp ├── course-schedule-ii-4.cpp ├── course-schedule-ii-5.cpp ├── course-schedule-ii-6.cpp ├── custom-sort-string-1.cpp ├── daily-temperatures.cpp ├── decode-string-1.cpp ├── decode-string-2.cpp ├── decode-ways-1.cpp ├── decode-ways-2.cpp ├── decode-ways-3.cpp ├── decode=ways.cpp ├── delete-and-earn-1.cpp ├── delete-and-earn-2.cpp ├── delete-node-in-a-bst-1.cpp ├── delete-node-in-a-linked-list-1.cpp ├── delete-node-in-a-linked-list-2.cpp ├── delete-node-in-a-linked-list.cpp ├── design-hit-counter-1.cpp ├── design-hit-counter-2.cpp ├── diameter-of-binary-tree-1.cpp ├── diameter-of-binary-tree-2.cpp ├── different-ways-to-add-parentheses.cpp ├── divide-two-integers-1.cpp ├── divide-two-integers-2.cpp ├── divide-two-integers-3.cpp ├── edit-distance.cpp ├── employee-importance-1.cpp ├── employee-importance.cpp ├── evaluate-division-1.cpp ├── evaluate-reverse-polish-notation.cpp ├── excel-sheet-column-number-1.cpp ├── excel-sheet-column-number.cpp ├── excel-sheet-column-title-1.cpp ├── excel-sheet-column-title-2.cpp ├── exclusive-time-of-functions-1.cpp ├── exclusive-time-of-functions-2.cpp ├── exclusive-time-of-functions-3.cpp ├── factorial-trailing-zeroes.cpp ├── find-all-anagrams-in-a-string-1.cpp ├── find-all-anagrams-in-a-string.cpp ├── find-all-duplicates-in-an-array-1.cpp ├── find-all-duplicates-in-an-array-2.cpp ├── find-all-numbers-disappeared-in-an-array.cpp ├── find-anagram-mappings.cpp ├── find-bottom-left-tree-value-1.cpp ├── find-bottom-left-tree-value-2.cpp ├── find-bottom-left-tree-value-3.cpp ├── find-bottom-left-tree-value-4.cpp ├── find-duplicate-file-in-system-1.cpp ├── find-eventual-safe-states-1.cpp ├── find-first-and-last-position-of-element-in-sorted-array-1.cpp ├── find-k-closest-elements.cpp ├── find-k-pairs-with-smallest-sums.cpp ├── find-largest-value-in-each-tree-row-1.cpp ├── find-largest-value-in-each-tree-row-2.cpp ├── find-median-from-data-stream-1.cpp ├── find-median-from-data-stream-2.cpp ├── find-minimum-in-rotated-sorted-array-1.cpp ├── find-minimum-in-rotated-sorted-array-2.cpp ├── find-minimum-in-rotated-sorted-array-ii.cpp ├── find-minimum-in-rotated-sorted-array-iter.cpp ├── find-minimum-in-rotated-sorted-array-recur.cpp ├── find-mode-in-binary-search-tree-1.cpp ├── find-peak-element.py ├── find-pivot-index-1.cpp ├── find-pivot-index-2.cpp ├── find-pivot-index1.cpp ├── find-pivot-index2.cpp ├── find-right-interval.cpp ├── find-smallest-letter-greater-than-target.cpp ├── find-the-celebrity-1.cpp ├── find-the-celebrity-2.cpp ├── find-the-celebrity-3.cpp ├── find-the-difference.cpp ├── find-the-duplicate-number-1.cpp ├── find-the-duplicate-number-2.cpp ├── first-bad-version-1.cpp ├── first-bad-version-2.cpp ├── first-bad-version.cpp ├── first-unique-character-in-a-string-1.cpp ├── first-unique-character-in-a-string-2.cpp ├── first-unique-character-in-a-string-3.cpp ├── first-unique-character-in-a-string-4.cpp ├── fizz-buzz-1.cpp ├── fizz-buzz.cpp ├── flatten-binary-tree-to-linked-list-1.cpp ├── flatten-binary-tree-to-linked-list-2.cpp ├── flatten-binary-tree-to-linked-list-3.cpp ├── flatten-nested-list-iterator-1.cpp ├── flatten-nested-list-iterator-2.cpp ├── flatten-nested-list-iterator-3.cpp ├── flip-game.cpp ├── flipping-an-image.cpp ├── flood-fill-1.cpp ├── flood-fill-2.cpp ├── fraction-to-recurring-decimal-1.cpp ├── friends-circles-1.cpp ├── friends-circles-2.cpp ├── frog-jump-1.cpp ├── frog-jump-2.cpp ├── game-of-life-1.cpp ├── game-of-life-2.cpp ├── game-of-life-3.cpp ├── game-of-life.cpp ├── generate-parentheses-1.cpp ├── generate-parentheses-2.cpp ├── generate-parentheses.cpp ├── goat-latin-1.cpp ├── graph-valid-tree-1.cpp ├── graph-valid-tree-2.cpp ├── graph-valid-tree-3.cpp ├── group-anagrams-1.cpp ├── group-anagrams-2.cpp ├── group-anagrams-3.cpp ├── group-anagrams-4.cpp ├── group-anagrams.cpp ├── guess-number-higher-or-lower-ii-1.cpp ├── guess-number-higher-or-lower-ii-2.cpp ├── guess-number-higher-or-lower.cpp ├── hamming-distance-1.cpp ├── hamming-distance-2.cpp ├── happy-number.cpp ├── heaters.cpp ├── house-robber-1.cpp ├── house-robber-2.cpp ├── house-robber-3.cpp ├── house-robber-4.cpp ├── image-smoother-2.cpp ├── image-smoother.cpp ├── implement-queue-using-stacks-1.cpp ├── implement-queue-using-stacks-2.cpp ├── implement-queue-using-stacks-3.cpp ├── implement-strstr-1.cpp ├── implement-strstr.cpp ├── implement-trie-prefix-tree-1.cpp ├── implement-trie-prefix-tree-2.cpp ├── implement-trie-prefix-tree-3.cpp ├── increasing-subsequences-1.cpp ├── inorder-successor-in-bst-1.cpp ├── inorder-successor-in-bst-2.cpp ├── inorder-successor-in-bst-3.cpp ├── inorder-successor-in-bst-4.cpp ├── inorder-successor-in-bst.cpp ├── insert-delete-getrandom-o1-1.cpp ├── insert-interval-1.cpp ├── integer-break-1.cpp ├── integer-break.cpp ├── integer-to-english-words-1.cpp ├── integer-to-english-words-2.cpp ├── integer-to-english-words-3.cpp ├── integer-to-english-words-4.cpp ├── integer-to-english-words-5.cpp ├── intersection-of-two-arrays-1.cpp ├── intersection-of-two-arrays-ii-1.cpp ├── intersection-of-two-arrays-ii-2.cpp ├── intersection-of-two-arrays-ii-3.cpp ├── intersection-of-two-arrays-ii-4.cpp ├── intersection-of-two-arrays-ii.cpp ├── intersection-of-two-linked-lists-1.cpp ├── intersection-of-two-linked-lists-2.cpp ├── intersection-of-two-linked-lists-3.cpp ├── intersection-of-two-linked-lists-4.cpp ├── intersection-of-two-linked-lists-5.cpp ├── invert-binary-tree-1.cpp ├── invert-binary-tree-2.cpp ├── invert-binary-tree-3.cpp ├── invert-binary-tree-4.cpp ├── invert-binary-tree-5.cpp ├── invert-binary-tree-6.cpp ├── ipo.cpp ├── is-graph-bipartite-1.cpp ├── is-graph-bipartite-2.cpp ├── is-graph-bipartite-3.cpp ├── is-graph-bipartite-4.cpp ├── is-subsequence-1.cpp ├── is-subsequence-2.cpp ├── is-subsequence.cpp ├── island-perimeter-1.cpp ├── isomorphic-strings.cpp ├── jewels-and-stones-1.cpp ├── judge-route-circle.cpp ├── jump-game.cpp ├── k-diff-pairs-in-an-array.cpp ├── k-empty-slots-1.cpp ├── k-empty-slots-2.cpp ├── keyboard-row-1.cpp ├── keys-and-rooms-1.cpp ├── keys-and-rooms-2.cpp ├── keys-and-rooms-3.cpp ├── kill-process-1.cpp ├── knight-probability-in-chessboard-1.cpp ├── knight-probability-in-chessboard-2.cpp ├── kth-largest-element-in-a-stream-1.cpp ├── kth-largest-element-in-a-stream-2.cpp ├── kth-largest-element-in-an-array-1.cpp ├── kth-largest-element-in-an-array-2.cpp ├── kth-largest-element-in-an-array-3.cpp ├── kth-largest-element-in-an-array-4.cpp ├── kth-largest-element-in-an-array-5.cpp ├── kth-largest-element-in-an-array-6.cpp ├── kth-largest-element-in-an-array-heap.cpp ├── kth-smallest-element-in-a-bst-1.cpp ├── kth-smallest-element-in-a-bst-2.cpp ├── kth-smallest-element-in-a-bst.cpp ├── kth-smallest-element-in-a-sorted-matrix-1.cpp ├── largest-number-at-least-twice-of-other-2.cpp ├── largest-number-at-least-twice-of-others-1.cpp ├── largest-plus-sign-1.cpp ├── largest-triangle-area-1.cpp ├── length-of-last-word.cpp ├── letter-case-permutation-1.cpp ├── letter-case-permutation-2.cpp ├── letter-case-permutation-3.cpp ├── letter-combinations-of-a-phone-number-1.cpp ├── letter-combinations-of-a-phone-number-10.cpp ├── letter-combinations-of-a-phone-number-11.cpp ├── letter-combinations-of-a-phone-number-12.cpp ├── letter-combinations-of-a-phone-number-2.cpp ├── letter-combinations-of-a-phone-number-3.cpp ├── letter-combinations-of-a-phone-number-4.cpp ├── letter-combinations-of-a-phone-number-5.cpp ├── letter-combinations-of-a-phone-number-6.cpp ├── letter-combinations-of-a-phone-number-7.cpp ├── letter-combinations-of-a-phone-number-8.cpp ├── letter-combinations-of-a-phone-number-9.cpp ├── letter-combinations-of-a-phone-number.cpp ├── license-key-formatting-1.cpp ├── linked-list-cycle-ii-1.cpp ├── linked-list-cycle-ii.cpp ├── longest-absolute-file-path.cpp ├── longest-common-prefix.cpp ├── longest-consecutive-sequence-1.cpp ├── longest-continuous-increasing-subsequence-1.cpp ├── longest-continuous-increasing-subsequence-2.cpp ├── longest-continuous-increasing-subsequence-3.cpp ├── longest-continuous-increasing-subsequence.cpp ├── longest-harmonious-subsequence.cpp ├── longest-increasing-subsequence-1.cpp ├── longest-increasing-subsequence-2.cpp ├── longest-palindrome.cpp ├── longest-palindromic-subsequence-1.cpp ├── longest-palindromic-subsequence-2.cpp ├── longest-palindromic-subsequence-3.cpp ├── longest-palindromic-subsequence-4.cpp ├── longest-palindromic-substrin-6.cpp ├── longest-palindromic-substring-1.cpp ├── longest-palindromic-substring-2.cpp ├── longest-palindromic-substring-3.cpp ├── longest-palindromic-substring-4.cpp ├── longest-palindromic-substring-5.cpp ├── longest-palindromic-substring-6.cpp ├── longest-palindromic-substring-7.cpp ├── longest-palindromic-substring.cpp ├── longest-substring-with-at-least-k-repeating-characters.cpp ├── longest-substring-without-repeating-characters-1.cpp ├── longest-substring-without-repeating-characters-2.cpp ├── longest-substring-without-repeating-characters.cpp ├── longest-univalue-path-1.cpp ├── longest-univalue-path.cpp ├── longest-valid-parentheses-1.cpp ├── longest-valid-parentheses-2.cpp ├── loud-and-rich-1.com ├── loud-and-rich-2.cpp ├── loud-and-rich-3.cpp ├── lowest-common-ancestor-of-a-binary-search-tree-1.cpp ├── lowest-common-ancestor-of-a-binary-search-tree-2.cpp ├── lowest-common-ancestor-of-a-binary-search-tree-3.cpp ├── lowest-common-ancestor-of-a-binary-search-tree-4.cpp ├── lowest-common-ancestor-of-a-binary-search-tree-5.cpp ├── lowest-common-ancestor-of-a-binary-search-tree-6.cpp ├── lowest-common-ancestor-of-a-binary-tree-1.cpp ├── lowest-common-ancestor-of-a-binary-tree-3.cpp ├── lowest-common-ancestor-of-a-binary-tree-4.cpp ├── lowest-common-ancestor-of-a-binary-tree.cpp ├── majority-element.cpp ├── max-area-of-island-1.cpp ├── max-area-of-island-2.cpp ├── max-area-of-island-3.cpp ├── max-area-of-island-4.cpp ├── max-area-of-island-5.cpp ├── max-area-of-island-6.cpp ├── max-chunks-to-make-sorted-ii.cpp ├── max-consecutive-ones-1.cpp ├── max-consecutive-ones.cpp ├── maximum-average-subarray-i.cpp ├── maximum-binary-tree-1.cpp ├── maximum-depth-of-binary-tree-1.cpp ├── maximum-depth-of-binary-tree-2.cpp ├── maximum-depth-of-binary-tree-3.cpp ├── maximum-length-of-pair-chain-1.cpp ├── maximum-length-of-repeated-subarray-1.cpp ├── maximum-length-of-repeated-subarray-2.cpp ├── maximum-length-of-repeated-subarray-3.cpp ├── maximum-product-of-three-numbers.cpp ├── maximum-size-subarray-sum-equals-k-1.cpp ├── maximum-size-subarray-sum-equals-k-2.cpp ├── maximum-size-subarray-sum-equals-k-3.cpp ├── maximum-subarray-1.cpp ├── maximum-subarray-2.cpp ├── maximum-subarray-3.cpp ├── maximum-subarray-4.cpp ├── maximum-subarray-divide-&-conquer.cpp ├── maximum-subarray.cpp ├── maximum-sum-of-3-non-overlapping-subarrays-1.cpp ├── maximum-sum-of-3-non-overlapping-subarrays-2.cpp ├── maximum-swap-1.cpp ├── maximum-swap-2.cpp ├── maximum-width-of-binary-tree-1.cpp ├── maximum-width-of-binary-tree-2.cpp ├── maximum-width-of-binary-tree-3.cpp ├── median-of-two-sorted-arrays-1.cpp ├── median-of-two-sorted-arrays.cpp ├── meeting-rooms-1.cpp ├── meeting-rooms-2.cpp ├── meeting-rooms-ii-1.cpp ├── meeting-rooms-ii-2.cpp ├── meeting-rooms-ii-3.cpp ├── meeting-rooms-ii-4.cpp ├── meeting-rooms-ii-5.cpp ├── meeting-rooms-ii-6.cpp ├── merge-k-sorted-lists-1.cpp ├── merge-k-sorted-lists-10.cpp ├── merge-k-sorted-lists-11.cpp ├── merge-k-sorted-lists-12.cpp ├── merge-k-sorted-lists-13.cpp ├── merge-k-sorted-lists-14.cpp ├── merge-k-sorted-lists-15.cpp ├── merge-k-sorted-lists-16.cpp ├── merge-k-sorted-lists-2.cpp ├── merge-k-sorted-lists-3.cpp ├── merge-k-sorted-lists-4.cpp ├── merge-k-sorted-lists-5.cpp ├── merge-k-sorted-lists-6.cpp ├── merge-k-sorted-lists-7.cpp ├── merge-k-sorted-lists-8.cpp ├── merge-k-sorted-lists-9.cpp ├── merge-sorted-array-1.cpp ├── merge-sorted-array-2.cpp ├── merge-sorted-array-3.cpp ├── merge-sorted-array-4.cpp ├── merge-sorted-array-5.cpp ├── merge-sorted-array.cpp ├── merge-two-binary-trees-1.cpp ├── merge-two-binary-trees.cpp ├── merge-two-sorted-lists-1.cpp ├── merge-two-sorted-lists-2.cpp ├── merge-two-sorted-lists-3.cpp ├── merge-two-sorted-lists-4.cpp ├── merge-two-sorted-lists-5.cpp ├── merge-two-sorted-lists-6.cpp ├── merge-two-sorted-lists-7.cpp ├── merge-two-sorted-lists-8.cpp ├── merge-two-sorted-lists.cpp ├── min-cost-climbing-stairs-1.cpp ├── min-cost-climbing-stairs-2.cpp ├── min-cost-climbing-stairs.cpp ├── min-stack-1.cpp ├── min-stack-2.cpp ├── min-stack-a.cpp ├── minesweeper-1.cpp ├── minimum-ascii-delete-sum-for-two-strings-1.cpp ├── minimum-ascii-delete-sum-for-two-strings-2.cpp ├── minimum-depth-of-binary-tree-1.cpp ├── minimum-depth-of-binary-tree-2.cpp ├── minimum-height-trees-1.cpp ├── minimum-height-trees-2.cpp ├── minimum-index-sum-of-two-lists.cpp ├── minimum-moves-to-equal-array-elements.cpp ├── minimum-path-sum-1.cpp ├── minimum-path-sum-2.cpp ├── minimum-path-sum.cpp ├── minimum-size-subarray-sum-1.cpp ├── minimum-size-subarray-sum-2.cpp ├── minimum-size-subarray-sum-3.cpp ├── minimum-window-subsequence-1.cpp ├── minimum-window-substring-1.cpp ├── minimum-window-substring-2.cpp ├── minimum-window-substring-3.cpp ├── missing-number.cpp ├── missing-numer-1.cpp ├── missing-ranges-1.cpp ├── most-common-word-1.cpp ├── most-frequent-subtree-sum-1.cpp ├── move-zeroes-1.cpp ├── move-zeroes-2.cpp ├── move-zeroes-3.cpp ├── move-zeroes-4.cpp ├── move-zeroes-5.cpp ├── move-zeroes-6.cpp ├── move-zeroes-7.cpp ├── move-zeroes-8.cpp ├── move-zeroes.cpp ├── multiply-strings-1.cpp ├── my-calendar-i-1.cpp ├── my-calendar-i.cpp ├── my-calendar-iii-1.cpp ├── n-queens-ii.cpp ├── n-queens.cpp ├── network-delay-time-1.cpp ├── network-delay-time.cpp ├── next-closest-time-1.cpp ├── next-permutation-1.cpp ├── next-permutation-2.cpp ├── next-permutation.cpp ├── number-of-1-bits-1.cpp ├── number-of-1-bits-2.cpp ├── number-of-1-bits.cpp ├── number-of-boomerangs.cpp ├── number-of-lines-to-write-string.cpp ├── number-of-matching-subsequences.cpp ├── number-of-subarrays-with-bounded-maximum.cpp ├── odd-even-linked-list-1.cpp ├── odd-even-linked-list-2.cpp ├── one-and-zeroes-1.cpp ├── one-edit-distance-1.cpp ├── one-edit-distance-2.cpp ├── one-edit-distance-3.cpp ├── one-edit-distance-4.cpp ├── ones-and-zeroes.cpp ├── onstruct-binary-tree-from-preorder-and-inorder-traversal-1.cpp ├── open-the-lock-1.cpp ├── owest-common-ancestor-of-a-binary-tree-5.cpp ├── pacific-atlantic-water-flow-1.cpp ├── paint-fence.cpp ├── paint-house-ii-1.cpp ├── paint-house-ii-2.cpp ├── palindrome-linked-list-1.cpp ├── palindrome-linked-list-2.cpp ├── palindrome-number-1.cpp ├── palindrome-number-2.cpp ├── palindrome-number-3.cpp ├── palindrome-pairs-1.cpp ├── palindrome-permutation.cpp ├── palindromic-substrings-1.cpp ├── palindromic-substrings-2.cpp ├── palindromic-substrings-3.cpp ├── palindromic-substrings-4.cpp ├── palindromic-substrings-iter.cpp ├── palindromic-substrings-recur.cpp ├── partition-equal-subset-sum-1.cpp ├── partition-equal-subset-sum.cpp ├── partition-list.cpp ├── partition-to-k-equal-sum-subsets.cpp ├── pascals-triangle-1.cpp ├── pascals-triangle-ii-1.cpp ├── pascals-triangle.cpp ├── path-sum-1.cpp ├── path-sum-2.cpp ├── path-sum-ii-1.cpp ├── path-sum-ii.cpp ├── path-sum-iii-1.cpp ├── path-sum-iii.cpp ├── peak-index-in-a-mountain-array.cpp ├── perfect-squares-1.cpp ├── perfect-squares.cpp ├── plus-one.cpp ├── populating-next-right-pointers-in-each-node-1.cpp ├── populating-next-right-pointers-in-each-node-2.cpp ├── populating-next-right-pointers-in-each-node-3.cpp ├── populating-next-right-pointers-in-each-node-ii-1.cpp ├── populating-next-right-pointers-in-each-node-ii-2.cpp ├── populating-next-right-pointers-in-each-node-ii-3.cpp ├── populating-next-right-pointers-in-each-node-ii-4.cpp ├── populating-next-right-pointers-in-each-node-ii-5.cpp ├── positions-of-large-groups.cpp ├── power-of-three.cpp ├── power-of-two.cpp ├── powx-n-1.cpp ├── powx-n-2.cpp ├── powx-n-3.cpp ├── powx-n-4.cpp ├── predict-the-winner-1.cpp ├── preimage-size-of-factorial-zeroes-function-1.cpp ├── product-of-array-except-self-1.cpp ├── product-of-array-except-self-2.cpp ├── product-of-array-except-self-3.cpp ├── product-of-array-except-self-4.cpp ├── product-of-array-except-self-5.cpp ├── product-of-array-except-self-6.cpp ├── product-of-array-except-self-7.cpp ├── product-of-array-except-self.cpp ├── push-dominoes-1.cpp ├── push-dominoes-2.cpp ├── range-addition-ii.cpp598. Range Addition II ├── range-sum-query-immutable-1.cpp ├── range-sum-query-immutable-2.cpp ├── ransom-note-1.cpp ├── read-n-characters-given-read4-1.cpp ├── read-n-characters-given-read4-2.cpp ├── read-n-characters-given-read4-ii-call-multiple-times-1.cpp ├── read-n-characters-given-read4-ii-call-multiple-times-2.cpp ├── reconstruct-itinerary-1.cpp ├── reconstruct-itinerary-2.cpp ├── reconstruct-itinerary-3.cpp ├── recover-binary-search-tree-1.cpp ├── recover-binary-search-tree-2.cpp ├── regular-expression-matching-1.cpp ├── remove-duplicates-from-sorted-array-1.cpp ├── remove-duplicates-from-sorted-array-2.cpp ├── remove-duplicates-from-sorted-array-3.cpp ├── remove-duplicates-from-sorted-array-4.cpp ├── remove-duplicates-from-sorted-array-5.cpp ├── remove-duplicates-from-sorted-array-ii-2.cpp ├── remove-duplicates-from-sorted-array-ii-3.cpp ├── remove-duplicates-from-sorted-array-ii-4.cpp ├── remove-duplicates-from-sorted-array-ii.cpp ├── remove-duplicates-from-sorted-array.cpp ├── remove-duplicates-from-sorted-list.cpp ├── remove-element.cpp ├── remove-nth-node-from-end-of-list-1.cpp ├── remove-nth-node-from-end-of-list-2,cpp ├── remove-nth-node-from-end-of-list-3.cpp ├── remove-nth-node-from-end-of-list-4.cpp ├── remove-nth-node-from-end-of-list.cpp ├── repeated-string-match-1.cpp ├── repeated-string-match.cpp ├── reverse-bits-1.cpp ├── reverse-bits.cpp ├── reverse-integer-1.cpp ├── reverse-integer-2.cpp ├── reverse-integer-3.cpp ├── reverse-integer-4.cpp ├── reverse-integer-5.cpp ├── reverse-linked-list-1.cpp ├── reverse-linked-list-2.cpp ├── reverse-linked-list-3.cpp ├── reverse-linked-list-4.cpp ├── reverse-linked-list-5.cpp ├── reverse-linked-list-6.cpp ├── reverse-linked-list-7.cpp ├── reverse-linked-list-8.cpp ├── reverse-linked-list-9.cpp ├── reverse-nodes-in-k-group-1.cpp ├── reverse-string-1.cpp ├── reverse-string-2.cpp ├── reverse-string-3.cpp ├── reverse-string-4.cpp ├── reverse-string-5.cpp ├── reverse-string.cpp ├── reverse-vowels-of-a-string.cpp ├── reverse-words-in-a-string-1.cpp ├── reverse-words-in-a-string-2.cpp ├── reverse-words-in-a-string-ii-1.cpp ├── reverse-words-in-a-string-iii.cpp ├── robot-room-cleaner-1.cpp ├── robot-room-cleaner-2.cpp ├── roman-to-integer-1.cpp ├── roman-to-integer-2.cpp ├── roman-to-integer-3.cpp ├── roman-to-integer-4.cpp ├── roman-to-integer-5.cpp ├── roman-to-integer-6.cpp ├── roman-to-integer-7.cpp ├── rotate-array-1.cpp ├── rotate-array-2.cpp ├── rotate-array.cpp ├── rotate-image-1.cpp ├── rotate-image-2.cpp ├── rotate-image-3.cpp ├── rotate-image.cpp ├── route-between-two-nodes-in-graph.cpp ├── russian-doll-envelopes-1.cpp ├── russian-doll-envelopes-2.cpp ├── same-number.cpp ├── same-tree-1.cpp ├── same-tree-2.cpp ├── same-tree-3.cpp ├── same-tree-4.cpp ├── search-a-2d-matrix-1.cpp ├── search-a-2d-matrix-2.cpp ├── search-a-2d-matrix-ii-1.cpp ├── search-a-2d-matrix-ii-2.cpp ├── search-a-2d-matrix-ii-3.cpp ├── search-for-a-range.cpp ├── search-in-rotated-sorted-array-1.cpp ├── search-in-rotated-sorted-array-2.cpp ├── search-in-rotated-sorted-array-3.cpp ├── search-in-rotated-sorted-array-4.cpp ├── search-in-rotated-sorted-array-5.cpp ├── search-in-rotated-sorted-array-6.cpp ├── search-in-rotated-sorted-array-7.cpp ├── search-in-rotated-sorted-array-8.cpp ├── search-in-rotated-sorted-array-ii-1.cpp ├── search-in-rotated-sorted-array-ii-2.cpp ├── search-in-rotated-sorted-array-ii.cpp ├── search-in-rotated-sorted-array.cpp ├── search-insert-position.cpp ├── second-minimum-node-in-a-binary-tree-1.cpp ├── self-dividing-numbers.cpp ├── sentence-similarity-1.cpp ├── serialize-and-deserialize-bst-1.cpp ├── serialize-and-deserialize-bst-2.cpp ├── set-matrix-zeroes-1.cpp ├── set-matrix-zeroes.cpp ├── set-mismatch-1.cpp ├── shopping-offers-1.cpp ├── shopping-offers-2.cpp ├── shortest-unsorted-continuous-subarray-1.cpp ├── similar-rgb-color.cpp ├── single-element-in-a-sorted-array.cpp ├── single-number-iv.cpp ├── single-number.cpp ├── sliding-puzzle-1.cpp ├── sliding-window-maximum.cpp ├── smallest-range-1.cpp ├── sort-colors-1.cpp ├── sort-colors-2.cpp ├── sort-colors-3.cpp ├── sparse-matrix-multiplication-1.cpp ├── spiral-matrix-1.cpp ├── spiral-matrix-2.cpp ├── spiral-matrix-ii.cpp ├── split-linked-list-in-parts-1.cpp ├── split-linked-list-in-parts.cpp ├── sqrtx-1.cpp ├── sqrtx-2.cpp ├── sqrtx-3.cpp ├── sqrtx-4.cpp ├── sqrtx-5.cpp ├── sqrtx.cpp ├── string-compression-1.cpp ├── string-compression-2.cpp ├── string-compression.cpp ├── string-to-integer-atoi-1.cpp ├── string-to-integer-atoi-2.cpp ├── string-to-integer-atoi-3.cpp ├── string-to-integer-atoi-4.cpp ├── strobogrammatic-number-1.cpp ├── subarray-product-less-than-k-1.cpp ├── subarray-product-less-than-k-2.cpp ├── subarray-sum-equals-k-1.cpp ├── subarray-sum-equals-k-2.cpp ├── subarray-sum-equals-k.cpp ├── subdomain-visit-count.cpp ├── subset-1.cpp ├── subset-2.cpp ├── subset-3.cpp ├── subset-ii-1.cpp ├── subset-ii-2.cpp ├── subsets-1.cpp ├── subsets-2.cpp ├── subsets-3.cpp ├── subsets-4.cpp ├── subsets-ii-1.cpp ├── subsets-ii-2.cpp ├── subsets-ii.cpp ├── subtree-of-another-tree-1.cpp ├── sum-of-left-leaves-1.cpp ├── sum-of-left-leaves-2.cpp ├── sum-of-left-leaves-3.cpp ├── sum-of-left-leaves-4.cpp ├── sum-of-left-leaves-5.cpp ├── sum-of-two-integers.cpp ├── sum-root-to-leaf-numbers-1.cpp ├── sum-root-to-leaf-numbers-2.cpp ├── sum-root-to-leaf-numbers-3.cpp ├── sum-root-to-leaf-numbers-4.cpp ├── sum-root-to-leaf-numbers-5.cpp ├── surrounded-regions-1.cpp ├── swap-nodes-in-pairs-1.cpp ├── swap-nodes-in-pairs-2.cpp ├── swap-nodes-in-pairs.cpp ├── swim-in-rising-water-1.cpp ├── swim-in-rising-water-2.cpp ├── symmetric-tree-1.cpp ├── symmetric-tree-2.cpp ├── symmetric-tree-3.cpp ├── symmetric-tree-4.cpp ├── symmetric-tree-5.cpp ├── target-sum-1.cpp ├── target-sum-2.cpp ├── target-sum-3.cpp ├── target-sum-4.cpp ├── target-sum-5.cpp ├── target-sum-6.cpp ├── task-scheduler-1.cpp ├── task-scheduler-2.cpp ├── task-scheduler-3.cpp ├── task-scheduler-4.cpp ├── teemo-attacking.cpp ├── text-justification-1.cpp ├── the-skyline-problem-1.cpp ├── the-skyline-problem.cpp ├── third-maximum-number.cpp ├── toeplitz-matrix-1.cpp ├── top-k-frequent-elements-1.cpp ├── trapping-rain-water-1.cpp ├── trapping-rain-water-2.cpp ├── trapping-rain-water-3.cpp ├── trapping-rain-water-4.cpp ├── trapping-rain-water-5.cpp ├── trapping-rain-water-6.cpp ├── triangle-1.cpp ├── triangle-2.cpp ├── triangle-3.cpp ├── trim-a-binary-search-tree-1.cpp ├── trim-a-binary-search-tree-2.cpp ├── twitch-words.cpp ├── two-sum-1.cpp ├── two-sum-2.cpp ├── two-sum-3.cpp ├── two-sum-4.cpp ├── two-sum-iv-input-is-a-bst-1.cpp ├── two-sum-iv-input-is-a-bst-2.cpp ├── two-sum-iv-input-is-a-bst-3.cpp ├── two-sum-iv-input-is-a-bst-4.cpp ├── ugly-number.cpp ├── unique-binary-search-trees.cpp ├── unique-morse-code-words.cpp ├── unique-paths-1.cpp ├── unique-paths-2.cpp ├── unique-paths-3.cpp ├── unique-paths-ii-1.cpp ├── unique-paths-ii.cpp ├── valid-anagram-1.cpp ├── valid-number-1.cpp ├── valid-palindrom-ii-1.cpp ├── valid-palindrome-1.cpp ├── valid-palindrome-2.cpp ├── valid-palindrome-3.cpp ├── valid-palindrome-ii-1.cpp ├── valid-palindrome.cpp ├── valid-parentheses-1.cpp ├── valid-parentheses-2.cpp ├── valid-parentheses-3.cpp ├── valid-perfect-square.cpp ├── valid-sudoku-1.cpp ├── valid-sudoku-2.cpp ├── valid-sudoku.cpp ├── valid-triangle-number-1.cpp ├── valid-triangle-number-2.cpp ├── valid-triangle-number.cpp ├── valid-word-square.cpp ├── validate-ip-address-1.cpp ├── walls-and-gates-1.cpp ├── wildcard-matching-1.cpp ├── wildcard-matching-2.cpp ├── word-pattern-1.cpp ├── word-pattern-2.cpp ├── word-pattern-ii-1.cpp ├── word-search-1.cpp ├── word-search-2.cpp ├── word-search-ii-1.cpp ├── word-search-ii-2.cpp ├── word-search.cpp ├── zigzag-conversion-1.cpp └── zigzag-conversion.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Compiled Object files 5 | *.slo 6 | *.lo 7 | *.o 8 | *.obj 9 | 10 | # Precompiled Headers 11 | *.gch 12 | *.pch 13 | 14 | # Compiled Dynamic libraries 15 | *.so 16 | *.dylib 17 | *.dll 18 | 19 | # Fortran module files 20 | *.mod 21 | *.smod 22 | 23 | # Compiled Static libraries 24 | *.lai 25 | *.la 26 | *.a 27 | *.lib 28 | 29 | # Executables 30 | *.exe 31 | *.out 32 | *.app 33 | -------------------------------------------------------------------------------- /047. Permutations II/permutations-ii-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/permutations-ii/description/ 2 | 3 | class Solution { 4 | public: 5 | 6 | void helper(vector nums, int size, vector>& ans){ 7 | if (size == nums.size() - 1){ 8 | ans.push_back(nums); 9 | return; 10 | } 11 | 12 | for(int i = size; i < nums.size(); i++){ 13 | if (i != size && (nums[i] == nums[size])) 14 | continue; 15 | swap(nums[size], nums[i]); 16 | helper(nums, size + 1, ans); 17 | } 18 | } 19 | vector> permuteUnique(vector& nums) { 20 | vector> ans; 21 | sort(nums.begin(), nums.end()); 22 | helper(nums, 0, ans); 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /067. Add Binary/add-binary-5.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/add-binary/description/ 2 | 3 | class Solution { 4 | public: 5 | string addBinary(string a, string b) { 6 | int i = a.length() - 1, j = b.length() - 1, c = 0; 7 | stringstream ss; 8 | while(i >= 0 || j >= 0 || c == 1){ 9 | c += i >= 0 ? a[i--] - '0' : 0; 10 | c += j >= 0 ? b[j--] - '0' : 0; 11 | ss << string(1, c % 2 + '0'); 12 | c = c/2; 13 | } 14 | 15 | string ans = ss.str(); 16 | reverse(ans.begin(), ans.end()); 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /139. Word Break/word-break-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/word-break/description/ 2 | 3 | class Solution { 4 | public: 5 | bool wordBreak(string s, vector& wordDict) { 6 | int n = s.length(); 7 | vector dp(n + 1, false); 8 | dp[0] = true; 9 | unordered_set hashSet(wordDict.begin(), wordDict.end()); 10 | 11 | for(int i = 1; i <= n; i++){ 12 | for(int j = 0 ; j < i; j++){ 13 | if (dp[j] && hashSet.count(s.substr(j, i - j))){ 14 | dp[i] = true; 15 | break; 16 | } 17 | } 18 | } 19 | return dp[n]; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /139. Word Break/word-break-4.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/word-break/description/ 2 | 3 | class Solution { 4 | public: 5 | bool wordBreak(string s, vector& wordDict) { 6 | if (s.length() == 0) return true; 7 | if (dp.count(s)) return dp[s]; 8 | 9 | for(auto str: wordDict){ 10 | if (s.find(str) == 0 && wordBreak(s.substr(str.length()), wordDict)) 11 | return dp[s] = true; 12 | } 13 | 14 | return dp[s] = false; 15 | } 16 | 17 | private: 18 | unordered_map dp; 19 | }; 20 | -------------------------------------------------------------------------------- /141. Linked List Cycle/linked-list-cycle-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/linked-list-cycle/description/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode(int x) : val(x), next(NULL) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | bool hasCycle(ListNode *head) { 14 | ListNode *slow = head, *fast = head ? head->next : head; 15 | 16 | while(fast && fast->next && slow != fast){ 17 | slow = slow->next; 18 | fast = fast->next->next; 19 | } 20 | 21 | return slow && slow == fast; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /141. Linked List Cycle/linked-list-cycle-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/linked-list-cycle/description/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode(int x) : val(x), next(NULL) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | bool hasCycle(ListNode *head) { 14 | ListNode* slow = head; 15 | ListNode* fast = head ? head->next : NULL; 16 | 17 | while(slow && fast && slow != fast){ 18 | slow = slow->next; 19 | fast = fast && fast->next ? fast->next->next : NULL; 20 | } 21 | 22 | return slow && fast && slow == fast; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /141. Linked List Cycle/linked-list-cycle-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/linked-list-cycle/description/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode(int x) : val(x), next(NULL) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | bool hasCycle(ListNode *head) { 14 | ListNode* slow = head, *fast = slow ? slow->next : NULL; 15 | 16 | while(fast && slow != fast){ 17 | slow = slow->next; 18 | fast = fast->next ? fast->next->next : NULL; 19 | } 20 | 21 | return fast; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /141. Linked List Cycle/linked-list-cycle-4.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/linked-list-cycle/description/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode(int x) : val(x), next(NULL) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | bool hasCycle(ListNode *head) { 14 | ListNode* slow = head, *fast = head ? head->next : NULL; 15 | 16 | while(slow != fast){ 17 | slow = slow->next; 18 | fast = fast && fast->next ? fast->next->next: NULL; 19 | } 20 | 21 | return fast != NULL; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /141. Linked List Cycle/linked-list-cycle-5.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/linked-list-cycle/description/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode(int x) : val(x), next(NULL) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | bool hasCycle(ListNode *head) { 14 | ListNode* slow = head, *fast = head && head->next ? head->next->next : NULL; 15 | 16 | 17 | while(slow != fast){ 18 | slow = slow->next; 19 | fast = fast && fast->next ? fast->next->next : NULL; 20 | } 21 | 22 | return fast && slow == fast; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /141. Linked List Cycle/linked-list-cycle-6.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/linked-list-cycle/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode(int x) : val(x), next(NULL) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | bool hasCycle(ListNode *head) { 14 | ListNode* slow = head, *fast = head && head->next ? head->next : NULL; 15 | 16 | while(slow != fast){ 17 | slow = slow->next; 18 | fast = (fast && fast->next ? fast->next->next : NULL); 19 | } 20 | 21 | return slow == fast && slow; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /141. Linked List Cycle/linked-list-cycle.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/linked-list-cycle/description/ 2 | #include 3 | using namespace std; 4 | 5 | /** 6 | * Definition for singly-linked list. 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 | bool hasCycle(ListNode *head) { 16 | ListNode* slow = head, *fast = head; 17 | bool flag = false; 18 | while(slow && fast && fast->next && !flag){ 19 | slow = slow->next; 20 | fast = fast->next->next; 21 | flag = (slow == fast) ? true : false; 22 | } 23 | return flag; 24 | } 25 | }; 26 | 27 | -------------------------------------------------------------------------------- /3sum-closest-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/3sum-closest/description/ 2 | 3 | #define ff(i, m, n) for(i = m; i < n; i++) 4 | #define ffr(i, m, n) for(i = m; i >= n; i--) 5 | #define ss(v) sort(v.begin(), v.end()) 6 | class Solution { 7 | public: 8 | int threeSumClosest(vector& nums, int target) { 9 | int i, j, k, n = nums.size(), ans = n > 2 ? nums[0] + nums[1] + nums[2] : 0; 10 | ss(nums); 11 | ff(i,0,n){ 12 | j = i + 1; k = n - 1; 13 | while(j < k){ 14 | int temp = nums[i] + nums[j] + nums[k]; 15 | if (abs(temp - target) < abs(ans - target)) 16 | ans = temp; 17 | if (temp > target) k--; 18 | else j++; 19 | } 20 | } 21 | return ans; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /add-digits-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/add-digits/description/ 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int addDigits(int num) { 8 | if (num % 10 == num) return num; 9 | for(int i = 1; i < 10; i++){ 10 | if ((num - i) % 9 == 0) 11 | return i; 12 | } 13 | } 14 | }; 15 | 16 | int stringToInteger(string input) { 17 | return stoi(input); 18 | } 19 | 20 | int main() { 21 | string line; 22 | while (getline(cin, line)) { 23 | int num = stringToInteger(line); 24 | 25 | int ret = Solution().addDigits(num); 26 | 27 | string out = to_string(ret); 28 | cout << out << endl; 29 | } 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /add-strings.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/add-strings/description/ 2 | 3 | class Solution { 4 | public: 5 | string addStrings(string num1, string num2) { 6 | // write your code here 7 | string ans = ""; 8 | int carry = 0, i = num1.length() - 1, j = num2.length() - 1, temp; 9 | 10 | while(i >= 0 || j >= 0){ 11 | temp = (i >= 0 ? num1[i--] - '0' : 0) + (j >= 0 ? num2[j--] - '0' : 0) + carry; 12 | carry = temp / 10; 13 | char c = temp % 10 + '0'; 14 | ans = c + ans; 15 | } 16 | 17 | if (carry) 18 | ans = '1' + ans; 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /arithmetic-slices-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/arithmetic-slices/description/ 2 | 3 | class Solution { 4 | public: 5 | int numberOfArithmeticSlices(vector& A) { 6 | int ans = 0, n = A.size(); 7 | if (n < 3) return ans; 8 | int diff = A[1] - A[0], len = 2; 9 | 10 | for(int i = 2; i < n; i++){ 11 | int temp = A[i] - A[i-1]; 12 | if (temp == diff) len++; 13 | else { 14 | ans += (len - 2) * (len - 1) / 2; 15 | diff = temp; 16 | len = 2; 17 | } 18 | } 19 | 20 | if (len > 2) ans += (len - 2) * (len - 1) / 2; 21 | return ans; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /arranging-coins-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/arranging-coins/description/ 2 | 3 | class Solution { 4 | public: 5 | int arrangeCoins(int n) { 6 | long low = 1, high = n, mid, coin; 7 | 8 | while(low <= high){ 9 | mid = low + (high - low) / 2; 10 | coin = mid * (mid + 1) / 2; 11 | if (coin < n) low = mid + 1; 12 | else if (coin > n) high = mid - 1; 13 | else return mid; 14 | } 15 | 16 | return low - 1; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /array-nesting-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/array-nesting/description/ 2 | 3 | class Solution { 4 | public: 5 | int arrayNesting(vector& nums) { 6 | int n = nums.size(), ans = 0; 7 | unordered_set visit; 8 | for(int i = 0; i < n; i++){ 9 | if (!visit.count(i)){ 10 | int temp = 0, node = i; 11 | while(!visit.count(node)){ 12 | temp++; 13 | visit.insert(node); 14 | node = nums[node]; 15 | } 16 | ans = max(temp, ans); 17 | } 18 | } 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /array-nesting.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/array-nesting/description/ 2 | 3 | class Solution { 4 | public: 5 | int arrayNesting(vector& nums) { 6 | int answer = 0, temp = 0, buffer; 7 | 8 | for(int i = 0; i < nums.size(); i++){ 9 | temp = 0; 10 | 11 | while(nums[i] != -1){ 12 | buffer = nums[i]; 13 | nums[i] = -1; 14 | i = buffer; 15 | temp++; 16 | } 17 | 18 | answer = (temp > answer) ? temp : answer; 19 | } 20 | 21 | return answer; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /balanced-binary-tree-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/balanced-binary-tree/description/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | 15 | int getHeight(TreeNode* root){ 16 | if (!root) return 0; 17 | return 1 + max(getHeight(root->left), getHeight(root->right)); 18 | } 19 | bool isBalanced(TreeNode* root) { 20 | return (!root) ? true : (abs(getHeight(root->left) - getHeight(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right)); 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /balanced-binary-tree-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/balanced-binary-tree/description/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | bool isBalanced(TreeNode* root) { 15 | return helper(root) != -1; 16 | } 17 | 18 | int helper(TreeNode* root){ 19 | if (!root) return 0; 20 | int l = helper(root->left); 21 | int r = helper(root->right); 22 | if (l == -1 || r == -1) return -1; 23 | if (l - r >= -1 && l - r <= 1) return 1 + max(l, r); 24 | else return -1; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /beautiful-arrangement-ii-1.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/beautiful-arrangement-ii/submissions/1 2 | 3 | class Solution { 4 | public: 5 | vector constructArray(int n, int k) { 6 | int i = 1, j = n; 7 | vector answer(n); 8 | int idx = 0; 9 | while(j >= i){ 10 | if (k > 1){ 11 | answer[idx++] = (k-- % 2 ? i++ : j--); 12 | } else { 13 | answer[idx++] = i++; 14 | } 15 | } 16 | 17 | return answer; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /best-time-to-buy-and-sell-stock-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/ 2 | 3 | class Solution { 4 | public: 5 | int maxProfit(vector& prices) { 6 | int ans = 0, currMin = prices.size() ? prices[0] : 0; 7 | for(int p : prices){ 8 | ans = max(ans, p - currMin); 9 | currMin = min(p, currMin); 10 | } 11 | return ans; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /best-time-to-buy-and-sell-stock-4.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/ 2 | 3 | class Solution { 4 | public: 5 | int maxProfit(vector& prices) { 6 | int mn = INT_MAX, ans = 0; 7 | 8 | for(int price : prices){ 9 | if (price < mn) mn = price; 10 | else if (price > mn) ans = max(price - mn, ans); 11 | } 12 | 13 | return ans; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /best-time-to-buy-and-sell-stock-5.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/ 2 | 3 | class Solution { 4 | public: 5 | int maxProfit(vector& prices) { 6 | int ans = 0, n = prices.size(), buy = n ? prices[0]: 0; 7 | 8 | for(int price : prices){ 9 | ans = max(ans, price - buy); 10 | buy = min(buy, price); 11 | } 12 | 13 | return ans; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /best-time-to-buy-and-sell-stock-6.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/ 2 | 3 | class Solution { 4 | public: 5 | int maxProfit(vector& prices) { 6 | int ans = 0, min_price = prices.size() ? prices[0] : 0; 7 | 8 | for(auto price: prices){ 9 | ans = max(ans, price - min_price); 10 | min_price = min(min_price, price); 11 | } 12 | return ans; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /best-time-to-buy-and-sell-stock-ii-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ 2 | 3 | class Solution { 4 | public: 5 | int maxProfit(vector& prices) { 6 | int n = prices.size(), ans = 0; 7 | if (n <= 0) return ans; 8 | 9 | vector sell(n + 1, 0), buy(n + 1, 0); 10 | 11 | buy[0] = -prices[0]; 12 | sell[0] = 0; 13 | 14 | for(int i = 1; i <= n; i++){ 15 | sell[i] = i == n ? sell[i-1] : max(sell[i-1], buy[i-1] + prices[i]); 16 | buy[i] = i == n ? buy[i-1] : max(buy[i-1], sell[i-1] - prices[i]); 17 | } 18 | 19 | return sell[n]; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /best-time-to-buy-and-sell-stock-with-cooldown-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/ 2 | 3 | typedef vector> vvi; 4 | typedef vector vi; 5 | class Solution { 6 | public: 7 | int maxProfit(vector& prices) { 8 | int n = prices.size(), cooldown = 1; 9 | if (n == 0) return 0; 10 | vvi dp(n + 1, vi(2,0)); 11 | 12 | dp[0][1] = INT_MIN; // you cannot buy a non-existent item 13 | dp[1][1] = -prices[0]; 14 | 15 | for(int i = 2; i <= n; i++){ 16 | dp[i][0] = max(dp[i - 1][0], dp[i-1][1] + prices[i-1]); 17 | dp[i][1] = max(dp[i - 1][1], dp[i - 1 - cooldown][0] - prices[i-1]); 18 | } 19 | 20 | return dp[n][0]; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /best-time-to-buy-and-sell-stock-with-transaction-fee-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/description/ 2 | 3 | class Solution { 4 | public: 5 | int maxProfit(vector& prices, int fee) { 6 | int n = prices.size(); 7 | int sell = 0, buy = -prices[0], psell; 8 | for(int i = 2; i <= n; i++){ 9 | psell = sell; 10 | sell = max(sell, buy + prices[i-1] - fee); 11 | buy = max(buy, psell - prices[i-1]); 12 | } 13 | return sell; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /best-time-to-buy-and-sell-stock-with-transaction-fee.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/description/ 2 | 3 | class Solution { 4 | public: 5 | int maxProfit(vector& prices, int fee) { 6 | int T_i_0 = 0, T_i_1 = -prices[0],temp; 7 | 8 | for(int i = 1; i < prices.size(); i ++){ 9 | temp = T_i_0; 10 | // we've 0 stocks at the end 11 | // rest, sell 12 | T_i_0 = max(T_i_0, T_i_1 + prices[i] - fee); 13 | 14 | // We've 1 stocks at the end 15 | // rest, buy 16 | T_i_1 = max(T_i_1, temp - prices[i]); 17 | } 18 | 19 | return T_i_0; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /binary-gap-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/contest/weekly-contest-93/problems/binary-gap/ 2 | 3 | class Solution { 4 | public: 5 | int binaryGap(int N) { 6 | int ans = 0, i = 0, pos = -1; 7 | 8 | while(N){ 9 | int temp = N % 2; 10 | if (temp == 1) { 11 | if (pos != -1) ans = max(ans, i - pos); 12 | 13 | pos = i; 14 | } 15 | N /= 2; 16 | i++; 17 | } 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /binary-number-with-alternating-bits.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/binary-number-with-alternating-bits/description/ 2 | 3 | class Solution { 4 | public: 5 | bool hasAlternatingBits(int n) { 6 | int temp = (n ^ (n >> 1)) + 1; 7 | return !(temp & (temp - 1)); 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /binary-tree-level-order-traversal-ii-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/binary-tree-level-order-traversal-ii/description/ 2 | class Solution { 3 | public: 4 | void helper(TreeNode* root, vector>& ans, int h){ 5 | if(!root) return; 6 | else if (ans.size() == h - 1) ans.push_back(vector()); 7 | 8 | ans[h - 1].push_back(root->val); 9 | helper(root->left, ans, h + 1); 10 | helper(root->right, ans, h + 1); 11 | 12 | } 13 | vector> levelOrderBottom(TreeNode* root) { 14 | vector> answer; 15 | helper(root, answer, 1); 16 | 17 | reverse(answer.begin(), answer.end()); 18 | return answer; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /binary-tree-tilt-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/binary-tree-tilt/description/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int sum = 0; 15 | int findTilt(TreeNode* root) { 16 | helper(root); 17 | return sum; 18 | } 19 | 20 | int helper(TreeNode* root){ 21 | if (!root) return 0; 22 | int l = helper(root->left); 23 | int r = helper(root->right); 24 | sum += abs(l - r); 25 | return l + r + root->val; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /can-place-flowers.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/can-place-flowers/description/ 2 | 3 | class Solution { 4 | public: 5 | bool canPlaceFlowers(vector& flowerbed, int n) { 6 | int zeroCount = 1, possibleSpots = 0; 7 | 8 | for(int n : flowerbed){ 9 | if (n == 0){ 10 | zeroCount++; 11 | if (zeroCount == 3){ 12 | possibleSpots++; 13 | zeroCount = 1; 14 | } 15 | } else { 16 | zeroCount = 0; 17 | } 18 | } 19 | if (zeroCount == 2) possibleSpots++; 20 | return (possibleSpots >= n) ? true : false; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /climbing-stairs-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/climbing-stairs/description/ 2 | 3 | class Solution { 4 | public: 5 | int climbStairs(int n) { 6 | int a = 1, b = 2, c; 7 | if (n < 3) return n; 8 | // a -> i - 1th, b -> ith 9 | for(int i = 3; i <= n; i++){ 10 | c = b; 11 | b = b + a; 12 | a = c; 13 | } 14 | 15 | return b; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /climbing-stairs-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/climbing-stairs/description/ 2 | 3 | class Solution { 4 | public: 5 | int climbStairs(int n) { 6 | if (n < 2) return n; 7 | int a = 1, b = 1; 8 | // a: number of steps to reach n - 1 9 | // b: number of steps to reach n - 2 10 | 11 | for(int i = 2; i <= n; i++){ 12 | a = b + a; 13 | b = a - b; 14 | } 15 | 16 | return a; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /coin-change-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/coin-change/description/ 2 | 3 | class Solution { 4 | public: 5 | int coinChange(vector& coins, int amount) { 6 | unordered_map dp; 7 | dp[0] = 0; 8 | for(int i = 1; i <= amount; i++){ 9 | dp[i] = INT_MAX; 10 | for(auto coin : coins){ 11 | if (i - coin >= 0 && dp[i-coin] != INT_MAX) 12 | dp[i] = min(dp[i-coin] + 1, dp[i]); 13 | } 14 | } 15 | 16 | return dp[amount] != INT_MAX ? dp[amount] : -1; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /combination-sum-iv-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/combination-sum-iv/description/ 2 | 3 | class Solution { 4 | public: 5 | 6 | unordered_map dp; 7 | int combinationSum4(vector& nums, int target) { 8 | 9 | if (target <= 0) return target == 0; 10 | else if (dp.count(target)) return dp[target]; 11 | 12 | int ans = 0; 13 | for(int num : nums){ 14 | ans += combinationSum4(nums, target - num); 15 | } 16 | dp[target] = ans; 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /combination-sum-iv-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/combination-sum-iv/description/ 2 | 3 | class Solution { 4 | public: 5 | unordered_map dp; 6 | 7 | int combinationSum4(vector& nums, int target) { 8 | return nums.size() > 0 ? helper(nums, target) : target == 0; 9 | } 10 | 11 | int helper(vector& nums, int target){ 12 | if (target <= 0) return target == 0; 13 | else if (dp.count(target)) return dp[target]; 14 | 15 | int ans = 0; 16 | 17 | for(int i = 0; i < nums.size(); i++) 18 | ans += helper(nums, target - nums[i]); 19 | 20 | return dp[target] = ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /combination-sum-iv-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/combination-sum-iv/description/ 2 | 3 | class Solution { 4 | public: 5 | int combinationSum4(vector& nums, int target) { 6 | vector dp (target + 1, 0); 7 | 8 | for(int n : nums){ 9 | if (n <= target) 10 | dp[n] = 1; 11 | } 12 | 13 | for(int i = 1; i <= target; i++){ 14 | for(int j = 0; j < nums.size(); j++) 15 | dp[i] += (i - nums[j] >= 0) ? dp[i - nums[j]] : 0; 16 | } 17 | 18 | return dp[target]; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /container-with-most-water-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/container-with-most-water/description/ 2 | 3 | class Solution { 4 | public: 5 | int maxArea(vector& height) { 6 | int i = 0, j = height.size() - 1, ans = 0; 7 | while(i < j){ 8 | if (height[i] < height[j]){ 9 | ans = max(ans, height[i] * (j - i)); 10 | i++; 11 | } else { 12 | ans = max(ans, height[j] * (j - i)); 13 | j--; 14 | } 15 | } 16 | 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /container-with-most-water-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/container-with-most-water/description/ 2 | 3 | class Solution { 4 | public: 5 | int maxArea(vector& height) { 6 | int ans = 0, i = 0, j = height.size() - 1; 7 | 8 | while(i < j){ 9 | if (height[i] < height[j]){ 10 | ans = max(ans, height[i] * (j - i)); 11 | i++; 12 | } else { 13 | ans = max(ans, height[j] * (j - i)); 14 | j--; 15 | } 16 | } 17 | 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /contains-duplicate-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/contains-duplicate/description/ 2 | class Solution { 3 | public: 4 | bool containsDuplicate(vector& nums) { 5 | unordered_map hash_table; 6 | int ans = false; 7 | for(int i = 0; i < nums.size() && !ans; i++){ 8 | auto itr = hash_table.find(nums[i]); 9 | if (itr != hash_table.end()) 10 | ans = true; 11 | else hash_table[nums[i]] = true; 12 | } 13 | return ans; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /contains-duplicate-ii.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/contains-duplicate-ii/description/ 2 | 3 | class Solution { 4 | public: 5 | bool containsNearbyDuplicate(vector& nums, int k) { 6 | if (k ==0) return false; 7 | unordered_map table; 8 | int num; 9 | for(int i = 0; i < nums.size(); i++){ 10 | num = nums[i]; 11 | if (table.find(num) != table.end() && i - table[num] <= k){ 12 | // number was encountered previously 13 | return true; 14 | } 15 | // update in either case because future number might be within the range 16 | table[num] = i; 17 | } 18 | 19 | return false; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /contiguous-array-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/contiguous-array/description/ 2 | 3 | class Solution { 4 | public: 5 | int findMaxLength(vector& nums) { 6 | int p = 0, ans = 0, i = 0; 7 | unordered_map countMap; 8 | countMap[0] = -1; 9 | 10 | for(int n : nums){ 11 | p += n ? 1 : -1; 12 | if (countMap.count(p)) 13 | ans = max(ans, i - countMap[p]); 14 | else countMap[p] = i; 15 | i++; 16 | } 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /continuous-subarray-sum-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/continuous-subarray-sum/description/ 2 | 3 | class Solution { 4 | public: 5 | bool checkSubarraySum(vector& nums, int k) { 6 | unordered_map preSum; 7 | int p = 0; 8 | preSum[0] = -1; 9 | 10 | for(int i = 0; i < nums.size(); i++){ 11 | p = k ? (p + nums[i]) % k : p + nums[i]; 12 | if (preSum.count(p) && i - preSum[p] > 1) 13 | return true; 14 | if (!preSum.count(p)) 15 | preSum[p] = i; 16 | } 17 | 18 | return false; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /continuous-subarray-sum.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/continuous-subarray-sum/description/ 2 | 3 | class Solution { 4 | public: 5 | bool checkSubarraySum(vector& nums, int k) { 6 | unordered_map remHash = {{0, -1}}; 7 | unordered_map :: iterator itr; 8 | int runningRem = 0; 9 | for(int i = 0; i < nums.size(); i++){ 10 | runningRem += nums[i]; 11 | if (k != 0) runningRem %= k; 12 | if ((itr = remHash.find(runningRem)) != remHash.end()) { 13 | if(i - itr->second > 1) 14 | return true; 15 | } 16 | else remHash[runningRem] = i; 17 | } 18 | return false; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /convert-bst-to-greater-tree-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/convert-bst-to-greater-tree/description/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int globalValue = 0; 15 | TreeNode* convertBST(TreeNode* root) { 16 | if (!root) 17 | return root; 18 | 19 | convertBST(root->right); 20 | globalValue = (root->val += globalValue); 21 | convertBST(root->left); 22 | 23 | return root; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /count-numbers-with-unique-digits-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/count-numbers-with-unique-digits/description/ 2 | 3 | class Solution { 4 | public: 5 | int countNumbersWithUniqueDigits(int n) { 6 | if (n == 0 || n == 1) return n ? 10 : 1; 7 | int curr = 9, ans = 10, temp = 9; 8 | 9 | for(int i = 2; i <= n && i < 10; i++){ 10 | curr *= temp; 11 | ans += curr; 12 | temp--; 13 | } 14 | 15 | return ans; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /count-primes-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/count-primes/description/ 2 | class Solution { 3 | public: 4 | int countPrimes(int n) { 5 | int ans = 0; // handles non-negative numbers 6 | if (n == 0) return ans; 7 | 8 | bool flag[n]; 9 | for(int i = 0; i < n; i++) 10 | flag[i] = false; 11 | 12 | for(int i = 2; i < n; i++){ 13 | if (flag[i] == false){ 14 | ans++; 15 | for(int j = 2; i * j < n; j++) 16 | flag[i * j] = true; 17 | } 18 | } 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /counting-bits-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/counting-bits/description/ 2 | 3 | typedef vector vi; 4 | class Solution { 5 | public: 6 | vector countBits(int num) { 7 | 8 | vi answer(num+1, 0); 9 | 10 | for(int i = 1; i <= num; i++) 11 | answer[i] = answer[i >> 1] + (i & 1); 12 | 13 | return answer; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /custom-sort-string-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/custom-sort-string/description/ 2 | 3 | class Solution { 4 | public: 5 | string customSortString(string S, string T) { 6 | vector t(26, 0); 7 | stringstream ss; 8 | 9 | for(char c : T) 10 | t[c - 'a']++; 11 | 12 | for(char c : S) 13 | while(t[c - 'a']-- > 0) ss << string(1, c); 14 | 15 | for(int i = 0; i < 26; i++) 16 | while(t[i]-- > 0) ss << string(1, 'a' + i); 17 | 18 | return ss.str(); 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /delete-node-in-a-linked-list-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/delete-node-in-a-linked-list/description/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode(int x) : val(x), next(NULL) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | void deleteNode(ListNode* node) { 14 | node->val = node->next->val; 15 | node->next = node->next->next; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /delete-node-in-a-linked-list-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/delete-node-in-a-linked-list/description/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode(int x) : val(x), next(NULL) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | void deleteNode(ListNode* node) { 14 | swap(node->val, node->next->val); 15 | node->next = node->next->next; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /delete-node-in-a-linked-list.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/delete-node-in-a-linked-list/description/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode(int x) : val(x), next(NULL) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | void deleteNode(ListNode* node) { 14 | ListNode* prev; 15 | while(node->next != NULL){ 16 | prev = node; 17 | node->val = node->next->val; 18 | node = node->next; 19 | } 20 | prev->next = NULL; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /diameter-of-binary-tree-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/diameter-of-binary-tree/description/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int diameterOfBinaryTree(TreeNode* root) { 15 | int ans = 1; 16 | helper(root, ans); 17 | return ans - 1; 18 | } 19 | 20 | int helper(TreeNode* root, int& ans){ 21 | if (!root) return 0; 22 | int l = helper(root->left, ans); 23 | int r = helper(root->right, ans); 24 | ans = max(ans, l + r + 1); 25 | return 1 + max(l, r); 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /divide-two-integers-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/divide-two-integers/ 2 | 3 | class Solution { 4 | public: 5 | int divide(int dividend, int divisor) { 6 | if (dividend == INT_MIN && abs(divisor) == 1) return divisor == -1 ? INT_MAX : INT_MIN; 7 | int ans = 0, sign = (dividend < 0 ^ divisor < 0) ? -1 : 1; 8 | long dvd = labs(dividend), dvs = labs(divisor); 9 | 10 | while(dvd >= dvs){ 11 | int temp = helper(dvd, dvs); 12 | dvd = dvd - dvs*temp; 13 | ans += temp; 14 | } 15 | 16 | return sign*ans; 17 | } 18 | 19 | int helper(long dvd, long dvs){ 20 | long i = 1; 21 | while(dvd >= dvs*i) 22 | i = i * 2; 23 | return i / 2; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /divide-two-integers-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/divide-two-integers/description/ 2 | 3 | class Solution { 4 | public: 5 | int divide(int dividend, int divisor) { 6 | long div = labs(dividend), dis = labs(divisor), ans = 0; 7 | 8 | while(div >= dis){ 9 | long m = 1; 10 | long num = dis; 11 | 12 | while((num << 1) < div){ 13 | num <<= 1; 14 | m <<= 1; 15 | } 16 | ans += m; 17 | div = div - num; 18 | } 19 | 20 | if ((dividend < 0) ^ (divisor < 0)) return -ans < INT_MIN ? INT_MIN : -ans; 21 | return ans > INT_MAX ? INT_MAX : ans; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /employee-importance.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/employee-importance/description/ 2 | 3 | class Solution { 4 | public: 5 | int getImportance(vector employees, int id) { 6 | unordered_map hashMap; 7 | stack stk; 8 | Employee* eTemp; 9 | int totalImp = 0; 10 | for(auto &e : employees) 11 | hashMap[e->id] = e; 12 | 13 | stk.push(hashMap[id]); 14 | while(!stk.empty()){ 15 | eTemp = stk.top(); 16 | stk.pop(); 17 | totalImp += eTemp->importance; 18 | for(auto &i : eTemp->subordinates) 19 | stk.push(hashMap[i]); 20 | } 21 | 22 | return totalImp; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /excel-sheet-column-number-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/excel-sheet-column-number/ 2 | 3 | class Solution { 4 | public: 5 | int titleToNumber(string s) { 6 | int result = 0; 7 | for(int i = 0; i < s.length(); result = result * 26 + s[i++] - 'A' + 1); 8 | return result; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /excel-sheet-column-title-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/excel-sheet-column-title/description/ 2 | 3 | class Solution { 4 | public: 5 | string convertToTitle(int n) { 6 | string ans = ""; 7 | int j; 8 | while(n){ 9 | j = (n - 1) % 26; 10 | n = (n - 1) / 26; 11 | ans.insert(0, 1, 'A' + j); 12 | } 13 | return ans; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /excel-sheet-column-title-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/excel-sheet-column-title/description/ 2 | 3 | class Solution { 4 | public: 5 | string convertToTitle(int n) { 6 | stringstream ss; 7 | while(n){ 8 | int c = (n - 1) % 26; 9 | n = (n - 1) / 26; 10 | ss << string(1, 'A' + c); 11 | } 12 | string ans = ss.str(); 13 | reverse(ans.begin(), ans.end()); 14 | return ans; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /factorial-trailing-zeroes.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/factorial-trailing-zeroes/description/ 2 | 3 | class Solution { 4 | public: 5 | int trailingZeroes(int n) { 6 | long long int answer = 0, div = 5; 7 | while(div <= n){ 8 | answer += n / div; 9 | div *= 5; 10 | } 11 | return answer; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /find-all-duplicates-in-an-array-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-all-duplicates-in-an-array/submissions/1 2 | 3 | class Solution { 4 | public: 5 | vector findDuplicates(vector& nums) { 6 | vector ans; 7 | int n = nums.size(); 8 | 9 | for(int i = 0; i < n; i++){ 10 | int index = (nums[i] - 1) % n; 11 | nums[index] += n; 12 | } 13 | 14 | for(int i = 0; i < n; i++){ 15 | if ((nums[i] / n == 2 && nums[i] % n != 0) || nums[i] / n == 3){ 16 | ans.push_back(i + 1); 17 | } 18 | } 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /find-all-duplicates-in-an-array-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-all-duplicates-in-an-array/description/ 2 | 3 | class Solution { 4 | public: 5 | vector findDuplicates(vector& nums) { 6 | vector ans; 7 | int n = nums.size(); 8 | 9 | for(int i = 0; i < n; i++){ 10 | int index = abs(nums[i]) - 1; 11 | if (nums[index] < 0) ans.push_back(abs(nums[i])); 12 | else nums[index] *= -1; 13 | } 14 | return ans; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /find-all-numbers-disappeared-in-an-array.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/description/ 2 | 3 | class Solution { 4 | public: 5 | vector findDisappearedNumbers(vector& nums) { 6 | vector ans; 7 | int n = nums.size(); 8 | 9 | for(int i = 0; i < n; i++){ 10 | int index = abs(nums[i]) - 1; // correct index position of nums[i] 11 | nums[index] = -1*abs(nums[index]); 12 | } 13 | 14 | for(int i = 0; i < n; i++){ 15 | if (nums[i] > 0) 16 | ans.push_back(i + 1); 17 | } 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /find-anagram-mappings.cpp: -------------------------------------------------------------------------------- 1 | // https://www.lintcode.com/problem/find-anagram-mappings/description 2 | 3 | class Solution { 4 | public: 5 | /** 6 | * @param A: lists A 7 | * @param B: lists B 8 | * @return: the index mapping 9 | */ 10 | vector anagramMappings(vector &A, vector &B) { 11 | // Write your code here 12 | unordered_map> hashMap; 13 | vector ans; 14 | for(int i = 0; i < B.size(); i++){ 15 | if (!hashMap.count(B[i])) 16 | hashMap[B[i]] = stack(); 17 | hashMap[B[i]].push(i); 18 | } 19 | 20 | for(int &a : A){ 21 | ans.push_back(hashMap[a].top()); 22 | hashMap[a].pop(); 23 | } 24 | return ans; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /find-bottom-left-tree-value-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-bottom-left-tree-value/description/ 2 | -------------------------------------------------------------------------------- /find-bottom-left-tree-value-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-bottom-left-tree-value/description/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | 15 | int findBottomLeftValue(TreeNode* root) { 16 | queue q; 17 | q.push(root); 18 | 19 | while(!q.empty()){ 20 | root = q.front(); 21 | q.pop(); 22 | if (root->right) 23 | q.push(root->right); 24 | if (root->left) 25 | q.push(root->left); 26 | } 27 | return root->val; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /find-minimum-in-rotated-sorted-array-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/ 2 | 3 | class Solution { 4 | public: 5 | int findMin(vector& nums) { 6 | int s = 0, e = nums.size() - 1; 7 | while(s <= e){ 8 | int m = s + (e - s) / 2; 9 | if (m > s && nums[m] < nums[m-1]) 10 | return nums[m]; 11 | else if (m < e && nums[m] > nums[m+1]) 12 | return nums[m+1]; 13 | else if (nums[s] >= nums[m]) e = m - 1; 14 | else s = m + 1; 15 | } 16 | 17 | return nums[0]; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /find-minimum-in-rotated-sorted-array-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/ 2 | 3 | class Solution { 4 | public: 5 | int findMin(vector& nums) { 6 | int s = 0, e = nums.size() - 1; 7 | 8 | while(s < e){ 9 | int m = s + (e - s) / 2; 10 | if (m > s && nums[m] < nums[m-1]) return nums[m]; 11 | else if (m < e && nums[m] > nums[m+1]) return nums[m+1]; 12 | else if (nums[s] < nums[m]) s = m + 1; 13 | else e = m - 1; 14 | } 15 | 16 | return nums[0]; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /find-pivot-index-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-pivot-index/description/ 2 | 3 | class Solution { 4 | public: 5 | int pivotIndex(vector& nums) { 6 | int rt = 0, lt = 0, ans = -1; 7 | 8 | for(auto num : nums) 9 | rt += num; 10 | 11 | for(int i = 0; i < nums.size(); i++){ 12 | rt = rt - nums[i]; 13 | if (rt == lt) return i; 14 | lt += nums[i]; 15 | } 16 | 17 | return -1; 18 | 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /find-pivot-index-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-pivot-index/description/ 2 | 3 | class Solution { 4 | public: 5 | int pivotIndex(vector& nums) { 6 | int total = 0, lt = 0, ans = -1; 7 | 8 | for(auto num : nums) 9 | total += num; 10 | 11 | for(int i = 0; i < nums.size(); i++){ 12 | if (lt == total - nums[i] - lt) return i; 13 | lt += nums[i]; 14 | } 15 | 16 | return -1; 17 | 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /find-smallest-letter-greater-than-target.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-smallest-letter-greater-than-target/description 2 | 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | char nextGreatestLetter(vector& letters, char target) { 9 | vector hash_table(27, 0); 10 | char ans = 0; 11 | for(char c : letters) 12 | hash_table[c - 'a']++; 13 | 14 | target++; 15 | while(!ans){ 16 | target = (target > 'z') ? 'a' : target; 17 | ans = (hash_table[target++ - 'a'] > 0) ? --target : ans; 18 | } 19 | return ans; 20 | 21 | // auto ans = lower_bound(letters.begin(), letter.end(), target); 22 | } 23 | }; 24 | 25 | -------------------------------------------------------------------------------- /find-the-celebrity-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-the-celebrity/description/ 2 | 3 | // Forward declaration of the knows API. 4 | bool knows(int a, int b); 5 | 6 | class Solution { 7 | public: 8 | int findCelebrity(int n) { 9 | int cand = 0; 10 | for(int i = 1; i < n; i++) 11 | if (!knows(i, cand)) 12 | cand = i; 13 | for(int j = 0; j < n; j++) 14 | if (j == cand) continue; 15 | else if (!knows(j, cand) || knows(cand, j)) 16 | return -1; 17 | return cand; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /find-the-celebrity-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-the-celebrity/description/ 2 | 3 | // Forward declaration of the knows API. 4 | bool knows(int a, int b); 5 | 6 | class Solution { 7 | public: 8 | int findCelebrity(int n) { 9 | int ans = 0; 10 | 11 | for(int i = 1; i < n; i++){ 12 | if (knows(ans, i)) 13 | ans = i; 14 | } 15 | 16 | for(int i = 0; i < n; i++){ 17 | if (ans == i) continue; 18 | if (!knows(i, ans) || knows(ans, i)) return -1; 19 | } 20 | 21 | return ans; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /find-the-celebrity-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-the-celebrity/description/ 2 | 3 | // Forward declaration of the knows API. 4 | bool knows(int a, int b); 5 | 6 | class Solution { 7 | public: 8 | int findCelebrity(int n) { 9 | int cel = 0; 10 | 11 | for(int i = 1; i < n; i++){ 12 | if (knows(i, cel) && !knows(cel, i)) 13 | cel = cel; 14 | else 15 | cel = i; 16 | } 17 | 18 | for(int i = 0; i < n; i++){ 19 | if (cel == i) continue; 20 | else if (knows(i, cel) && !knows(cel, i)) 21 | cel = cel; 22 | else return -1; 23 | } 24 | 25 | return cel; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /find-the-difference.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-the-difference/description/ 2 | 3 | class Solution { 4 | public: 5 | char findTheDifference(string s, string t) { 6 | char r = 0; 7 | for(char c : s) r ^= c; 8 | for(char c : t) r ^= c; 9 | return r; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /find-the-duplicate-number-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-the-duplicate-number/description/ 2 | 3 | class Solution { 4 | public: 5 | int findDuplicate(vector& nums) { 6 | int slow = nums[0]; 7 | int fast = nums[nums[0]]; 8 | 9 | while(slow != fast){ 10 | slow = nums[slow]; 11 | fast = nums[nums[fast]]; 12 | } 13 | 14 | fast = 0; 15 | 16 | while(fast != slow){ 17 | slow = nums[slow]; 18 | fast = nums[fast]; 19 | } 20 | return fast; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /find-the-duplicate-number-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/find-the-duplicate-number/solution/# 2 | 3 | class Solution { 4 | public: 5 | int findDuplicate(vector& nums) { 6 | int slow = nums[0], fast = nums[nums[0]]; 7 | 8 | while(slow != fast){ 9 | slow = nums[slow]; 10 | fast = nums[nums[fast]]; 11 | } 12 | 13 | slow = 0; 14 | 15 | while(slow != fast){ 16 | slow = nums[slow]; 17 | fast = nums[fast]; 18 | } 19 | 20 | return slow; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /first-bad-version-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/first-bad-version/description/ 2 | 3 | // Forward declaration of isBadVersion API. 4 | bool isBadVersion(int version); 5 | 6 | class Solution { 7 | public: 8 | int firstBadVersion(int n) { 9 | int s = 1, e = isBadVersion(1) ? 1 : n, m; 10 | 11 | // find leftmost true 12 | while(e - s > 1){ 13 | m = s + (e - s) / 2; 14 | if (isBadVersion(m)) e = m; 15 | else s = m; 16 | } 17 | 18 | return e; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /first-bad-version-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/first-bad-version/description/ 2 | 3 | // Forward declaration of isBadVersion API. 4 | bool isBadVersion(int version); 5 | 6 | class Solution { 7 | public: 8 | int firstBadVersion(int n) { 9 | // right most good 10 | int l = isBadVersion(1) ? 0 : 1, r = n; 11 | while(r - l > 1){ 12 | int m = l + (r - l) / 2; 13 | if (isBadVersion(m)) r = m; 14 | else l = m; 15 | } 16 | return l + 1; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /first-unique-character-in-a-string-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/first-unique-character-in-a-string/description/ 2 | 3 | class Solution { 4 | public: 5 | int firstUniqChar(string s) { 6 | vector char_count(26, 0); 7 | int ans = 0; 8 | for(char c : s) 9 | char_count[c - 'a']++; 10 | 11 | for(char c : s){ 12 | if (char_count[c - 'a'] == 1) 13 | return ans; 14 | ++ans; 15 | } 16 | 17 | return -1; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /first-unique-character-in-a-string-4.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/first-unique-character-in-a-string/description/ 2 | 3 | class Solution { 4 | public: 5 | int firstUniqChar(string s) { 6 | int n = s.length(), ans = n + 1; 7 | vector hash(26, n + 1); 8 | 9 | for(int i = 0; i < n; i++){ 10 | int idx = s[i] - 'a'; 11 | if (hash[idx] < n) hash[idx] = n; 12 | else if (hash[idx] == n + 1) hash[idx] = i; 13 | } 14 | 15 | for(int i = 0; i < 26; i++) 16 | ans = min(hash[i], ans); 17 | 18 | return ans < n ? ans : -1; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /fizz-buzz-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/fizz-buzz/description/ 2 | 3 | class Solution { 4 | public: 5 | vector fizzBuzz(int n) { 6 | vector ans; 7 | 8 | for(int i = 1; i <= n; i++){ 9 | string temp = ""; 10 | if (i % 3 == 0) temp = temp + "Fizz"; 11 | if (i % 5 == 0) temp = temp + "Buzz"; 12 | if (temp.length() == 0) temp = to_string(i); 13 | ans.push_back(temp); 14 | } 15 | return ans; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /fizz-buzz.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/fizz-buzz/submissions/1 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | vector fizzBuzz(int n) { 8 | vector ans(n); 9 | const string s1 = "Fizz", s2 = "Buzz", s3 = s1 + s2; 10 | for(int i = 0; i < n; i++){ 11 | bool flag3 = ((i+1) % 3 == 0); 12 | bool flag5 = ((i+1) % 5 == 0); 13 | 14 | ans[i] = (flag3 && flag5) ? s3 : (flag3 ? s1 : (flag5 ? s2 : to_string(i+1))); 15 | } 16 | return ans; 17 | } 18 | }; 19 | 20 | -------------------------------------------------------------------------------- /flatten-binary-tree-to-linked-list-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | void flatten(TreeNode* root) { 15 | // helper(root); 16 | if (!root) return; 17 | flatten(root->left); 18 | flatten(root->right); 19 | TreeNode* temp = root->right; 20 | root->right = root->left; 21 | root->left = NULL; 22 | while(root->right) root = root->right; 23 | root->right = temp; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /flatten-binary-tree-to-linked-list-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | 15 | TreeNode* prev = NULL; 16 | void flatten(TreeNode* root) { 17 | if (!root) return; 18 | 19 | flatten(root->right); 20 | flatten(root->left); 21 | 22 | root->right = prev; 23 | prev = root; 24 | root->left = NULL; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /flatten-nested-list-iterator-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/flatten-nested-list-iterator/description/ 2 | 3 | class NestedIterator { 4 | public: 5 | NestedIterator(vector &nestedList) { 6 | flatten(nestedList); 7 | } 8 | 9 | int next() { 10 | int v = q.front(); 11 | q.pop(); 12 | return v; 13 | } 14 | 15 | bool hasNext() { 16 | return !q.empty(); 17 | } 18 | 19 | private: 20 | queue q; 21 | 22 | void flatten(vector &nestedList){ 23 | for(auto nn : nestedList){ 24 | if (nn.isInteger()) q.push(nn.getInteger()); 25 | else flatten(nn.getList()); 26 | } 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /flip-game.cpp: -------------------------------------------------------------------------------- 1 | // https://www.lintcode.com/problem/flip-game/description 2 | 3 | class Solution { 4 | public: 5 | /** 6 | * @param s: the given string 7 | * @return: all the possible states of the string after one valid move 8 | */ 9 | vector generatePossibleNextMoves(string &s) { 10 | // write your code here 11 | vector ans; 12 | int start = 1; 13 | 14 | while(start < s.length()){ 15 | if (s[start] == '+' && s[start - 1] == '+'){ 16 | ans.push_back(s); 17 | ans.back()[start] = '-'; 18 | ans.back()[start - 1] = '-'; 19 | } 20 | start++; 21 | } 22 | 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /flipping-an-image.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/flipping-an-image/description/ 2 | 3 | class Solution { 4 | public: 5 | vector> flipAndInvertImage(vector>& A) { 6 | int n = A.size(), m = A[0].size(); 7 | vector> answer(n, vector(m, 0)); 8 | 9 | for(int i = 0; i < n; i++) 10 | for(int j = m - 1; j >= 0; j--) 11 | answer[i][m - 1 - j] = (!A[i][j]); 12 | 13 | return answer; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /friends-circles-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/friend-circles/description/ 2 | 3 | 4 | class Solution { 5 | public: 6 | typedef vector> vvi; 7 | int findCircleNum(vector>& M) { 8 | int n = M.size(); 9 | int ans = 0; 10 | for(int i = 0; i < n; i++){ 11 | dfs(M, i, ans, true); 12 | } 13 | return ans; 14 | } 15 | 16 | void dfs(vvi& M, int i, int& ans, bool flag){ 17 | for(int j = 0; j < M.size(); j++){ 18 | if (M[i][j] == 1){ 19 | M[i][j] = 0; 20 | if (j != i) dfs(M, j, ans, false); 21 | else if (flag && i == j) ans++; 22 | } 23 | } 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /frog-jump-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/frog-jump/ 2 | 3 | class Solution { 4 | public: 5 | bool canCross(vector& stones) { 6 | unordered_map> dp; 7 | int n = stones.size(); 8 | for(auto stone : stones) 9 | dp[stone] = unordered_set(); 10 | 11 | dp[0].insert(0); 12 | 13 | for(auto stone : stones){ 14 | for(auto k : dp[stone]){ 15 | for(int step = k - 1; step <= k + 1; step++){ 16 | if (step > 0 && dp.count(stone + step)) 17 | dp[stone+step].insert(step); 18 | } 19 | } 20 | } 21 | 22 | return dp[stones[n-1]].size(); 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /goat-latin-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/goat-latin/description/ 2 | 3 | class Solution { 4 | public: 5 | string toGoatLatin(string S) { 6 | bool flag = false; 7 | string token; 8 | stringstream ss(S), ans; 9 | string aux = "a"; 10 | while(ss >> token){ 11 | if (flag) ans << " "; 12 | if (!isVowel(token[0])) 13 | token = token.substr(1) + string(1, token[0]); 14 | ans << token << "ma" << aux; 15 | aux = aux + "a"; 16 | flag = true; 17 | } 18 | return ans.str(); 19 | } 20 | 21 | bool isVowel(char c ){ 22 | c = tolower(c); 23 | return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /guess-number-higher-or-lower.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/guess-number-higher-or-lower/description/ 2 | 3 | // Forward declaration of guess API. 4 | // @param num, your guess 5 | // @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 6 | int guess(int num); 7 | 8 | class Solution { 9 | public: 10 | int guessNumber(int n) { 11 | long low = 1, high = n, mid; 12 | 13 | while(low <= high){ 14 | mid = low + ((high - low) >> 1); 15 | int g = guess(mid); 16 | if (g == 0) return mid; 17 | else if (g == 1) low = mid + 1; 18 | else high = mid - 1; 19 | } 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /hamming-distance-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/hamming-distance/description/ 2 | 3 | class Solution { 4 | public: 5 | int hammingDistance(int x, int y) { 6 | x ^= y; 7 | int ans = 0; 8 | while(x){ 9 | ans += (x&1); 10 | x = x >> 1; 11 | } 12 | return ans; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /hamming-distance-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/hamming-distance/description/ 2 | 3 | class Solution { 4 | public: 5 | int hammingDistance(int x, int y) { 6 | int z = x^y, ans = 0; 7 | while(z){ 8 | ans++; 9 | z = (z & (z - 1)); 10 | } 11 | return ans; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /happy-number.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/happy-number/description/ 2 | 3 | class Solution { 4 | public: 5 | 6 | int digitSum(int n){ 7 | int ans = 0; 8 | 9 | while(n){ 10 | int d = n % 10; 11 | ans += d*d; 12 | n /= 10; 13 | } 14 | 15 | return ans; 16 | } 17 | 18 | bool isHappy(int n) { 19 | int slow, fast; 20 | slow = fast = n; 21 | do { 22 | slow = digitSum(slow); 23 | fast = digitSum(fast); 24 | fast = digitSum(fast); 25 | } while (slow != fast); 26 | return (slow == 1) ? true : false; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /house-robber-4.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/house-robber/ 2 | 3 | class Solution { 4 | public: 5 | int rob(vector& nums) { 6 | int a = 0, b = 0; 7 | 8 | for(int i = 0; i < nums.size(); i++){ 9 | if (i % 2) b = max(a, b + nums[i]); 10 | else a = max(a + nums[i], b); 11 | } 12 | 13 | return max(a, b); 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /intersection-of-two-arrays-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/intersection-of-two-arrays/description/ 2 | 3 | class Solution { 4 | public: 5 | vector intersection(vector& nums1, vector& nums2) { 6 | unordered_map hashMap; 7 | unordered_map :: iterator itr; 8 | set ans; 9 | for(auto &a : nums1) 10 | hashMap[a] = true; 11 | 12 | for(auto &a : nums2){ 13 | if ((itr = hashMap.find(a)) != hashMap.end()) 14 | ans.insert(a); 15 | } 16 | 17 | return vector(ans.begin(), ans.end()); 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /intersection-of-two-linked-lists-4.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/intersection-of-two-linked-lists/description/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode(int x) : val(x), next(NULL) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 14 | ListNode *A = headA, *B = headB; 15 | 16 | while(A != B){ 17 | A = !A ? headB : A->next; 18 | B = !B ? headA : B->next; 19 | } 20 | 21 | return A; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /invert-binary-tree-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/invert-binary-tree/description/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | TreeNode* invertTree(TreeNode* root) { 15 | if (!root) 16 | return root; 17 | TreeNode *ans = new TreeNode(root->val); 18 | ans->right = invertTree(root->left); 19 | ans->left = invertTree(root->right); 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /invert-binary-tree-6.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/invert-binary-tree/description/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | TreeNode* invertTree(TreeNode* root) { 15 | if (!root) 16 | return root; 17 | 18 | TreeNode* temp = root->right; 19 | root->right = root->left; 20 | root->left = temp; 21 | 22 | invertTree(root->right); 23 | invertTree(root->left); 24 | return root; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /jewels-and-stones-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/jewels-and-stones/description/ 2 | 3 | class Solution { 4 | public: 5 | int numJewelsInStones(string J, string S) { 6 | unordered_set jewelsMap(J.begin(), J.end()); 7 | int ans = 0; 8 | 9 | for(char c : S) 10 | ans += jewelsMap.count(c); 11 | 12 | return ans; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /keys-and-rooms-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/keys-and-rooms/description/ 2 | 3 | class Solution { 4 | public: 5 | bool canVisitAllRooms(vector>& rooms) { 6 | int N = rooms.size(), curr, counter = 0; 7 | vector visited(N, false); 8 | dfs(rooms, visited, counter, 0); 9 | return counter == N; 10 | } 11 | 12 | void dfs(vector>& rooms, vector& visited, int& counter, int start){ 13 | if (visited[start]) return; 14 | visited[start] =true; 15 | counter++; 16 | for(auto key : rooms[start]) 17 | dfs(rooms, visited, counter, key); 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /keys-and-rooms-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/keys-and-rooms/description/ 2 | 3 | class Solution { 4 | public: 5 | bool canVisitAllRooms(vector>& rooms) { 6 | int N = rooms.size(), curr, counter = 0; 7 | vector visited(N, false); 8 | queue stk; 9 | stk.push(0); 10 | 11 | while(!stk.empty()){ 12 | curr = stk.front(); 13 | stk.pop(); 14 | if(visited[curr]) 15 | continue; 16 | counter++; 17 | visited[curr] = true; 18 | for(auto room : rooms[curr]){ 19 | stk.push(room); 20 | } 21 | } 22 | 23 | return counter == N; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /keys-and-rooms-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/keys-and-rooms/description/ 2 | 3 | class Solution { 4 | public: 5 | bool canVisitAllRooms(vector>& rooms) { 6 | int N = rooms.size(), curr, counter = 0; 7 | vector visited(N, false); 8 | stack stk; 9 | stk.push(0); 10 | 11 | while(!stk.empty()){ 12 | curr = stk.top(); 13 | stk.pop(); 14 | if(visited[curr]) 15 | continue; 16 | counter++; 17 | visited[curr] = true; 18 | for(auto room : rooms[curr]){ 19 | stk.push(room); 20 | } 21 | } 22 | 23 | return counter == N; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /kth-largest-element-in-a-stream-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/kth-largest-element-in-a-stream/ 2 | 3 | 4 | class KthLargest { 5 | private: 6 | int k; 7 | priority_queue, greater> pq; 8 | public: 9 | KthLargest(int k, vector nums) { 10 | this->k = k; 11 | 12 | for(auto n : nums){ 13 | pq.push(n); 14 | if (pq.size() > k) pq.pop(); 15 | } 16 | } 17 | 18 | int add(int val) { 19 | pq.push(val); 20 | if (pq.size() > k) pq.pop(); 21 | return pq.top(); 22 | } 23 | }; 24 | 25 | /** 26 | * Your KthLargest object will be instantiated and called as such: 27 | * KthLargest obj = new KthLargest(k, nums); 28 | * int param_1 = obj.add(val); 29 | */ 30 | -------------------------------------------------------------------------------- /kth-largest-element-in-a-stream-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/kth-largest-element-in-a-stream/description/ 2 | 3 | class KthLargest { 4 | public: 5 | KthLargest(int k, vector nums) { 6 | this->k = k; 7 | for(auto n : nums){ 8 | pq.push(n); 9 | if (pq.size() > k) pq.pop(); 10 | } 11 | } 12 | 13 | int add(int val) { 14 | pq.push(val); 15 | 16 | if (pq.size() > k) pq.pop(); 17 | return pq.top(); 18 | } 19 | 20 | private: 21 | priority_queue, greater> pq; 22 | int k; 23 | }; 24 | 25 | /** 26 | * Your KthLargest object will be instantiated and called as such: 27 | * KthLargest obj = new KthLargest(k, nums); 28 | * int param_1 = obj.add(val); 29 | */ 30 | -------------------------------------------------------------------------------- /kth-largest-element-in-an-array-6.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/kth-largest-element-in-an-array/description/ 2 | 3 | class Solution { 4 | public: 5 | int findKthLargest(vector& nums, int k) { 6 | int n = nums.size(), lb = 0, ub = n - 1; 7 | k = n - k; 8 | 9 | while(true){ 10 | int p = nums[ub], i = lb - 1, j = lb; 11 | 12 | while(j <= ub){ 13 | if (p >= nums[j]) 14 | swap(nums[++i], nums[j]); 15 | j++; 16 | } 17 | 18 | if (i == k) return nums[k]; 19 | else if (i > k) ub = i - 1; 20 | else lb = i + 1; 21 | 22 | } 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /largest-number-at-least-twice-of-other-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/largest-number-at-least-twice-of-others/submissions/1 2 | 3 | class Solution { 4 | public: 5 | int dominantIndex(vector& nums) { 6 | int max1 = INT_MIN, max2 = INT_MIN, index; 7 | // max2 < max1; 8 | for(int i = 0; i < nums.size(); i++){ 9 | if (max1 < nums[i]){ 10 | max2 = max1; 11 | max1 = nums[i]; 12 | index = i; 13 | } else if (max2 < nums[i]){ 14 | max2 = nums[i]; 15 | } 16 | } 17 | return (max1 >= 2 * max2) ? index : -1; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /length-of-last-word.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/length-of-last-word/description/ 2 | 3 | class Solution { 4 | public: 5 | int lengthOfLastWord(string s) { 6 | int endWidx = s.length() - 1, startWidx; 7 | 8 | // iterating till the last character of last word is encountered 9 | for(; endWidx >= 0 && s[endWidx] == ' '; endWidx--); 10 | 11 | startWidx = endWidx; 12 | // iterating till the first character of the last word 13 | for(; startWidx >= 0 && s[startWidx] != ' '; startWidx--); 14 | 15 | return endWidx - startWidx; 16 | 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /letter-case-permutation-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/letter-case-permutation/description/ 2 | 3 | typedef vector vs; 4 | class Solution { 5 | public: 6 | vector letterCasePermutation(string S) { 7 | vs ans; 8 | helper(S, 0, ans); 9 | return ans; 10 | } 11 | 12 | void helper(string& s, int i, vs& ans){ 13 | while(i < s.length() && !isalpha(s[i])) i++; 14 | if (i == s.length()) { 15 | ans.push_back(s); 16 | return; 17 | } 18 | 19 | s[i] = tolower(s[i]); 20 | helper(s, i + 1, ans); 21 | s[i] = toupper(s[i]); 22 | helper(s, i + 1, ans); 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /license-key-formatting-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/license-key-formatting/ 2 | 3 | class Solution { 4 | public: 5 | string licenseKeyFormatting(string S, int K) { 6 | list ss; 7 | int n = S.length(), k = 0; 8 | 9 | for(int i = n - 1; i >= 0; i--){ 10 | if (S[i] == '-') continue; 11 | else if (k == K){ 12 | ss.push_front('-'); 13 | k = 0; 14 | } 15 | ss.push_front(toupper(S[i])); 16 | k++; 17 | } 18 | 19 | return string(ss.begin(), ss.end()); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /longest-common-prefix.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/longest-common-prefix/description/ 2 | #include 3 | using namespace std; 4 | class Solution { 5 | public: 6 | string longestCommonPrefix(vector& strs) { 7 | string s; 8 | int shortest_len; 9 | 10 | if (strs.size() == 0) return ""; 11 | 12 | s = strs[0]; 13 | for(string c: strs){ 14 | string temp = ""; 15 | shortest_len = min(c.length(), s.length()); 16 | for(int i = 0; i < shortest_len; i++){ 17 | if(s[i] == c[i]) 18 | temp += s[i]; 19 | else break; 20 | 21 | } 22 | s = temp; 23 | } 24 | return s; 25 | } 26 | }; 27 | 28 | -------------------------------------------------------------------------------- /longest-consecutive-sequence-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/longest-consecutive-sequence/description/ 2 | 3 | typedef unordered_map umpii; 4 | class Solution { 5 | public: 6 | int longestConsecutive(vector& nums) { 7 | int left, right, ans = 0; 8 | umpii len; 9 | 10 | for(int c : nums){ 11 | if (len.count(c)) 12 | continue; 13 | left = len.count(c-1) ? len[c-1] : 0; 14 | right = len.count(c+1) ? len[c+1] : 0; 15 | len[c] = left + right + 1; 16 | ans = max(ans, len[c]); 17 | len[c-left] = len[c]; 18 | len[c+right] = len[c]; 19 | } 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /longest-continuous-increasing-subsequence-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/longest-continuous-increasing-subsequence/description/ 2 | 3 | class Solution { 4 | public: 5 | int findLengthOfLCIS(vector& nums) { 6 | if (nums.size() < 1) return 0; 7 | int prev = nums[0] - 1, count = 0, temp = 0; 8 | for(int num : nums){ 9 | if (num > prev){ 10 | temp++; 11 | } else { 12 | count = max(count, temp); 13 | temp = 1; 14 | } 15 | prev = num; 16 | } 17 | count = max(count, temp); 18 | return count; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /longest-harmonious-subsequence.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/longest-harmonious-subsequence/description/ 2 | 3 | class Solution { 4 | public: 5 | int findLHS(vector& nums) { 6 | unordered_map hash; 7 | unordered_map :: iterator itr; 8 | int ans = 0, i; 9 | 10 | for(int &i : nums) hash[i]++; 11 | 12 | for(auto &t : hash){ 13 | for(i = -1; i <= 1; i += 2) 14 | if ((itr = hash.find(t.first + i)) != hash.end()) 15 | ans = max(ans, t.second + itr->second); 16 | } 17 | 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /longest-palindrome.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/longest-palindrome/description/ 2 | 3 | class Solution { 4 | public: 5 | int longestPalindrome(string s) { 6 | // longest palindrome - largest odd number, all the evens and rest of the odds less one 7 | vector hash(60, 0); 8 | int ans = 0, temp = 0, m; 9 | 10 | for(char &c : s){ 11 | ++hash[c-'A']; 12 | } 13 | 14 | for(auto &m : hash){ 15 | ans += m - m % 2; 16 | if (m % 2 == 1 && temp == 0){ 17 | ans += 1; 18 | temp = m; 19 | } 20 | } 21 | 22 | return ans; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /longest-palindromic-substring-5.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/longest-palindromic-substring/ 2 | 3 | class Solution { 4 | public: 5 | string longestPalindrome(string s) { 6 | int n = s.length(), start = 0, len = 1; 7 | 8 | for(int i = 1; i < n; i++){ 9 | helper(i-1, i, n, start, len, s); 10 | helper(i-1, i+1, n, start, len, s); 11 | } 12 | 13 | return s.substr(start, len); 14 | } 15 | 16 | void helper(int l, int h, int n, int& start, int& len, string& s){ 17 | while(l >= 0 && h < n && s[l] == s[h]){ 18 | if (h - l + 1 > len){ 19 | start = l; 20 | len = h - l + 1; 21 | } 22 | 23 | h++; 24 | l--; 25 | } 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /longest-substring-without-repeating-characters-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/longest-substring-without-repeating-characters/description/ 2 | 3 | class Solution { 4 | public: 5 | int lengthOfLongestSubstring(string s) { 6 | int i = 0, j = 1, n = s.length(), ans = n > 0; 7 | if (n == 0) return ans; 8 | 9 | unordered_map hashMap; 10 | 11 | hashMap[s[i]]++; 12 | 13 | while(j < n){ 14 | char idx = s[j]; 15 | while(hashMap[idx] != 0) 16 | hashMap[s[i++]]--; 17 | ans = max(ans, j - i + 1); 18 | hashMap[idx]++; 19 | j++; 20 | } 21 | 22 | return ans; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /longest-substring-without-repeating-characters-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/longest-substring-without-repeating-characters/description/ 2 | 3 | class Solution { 4 | public: 5 | int lengthOfLongestSubstring(string s) { 6 | unordered_set seen_chars; 7 | int ans = 0, n = s.length(), st = 0, en = 0; 8 | 9 | while(en < n){ 10 | while(seen_chars.count(s[en]) && s[st] != s[en]){ 11 | seen_chars.erase(s[st]); 12 | ++st; 13 | } 14 | 15 | if (seen_chars.count(s[en])) 16 | ++st; 17 | 18 | seen_chars.insert(s[en]); 19 | ++en; 20 | 21 | ans = max(ans, en - st); 22 | } 23 | 24 | return ans; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /lowest-common-ancestor-of-a-binary-search-tree-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 15 | if (p->val > q->val) swap(p, q); 16 | 17 | if (p->val <= root->val && root->val <= q->val ) return root; 18 | else if (p->val > root->val) return lowestCommonAncestor(root->right, p, q); 19 | else if (q->val < root->val) return lowestCommonAncestor(root->left, p ,q); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /lowest-common-ancestor-of-a-binary-search-tree-4.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 15 | if (p->val > q->val){swap(p, q);} 16 | // making sure that p < q; 17 | while(root){ 18 | if (root->val > q->val) root = root->left; 19 | else if (root->val < p->val) root = root->right; 20 | else return root; 21 | } 22 | return root; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /lowest-common-ancestor-of-a-binary-tree-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/description/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 15 | if (!root || root == p || root == q) return root; 16 | auto left = lowestCommonAncestor(root->left, p, q); 17 | auto right = lowestCommonAncestor(root->right, p, q); 18 | if (left && right) return root; 19 | else if (left) return left; 20 | else return right; 21 | 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /max-consecutive-ones-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/max-consecutive-ones/description/ 2 | 3 | class Solution { 4 | public: 5 | int findMaxConsecutiveOnes(vector& nums) { 6 | int ans = 0, temp = 0; 7 | 8 | for(int num : nums){ 9 | temp += num; 10 | if (num == 0){ 11 | ans = max(ans, temp); 12 | temp = 0; 13 | } 14 | } 15 | 16 | ans = max(ans, temp); 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /max-consecutive-ones.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/max-consecutive-ones/description/ 2 | 3 | class Solution { 4 | public: 5 | int findMaxConsecutiveOnes(vector& nums) { 6 | int ans = 0, temp = 0; 7 | 8 | for(auto num: nums){ 9 | temp += num; 10 | ans = (temp > ans) ? temp : ans; 11 | if (num == 0) temp = 0; 12 | } 13 | 14 | return ans; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /maximum-average-subarray-i.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/maximum-average-subarray-i/description/ 2 | 3 | class Solution { 4 | public: 5 | double findMaxAverage(vector& nums, int k) { 6 | int running_sum = accumulate(nums.begin(), nums.begin() + k, 0); 7 | int max_sum = running_sum; 8 | 9 | for(int i = 0; i + k < nums.size() ; i++){ 10 | running_sum = running_sum - nums[i] + nums[i+k]; 11 | if(running_sum > max_sum) max_sum = running_sum; 12 | } 13 | return max_sum * 1.0 / k; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /maximum-size-subarray-sum-equals-k-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/description/ 2 | 3 | class Solution { 4 | public: 5 | int maxSubArrayLen(vector& nums, int k) { 6 | unordered_map preSum; 7 | int p = 0, ans = 0; 8 | preSum[0] = -1; 9 | 10 | for(int i = 0; i < nums.size(); i++){ 11 | p += nums[i]; 12 | if (preSum.count(p - k)) ans = max(ans, i - preSum[p - k]); 13 | if (!preSum.count(p)) preSum[p] = i; 14 | } 15 | 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /maximum-subarray-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/maximum-subarray/description/ 2 | 3 | class Solution { 4 | public: 5 | int maxSubArray(vector& nums) { 6 | int n = nums.size(), ans = n ? nums[0] : 0; 7 | if(!n) return ans; 8 | int currSum = 0; 9 | 10 | for(int i = 0; i < n; i++){ 11 | currSum += nums[i]; 12 | if (currSum < 0) { 13 | currSum = 0; 14 | ans = max(ans, nums[i]); 15 | } 16 | else ans = max(ans, currSum); 17 | } 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /maximum-subarray-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/maximum-subarray/description/ 2 | 3 | class Solution { 4 | public: 5 | int maxSubArray(vector& nums) { 6 | int n = nums.size(), ans, curr; 7 | if (n == 0) return 0; 8 | 9 | curr = nums[0]; 10 | ans = nums[0]; 11 | 12 | for(int i = 1; i < n; i++){ 13 | curr = nums[i] + (curr > 0 ? curr : 0); 14 | ans = max(curr, ans); 15 | } 16 | 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /maximum-subarray-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/maximum-subarray/ 2 | 3 | class Solution { 4 | public: 5 | int maxSubArray(vector& nums) { 6 | int n = nums.size(), ans, curr; 7 | ans = curr = n ? nums[0] : 0; 8 | 9 | for(int i = 1; i < n; i++){ 10 | curr = nums[i] + (curr > 0 ? curr : 0); 11 | ans = max(ans, curr); 12 | } 13 | 14 | return ans; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /maximum-subarray-4.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/maximum-subarray/description/ 2 | 3 | class Solution { 4 | public: 5 | int maxSubArray(vector& nums) { 6 | int ans = nums[0], sum = 0; 7 | 8 | for(int num : nums){ 9 | sum += num; 10 | ans = max(ans, sum); 11 | sum = max(sum, 0); 12 | } 13 | 14 | return ans; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /meeting-rooms-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/meeting-rooms/description/ 2 | 3 | /** 4 | * Definition for an interval. 5 | * struct Interval { 6 | * int start; 7 | * int end; 8 | * Interval() : start(0), end(0) {} 9 | * Interval(int s, int e) : start(s), end(e) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | 15 | bool canAttendMeetings(vector& intervals) { 16 | map m; 17 | int counter = 0; 18 | for(auto i : intervals){ 19 | m[i.start]++; 20 | m[i.end]--; 21 | } 22 | 23 | for(auto kv : m){ 24 | counter += kv.second; 25 | if (counter > 1) return false; 26 | } 27 | return true; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /meeting-rooms-ii-5.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/meeting-rooms-ii/description/ 2 | 3 | class Solution { 4 | public: 5 | int minMeetingRooms(vector& intervals) { 6 | int ans = 0, cur = 0; 7 | map mp; 8 | 9 | for(auto ii : intervals){ 10 | mp[ii.start] += 1; 11 | mp[ii.end] -= 1; 12 | } 13 | 14 | for(auto itr : mp) 15 | ans = max(ans, cur += itr.second); 16 | 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /merge-sorted-array-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/merge-sorted-array/description/ 2 | 3 | class Solution { 4 | public: 5 | void merge(vector& nums1, int m, vector& nums2, int n) { 6 | int k = m + n - 1, i = m - 1, j = n - 1; 7 | while(k >= 0){ 8 | if (i >= 0 && j >= 0){ 9 | nums1[k--] = max(nums1[i], nums2[j]); 10 | (nums1[i] > nums2[j]) ? i-- : j--; 11 | } else if (i >= 0){ 12 | nums1[k--] = nums1[i--]; 13 | } else { 14 | nums1[k--] = nums2[j--]; 15 | } 16 | } 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /merge-sorted-array-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/merge-sorted-array/description/ 2 | 3 | class Solution { 4 | public: 5 | void merge(vector& nums1, int m, vector& nums2, int n) { 6 | int k = m + n - 1, i = m - 1, j = n - 1; 7 | 8 | while(i >= 0 && j >= 0){ 9 | nums1[k--] = max(nums1[i], nums2[j]); 10 | if (nums1[i] > nums2[j]) i--; 11 | else j--; 12 | } 13 | 14 | while(i >= 0) 15 | nums1[k--] = nums1[i--]; 16 | while(j >= 0) 17 | nums1[k--] = nums2[j--]; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /merge-sorted-array-4.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/merge-sorted-array/description/ 2 | 3 | class Solution { 4 | public: 5 | void merge(vector& nums1, int m, vector& nums2, int n) { 6 | int i = m - 1, j = n - 1, k = m + n - 1; 7 | while(i >= 0 && j >= 0){ 8 | if (nums1[i] > nums2[j]) 9 | nums1[k--] = nums1[i--]; 10 | else 11 | nums1[k--] = nums2[j--]; 12 | } 13 | 14 | while(i >= 0) 15 | nums1[k--] = nums1[i--]; 16 | while(j >= 0) 17 | nums1[k--] = nums2[j--]; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /merge-sorted-array-5.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/merge-sorted-array/description/ 2 | 3 | class Solution { 4 | public: 5 | void merge(vector& nums1, int m, vector& nums2, int n) { 6 | int i = m-1, j = n-1, k = m + n - 1; 7 | 8 | while(i >= 0 && j >= 0) 9 | nums1[k--] = (nums1[i] > nums2[j] ? nums1[i--] : nums2[j--]); 10 | 11 | while(i >= 0) 12 | nums1[k--] = nums1[i--]; 13 | 14 | while(j >= 0) 15 | nums1[k--] = nums2[j--]; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /merge-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/merge-sorted-array/description/ 2 | 3 | class Solution { 4 | public: 5 | void merge(vector& nums1, int m, vector& nums2, int n) { 6 | 7 | int i = m - 1, j = n - 1, k = m + n - 1; 8 | 9 | while(i >= 0 && j >= 0){ 10 | if (nums1[i] > nums2[j]){ 11 | nums1[k--] = nums1[i--]; 12 | } else if (nums1[i] <= nums2[j]){ 13 | nums1[k--] = nums2[j--]; 14 | } 15 | } 16 | 17 | while(j >= 0){ 18 | nums1[k--] = nums2[j--]; 19 | } 20 | 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /merge-two-binary-trees.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/merge-two-binary-trees/description/ 2 | 3 | class Solution { 4 | public: 5 | 6 | void helper(TreeNode* t1, TreeNode* t2, TreeNode** tanswer){ 7 | if (!(t1 || t2)) 8 | return; 9 | *tanswer = new TreeNode((t1 ? t1->val : 0) + (t2 ? t2->val : 0)); 10 | helper((t1 ? t1->left : NULL), (t2 ? t2->left : NULL), &((*tanswer)->left)); 11 | helper((t1 ? t1->right : NULL), (t2 ? t2->right : NULL), &((*tanswer)->right)); 12 | } 13 | TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) { 14 | TreeNode* tanswer = NULL; 15 | helper(t1, t2, &tanswer); 16 | return tanswer; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /merge-two-sorted-lists-5.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/merge-two-sorted-lists/description/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode(int x) : val(x), next(NULL) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 14 | if (l1 && l2){ 15 | if (l1->val > l2->val){ 16 | l2->next = mergeTwoLists(l1, l2->next); 17 | return l2; 18 | } else { 19 | l1->next = mergeTwoLists(l1->next, l2); 20 | return l1; 21 | } 22 | } 23 | 24 | return l1 ? l1 : l2; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /merge-two-sorted-lists-8.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/merge-two-sorted-lists/description/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode(int x) : val(x), next(NULL) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 14 | ListNode* head = new ListNode(-1), *temp = head; 15 | 16 | while(l1 && l2){ 17 | (l1->val < l2->val) ? ((temp->next = l1) && (l1 = l1->next)) : ((temp->next = l2) && (l2 = l2->next)); 18 | temp = temp->next; 19 | } 20 | 21 | temp->next = l1 ? l1 : l2; 22 | 23 | return head->next; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /min-cost-climbing-stairs.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/min-cost-climbing-stairs/description/ 2 | 3 | class Solution { 4 | public: 5 | int minCostClimbingStairs(vector& cost) { 6 | int first = cost[0], second = cost[1], temp, size = cost.size(); 7 | 8 | for(int i = 2; i < size; i++){ 9 | first = cost[i] + min(first, second); 10 | temp = first; 11 | first = second; 12 | second = temp; 13 | } 14 | 15 | return min(first, second); 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /minimum-depth-of-binary-tree-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/minimum-depth-of-binary-tree/description/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int minDepth(TreeNode* root) { 15 | if (!root) return 0; 16 | if (!root->left && !root->right) return 1; 17 | else if (root->left && root->right) return 1 + min(minDepth(root->left), minDepth(root->right)); 18 | else if (root->left) return 1 + minDepth(root->left); 19 | else return 1 + minDepth(root->right); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /minimum-moves-to-equal-array-elements.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/minimum-moves-to-equal-array-elements/description/ 2 | 3 | class Solution { 4 | public: 5 | int minMoves(vector& nums) { 6 | int sum = 0, minN = INT_MAX; 7 | 8 | for(int &n : nums){ 9 | sum += n; 10 | minN = min(minN, n); 11 | } 12 | 13 | return sum - nums.size()*minN; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /minimum-size-subarray-sum-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/minimum-size-subarray-sum/description/ 2 | 3 | class Solution { 4 | public: 5 | int minSubArrayLen(int s, vector& nums) { 6 | if (nums.size() == 0) 7 | return 0; 8 | int rSum = nums[0]; 9 | int ans = rSum >= s ? 1 : INT_MAX, start = 0, end = 1; 10 | while(start != end && end < nums.size()){ 11 | ans = (rSum += nums[end++]) >= s ? min(ans, end - start) : ans; 12 | while(rSum - nums[start] >= s){ 13 | rSum -= nums[start++]; 14 | ans = min(ans, end - start); 15 | } 16 | } 17 | return ans == INT_MAX ? 0 : ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /minimum-size-subarray-sum-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/minimum-size-subarray-sum/description/ 2 | 3 | class Solution { 4 | public: 5 | int minSubArrayLen(int s, vector& nums) { 6 | int i = 0, j = 0, ans = INT_MAX, temp = 0; 7 | while(j < nums.size()){ 8 | temp += nums[j++]; 9 | while(temp >= s){ 10 | ans = min(ans, j - i); 11 | temp -= nums[i++]; 12 | } 13 | } 14 | return ans != INT_MAX ? ans : 0; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /missing-numer-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/missing-number/description/ 2 | 3 | class Solution { 4 | public: 5 | int missingNumber(vector& nums) { 6 | int x = 0, n = nums.size(); 7 | for(int i = 0; i < n; i++) 8 | x = (x ^ i ^ nums[i]); 9 | return x ^ n; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /move-zeroes-1.cpp: -------------------------------------------------------------------------------- 1 | // https://www.lintcode.com/problem/move-zeroes/description 2 | class Solution { 3 | public: 4 | /** 5 | * @param nums: an integer array 6 | * @return: nothing 7 | */ 8 | void moveZeroes(vector &nums) { 9 | // write your code here 10 | int nz = 0, zp = 0, i = 0, n = nums.size(); 11 | 12 | while(nz < n && zp < n){ 13 | while(nums[zp] != 0 && zp < n) zp++; 14 | nz = zp; 15 | while(nums[nz] == 0 && nz < n) nz++; 16 | if (nz >= n) 17 | break; 18 | swap(nums[nz], nums[zp]); 19 | } 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /move-zeroes-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/move-zeroes/description/ 2 | 3 | class Solution { 4 | public: 5 | void moveZeroes(vector& nums) { 6 | int i = 0; 7 | 8 | for(int num : nums){ 9 | if (num) nums[i++] = num; 10 | } 11 | 12 | while(i < nums.size()) 13 | nums[i++] = 0; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /move-zeroes-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/move-zeroes/description/ 2 | 3 | class Solution { 4 | public: 5 | void moveZeroes(vector& nums) { 6 | int i = 0, j = 0; 7 | while(j < nums.size()){ 8 | if (!nums[j] && !nums[i]) j++; 9 | else if (nums[j]){ 10 | swap(nums[i], nums[j]); 11 | i++; j++; 12 | } 13 | } 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /move-zeroes-4.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/move-zeroes/description/ 2 | 3 | class Solution { 4 | public: 5 | void moveZeroes(vector& nums) { 6 | int i = 0, j = 0; 7 | while(j < nums.size()){ 8 | if (nums[j] != 0) 9 | swap(nums[i++], nums[j]); 10 | j++; 11 | } 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /move-zeroes-5.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/move-zeroes/description/ 2 | 3 | class Solution { 4 | public: 5 | void moveZeroes(vector& nums) { 6 | int i = 0, j = 0, n = nums.size(); 7 | 8 | while(j < n) { 9 | if(nums[j] != 0) 10 | nums[i++] = nums[j]; 11 | j++; 12 | } 13 | 14 | while(i < n) 15 | nums[i++] = 0; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /move-zeroes-6.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/move-zeroes/description/ 2 | 3 | class Solution { 4 | public: 5 | void moveZeroes(vector& nums) { 6 | int i = -1, j = 0, n = nums.size(); 7 | 8 | while(j < n) { 9 | if(nums[j] != 0) 10 | swap(nums[++i], nums[j]); 11 | j++; 12 | } 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /move-zeroes-7.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/move-zeroes/ 2 | 3 | class Solution { 4 | public: 5 | void moveZeroes(vector& nums) { 6 | int i = 0, n = nums.size(), j = 0; 7 | 8 | while(i < n){ 9 | if (nums[i] != 0) 10 | nums[j++] = nums[i]; 11 | i++; 12 | } 13 | while(j < n) 14 | nums[j++] = 0; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /move-zeroes-8.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/move-zeroes/ 2 | 3 | class Solution { 4 | public: 5 | void moveZeroes(vector& nums) { 6 | int i = 0, n = nums.size(), j = 0; 7 | 8 | while(i < n) 9 | nums[i++] != 0 ? nums[j++] = nums[i-1] : -1; 10 | 11 | while(j < n) 12 | nums[j++] = 0; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /move-zeroes.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/move-zeroes/description/ 2 | 3 | class Solution { 4 | public: 5 | void moveZeroes(vector& nums) { 6 | int insertIndex = 0; 7 | 8 | for(int num: nums){ 9 | if (num != 0) nums[insertIndex++] = num; 10 | } 11 | 12 | while(insertIndex < nums.size()) 13 | nums[insertIndex++] = 0; 14 | 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /my-calendar-iii-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/my-calendar-iii/description/ 2 | class MyCalendarThree { 3 | public: 4 | map events; 5 | MyCalendarThree() { 6 | 7 | } 8 | 9 | int book(int start, int end) { 10 | events[start]++; 11 | events[end]--; 12 | 13 | int ongoing = 0, k = 0; 14 | 15 | for(auto p : events){ 16 | k = max(k, ongoing += p.second); 17 | } 18 | 19 | return k; 20 | } 21 | }; 22 | 23 | /** 24 | * Your MyCalendarThree object will be instantiated and called as such: 25 | * MyCalendarThree obj = new MyCalendarThree(); 26 | * int param_1 = obj.book(start,end); 27 | */ 28 | -------------------------------------------------------------------------------- /next-permutation-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/next-permutation/description/ 2 | 3 | class Solution { 4 | public: 5 | void nextPermutation(vector& nums) { 6 | int n = nums.size(), i = n - 1, j = n - 1; 7 | 8 | while(i > 0 && nums[i - 1] >= nums[i]) 9 | i--; 10 | 11 | if (i > 0) { 12 | int p = nums[i - 1]; 13 | while(nums[j] <= p) 14 | j--; 15 | swap(nums[i - 1], nums[j]); 16 | } 17 | 18 | j = n - 1; 19 | while (j > i) 20 | swap(nums[j--], nums[i++]); 21 | 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /number-of-1-bits-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/number-of-1-bits/description/ 2 | 3 | class Solution { 4 | public: 5 | int hammingWeight(uint32_t n) { 6 | int ans = 0; 7 | while(n){ 8 | ans++; 9 | n &= (n-1); 10 | } 11 | return ans; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /number-of-1-bits-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/number-of-1-bits/ 2 | 3 | class Solution { 4 | public: 5 | int hammingWeight(uint32_t n) { 6 | int ans = 0; 7 | 8 | while(n){ 9 | ans++; 10 | n &= (n-1); 11 | } 12 | 13 | return ans; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /number-of-1-bits.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/number-of-1-bits/description/ 2 | class Solution { 3 | public: 4 | int hammingWeight(uint32_t n) { 5 | int count = 0; 6 | while(n){ 7 | n = n & (n - 1); 8 | count++; 9 | } 10 | return count; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /odd-even-linked-list-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/odd-even-linked-list/description/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode(int x) : val(x), next(NULL) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* oddEvenList(ListNode* head) { 14 | if (!head) return head; 15 | 16 | ListNode* odd = head, *even = head->next, *evenHead = even; 17 | 18 | while(even && even->next){ 19 | odd->next = even->next; 20 | odd = odd->next; 21 | even->next = odd->next; 22 | even = even->next; 23 | } 24 | 25 | odd->next = evenHead; 26 | return head; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /one-edit-distance-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/one-edit-distance/description/ 2 | 3 | class Solution { 4 | public: 5 | bool isOneEditDistance(string s, string t) { 6 | int m = s.length(), n = t.length(); 7 | if (n > m){ 8 | swap(s, t); 9 | swap(m, n); 10 | } 11 | // s is longer than t 12 | for(int i = 0; i < m; i++){ 13 | if (i < n && s[i] != t[i]) 14 | return m == n ? check(s, t, i + 1, i + 1) : check(s, t, i + 1, i); 15 | } 16 | return m - n == 1; 17 | } 18 | 19 | bool check(string& s, string& t, int i, int j){ 20 | while(i < s.length() && j < t.length()) 21 | if (s[i++] != t[j++]) return false; 22 | return i == s.length() && j == t.length(); 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /one-edit-distance-4.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/one-edit-distance/description/ 2 | 3 | class Solution { 4 | public: 5 | bool isOneEditDistance(string s, string t) { 6 | int n = s.length(), m = t.length(), i = 0, j = 0, diff = 0; 7 | 8 | if (m > n) { 9 | swap(s, t); 10 | swap(m, n); 11 | } 12 | 13 | while(i < n && j < m){ 14 | if (s[i] == t[j]) { 15 | i++; 16 | j++; 17 | } else if (m == n){ 18 | i++; 19 | j++; 20 | diff++; 21 | } else { 22 | i++; 23 | diff++; 24 | } 25 | } 26 | 27 | diff += n - i; 28 | 29 | return diff == 1; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /owest-common-ancestor-of-a-binary-tree-5.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/description/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 15 | if (!root) return NULL; 16 | else if (root == p || root == q) return root; 17 | 18 | TreeNode* left = lowestCommonAncestor(root->left, p, q); 19 | TreeNode* right = lowestCommonAncestor(root->right, p, q); 20 | 21 | return left && right ? root : (left ? left : right); 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /paint-fence.cpp: -------------------------------------------------------------------------------- 1 | // https://www.lintcode.com/problem/paint-fence/description 2 | class Solution { 3 | public: 4 | /** 5 | * @param n: non-negative integer, n posts 6 | * @param k: non-negative integer, k colors 7 | * @return: an integer, the total number of ways 8 | */ 9 | int numWays(int n, int k) { 10 | // write your code 11 | vector same(n + 1, 0), different(n + 1, 0), total(n + 1, 0); 12 | different[1] = k; 13 | total[1] = k; 14 | 15 | for(int i = 2; i <= n; i++){ 16 | same[i] = different[i - 1]; 17 | different[i] = total[i - 1] * (k - 1); 18 | total[i] = same[i] + different[i]; 19 | } 20 | return total[n]; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /palindrome-number-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/palindrome-number/description/ 2 | 3 | class Solution { 4 | public: 5 | bool isPalindrome(int x) { 6 | int y = 0, temp = abs(x); 7 | while(temp){ 8 | y = y * 10 + (temp % 10); 9 | temp = temp / 10; 10 | } 11 | return y == x; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /palindrome-number-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/palindrome-number/description/ 2 | 3 | class Solution { 4 | public: 5 | bool isPalindrome(int x) { 6 | if (x < 0) return false; 7 | 8 | int y = 0, orig = x; 9 | 10 | while(orig){ 11 | y = y*10 + (orig%10); 12 | orig /= 10; 13 | } 14 | 15 | return x == y; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /palindrome-number-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/palindrome-number/description/ 2 | 3 | class Solution { 4 | public: 5 | bool isPalindrome(int x) { 6 | if (x < 0 || (x && x%10 == 0)) return false; 7 | 8 | int y = 0; 9 | 10 | while(x > y){ 11 | y = y*10 + (x%10); 12 | x /= 10; 13 | } 14 | 15 | return x == y || x == y/10; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /palindrome-permutation.cpp: -------------------------------------------------------------------------------- 1 | // https://www.lintcode.com/problem/palindrome-permutation/description 2 | 3 | class Solution { 4 | public: 5 | /** 6 | * @param s: the given string 7 | * @return: if a permutation of the string could form a palindrome 8 | */ 9 | bool canPermutePalindrome(string &s) { 10 | // write your code here 11 | bool ans = true; 12 | unordered_map charCount; 13 | int count = 0; 14 | 15 | for(char &c : s) { 16 | count += (++charCount[c] % 2 ? 1 : -1); 17 | } 18 | 19 | return count <= 1; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /palindromic-substrings-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/palindromic-substrings/description/ 2 | 3 | class Solution { 4 | public: 5 | int countSubstrings(string s) { 6 | int ans = 0; 7 | for(int i = 0; i < s.length(); i++){ 8 | ans += count_palindrome(s, i, i); 9 | ans += count_palindrome(s, i, i + 1); 10 | } 11 | return ans; 12 | } 13 | 14 | int count_palindrome(string & s, int prev, int next){ 15 | int count = 0; 16 | while(prev >= 0 && next < s.length() && s[prev--] == s[next++]) 17 | count++; 18 | return count; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /pascals-triangle-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/pascals-triangle/description/ 2 | 3 | typedef vector> vvi; 4 | typedef vector vi; 5 | 6 | class Solution { 7 | public: 8 | vector> generate(int numRows) { 9 | vvi ans; 10 | if (numRows) 11 | ans.push_back({1}); 12 | int val; 13 | for(int i = 1; i < numRows; i++){ 14 | vi temp; 15 | temp.push_back(1); 16 | for(int k = 1; k < i; k++){ 17 | temp.push_back(ans[i-1][k-1] + ans[i-1][k]); 18 | } 19 | temp.push_back(1); 20 | ans.push_back(temp); 21 | } 22 | return ans; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /pascals-triangle-ii-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/pascals-triangle-ii/description/ 2 | 3 | class Solution { 4 | public: 5 | vector getRow(int rowIndex) { 6 | vector answer; 7 | 8 | answer.push_back(1); 9 | 10 | for(int k = 1; k <= rowIndex; k++) { 11 | long temp = (answer.back() * (rowIndex - k + (long)1)) / k; 12 | answer.push_back((int)temp); 13 | } 14 | return answer; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /path-sum-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/path-sum/description/ 2 | 3 | class Solution { 4 | public: 5 | 6 | bool hasPathSum(TreeNode* root, int sum) { 7 | if (root == NULL) return false; 8 | int curr_sum = sum - root->val; 9 | if (curr_sum == 0 && !(root->left || root->right)) return true; // if the current node is all that there is 10 | 11 | bool left = hasPathSum(root->left, curr_sum); 12 | bool right = hasPathSum(root->right, curr_sum); 13 | 14 | return left || right; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /peak-index-in-a-mountain-array.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/peak-index-in-a-mountain-array/description/ 2 | 3 | class Solution { 4 | public: 5 | int peakIndexInMountainArray(vector& A) { 6 | int low = 0, high = A.size(); 7 | 8 | while(low < high){ 9 | int mid = (low + high) / 2; 10 | // avoid mid being 0 ? 11 | if (A[mid] > A[mid - 1] && A[mid] > A[mid + 1]) return mid; 12 | else if (A[mid] > A[mid - 1]) low = mid; 13 | else high = mid; 14 | } 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /populating-next-right-pointers-in-each-node-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/populating-next-right-pointers-in-each-node/description/ 2 | 3 | /** 4 | * Definition for binary tree with next pointer. 5 | * struct TreeLinkNode { 6 | * int val; 7 | * TreeLinkNode *left, *right, *next; 8 | * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | void connect(TreeLinkNode *root) { 14 | if (!root || !root->left) return; // entire level is empty since it is complete binary tree 15 | root->left->next = root->right; // for left child 16 | if (root->next) 17 | root->right->next = root->next->left; 18 | connect(root->left); 19 | connect(root->right); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /power-of-three.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/power-of-three/description/ 2 | 3 | class Solution { 4 | public: 5 | bool isPowerOfThree(int n) { 6 | // Write your code here 7 | int maxThree = 1162261467; 8 | return n > 0 && (maxThree % n == 0); 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /power-of-two.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/power-of-two/description/ 2 | 3 | class Solution { 4 | public: 5 | bool isPowerOfTwo(int n) { 6 | if (n > 0 && (n & (n - 1)) == 0) 7 | return true; 8 | return false; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /powx-n-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/powx-n/description/ 2 | 3 | class Solution { 4 | public: 5 | double myPow(double x, int n) { 6 | double temp; 7 | if (n == 0) temp = 1.0; 8 | else if (n == 1) temp = x; 9 | else if (n == -1) temp = 1.0 / x; 10 | else { 11 | temp = myPow(x, n / 2); 12 | temp = (n & 1 ? myPow(x, n % 2) : 1.0 ) * temp * temp; 13 | } 14 | return temp; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /powx-n-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/powx-n/description/ 2 | 3 | class Solution { 4 | public: 5 | double myPow(double x, int n) { 6 | long nl = n; 7 | double ans = 1.0; 8 | if (nl < 0){ 9 | x = 1.0 / x; 10 | nl = -1l * n; 11 | } 12 | 13 | while(nl){ 14 | if (nl & 1){ 15 | ans = ans * x; 16 | nl = nl - 1; 17 | } 18 | nl /= 2; 19 | x = (x * x); 20 | } 21 | return ans; 22 | } 23 | 24 | 25 | }; 26 | -------------------------------------------------------------------------------- /powx-n-4.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/powx-n/description/ 2 | 3 | class Solution { 4 | public: 5 | double myPow(double x, int n) { 6 | if (x == 0) return 0; 7 | 8 | long nn = (n < 0 ? -1 : 1) * (long)n; 9 | double ans = 1.0; 10 | 11 | while(nn > 0){ 12 | if (nn&1) 13 | ans = ans * x; 14 | nn >>= 1; 15 | x = x*x; 16 | } 17 | 18 | return n < 0 ? 1/ans: ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /product-of-array-except-self-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/product-of-array-except-self/description/ 2 | 3 | #define mp(A, B) make_pair(A, B) 4 | #define ff(i, m, n) for(i = m; i < n; i++) 5 | #define ffr(i, m, n) for(i = m; i >= n; i--) 6 | #define ss(v) sort(v.begin(), v.end()) 7 | typedef pair pii; 8 | typedef vector vi; 9 | class Solution { 10 | public: 11 | vector productExceptSelf(vector& nums) { 12 | int n = nums.size(), i, runProd = 1; 13 | vi ans(n, 1); 14 | ff(i, 0, n) 15 | ans[i] = (i > 0 ? ans[i-1] : 1) * nums[i]; 16 | 17 | ffr(i, n - 1, 0){ 18 | ans[i] = (i > 0 ? ans[i-1] : 1) * runProd; 19 | runProd *= nums[i]; 20 | } 21 | return ans; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /product-of-array-except-self-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/product-of-array-except-self/description/ 2 | 3 | typedef vector vi; 4 | #define ff(i, m, n) for(i = m; i < n; i++) 5 | #define ffr(i, m, n) for(i = m; i >= n; i--) 6 | 7 | class Solution { 8 | public: 9 | vector productExceptSelf(vector& nums) { 10 | int n = nums.size(), i; 11 | vi a(n, 1), b(n, 1), ans(n, 1); 12 | 13 | ff(i, 0, n){ 14 | a[i] = (i > 0 ? a[i-1] : 1) * nums[i]; 15 | b[n - i - 1] = (i > 0 ? b[n - i] : 1) * nums[n - i - 1]; 16 | } 17 | 18 | ff(i, 0, n){ 19 | ans[i] = (i > 0 ? a[i-1] : 1) * (i < n - 1 ? b[i + 1] : 1); 20 | } 21 | 22 | return ans; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /product-of-array-except-self-4.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/product-of-array-except-self/description/ 2 | 3 | typedef vector vi; 4 | #define ff(i, m, n) for(i = m; i < n; i++) 5 | #define ffr(i, m, n) for(i = m; i >= n; i--) 6 | 7 | class Solution { 8 | public: 9 | vector productExceptSelf(vector& nums) { 10 | int n = nums.size(), i, runProd = 1; 11 | vi ans(n, 1); 12 | 13 | ff(i, 0, n) 14 | ans[i] = (i > 0 ? ans[i-1] : 1) * nums[i]; 15 | 16 | ffr(i, n-1, 0){ 17 | ans[i] = (i > 0 ? ans[i-1] : 1) * runProd; 18 | runProd = runProd * nums[i]; 19 | } 20 | 21 | return ans; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /product-of-array-except-self-5.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/product-of-array-except-self/description/ 2 | 3 | class Solution { 4 | public: 5 | vector productExceptSelf(vector& nums) { 6 | int n = nums.size(), i = 0, prevProd = 1; 7 | vector ans(n, 0); 8 | 9 | for(int i = 0; i < n; i++) 10 | ans[i] = i > 0 ? ans[i-1] * nums[i] : nums[i]; 11 | 12 | for(int i = n - 1; i >= 0; i--){ 13 | ans[i] = i > 0 ? ans[i - 1] * prevProd : prevProd; 14 | prevProd *= nums[i]; 15 | } 16 | 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /product-of-array-except-self-6.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/product-of-array-except-self/description/ 2 | 3 | class Solution { 4 | public: 5 | vector productExceptSelf(vector& nums) { 6 | int n = nums.size(), prod = 1; 7 | vector res(n, 1); 8 | 9 | res[0] = nums[0]; 10 | 11 | for(int i = 1; i < n; i++) 12 | res[i] = nums[i] * res[i-1]; 13 | 14 | for(int i = n - 1; i >= 0; i--){ 15 | res[i] = prod * ( i > 0 ? res[i-1] : 1); 16 | prod *= nums[i]; 17 | } 18 | 19 | return res; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /product-of-array-except-self.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/product-of-array-except-self/description/ 2 | 3 | class Solution { 4 | public: 5 | vector productExceptSelf(vector& nums) { 6 | 7 | vector answer(nums.size()); 8 | answer[0] = nums[0]; 9 | 10 | for(int i = 1; i < nums.size(); i++) 11 | answer[i] = answer[i-1] * nums[i]; 12 | 13 | int runProd = 1, temp; 14 | 15 | for(int i = nums.size() - 1; i > 0; i--){ 16 | answer[i] = answer[i-1] * runProd; 17 | runProd *= nums[i]; 18 | } 19 | 20 | answer[0] = runProd; 21 | 22 | return answer; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /range-addition-ii.cpp598. Range Addition II: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/range-addition-ii/description/ 2 | 3 | class Solution { 4 | public: 5 | int maxCount(int m, int n, vector>& ops) { 6 | int r1 = m, r2 = n; 7 | for(vector& op : ops){ 8 | r1 = min(op[0], r1); 9 | r2 = min(op[1], r2); 10 | } 11 | 12 | return r1*r2; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /range-sum-query-immutable-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/range-sum-query-immutable/description/ 2 | 3 | typedef vector vi; 4 | class NumArray { 5 | public: 6 | vi sumArray; 7 | NumArray(vector nums) { 8 | int n = nums.size(); 9 | sumArray.resize(n); 10 | for(int i = 0; i < n; i++) 11 | sumArray[i] = nums[i] + (i > 0 ? sumArray[i-1] : 0); 12 | } 13 | 14 | int sumRange(int i, int j) { 15 | return sumArray[j] - (i > 0 ? sumArray[i-1] : 0); 16 | } 17 | }; 18 | 19 | /** 20 | * Your NumArray object will be instantiated and called as such: 21 | * NumArray obj = new NumArray(nums); 22 | * int param_1 = obj.sumRange(i,j); 23 | */ 24 | -------------------------------------------------------------------------------- /range-sum-query-immutable-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/range-sum-query-immutable/description/ 2 | 3 | class NumArray { 4 | public: 5 | vector preSum; 6 | int n; 7 | NumArray(vector nums) { 8 | n = nums.size(); 9 | if (!n) return; 10 | preSum = vector (n, 0); 11 | preSum[0] = nums[0]; 12 | for(int i = 1; i < n; i++) 13 | preSum[i] = preSum[i-1] + nums[i]; 14 | } 15 | 16 | int sumRange(int i, int j) { 17 | return preSum[j] - preSum[i] + preSum[i] - (i > 0? preSum[i-1]: 0); 18 | } 19 | }; 20 | 21 | /** 22 | * Your NumArray object will be instantiated and called as such: 23 | * NumArray obj = new NumArray(nums); 24 | * int param_1 = obj.sumRange(i,j); 25 | */ 26 | -------------------------------------------------------------------------------- /ransom-note-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/ransom-note/description/ 2 | 3 | class Solution { 4 | public: 5 | bool canConstruct(string ransomNote, string magazine) { 6 | vector rn(26, 0), mag(26, 0); 7 | str2Vec(ransomNote, rn); 8 | str2Vec(magazine, mag); 9 | 10 | for(int i = 0; i < 26; i++) 11 | if (rn[i] > mag[i]) 12 | return false; 13 | return true; 14 | } 15 | 16 | void str2Vec(string& str, vector& vec){ 17 | for(char c : str) 18 | vec[c - 'a']++; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /read-n-characters-given-read4-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/read-n-characters-given-read4/description/ 2 | 3 | // Forward declaration of the read4 API. 4 | int read4(char *buf); 5 | 6 | class Solution { 7 | public: 8 | /** 9 | * @param buf Destination buffer 10 | * @param n Maximum number of characters to read 11 | * @return The number of characters read 12 | */ 13 | int read(char *buf, int n) { 14 | if (!buf) return 0; 15 | int ans = 0, temp = 4; 16 | while(ans < n && temp == 4){ 17 | temp = read4(buf + ans); 18 | ans += temp; 19 | } 20 | return ans > n ? n : ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /read-n-characters-given-read4-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/read-n-characters-given-read4/description/ 2 | 3 | // Forward declaration of the read4 API. 4 | int read4(char *buf); 5 | 6 | class Solution { 7 | public: 8 | /** 9 | * @param buf Destination buffer 10 | * @param n Maximum number of characters to read 11 | * @return The number of characters read 12 | */ 13 | int read(char *buf, int n) { 14 | int c = 4, count = 0; 15 | 16 | while(count < n && c == 4) 17 | count += (c = read4(buf + count)); 18 | 19 | return count > n ? n : count; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /remove-duplicates-from-sorted-array-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/ 2 | 3 | class Solution { 4 | public: 5 | int removeDuplicates(vector& nums) { 6 | int i = 0, j = 1, n = nums.size(); 7 | 8 | if (n == 0 || n == 1) return n; 9 | 10 | while(j < n){ 11 | while(j < n && nums[i] >= nums[j]) 12 | j++; 13 | if (j == n) break; 14 | swap(nums[++i], nums[j++]); 15 | } 16 | 17 | return i+1; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /remove-duplicates-from-sorted-array-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/ 2 | 3 | class Solution { 4 | public: 5 | int removeDuplicates(vector& nums) { 6 | int i = 0, j = 1; 7 | if (!nums.size()) return 0; 8 | while(j < nums.size()){ 9 | if (nums[i] == nums[j]) j++; 10 | else nums[++i] = nums[j++]; 11 | } 12 | return i + 1; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /remove-duplicates-from-sorted-array-4.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/ 2 | 3 | class Solution { 4 | public: 5 | int removeDuplicates(vector& nums) { 6 | int i = 1, j = 1, n = nums.size(); 7 | 8 | if (n == 0 || n == 1) return n; 9 | 10 | while(i < n){ 11 | if (nums[i] != nums[i-1]) 12 | nums[j++] = nums[i]; 13 | i++; 14 | } 15 | 16 | return j; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /remove-duplicates-from-sorted-array-5.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/ 2 | 3 | class Solution { 4 | public: 5 | int removeDuplicates(vector& nums) { 6 | int i = 0, j = 0; 7 | 8 | while(j < nums.size()){ 9 | swap(nums[i++], nums[j++]); 10 | while(j < nums.size() && nums[i - 1] >= nums[j]) 11 | j++; 12 | } 13 | 14 | return i; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /remove-duplicates-from-sorted-array-ii-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/ 2 | 3 | class Solution { 4 | public: 5 | int removeDuplicates(vector& nums) { 6 | int i = 0, j = 0; 7 | while(j < nums.size() && i < nums.size()){ 8 | if (i < 2 || nums[i] > nums[i - 2]) i++; 9 | else if (nums[i - 2] >= nums[j]) j++; 10 | else if (nums[j] > nums[i]) swap(nums[j++], nums[i++]); 11 | } 12 | return i; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /remove-duplicates-from-sorted-array-ii-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/ 2 | 3 | class Solution { 4 | public: 5 | int removeDuplicates(vector& nums) { 6 | int i = 0; 7 | for(int n : nums){ 8 | if (i < 2 || n > nums[i-2]) 9 | nums[i++] = n; 10 | } 11 | return i; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /remove-duplicates-from-sorted-array-ii-4.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/description/ 2 | 3 | class Solution { 4 | public: 5 | int removeDuplicates(vector& nums) { 6 | int n = nums.size(); 7 | if (n <= 2) return n; 8 | int count = 1, j = 1, idx = 1; 9 | 10 | while(j < n){ 11 | if(nums[j] != nums[j-1]){ 12 | nums[idx++] = nums[j]; 13 | count = 1; 14 | } else if (count < 2){ 15 | nums[idx++] = nums[j]; 16 | count++; 17 | } 18 | j++; 19 | } 20 | 21 | return idx; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /remove-duplicates-from-sorted-list.cpp: -------------------------------------------------------------------------------- 1 | https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/ 2 | /** 3 | * Definition for singly-linked list. 4 | * struct ListNode { 5 | * int val; 6 | * ListNode *next; 7 | * ListNode(int x) : val(x), next(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | ListNode* deleteDuplicates(ListNode* head) { 13 | ListNode* answer = head, *temp = head; 14 | 15 | while(temp && temp->next){ 16 | if(temp->val == temp->next->val){ 17 | temp->next = temp->next->next; 18 | } else { 19 | temp = temp->next; 20 | } 21 | } 22 | 23 | return answer; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /remove-element.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/remove-element/description/ 2 | 3 | class Solution { 4 | public: 5 | int removeElement(vector& nums, int val) { 6 | int size = nums.size(), j = size - 1; 7 | for(int i = 0; i < size; i++){ 8 | 9 | // making sure the last element is not the value we wish to remove 10 | while(j >= 0 && nums[j] == val){ 11 | j--; 12 | } 13 | 14 | 15 | if (nums[i] == val && j > i){ 16 | swap(nums[i], nums[j]); 17 | j--; 18 | } 19 | } 20 | return j + 1; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /repeated-string-match-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/repeated-string-match/description/ 2 | 3 | class Solution { 4 | public: 5 | int repeatedStringMatch(string A, string B) { 6 | int n = 1, len = A.length(); 7 | 8 | stringstream ss; 9 | ss << A; 10 | 11 | while(len < B.length()){ 12 | ss << A; 13 | len += A.length(); 14 | n += 1; 15 | } 16 | 17 | if (ss.str().find(B) != string::npos) return n; 18 | 19 | ss << A; 20 | 21 | if (ss.str().find(B) != string::npos) return n + 1; 22 | return -1; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /reverse-bits-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-bits/ 2 | 3 | class Solution { 4 | public: 5 | uint32_t reverseBits(uint32_t n) { 6 | uint32_t ans = 0; 7 | int count = 0; 8 | while(n){ 9 | count++; 10 | ans = ((ans << 1) | (n & 1)); 11 | n = (n >> 1); 12 | } 13 | 14 | return (ans << (32 - count)); 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /reverse-bits.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-bits/description/ 2 | 3 | class Solution { 4 | public: 5 | uint32_t reverseBits(uint32_t n) { 6 | uint32_t result = 0; 7 | 8 | for(int i = 0; i < 32; i++){ 9 | result = result << 1; // making space for new bit 10 | result = result | (n & 1); // taking the last bit of n and adding it to result 11 | n = n >> 1; // removing last one bit from n 12 | } 13 | return result; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /reverse-integer-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-integer/description/ 2 | 3 | class Solution { 4 | public: 5 | int reverse(int x) { 6 | long ans = 0, sign = x < 0; 7 | x = sign ? -x : x; 8 | 9 | while(x && x != INT_MIN){ 10 | ans = ans*10 + (x % 10); 11 | if (ans > INT_MAX) return 0; 12 | x /= 10; 13 | } 14 | 15 | return sign ? -ans : ans; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /reverse-integer-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-integer/description/ 2 | 3 | class Solution { 4 | public: 5 | int reverse(int x) { 6 | int ans = 0; 7 | 8 | while(x){ 9 | int pop = x % 10; 10 | x /= 10; 11 | if (ans > INT_MAX/10 || (ans == INT_MAX && pop > INT_MAX % 10)) return 0; 12 | if (ans < INT_MIN/10 || (ans == INT_MIN && pop < INT_MIN % 10)) return 0; 13 | ans = ans * 10 + pop; 14 | } 15 | 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /reverse-integer-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-integer/description/ 2 | 3 | class Solution { 4 | public: 5 | int reverse(int x) { 6 | int ans = 0; 7 | while(x){ 8 | int pop = x % 10; 9 | x /= 10; 10 | if (ans > INT_MAX/10 || (ans == INT_MAX/10 && pop > INT_MAX % 10)) return 0; 11 | if (ans < INT_MIN/10 || (ans == INT_MIN/10 && pop < INT_MIN % 10)) return 0; 12 | ans = ans * 10 + pop; 13 | } 14 | return ans; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /reverse-integer-4.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-integer/ 2 | 3 | class Solution { 4 | public: 5 | int reverse(int x) { 6 | int ans = 0, t; 7 | 8 | while(x){ 9 | t = x % 10; 10 | x = x/10; 11 | if (ans > INT_MAX/10 || (ans == INT_MAX/10 && INT_MAX % 10 < t)) return 0; 12 | if (ans < INT_MIN/10 || (ans == INT_MIN/10 && INT_MIN % 10 > t)) return 0; 13 | ans = ans*10 + t; 14 | } 15 | 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /reverse-integer-5.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-integer/description/ 2 | 3 | class Solution { 4 | public: 5 | int reverse(int x) { 6 | int ans = 0; 7 | 8 | while(x){ 9 | int t = x % 10; 10 | x = x/ 10; 11 | if (ans > INT_MAX/10 || (ans == INT_MAX/10 && t > INT_MAX % 10)) return 0; 12 | if (ans < INT_MIN/10 || (ans == INT_MIN/10 && t < INT_MIN % 10)) return 0; 13 | cout << t << " " << x << endl; 14 | ans = ans * 10 + t; 15 | } 16 | 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /reverse-linked-list-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-linked-list/description/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode(int x) : val(x), next(NULL) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* reverseList(ListNode* head) { 14 | ListNode *prev = NULL, *next = NULL; 15 | 16 | while(head){ 17 | next = head->next; 18 | head->next = prev; 19 | prev = head; 20 | head = next; 21 | } 22 | 23 | return prev; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /reverse-linked-list-5.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-linked-list/description/ 2 | /** 3 | * Definition for singly-linked list. 4 | * struct ListNode { 5 | * int val; 6 | * ListNode *next; 7 | * ListNode(int x) : val(x), next(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | ListNode* reverseList(ListNode* head) { 13 | ListNode *prev = NULL, *next = NULL; 14 | 15 | while(head){ 16 | next = head->next; 17 | head->next = prev; 18 | prev = head; 19 | head = next; 20 | } 21 | return prev; 22 | } 23 | 24 | }; 25 | -------------------------------------------------------------------------------- /reverse-linked-list-7.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-linked-list/description/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode(int x) : val(x), next(NULL) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* reverseList(ListNode* head) { 14 | ListNode *prev = NULL, *curr = head, *temp; 15 | 16 | while(curr){ 17 | temp = curr->next; 18 | curr->next = prev; 19 | prev = curr; 20 | curr = temp; 21 | } 22 | 23 | return prev; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /reverse-linked-list-8.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-linked-list/description/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode(int x) : val(x), next(NULL) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* reverseList(ListNode* head) { 14 | ListNode* prev = NULL, *temp; 15 | 16 | while(head){ 17 | temp = head->next; 18 | head->next = prev; 19 | prev = head; 20 | head = temp; 21 | } 22 | 23 | return prev; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /reverse-linked-list-9.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-linked-list/description/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode(int x) : val(x), next(NULL) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* reverseList(ListNode* head) { 14 | ListNode* prev = NULL, *curr = head, *temp; 15 | 16 | while(curr){ 17 | temp = curr->next; 18 | curr->next = prev; 19 | prev = curr; 20 | curr = temp; 21 | } 22 | 23 | return prev; 24 | } 25 | }; 26 | 27 | -------------------------------------------------------------------------------- /reverse-string-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-string/description/ 2 | 3 | class Solution { 4 | public: 5 | string reverseString(string s) { 6 | int i = 0, j = s.length() - 1; 7 | while(i < j){ 8 | swap(s[i++], s[j--]); 9 | } 10 | return s; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /reverse-string-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-string/description/ 2 | 3 | class Solution { 4 | public: 5 | string reverseString(string s) { 6 | if (s.length()) 7 | reverseHelper(s, 0); 8 | return s; 9 | } 10 | 11 | void reverseHelper(string& s, int i){ 12 | if (s.length() - 1 - i > i){ 13 | swap(s[i], s[s.length() - 1 - i]); 14 | reverseHelper(s, i+1); 15 | } 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /reverse-string-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-string/description/ 2 | 3 | class Solution { 4 | public: 5 | string reverseString(string s) { 6 | int i = 0; 7 | 8 | while(s.length() && i < s.length() - 1 - i){ 9 | swap(s[i], s[s.length() - 1 - i]); 10 | ++i; 11 | } 12 | return s; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /reverse-string-4.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-string/description/ 2 | 3 | class Solution { 4 | public: 5 | string reverseString(string s) { 6 | int i = 0, n = s.length(); 7 | 8 | while(i < n - i - 1) 9 | swap(s[i++], s[n - i - 1]); 10 | 11 | return s; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /reverse-string-5.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-string/description/ 2 | 3 | class Solution { 4 | public: 5 | void reverseString(vector& s) { 6 | int start = 0, end = s.size() - 1; 7 | 8 | while(end > start) 9 | swap(s[end--], s[start++]); 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /reverse-words-in-a-string-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-words-in-a-string/description/ 2 | 3 | class Solution { 4 | public: 5 | void reverseWords(string &s) { 6 | stringstream ss(s); 7 | string token, ans = ""; 8 | 9 | while(ss >> token) 10 | ans = " " + token + ans; 11 | 12 | if (ans.length() > 0) s = ans.substr(1); 13 | else s = ans; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /reverse-words-in-a-string-ii-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-words-in-a-string-ii/ 2 | 3 | class Solution { 4 | public: 5 | void reverseWords(vector& str) { 6 | int s = 0, e = 0, n = str.size(); 7 | 8 | while(e <= n){ 9 | if (e == n || str[e] == ' '){ 10 | rev(str, s, e - 1); 11 | s = e + 1; 12 | } 13 | e++; 14 | } 15 | 16 | rev(str, 0, n - 1); 17 | } 18 | 19 | void rev(vector& str, int s, int e){ 20 | while(s < e) 21 | swap(str[s++], str[e--]); 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /reverse-words-in-a-string-iii.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/reverse-words-in-a-string-iii/description/ 2 | 3 | class Solution { 4 | public: 5 | 6 | void helper(string& s, int startIdx, int len){ 7 | int endIdx = startIdx + len - 1; 8 | while(startIdx <= endIdx){ 9 | swap(s[startIdx++], s[endIdx--]); 10 | } 11 | } 12 | string reverseWords(string s) { 13 | int startIdx = 0, len = 0; 14 | for(char c : s){ 15 | len += 1; 16 | if (c == ' ') { 17 | helper(s, startIdx, len - 1); 18 | startIdx += len; 19 | len = 0; 20 | } 21 | } 22 | 23 | helper(s, startIdx, len); 24 | return s; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /roman-to-integer-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/roman-to-integer/description/ 2 | 3 | class Solution { 4 | public: 5 | int romanToInt(string s) { 6 | int ans = 0, prev = 0, cur = 0; 7 | unordered_map hashMap( 8 | {{'I', 1}, 9 | {'V', 5}, 10 | {'X', 10}, 11 | {'L', 50}, 12 | {'C', 100}, 13 | {'D', 500}, 14 | {'M', 1000}} 15 | ); 16 | 17 | for(char& c : s){ 18 | cur = hashMap[c]; 19 | ans += cur - (cur <= prev ? 0 : prev << 1); 20 | prev = cur; 21 | } 22 | 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /roman-to-integer-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/roman-to-integer/description/ 2 | 3 | class Solution { 4 | public: 5 | int romanToInt(string s) { 6 | unordered_map mapping({{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}}); 7 | int c = 0, ans = 0; 8 | if (s.length() == 0) return ans; 9 | while(c < s.length() - 1){ 10 | if (mapping[s[c]] < mapping[s[c+1]]) ans -= mapping[s[c]]; 11 | else ans += mapping[s[c]]; 12 | ++c; 13 | } 14 | ans += mapping[s[c]]; 15 | return ans; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /roman-to-integer-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/roman-to-integer/description/ 2 | 3 | class Solution { 4 | public: 5 | int romanToInt(string s) { 6 | unordered_map char2Int = { 7 | {'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000} 8 | }; 9 | int ans = 0, prev = 0; 10 | 11 | for(char c : s){ 12 | ans += char2Int[c]; 13 | if (char2Int[c] > prev) ans -= 2*prev; 14 | prev = char2Int[c]; 15 | } 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /roman-to-integer-4.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/roman-to-integer/description/ 2 | 3 | class Solution { 4 | public: 5 | int romanToInt(string s) { 6 | int last = 0, ans = 0; 7 | unordered_map mp = {{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, 8 | {'C', 100}, {'D', 500}, {'M', 1000}}; 9 | 10 | for(char c : s){ 11 | if (mp[c] > last) 12 | ans = ans + mp[c] - 2*last; 13 | else ans = ans + mp[c]; 14 | last = mp[c]; 15 | } 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /roman-to-integer-5.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/roman-to-integer/description/ 2 | 3 | class Solution { 4 | public: 5 | int romanToInt(string s) { 6 | int prev = 0, ans = 0; 7 | unordered_map mp = {{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, 8 | {'D', 500}, {'M', 1000}}; 9 | for(char c : s){ 10 | ans += mp[c]; 11 | if (prev < mp[c]) ans -= 2*prev; 12 | prev = mp[c]; 13 | } 14 | 15 | return ans; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /roman-to-integer-6.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/roman-to-integer/description/ 2 | 3 | class Solution { 4 | public: 5 | int romanToInt(string s) { 6 | unordered_map mp = {{'I', 1}, {'V', 5}, {'X', 10}, 7 | {'L', 50}, {'C', 100}, {'D', 500}, 8 | {'M', 1000}}; 9 | 10 | int ans = 0, prev = 0; 11 | 12 | for(char c : s){ 13 | ans += mp[c]; 14 | if (mp[c] > prev) ans -= 2*prev; 15 | prev = mp[c]; 16 | } 17 | 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /roman-to-integer-7.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/roman-to-integer/description/ 2 | 3 | class Solution { 4 | public: 5 | int romanToInt(string s) { 6 | unordered_map mp = { 7 | {'I', 1}, {'V', 5}, {'X', 10}, 8 | {'L', 50}, {'C', 100}, {'D', 500}, 9 | {'M', 1000} 10 | }; 11 | 12 | int prev = 0, ans = 0; 13 | 14 | for(char c: s){ 15 | ans = ans + mp[c] + (mp[c] > prev ? -2*prev : 0); 16 | prev = mp[c]; 17 | } 18 | 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /rotate-array-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/rotate-array/ 2 | 3 | class Solution { 4 | public: 5 | void rotate(vector& nums, int k) { 6 | vector back = nums; 7 | int n = nums.size(), i = n - k, j = 0; 8 | 9 | while(j < n){ 10 | nums[j++] = back[i % n]; 11 | i++; 12 | } 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /rotate-array-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/rotate-array/description/ 2 | 3 | class Solution { 4 | public: 5 | void rotate(vector& nums, int k) { 6 | int n = nums.size(); 7 | k = k % n; 8 | rr(nums, 0, n-1); 9 | rr(nums, 0, k-1); 10 | rr(nums, k, n-1); 11 | } 12 | 13 | void rr(vector& nums, int s, int e){ 14 | while(s < e){ 15 | swap(nums[s++], nums[e--]); 16 | } 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /rotate-array.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/rotate-array/description/ 2 | class Solution { 3 | public: 4 | void rotate(vector& nums, int k) { 5 | k = k % nums.size(); 6 | reverse(nums.begin(), nums.end()); 7 | reverse(nums.begin(), nums.begin() + k); 8 | reverse(nums.begin() + k, nums.end()); 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /rotate-image-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/rotate-image/ 2 | 3 | class Solution { 4 | public: 5 | void rotate(vector>& matrix) { 6 | int n = matrix.size(), m = n ? matrix[0].size() : 0; 7 | reverse(matrix.begin(), matrix.end()); 8 | 9 | for(int i = 0; i < n; i++) 10 | for(int j = i + 1; j < m; j++) 11 | swap(matrix[i][j], matrix[j][i]); 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /rotate-image-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/rotate-image/description/ 2 | 3 | class Solution { 4 | public: 5 | void rotate(vector>& matrix) { 6 | reverse(matrix.begin(), matrix.end()); 7 | 8 | int n = matrix.size(); 9 | 10 | for(int i = 0; i < n; i++){ 11 | for(int j = i; j < n; j++) 12 | swap(matrix[i][j], matrix[j][i]); 13 | } 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /rotate-image-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/rotate-image/description/ 2 | 3 | class Solution { 4 | public: 5 | void rotate(vector>& matrix) { 6 | int n = matrix.size(), m = n ? matrix[0].size() : 0, i = 0; 7 | 8 | while(i < n - 1 - i){ 9 | swap(matrix[i], matrix[n - 1 - i]); 10 | i++; 11 | } 12 | 13 | for(int i = 0; i < n; i++){ 14 | for(int j = i; j < m; j++) 15 | swap(matrix[i][j], matrix[j][i]); 16 | } 17 | 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /same-number.cpp: -------------------------------------------------------------------------------- 1 | //https://www.lintcode.com/problem/same-number/description 2 | 3 | class Solution { 4 | public: 5 | /** 6 | * @param nums: the arrays 7 | * @param k: the distance of the same number 8 | * @return: the ans of this question 9 | */ 10 | string sameNumber(vector &nums, int k) { 11 | // Write your code here 12 | unordered_map hashMap; 13 | 14 | for(int i = 0; i < nums.size(); i++){ 15 | if (hashMap.count(nums[i]) && i - hashMap[nums[i]] < k) 16 | return "YES"; 17 | 18 | hashMap[nums[i]] = i; 19 | } 20 | 21 | return "NO"; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /same-tree-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/same-tree/description/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | bool isSameTree(TreeNode* p, TreeNode* q) { 15 | if (!(p || q)) return true; // both are NULL 16 | else if ((p && !q) || (!p && q)) return false; // one is NULL and other is not 17 | return (p->val == q->val) ? isSameTree(p->left, q->left) && isSameTree(p->right, q->right) : false; 18 | 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /same-tree-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/same-tree/description/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | bool isSameTree(TreeNode* p, TreeNode* q) { 15 | return (p && q && p->val == q->val && isSameTree(p->right, q->right) && isSameTree(p->left, q->left)) || (!p && !q); 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /search-a-2d-matrix-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/search-a-2d-matrix/description/ 2 | 3 | class Solution { 4 | public: 5 | bool searchMatrix(vector>& matrix, int target) { 6 | int m = matrix.size(), n = m ? matrix[0].size() : 0; 7 | 8 | if(m == 0 || n == 0) 9 | return false; 10 | 11 | int low = 0, high = m * n - 1; 12 | 13 | while(low <= high){ 14 | int mid = low + (high - low) / 2; 15 | int val = matrix[mid / n][mid - (mid / n)*n]; 16 | if ( val > target) high = mid - 1; 17 | else if (val < target) low = mid + 1; 18 | else return true; 19 | } 20 | return false; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /search-a-2d-matrix-ii-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/search-a-2d-matrix-ii/description/ 2 | 3 | class Solution { 4 | public: 5 | bool searchMatrix(vector>& matrix, int target) { 6 | int m = matrix.size(), n = m ? matrix[0].size() : 0; 7 | if (m == 0|| n == 0) return false; 8 | int row = 0, col = n - 1; 9 | 10 | while(row < m && col >= 0){ 11 | if (target == matrix[row][col]) return true; 12 | else if (target < matrix[row][col]) col--; 13 | else row++; 14 | } 15 | return false; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /search-a-2d-matrix-ii-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/search-a-2d-matrix-ii/description/ 2 | 3 | class Solution { 4 | public: 5 | bool searchMatrix(vector>& matrix, int target) { 6 | int m = matrix.size(), n = m ? matrix[0].size() : 0; 7 | if (!m || !n) return false; 8 | int i = 0, j = n - 1; 9 | 10 | while(i < m && j >= 0){ 11 | if (matrix[i][j] == target) 12 | return true; 13 | else if (matrix[i][j] > target) 14 | j--; 15 | else i++; 16 | } 17 | 18 | return false; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /search-in-rotated-sorted-array-4.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/search-in-rotated-sorted-array/description/ 2 | 3 | class Solution { 4 | public: 5 | int search(vector& nums, int target) { 6 | int l = 0, r = nums.size() - 1; 7 | 8 | while(l < r){ 9 | int m = l + (r - l)/2; 10 | if (nums[m] == target) return m; 11 | if (nums[l] <= nums[m]){ 12 | if (nums[l] <= target && nums[m] > target) r = m - 1; 13 | else l = m + 1; 14 | } else { 15 | if (nums[m] < target && nums[r] >= target) l = m + 1; 16 | else r = m - 1; 17 | } 18 | } 19 | 20 | return l == r && nums[l] == target ? l : -1; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /search-in-rotated-sorted-array-5.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/search-in-rotated-sorted-array/ 2 | 3 | class Solution { 4 | public: 5 | int search(vector& nums, int target) { 6 | int s = 0, e = nums.size() - 1; 7 | 8 | while(s <= e){ 9 | int m = s + (e - s)/2; 10 | if (nums[m] == target) return m; 11 | else if (nums[s] <= nums[m]){ 12 | if (target >= nums[s] && target < nums[m]) 13 | e = m - 1; 14 | else s = m + 1; 15 | } else { 16 | if (target > nums[m] && target <= nums[e]) 17 | s = m + 1; 18 | else e = m - 1; 19 | } 20 | } 21 | 22 | return -1; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /search-in-rotated-sorted-array-6.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/search-in-rotated-sorted-array/description/ 2 | 3 | class Solution { 4 | public: 5 | int search(vector& nums, int target) { 6 | int s = 0, e = nums.size() - 1; 7 | while(s <= e){ 8 | int m = s + (e - s) / 2; 9 | if (nums[m] == target) 10 | return m; 11 | else if (nums[s] <= nums[m]){ 12 | if (target >= nums[s] && target < nums[m]) 13 | e = m - 1; 14 | else s = m + 1; 15 | } else { 16 | if (target > nums[m] && target <= nums[e]) 17 | s = m + 1; 18 | else e = m - 1; 19 | } 20 | } 21 | 22 | return -1; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /search-in-rotated-sorted-array-7.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/search-in-rotated-sorted-array/description/ 2 | 3 | class Solution { 4 | public: 5 | int search(vector& nums, int target) { 6 | int i = 0, j = nums.size() - 1, m; 7 | 8 | while(i <= j){ 9 | m = i + (j - i)/2; 10 | if (nums[m] == target) return m; 11 | else if (nums[i] <= nums[m]){ 12 | if (nums[i] <= target && target < nums[m]) j = m - 1; 13 | else i = m + 1; 14 | } else { 15 | if (nums[m] < target && nums[j] >= target) i = m + 1; 16 | else j = m - 1; 17 | } 18 | } 19 | 20 | return -1; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /search-in-rotated-sorted-array-8.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/search-in-rotated-sorted-array/description/ 2 | 3 | class Solution { 4 | public: 5 | int search(vector& nums, int target) { 6 | int l = 0, r = nums.size() - 1; 7 | 8 | while(l <= r){ 9 | int m = l + (r - l)/2; 10 | if (target == nums[m]) return m; 11 | else if (nums[l] <= nums[m]){ 12 | if (target >= nums[l] && target < nums[m]) r = m - 1; 13 | else l = m + 1; 14 | } else { 15 | if (target > nums[m] && target <= nums[r]) l = m + 1; 16 | else r = m - 1; 17 | } 18 | } 19 | 20 | return -1; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /search-insert-position.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/search-insert-position/description/ 2 | 3 | class Solution { 4 | public: 5 | int searchInsert(vector& nums, int target) { 6 | int i = 0, j = nums.size(), mid, answer = -1; 7 | 8 | while(i < j && answer < 0) { 9 | mid = (i + j)/2; 10 | if (nums[mid] == target) 11 | answer = mid; 12 | else if (nums[mid] > target) { 13 | j = mid; 14 | } else 15 | i = mid + 1; 16 | } 17 | 18 | return answer >= 0 ? answer : i; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /set-mismatch-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/set-mismatch/description/ 2 | 3 | class Solution { 4 | public: 5 | vector findErrorNums(vector& nums) { 6 | int missing, repeated, idx; 7 | for(int &num : nums){ 8 | if (nums[abs(num) - 1] < 0) repeated = abs(num); 9 | else nums[abs(num) - 1] *= -1; 10 | } 11 | 12 | for(int i = 0; i < nums.size(); i++){ 13 | if (nums[i] > 0) missing = i + 1; 14 | } 15 | 16 | return {repeated, missing}; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /sliding-window-maximum.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/sliding-window-maximum/description/ 2 | 3 | class Solution { 4 | public: 5 | vector maxSlidingWindow(vector& nums, int k) { 6 | deque> d; 7 | vector ans; 8 | for(int i = 0; i < nums.size(); i++){ 9 | 10 | while(!d.empty() && d.back().first <= nums[i]) 11 | d.pop_back(); 12 | 13 | d.push_back({nums[i], i}); 14 | 15 | // test here 16 | while(!d.empty() && d.front().second <= i - k) 17 | d.pop_front(); 18 | 19 | if(d.back().second >= k - 1) ans.push_back(d.front().first); 20 | 21 | } 22 | 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /sort-colors-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/sort-colors/description/ 2 | 3 | class Solution { 4 | public: 5 | void sortColors(vector& nums) { 6 | int low = 0, mid = 0, high = nums.size() - 1; 7 | 8 | while(mid <= high){ 9 | if (nums[mid] == 0) swap(nums[low++], nums[mid++]); 10 | else if (nums[mid] == 1) mid++; 11 | else swap(nums[mid], nums[high--]); 12 | } 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /sort-colors-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/sort-colors/description/ 2 | 3 | class Solution { 4 | public: 5 | void sortColors(vector& nums) { 6 | int low = 0, mid = 0, high = nums.size() - 1; 7 | // 0 to low - 1 all 0 8 | // low to mid - 1 all 1 9 | // mid to high - 1 - still figuring 10 | // high to n - 1 all 2 11 | while(mid <= high){ 12 | if (nums[mid] == 0) swap(nums[mid++], nums[low++]); 13 | else if (nums[mid] == 1) mid++; 14 | else swap(nums[mid], nums[high--]); 15 | } 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /sqrtx-1.cpp: -------------------------------------------------------------------------------- 1 | // https://www.lintcode.com/problem/sqrtx/description 2 | 3 | class Solution { 4 | public: 5 | /** 6 | * @param x: An integer 7 | * @return: The sqrt of x 8 | */ 9 | int sqrt(int x) { 10 | // write your code here 11 | if (x == 0 || x == 1) return x; 12 | int s = 1, e = x, ans; 13 | 14 | 15 | while(e >= s){ 16 | int mid = s + (e - s) / 2; 17 | if (mid > x / mid){ 18 | e = mid - 1; 19 | } else { 20 | ans = mid; 21 | s = mid + 1; 22 | } 23 | } 24 | 25 | return ans; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /sqrtx-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/sqrtx/description/ 2 | 3 | class Solution { 4 | public: 5 | int mySqrt(int x) { 6 | if (x < 2) return x; 7 | int low = 1, high = x, ans, mid; 8 | 9 | while(low <= high){ 10 | mid = low + (high - low) / 2; 11 | if (mid > x / mid) high = mid - 1; 12 | else { 13 | ans = mid; 14 | low = mid + 1; 15 | } 16 | } 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /sqrtx-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/sqrtx/description/ 2 | 3 | class Solution { 4 | public: 5 | int mySqrt(int x) { 6 | if (x == 0) return x; 7 | int s = 1, e = x; 8 | // finding the right most number that give its square to be less 9 | // than or equal to x 10 | while(e - s > 1){ 11 | int m = s + (e - s) / 2; 12 | if (m <= x / m) s = m; 13 | else e = m; 14 | } 15 | 16 | return s; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /sqrtx-4.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/sqrtx/description/ 2 | 3 | class Solution { 4 | public: 5 | int mySqrt(int x) { 6 | if (x < 2) return x; 7 | int s = 0, e = x; 8 | 9 | while(e - s > 1){ 10 | int m = s + (e - s)/2; 11 | if(m <= x / m) s = m; 12 | else e = m; 13 | } 14 | 15 | return s; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /sqrtx-5.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/sqrtx/description/ 2 | 3 | class Solution { 4 | public: 5 | int mySqrt(int x) { 6 | if (x < 2) return x; 7 | int a = 0, b = x, m; 8 | // right most m such that m * m <= x 9 | 10 | while(b - a > 1){ 11 | m = a + (b - a) / 2; 12 | if (m > x/m) b = m; 13 | else a = m; 14 | } 15 | 16 | return a; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /sqrtx.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/sqrtx/description/ 2 | 3 | class Solution { 4 | public: 5 | int mySqrt(int x) { 6 | long low = 0, high = x; 7 | 8 | while(low <= high){ 9 | long mid = low + (high - low) / 2; 10 | if (mid * mid < x) low = mid + 1; 11 | else if (mid * mid > x) high = mid - 1; 12 | else return mid; 13 | } 14 | return low - 1; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /string-compression-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/string-compression/description/ 2 | 3 | class Solution { 4 | public: 5 | int compress(vector& chars) { 6 | int sidx = 0, count = 0, len = 0, n = chars.size(); 7 | 8 | for(int i = 0; i <= n; i++){ 9 | if (i < n && chars[sidx] == chars[i]) count++; 10 | else { 11 | chars[len++] = chars[sidx]; 12 | if (count > 1){ 13 | string cs = to_string(count); 14 | for(char c : cs) 15 | chars[len++] = c; 16 | } 17 | 18 | sidx = i; 19 | count = 1; 20 | } 21 | } 22 | 23 | return len; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /string-to-integer-atoi-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/string-to-integer-atoi/ 2 | 3 | class Solution { 4 | public: 5 | int myAtoi(string str) { 6 | bool sign = false; 7 | int i = 0, n = str.length(), ans = 0; 8 | while(i < n && str[i] == ' ') i++; 9 | 10 | if (i < n && (str[i] == '+' || str[i] == '-')) sign = (str[i++] == '-'); 11 | 12 | while(i < n && '0' <= str[i] && str[i] <= '9'){ 13 | if (ans > INT_MAX/10 || (ans == INT_MAX/10 && str[i] - '0' > INT_MAX % 10)) 14 | return sign ? INT_MIN : INT_MAX; 15 | 16 | ans = ans * 10 + str[i] - '0'; 17 | i++; 18 | } 19 | 20 | return sign ? -ans : ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /string-to-integer-atoi-4.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/string-to-integer-atoi/description/ 2 | 3 | class Solution { 4 | public: 5 | int myAtoi(string str) { 6 | int i = 0, n = str.length(), ans = 0; 7 | bool neg = false; 8 | while(i < n && str[i] == ' ') i++; 9 | if (str[i] == '-' || str[i] == '+'){ 10 | neg = (i < n && str[i] == '-'); 11 | i++; 12 | } 13 | 14 | while(i < n && str[i] >= '0' && str[i] <= '9'){ 15 | if (ans > INT_MAX/10 || ans == INT_MAX/10 && str[i] - '0' > INT_MAX%10) 16 | return neg ? INT_MIN : INT_MAX; 17 | ans = ans * 10 + str[i] - '0'; 18 | i++; 19 | } 20 | 21 | return neg ? -ans : ans; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /strobogrammatic-number-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/strobogrammatic-number/description/ 2 | 3 | class Solution { 4 | public: 5 | bool isStrobogrammatic(string num) { 6 | unordered_map mapping = { 7 | {'0', '0'}, {'1', '1'}, {'6', '9'}, {'8', '8'}, {'9', '6'} 8 | }; 9 | 10 | int i = num.size() - 1; 11 | 12 | for(char c : num){ 13 | if (!mapping.count(c)) return false; 14 | else if (mapping[c] != num[i--]) return false; 15 | } 16 | 17 | return true; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /subarray-product-less-than-k-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/subarray-product-less-than-k/description/ 2 | 3 | class Solution { 4 | public: 5 | int numSubarrayProductLessThanK(vector& nums, int k) { 6 | int start = 0, end = 0, ans = 0; 7 | long product = 1l; 8 | 9 | while(end < nums.size()){ 10 | // define end and find the start which will satisfy ! 11 | product *= nums[end]; 12 | while(start <= end && product >= k){ 13 | product /= nums[start++]; 14 | } 15 | ans += (end - start + 1); 16 | end++; 17 | } 18 | 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /subarray-sum-equals-k-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/subarray-sum-equals-k/description/ 2 | class Solution { 3 | public: 4 | int subarraySum(vector& nums, int k) { 5 | unordered_map countHash; 6 | unordered_map :: iterator itr; 7 | int ans = 0, runningCount = 0; 8 | countHash[0] = 1; // case when runningCount == k 9 | for(auto &num : nums){ 10 | runningCount += num; 11 | if ((itr = countHash.find(runningCount - k)) != countHash.end()) 12 | ans += itr->second; 13 | countHash[runningCount] += 1; 14 | } 15 | 16 | return ans; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /subsets-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/subsets/description/ 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | void helper(vector& temp, int i, vector& nums, vector>& answer){ 8 | answer.push_back(temp); 9 | for(int j = i ; j < nums.size(); j++){ 10 | temp.push_back(nums[j]); 11 | this->helper(temp, j + 1, nums, answer); 12 | temp.pop_back(); 13 | } 14 | } 15 | 16 | vector> subsets(vector& nums) { 17 | vector> answer; 18 | vector temp; 19 | this->helper(temp, 0, nums, answer); 20 | return answer; 21 | } 22 | }; 23 | 24 | -------------------------------------------------------------------------------- /subsets-ii.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/subsets-ii/description/ 2 | 3 | class Solution { 4 | public: 5 | 6 | vector temp; 7 | vector> ans; 8 | 9 | void helper(vector& nums, int i){ 10 | ans.push_back(temp); 11 | for(int j = i; j < nums.size(); j++){ 12 | if (j > i && nums[j] == nums[j-1]) continue; 13 | temp.push_back(nums[j]); 14 | helper(nums, j + 1); 15 | temp.pop_back(); 16 | } 17 | } 18 | vector> subsetsWithDup(vector& nums) { 19 | sort(nums.begin(), nums.end()); 20 | helper(nums, 0); 21 | return ans; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /sum-of-left-leaves-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/sum-of-left-leaves/description/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int ans = 0; 15 | int sumOfLeftLeaves(TreeNode* root, bool flag = false) { 16 | if (flag && root && !root->left && !root->right) ans += root->val; 17 | else if (root){ 18 | sumOfLeftLeaves(root->right, false); 19 | sumOfLeftLeaves(root->left, true); 20 | } 21 | return ans; 22 | } 23 | 24 | }; 25 | -------------------------------------------------------------------------------- /sum-of-left-leaves-4.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/sum-of-left-leaves/description/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int sumOfLeftLeaves(TreeNode* root, bool l = false) { 15 | if (!root) return 0; 16 | int ans = 0; 17 | ans += sumOfLeftLeaves(root->left, true); 18 | ans += sumOfLeftLeaves(root->right, false); 19 | if (!root->right && !root->left && l) ans = root->val; 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /sum-of-two-integers.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/sum-of-two-integers/description/ 2 | class Solution { 3 | public: 4 | int getSum(int a, int b) { 5 | 6 | return b == 0 ? a : getSum(a ^ b, (a & b) << 1); 7 | } 8 | }; 9 | -------------------------------------------------------------------------------- /swap-nodes-in-pairs-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/swap-nodes-in-pairs/description/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode(int x) : val(x), next(NULL) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* swapPairs(ListNode* head) { 14 | if (!head || !head->next) return head; 15 | ListNode* ans = head->next, *temp = head->next->next; 16 | 17 | ans->next = head; 18 | head->next = swapPairs(temp); 19 | 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /swap-nodes-in-pairs-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/swap-nodes-in-pairs/description/ 2 | 3 | /** 4 | * Definition for singly-linked list. 5 | * struct ListNode { 6 | * int val; 7 | * ListNode *next; 8 | * ListNode(int x) : val(x), next(NULL) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* swapPairs(ListNode* head) { 14 | ListNode* ans = new ListNode(-1), *temp = ans, *t; 15 | 16 | while(head && head->next){ 17 | t = head->next->next; 18 | ans->next = head->next; 19 | ans->next->next = head; 20 | ans = head; 21 | head = t; 22 | } 23 | 24 | ans->next = head; 25 | return temp->next; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /symmetric-tree-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/symmetric-tree/description/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | bool isSymmetric(TreeNode* root) { 15 | return (root && helper(root->right, root->left)) || !root; 16 | } 17 | 18 | bool helper(TreeNode* t1, TreeNode* t2){ 19 | if (!t1 && !t2) return true; 20 | return (t1 && t2 && t1->val == t2->val && helper(t1->right, t2->left) && helper(t2->right, t1->left)); 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /symmetric-tree-4.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/symmetric-tree/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | bool isSymmetric(TreeNode* root) { 15 | if (!root) return true; 16 | return helper(root->left, root->right); 17 | } 18 | 19 | bool helper(TreeNode* n1, TreeNode* n2){ 20 | if (!n1 && !n2) return true; 21 | else if (n1 && n2 && n1->val == n2->val) return helper(n1->left, n2->right) && helper(n1->right, n2->left); 22 | return false; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /target-sum-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/target-sum/description/ 2 | 3 | class Solution { 4 | public: 5 | int findTargetSumWays(vector& nums, int S) { 6 | int ans = 0; 7 | helper(nums, ans, S, 0, 0); 8 | return ans; 9 | } 10 | 11 | void helper(vector& nums, int& ans, int S, int tempSum, int idx){ 12 | if (idx == nums.size()) { 13 | if (S == tempSum) ans++; 14 | } else{ 15 | helper(nums, ans, S, tempSum + nums[idx], ++idx); 16 | helper(nums, ans, S, tempSum - nums[idx], idx); 17 | } 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /target-sum-4.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/target-sum/description/ 2 | 3 | class Solution { 4 | public: 5 | int findTargetSumWays(vector& nums, int S, int i = 0) { 6 | int ans = 0, n = nums.size(); 7 | if (n == i) return S == 0; 8 | ans += findTargetSumWays(nums, S - nums[i], i + 1) + findTargetSumWays(nums, S + nums[i], i + 1); 9 | return ans; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /target-sum-5.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/target-sum/description/ 2 | 3 | class Solution { 4 | public: 5 | int findTargetSumWays(vector& nums, int S, int idx = 0) { 6 | if (idx == nums.size()) return S == 0; 7 | return findTargetSumWays(nums, S - nums[idx], idx + 1) + findTargetSumWays(nums,S + nums[idx], idx + 1); 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /target-sum-6.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/target-sum/description/ 2 | 3 | class Solution { 4 | public: 5 | int findTargetSumWays(vector& nums, int S) { 6 | int n = nums.size(); 7 | if (n == 0) return S == 0; 8 | vector> dp(n + 1); 9 | 10 | dp[0][0] = 1; 11 | 12 | for(int i = 1; i <= n; i++){ 13 | for(auto kv : dp[i - 1]){ 14 | dp[i][kv.first + nums[i - 1]] += kv.second; 15 | dp[i][kv.first - nums[i - 1]] += kv.second; 16 | } 17 | } 18 | 19 | return dp[n][S]; 20 | } 21 | 22 | }; 23 | -------------------------------------------------------------------------------- /task-scheduler-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/task-scheduler/ 2 | 3 | class Solution { 4 | public: 5 | int leastInterval(vector& tasks, int n) { 6 | vector counts(26, 0); 7 | int maxCount = 0, points = 0; 8 | 9 | for(char t : tasks){ 10 | int c = ++counts[t - 'A']; 11 | if (c > maxCount){ 12 | points = 1; 13 | maxCount = c; 14 | } else if (c == maxCount) 15 | points++; 16 | } 17 | int slots = maxCount - 1; 18 | int emptyBuckets = slots * (n - (points - 1)); 19 | int remainingTasks = tasks.size() - maxCount*points; 20 | int idle = max(0, emptyBuckets - remainingTasks); 21 | return tasks.size() + idle; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /teemo-attacking.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/teemo-attacking/submissions/1 2 | 3 | class Solution { 4 | public: 5 | int findPoisonedDuration(vector& timeSeries, int duration) { 6 | int answer = (timeSeries.size() > 0) ? duration : 0, diff; 7 | for(int i = 1; i < timeSeries.size(); i++){ 8 | diff = timeSeries[i] - timeSeries[i - 1]; 9 | answer += (diff >= duration) ? duration : diff; 10 | } 11 | return answer; 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /third-maximum-number.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/third-maximum-number/description/ 2 | class Solution { 3 | public: 4 | int thirdMax(vector& nums) { 5 | long long int max1 = LONG_MIN, max2 = LONG_MIN, max3 = LONG_MIN; 6 | bool flag = false; 7 | // max1 < max2 < max3; 8 | 9 | for(int n : nums){ 10 | if (n > max3){ 11 | max1 = max2; 12 | max2 = max3; 13 | max3 = n; 14 | } else if (n > max2 && n != max3){ 15 | max1 = max2; 16 | max2 = n; 17 | } else if (n > max1 && n != max2 && n != max3 ){ 18 | max1 = n; 19 | } 20 | } 21 | 22 | return (max1 != LONG_MIN) ? max1 : max3; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /trapping-rain-water-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/trapping-rain-water/description/ 2 | 3 | class Solution { 4 | public: 5 | int trap(vector& height) { 6 | int ans = 0, maxl = 0, maxr = 0, l = 0, r = height.size() - 1; 7 | 8 | while(l <= r){ 9 | if (height[l] < height[r]){ 10 | if (height[l] > maxl) maxl = height[l]; 11 | else ans += maxl - height[l]; 12 | l++; 13 | } else { 14 | if (height[r] > maxr) maxr = height[r]; 15 | else ans += maxr - height[r]; 16 | r--; 17 | } 18 | } 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /trapping-rain-water-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/trapping-rain-water/description/ 2 | 3 | class Solution { 4 | public: 5 | int trap(vector& height) { 6 | int res = 0, l = 0, r = height.size() - 1, left = 0, right = 0; 7 | while(r > l){ 8 | if (height[r] > height[l]){ 9 | left = max(left, height[l]); 10 | res += left - height[l++]; 11 | } else { 12 | right = max(right, height[r]); 13 | res += right - height[r--]; 14 | } 15 | } 16 | return res; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /trapping-rain-water-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/trapping-rain-water/description/ 2 | 3 | class Solution { 4 | public: 5 | int trap(vector& height) { 6 | int ans = 0, lmax = 0, rmax = 0, lidx = 0, ridx = height.size() - 1; 7 | 8 | while(lidx < ridx){ 9 | if (height[lidx] > height[ridx]){ 10 | rmax = max(rmax, height[ridx]); 11 | ans += rmax - height[ridx--]; 12 | } else { 13 | lmax = max(lmax, height[lidx]); 14 | ans += lmax - height[lidx++]; 15 | } 16 | } 17 | 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /trapping-rain-water-4.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/trapping-rain-water/submissions/ 2 | 3 | class Solution { 4 | public: 5 | int trap(vector& height) { 6 | int ans = 0, l = 0, r = 0, i = 0, j = height.size() - 1; 7 | 8 | while(i < j){ 9 | if (height[i] < height[j]){ 10 | l = max(l, height[i]); 11 | ans += l - height[i++]; 12 | } else { 13 | r = max(r, height[j]); 14 | ans += r - height[j--]; 15 | } 16 | } 17 | 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /trapping-rain-water-5.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/trapping-rain-water/description/ 2 | 3 | class Solution { 4 | public: 5 | int trap(vector& height) { 6 | int ans = 0, i = 0, j = height.size() - 1, maxl = 0; 7 | while(i < j){ 8 | 9 | if (height[i] < height[j]){ 10 | maxl = max(height[i], maxl); 11 | ans += maxl - height[i]; 12 | i++; 13 | } else { 14 | maxl = max(height[j], maxl); 15 | ans += maxl - height[j]; 16 | j--; 17 | } 18 | } 19 | 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /trapping-rain-water-6.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/trapping-rain-water/ 2 | 3 | class Solution { 4 | public: 5 | int trap(vector& height) { 6 | int ans = 0, n = height.size(), i = 0, j = n - 1, lm = 0, rm = 0; 7 | 8 | while(i < j){ 9 | if (height[i] > height[j]){ 10 | height[j] >= rm ? (rm = height[j]) : ans += (rm - height[j]); 11 | j--; 12 | } else { 13 | height[i] >= lm ? (lm = height[i]) : ans += (lm - height[i]); 14 | i++; 15 | } 16 | } 17 | 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /two-sum-1.cpp: -------------------------------------------------------------------------------- 1 | // https://www.lintcode.com/problem/two-sum/description 2 | 3 | class Solution { 4 | public: 5 | /** 6 | * @param numbers: An array of Integer 7 | * @param target: target = numbers[index1] + numbers[index2] 8 | * @return: [index1, index2] (index1 < index2) 9 | */ 10 | vector twoSum(vector &numbers, int target) { 11 | // write your code here 12 | int n = numbers.size(); 13 | unordered_map um; 14 | 15 | for(int i = 0; i < numbers.size(); i++){ 16 | int key = target - numbers[i]; 17 | if (um.count(target - numbers[i])){ 18 | return {um[key], i}; 19 | } 20 | um[numbers[i]] = i; 21 | } 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /two-sum-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/two-sum/description/ 2 | 3 | class Solution { 4 | public: 5 | vector twoSum(vector& nums, int target) { 6 | vector ans; 7 | unordered_map ump; 8 | int i = 0; 9 | for(auto num : nums){ 10 | if (ump.count(target - num)) return {ump[target - num], i}; 11 | ump[num] = i++; 12 | } 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /two-sum-4.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/two-sum/description/ 2 | 3 | class Solution { 4 | public: 5 | vector twoSum(vector& nums, int target) { 6 | unordered_map ump; 7 | int i = 0; 8 | 9 | for(int num: nums){ 10 | if (ump.count(target - num)) return {ump[target-num], i}; 11 | ump[num] = i++; 12 | } 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /two-sum-iv-input-is-a-bst-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/two-sum-iv-input-is-a-bst/description/ 2 | 3 | /** 4 | * Definition for a binary tree node. 5 | * struct TreeNode { 6 | * int val; 7 | * TreeNode *left; 8 | * TreeNode *right; 9 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | unordered_set numSeen; 15 | bool findTarget(TreeNode* root, int k) { 16 | if (!root) return false; 17 | else if (numSeen.count(k - root->val)) return true; 18 | numSeen.insert(root->val); 19 | return findTarget(root->left, k) || findTarget(root->right, k); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /ugly-number.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/ugly-number/description/ 2 | 3 | class Solution { 4 | public: 5 | void reduce(int &num, int factor){ 6 | while(num % factor == 0 && num != 1 && num != 0) 7 | num /= factor; 8 | } 9 | bool isUgly(int num) { 10 | vector factors = {2, 3, 5}; 11 | for(int& factor: factors) 12 | reduce(num, factor); 13 | 14 | return num == 1; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /unique-morse-code-words.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/unique-morse-code-words/description/ 2 | class Solution { 3 | public: 4 | int uniqueMorseRepresentations(vector& words) { 5 | unordered_map map; 6 | const char* morseCode [] = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}; 7 | 8 | for(auto str: words){ 9 | stringstream ss; 10 | for (char c : str){ 11 | ss << morseCode[c - 'a']; 12 | } 13 | map[ss.str()] = true; 14 | } 15 | 16 | 17 | return map.size(); 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /unique-paths-ii-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/unique-paths-ii/description/ 2 | 3 | class Solution { 4 | public: 5 | int uniquePathsWithObstacles(vector>& obstacleGrid) { 6 | int m = obstacleGrid.size(), n = m ? obstacleGrid[0].size() : 0; 7 | if (m == 0 || n == 0) 8 | return 0; 9 | 10 | vector dp(n, 0); 11 | 12 | for(int i = 0; i < m; i++){ 13 | for(int j = 0; j < n; j++){ 14 | if (i == 0){ 15 | dp[j] = obstacleGrid[i][j] ? 0 : (j ? dp[j - 1] : 1); 16 | } else { 17 | dp[j] = obstacleGrid[i][j] ? 0 : dp[j] + dp[j - 1]; 18 | } 19 | } 20 | } 21 | 22 | return dp[n - 1]; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /valid-anagram-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/valid-anagram/submissions/1 2 | 3 | class Solution { 4 | public: 5 | void getCount(string s, vector& count){ 6 | for(auto c : s){ 7 | count[c - 'a'] += 1; 8 | } 9 | } 10 | 11 | bool isAnagram(string s, string t) { 12 | vector count1(26, 0); 13 | vector count2(26, 0); 14 | getCount(s, count1); 15 | getCount(t, count2); 16 | bool flag = true; 17 | for(int i = 0; i < 26 && flag; i++){ 18 | flag = (count1[i] == count2[i]); 19 | } 20 | return flag; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /valid-palindrom-ii-1.cpp: -------------------------------------------------------------------------------- 1 | // https://www.lintcode.com/problem/valid-palindrome-ii/description 2 | 3 | class Solution { 4 | public: 5 | /** 6 | * @param s: a string 7 | * @return: nothing 8 | */ 9 | bool validPalindrome(string &s) { 10 | // Write your code here 11 | int i = 0, j = s.length() - 1; 12 | 13 | while(j > i){ 14 | if (s[i++] == s[j--]) continue; 15 | else return check(s, i, j - 1) || check(s, i + 1, j); 16 | } 17 | return true; 18 | } 19 | 20 | bool check(string&s, int i, int j){ 21 | while(j > i){ 22 | if (s[i++] == s[j--]) continue; 23 | else return false; 24 | } 25 | return true; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /valid-palindrome-1.cpp: -------------------------------------------------------------------------------- 1 | // https://www.lintcode.com/problem/valid-palindrome/description 2 | 3 | class Solution { 4 | public: 5 | /** 6 | * @param s: A string 7 | * @return: Whether the string is a valid palindrome 8 | */ 9 | bool isPalindrome(string &s) { 10 | // write your code here 11 | int i = 0, j = s.length() - 1; 12 | while(j > i){ 13 | if (isalnum(s[i]) && isalnum(s[j])){ 14 | if (s[i] == s[j] || tolower(s[i]) == tolower(s[j])){ 15 | i++; j--; 16 | } else return false; 17 | } else if (isalnum(s[i])) j--; 18 | else if (isalnum(s[j])) i++; 19 | else { 20 | j--; i++; 21 | } 22 | } 23 | 24 | return true; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /valid-palindrome-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/valid-palindrome/description/ 2 | 3 | class Solution { 4 | public: 5 | bool isPalindrome(string s) { 6 | int i = 0, j = s.length() - 1; 7 | while(i < j){ 8 | if (isalnum(s[i]) && isalnum(s[j])){ 9 | if (tolower(s[i]) != tolower(s[j])) 10 | return false; 11 | i++; j--; 12 | } else if (isalnum(s[i])) j--; 13 | else if (isalnum(s[j])) i++; 14 | else {i++; j--;} 15 | } 16 | return true; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /valid-palindrome-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/valid-palindrome/description/ 2 | 3 | class Solution { 4 | public: 5 | bool isPalindrome(string s) { 6 | int i = 0, j = s.length() - 1, n = s.length(); 7 | while(j > i){ 8 | while(!isalnum(s[i]) && i < n) i++; 9 | while(!isalnum(s[j]) && j >= 0) j--; 10 | if (i < j && tolower(s[i]) == tolower(s[j])) {i++; j--;} 11 | else if (i < j) return false; 12 | } 13 | return true; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /valid-palindrome-ii-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/valid-palindrome-ii/description/ 2 | 3 | class Solution { 4 | public: 5 | bool validPalindrome(string s) { 6 | int i = 0, j = s.length() - 1; 7 | while(i < j){ 8 | if (s[i] == s[j]){ i++; j--;} 9 | else if (helper(s, i + 1, j) || helper(s, i, j - 1)) 10 | return true; 11 | else return false; 12 | } 13 | return true; 14 | } 15 | 16 | bool helper(string& s, int i, int j){ 17 | while(i < j){ 18 | if (s[i] == s[j]) { i++; j--;} 19 | else return false; 20 | } 21 | return true; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /valid-parentheses-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/valid-parentheses/description/ 2 | 3 | class Solution { 4 | public: 5 | bool isValid(string s) { 6 | unordered_map matching = { 7 | {'}','{'}, 8 | {')','('}, 9 | {']','['} 10 | }; 11 | unordered_map openingCount = {{'{', 0}, {'[', 0}, {'(', 0}}; 12 | stack stk; 13 | 14 | for(char c : s){ 15 | if (!openingCount.count(c)){ 16 | if (stk.size() && stk.top() == matching[c]) stk.pop(); 17 | else return false; 18 | } else stk.push(c); 19 | } 20 | 21 | return stk.empty(); 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /valid-parentheses-3.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/valid-parentheses/description/ 2 | 3 | class Solution { 4 | public: 5 | bool isValid(string s) { 6 | stack stk; 7 | unordered_map matching = {{')', '('}, {'}', '{'}, {']', '['}}; 8 | for(char c : s){ 9 | if (matching.count(c)) { 10 | if (stk.empty() || stk.top() != matching[c]) 11 | return false; 12 | stk.pop(); 13 | } else stk.push(c); 14 | } 15 | 16 | return stk.empty(); 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /valid-perfect-square.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/valid-perfect-square/description/ 2 | 3 | class Solution { 4 | public: 5 | bool isPerfectSquare(int num) { 6 | long low = 1, high = num, mid; 7 | 8 | while(low <= high){ 9 | mid = low + ((high - low) / 2); 10 | if (mid * mid < num) low = mid + 1; 11 | else if (mid * mid > num) high = mid - 1; 12 | else return true; 13 | } 14 | return false; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /valid-triangle-number.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/valid-triangle-number/description/ 2 | 3 | class Solution { 4 | public: 5 | int triangleNumber(vector& nums) { 6 | int answer = 0, n = nums.size(); 7 | sort(nums.begin(), nums.end()); 8 | for(int i = n - 1; i >= 0; i--){ 9 | int l = 0, r = i - 1; 10 | while(l < r){ 11 | if(nums[l] + nums[r] > nums[i]){ 12 | answer += r - l; 13 | r--; 14 | } else l++; 15 | } 16 | } 17 | 18 | return answer; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /word-pattern-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/word-pattern/description/ 2 | 3 | class Solution { 4 | public: 5 | bool wordPattern(string pattern, string str) { 6 | unordered_map mp1; 7 | unordered_map mp2; 8 | stringstream ss(str); 9 | string token; 10 | int i = 0; 11 | 12 | while( ss >> token){ 13 | if (i == pattern.size()) return false; 14 | if (mp1.count(pattern[i]) && mp1[pattern[i]] != token) return false; 15 | if (mp2.count(token) && mp2[token] != pattern[i]) return false; 16 | mp1[pattern[i]] = token; 17 | mp2[token] = pattern[i++]; 18 | } 19 | 20 | return i == pattern.size(); 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /word-pattern-2.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/word-pattern/description/ 2 | 3 | class Solution { 4 | public: 5 | bool wordPattern(string pattern, string str) { 6 | unordered_map m1; 7 | unordered_map m2; 8 | stringstream ss(str); 9 | int i = 0, n = pattern.length(); 10 | 11 | for(string temp; ss >> temp; i++){ 12 | if (i == n || m1[pattern[i]] != m2[temp]) 13 | return false; 14 | m1[pattern[i]] = m2[temp] = i + 1; 15 | } 16 | 17 | return i == n; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /zigzag-conversion-1.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/zigzag-conversion/description/ 2 | 3 | class Solution { 4 | public: 5 | string convert(string s, int numRows) { 6 | string ans = ""; 7 | int i = 0, n = s.length(), diff = 2*(numRows - 1), dd = diff; 8 | if (numRows == 1) return s; 9 | while(i < numRows){ 10 | // cout << i << ": "; 11 | for(int j = i; j < n; j += dd){ 12 | ans += string(1, s[j]); 13 | // cout << j << ","; 14 | dd = abs(diff - dd) ? abs(diff - dd) : diff; 15 | } 16 | i++; 17 | dd = 2*i; 18 | // cout << "(" << dd << ")" << endl; 19 | } 20 | 21 | return ans; 22 | } 23 | }; 24 | --------------------------------------------------------------------------------