├── .gitignore ├── 75-Blind-Questions └── README.md ├── Beginner level └── README.md ├── CONTRIBUTING.md ├── Intermediate level └── README.md ├── README.md └── Solutions ├── C++ ├── 0001-two-sum │ ├── 0001-two-sum.cpp │ ├── NOTES.md │ └── README.md ├── 0002-add-two-numbers │ ├── 0002-add-two-numbers.cpp │ ├── NOTES.md │ └── README.md ├── 0003-longest-substring-without-repeating-characters │ ├── 0003-longest-substring-without-repeating-characters.cpp │ ├── NOTES.md │ └── README.md ├── 0004-median-of-two-sorted-arrays │ ├── 0004-median-of-two-sorted-arrays.cpp │ ├── NOTES.md │ └── README.md ├── 0005-longest-palindromic-substring │ ├── 0005-longest-palindromic-substring.cpp │ ├── NOTES.md │ └── README.md ├── 0007-reverse-integer │ ├── 0007-reverse-integer.cpp │ ├── NOTES.md │ └── README.md ├── 0011-container-with-most-water │ ├── 0011-container-with-most-water.cpp │ ├── NOTES.md │ └── README.md ├── 0015-3sum │ ├── 0015-3sum.cpp │ ├── NOTES.md │ └── README.md ├── 0016-3sum-closest │ ├── 0016-3sum-closest.cpp │ ├── NOTES.md │ └── README.md ├── 0019-remove-nth-node-from-end-of-list │ ├── 0019-remove-nth-node-from-end-of-list.cpp │ └── NOTES.md ├── 0020-valid-parentheses │ ├── 0020-valid-parentheses.cpp │ ├── NOTES.md │ └── README.md ├── 0021-merge-two-sorted-lists │ ├── 0021-merge-two-sorted-lists.cpp │ ├── NOTES.md │ └── README.md ├── 0022-generate-parentheses │ ├── 0022-generate-parentheses.cpp │ └── README.md ├── 0023-merge-k-sorted-lists │ ├── 0023-merge-k-sorted-lists.cpp │ ├── NOTES.md │ └── README.md ├── 0024-swap-nodes-in-pairs │ ├── 0024-swap-nodes-in-pairs.cpp │ ├── NOTES.md │ └── README.md ├── 0033-search-in-rotated-sorted-array │ ├── 0033-search-in-rotated-sorted-array.cpp │ ├── NOTES.md │ └── README.md ├── 0034-find-first-and-last-position-of-element-in-sorted-array │ ├── 0034-find-first-and-last-position-of-element-in-sorted-array.cpp │ ├── NOTES.md │ └── README.md ├── 0039-combination-sum │ ├── 0039-combination-sum.cpp │ ├── NOTES.md │ └── README.md ├── 0043-multiply-strings │ ├── 0043-multiply-strings.cpp │ ├── NOTES.md │ └── README.md ├── 0045-jump-game-ii │ ├── 0045-jump-game-ii.cpp │ ├── NOTES.md │ └── README.md ├── 0046-permutations │ ├── 0046-permutations.cpp │ ├── NOTES.md │ └── README.md ├── 0048-rotate-image │ ├── 0048-rotate-image.cpp │ ├── NOTES.md │ └── README.md ├── 0049-group-anagrams │ ├── 0049-group-anagrams.cpp │ ├── NOTES.md │ └── README.md ├── 0053-maximum-subarray │ ├── 0053-maximum-subarray.cpp │ ├── NOTES.md │ └── README.md ├── 0054-spiral-matrix │ ├── 0054-spiral-matrix.cpp │ ├── NOTES.md │ └── README.md ├── 0055-jump-game │ ├── 0055-jump-game.cpp │ ├── NOTES.md │ └── README.md ├── 0056-merge-intervals │ ├── 0056-merge-intervals.cpp │ ├── NOTES.md │ └── README.md ├── 0057-insert-interval │ ├── 0057-insert-interval.cpp │ ├── NOTES.md │ └── README.md ├── 0061-rotate-list │ ├── 0061-rotate-list.cpp │ ├── NOTES.md │ └── README.md ├── 0062-unique-paths │ ├── 0062-unique-paths.cpp │ ├── NOTES.md │ └── README.md ├── 0070-climbing-stairs │ ├── 0070-climbing-stairs.cpp │ ├── NOTES.md │ └── README.md ├── 0073-set-matrix-zeroes │ ├── 0073-set-matrix-zeroes.cpp │ ├── NOTES.md │ └── README.md ├── 0076-minimum-window-substring │ ├── 0076-minimum-window-substring.cpp │ ├── NOTES.md │ └── README.md ├── 0078-subsets │ ├── 0078-subsets.cpp │ ├── NOTES.md │ └── README.md ├── 0079-word-search │ ├── 0079-word-search.cpp │ ├── NOTES.md │ └── README.md ├── 0091-decode-ways │ ├── 0091-decode-ways.cpp │ ├── NOTES.md │ └── README.md ├── 0092-reverse-linked-list-ii │ ├── 0092-reverse-linked-list-ii.cpp │ ├── NOTES.md │ └── README.md ├── 0098-validate-binary-search-tree │ ├── 0098-validate-binary-search-tree.cpp │ ├── NOTES.md │ └── README.md ├── 0100-same-tree │ ├── 0100-same-tree.cpp │ ├── NOTES.md │ └── README.md ├── 0101-symmetric-tree │ ├── 0101-symmetric-tree.cpp │ ├── NOTES.md │ └── README.md ├── 0102-binary-tree-level-order-traversal │ ├── 0102-binary-tree-level-order-traversal.cpp │ ├── NOTES.md │ └── README.md ├── 0103-binary-tree-zigzag-level-order-traversal │ ├── 0103-binary-tree-zigzag-level-order-traversal.cpp │ ├── NOTES.md │ └── README.md ├── 0104-maximum-depth-of-binary-tree │ ├── 0104-maximum-depth-of-binary-tree.cpp │ ├── NOTES.md │ └── README.md ├── 0105-construct-binary-tree-from-preorder-and-inorder-traversal │ ├── 0105-construct-binary-tree-from-preorder-and-inorder-traversal.cpp │ ├── NOTES.md │ └── README.md ├── 0106-construct-binary-tree-from-inorder-and-postorder-traversal │ ├── 0106-construct-binary-tree-from-inorder-and-postorder-traversal.cpp │ ├── NOTES.md │ └── README.md ├── 0108-convert-sorted-array-to-binary-search-tree │ ├── 0108-convert-sorted-array-to-binary-search-tree.cpp │ ├── NOTES.md │ └── README.md ├── 0113-path-sum-ii │ ├── 0113-path-sum-ii.cpp │ ├── NOTES.md │ └── README.md ├── 0121-best-time-to-buy-and-sell-stock │ ├── 0121-best-time-to-buy-and-sell-stock.cpp │ ├── NOTES.md │ └── README.md ├── 0122-best-time-to-buy-and-sell-stock-ii │ ├── 0122-best-time-to-buy-and-sell-stock-ii.cpp │ ├── NOTES.md │ └── README.md ├── 0124-binary-tree-maximum-path-sum │ ├── 0124-binary-tree-maximum-path-sum.cpp │ ├── NOTES.md │ └── README.md ├── 0125-valid-palindrome │ ├── 0125-valid-palindrome.cpp │ ├── NOTES.md │ └── README.md ├── 0126-word-ladder-ii │ ├── 0126-word-ladder-ii.cpp │ ├── NOTES.md │ └── README.md ├── 0128-longest-consecutive-sequence │ ├── 0128-longest-consecutive-sequence.cpp │ ├── NOTES.md │ └── README.md ├── 0129-sum-root-to-leaf-numbers │ ├── 0129-sum-root-to-leaf-numbers.cpp │ ├── NOTES.md │ └── README.md ├── 0133-clone-graph │ ├── 0133-clone-graph.cpp │ ├── NOTES.md │ └── README.md ├── 0134-gas-station │ ├── 0134-gas-station.cpp │ ├── NOTES.md │ └── README.md ├── 0136-single-number │ ├── 0136-single-number.cpp │ ├── NOTES.md │ └── README.md ├── 0138-copy-list-with-random-pointer │ ├── 0138-copy-list-with-random-pointer.cpp │ ├── NOTES.md │ └── README.md ├── 0139-word-break │ ├── 0139-word-break.cpp │ ├── NOTES.md │ └── README.md ├── 0141-linked-list-cycle │ ├── 0141-linked-list-cycle.cpp │ ├── NOTES.md │ └── README.md ├── 0143-reorder-list │ ├── 0143-reorder-list.cpp │ ├── NOTES.md │ └── README.md ├── 0150-evaluate-reverse-polish-notation │ ├── 0150-evaluate-reverse-polish-notation.cpp │ ├── NOTES.md │ └── README.md ├── 0152-maximum-product-subarray │ ├── 0152-maximum-product-subarray.cpp │ ├── NOTES.md │ └── README.md ├── 0153-find-minimum-in-rotated-sorted-array │ ├── 0153-find-minimum-in-rotated-sorted-array.cpp │ ├── NOTES.md │ └── README.md ├── 0155-min-stack │ ├── 0155-min-stack.cpp │ ├── NOTES.md │ └── README.md ├── 0173-binary-search-tree-iterator │ ├── 0173-binary-search-tree-iterator.cpp │ ├── NOTES.md │ └── README.md ├── 0179-largest-number │ ├── 0179-largest-number.cpp │ ├── NOTES.md │ └── README.md ├── 0187-repeated-dna-sequences │ ├── 0187-repeated-dna-sequences.cpp │ ├── NOTES.md │ └── README.md ├── 0189-rotate-array │ ├── 0189-rotate-array.cpp │ ├── NOTES.md │ └── README.md ├── 0190-reverse-bits │ ├── 0190-reverse-bits.cpp │ ├── NOTES.md │ └── README.md ├── 0191-number-of-1-bits │ ├── NOTES.md │ └── README.md ├── 0198-house-robber │ ├── 0198-house-robber.cpp │ ├── NOTES.md │ └── README.md ├── 0199-binary-tree-right-side-view │ ├── 0199-binary-tree-right-side-view.cpp │ ├── NOTES.md │ └── README.md ├── 0200-number-of-islands │ ├── 0200-number-of-islands.cpp │ ├── NOTES.md │ └── README.md ├── 0206-reverse-linked-list │ ├── 0206-reverse-linked-list.cpp │ ├── NOTES.md │ └── README.md ├── 0207-course-schedule │ ├── 0207-course-schedule.cpp │ ├── NOTES.md │ └── README.md ├── 0208-implement-trie-prefix-tree │ ├── 0208-implement-trie-prefix-tree.cpp │ ├── NOTES.md │ └── README.md ├── 0209-minimum-size-subarray-sum │ ├── 0209-minimum-size-subarray-sum.cpp │ └── NOTES.md ├── 0211-design-add-and-search-words-data-structure │ ├── 0211-design-add-and-search-words-data-structure.cpp │ ├── NOTES.md │ └── README.md ├── 0212-word-search-ii │ ├── 0212-word-search-ii.cpp │ ├── NOTES.md │ └── README.md ├── 0213-house-robber-ii │ ├── 0213-house-robber-ii.cpp │ ├── NOTES.md │ └── README.md ├── 0215-kth-largest-element-in-an-array │ ├── 0215-kth-largest-element-in-an-array.cpp │ ├── NOTES.md │ └── README.md ├── 0217-contains-duplicate │ ├── 0217-contains-duplicate.cpp │ ├── NOTES.md │ └── README.md ├── 0226-invert-binary-tree │ ├── 0226-invert-binary-tree.cpp │ ├── NOTES.md │ └── README.md ├── 0227-basic-calculator-ii │ ├── 0227-basic-calculator-ii.cpp │ ├── NOTES.md │ └── README.md ├── 0230-kth-smallest-element-in-a-bst │ ├── 0230-kth-smallest-element-in-a-bst.cpp │ ├── NOTES.md │ └── README.md ├── 0231-power-of-two │ ├── 0231-power-of-two.cpp │ ├── NOTES.md │ └── README.md ├── 0232-implement-queue-using-stacks │ ├── 0232-implement-queue-using-stacks.cpp │ ├── NOTES.md │ └── README.md ├── 0235-lowest-common-ancestor-of-a-binary-search-tree │ ├── 0235-lowest-common-ancestor-of-a-binary-search-tree.cpp │ ├── NOTES.md │ └── README.md ├── 0236-lowest-common-ancestor-of-a-binary-tree │ ├── 0236-lowest-common-ancestor-of-a-binary-tree.cpp │ ├── NOTES.md │ └── README.md ├── 0238-product-of-array-except-self │ ├── 0238-product-of-array-except-self.cpp │ ├── NOTES.md │ └── README.md ├── 0242-valid-anagram │ ├── 0242-valid-anagram.cpp │ ├── NOTES.md │ └── README.md ├── 0268-missing-number │ ├── 0268-missing-number.cpp │ ├── NOTES.md │ └── README.md ├── 0295-find-median-from-data-stream │ ├── 0295-find-median-from-data-stream.cpp │ ├── NOTES.md │ └── README.md ├── 0297-serialize-and-deserialize-binary-tree │ ├── 0297-serialize-and-deserialize-binary-tree.cpp │ ├── NOTES.md │ └── README.md ├── 0300-longest-increasing-subsequence │ ├── 0300-longest-increasing-subsequence.cpp │ ├── NOTES.md │ └── README.md ├── 0303-range-sum-query-immutable │ ├── 0303-range-sum-query-immutable.cpp │ └── README.md ├── 0304-range-sum-query-2d-immutable │ ├── 0304-range-sum-query-2d-immutable.cpp │ ├── NOTES.md │ └── README.md ├── 0322-coin-change │ ├── 0322-coin-change.cpp │ ├── NOTES.md │ └── README.md ├── 0323-number-of-connected-components-in-an-undirected-graph │ └── 0323-number-of-connected-components-in-an-undirected-graph.cpp ├── 0338-counting-bits │ ├── 0338-counting-bits.cpp │ ├── NOTES.md │ └── README.md ├── 0341-flatten-nested-list-iterator │ ├── 0341-flatten-nested-list-iterator.cpp │ └── NOTES.md ├── 0347-top-k-frequent-elements │ ├── 0347-top-k-frequent-elements.cpp │ ├── NOTES.md │ └── README.md ├── 0371-sum-of-two-integers │ ├── 0371-sum-of-two-integers.cpp │ ├── NOTES.md │ └── README.md ├── 0380-insert-delete-getrandom-o1 │ ├── 0380-insert-delete-getrandom-o1.cpp │ ├── NOTES.md │ └── README.md ├── 0402-remove-k-digits │ ├── 0402-remove-k-digits.cpp │ ├── NOTES.md │ └── README.md ├── 0416-partition-equal-subset-sum │ ├── 0416-partition-equal-subset-sum.cpp │ ├── NOTES.md │ └── README.md ├── 0417-pacific-atlantic-water-flow │ ├── 0417-pacific-atlantic-water-flow.cpp │ ├── NOTES.md │ └── README.md ├── 0421-maximum-xor-of-two-numbers-in-an-array │ ├── 0421-maximum-xor-of-two-numbers-in-an-array.cpp │ ├── NOTES.md │ └── README.md ├── 0424-longest-repeating-character-replacement │ ├── 0424-longest-repeating-character-replacement.cpp │ └── README.md ├── 0435-non-overlapping-intervals │ ├── 0435-non-overlapping-intervals.cpp │ ├── NOTES.md │ └── README.md ├── 0438-find-all-anagrams-in-a-string │ ├── 0438-find-all-anagrams-in-a-string.cpp │ ├── NOTES.md │ └── README.md ├── 0445-add-two-numbers-ii │ ├── 0445-add-two-numbers-ii.cpp │ ├── NOTES.md │ └── README.md ├── 0449-serialize-and-deserialize-bst │ ├── 0449-serialize-and-deserialize-bst.cpp │ ├── NOTES.md │ └── README.md ├── 0450-delete-node-in-a-bst │ ├── 0450-delete-node-in-a-bst.cpp │ └── NOTES.md ├── 0451-sort-characters-by-frequency │ ├── 0451-sort-characters-by-frequency.cpp │ ├── NOTES.md │ └── README.md ├── 0494-target-sum │ ├── 0494-target-sum.cpp │ ├── NOTES.md │ └── README.md ├── 0523-continuous-subarray-sum │ ├── 0523-continuous-subarray-sum.cpp │ └── README.md ├── 0547-number-of-provinces │ ├── 0547-number-of-provinces.cpp │ ├── NOTES.md │ └── README.md ├── 0554-brick-wall │ ├── 0554-brick-wall.cpp │ ├── NOTES.md │ └── README.md ├── 0560-subarray-sum-equals-k │ ├── 0560-subarray-sum-equals-k.cpp │ ├── NOTES.md │ └── README.md ├── 0567-permutation-in-string │ ├── 0567-permutation-in-string.cpp │ ├── NOTES.md │ └── README.md ├── 0572-subtree-of-another-tree │ ├── 0572-subtree-of-another-tree.cpp │ ├── NOTES.md │ └── README.md ├── 0605-can-place-flowers │ ├── 0605-can-place-flowers.cpp │ └── README.md ├── 0621-task-scheduler │ ├── 0621-task-scheduler.cpp │ ├── NOTES.md │ └── README.md ├── 0622-design-circular-queue │ ├── 0622-design-circular-queue.cpp │ └── README.md ├── 0647-palindromic-substrings │ ├── 0647-palindromic-substrings.cpp │ ├── NOTES.md │ └── README.md ├── 0658-find-k-closest-elements │ ├── 0658-find-k-closest-elements.cpp │ ├── NOTES.md │ └── README.md ├── 0665-non-decreasing-array │ ├── 0665-non-decreasing-array.cpp │ ├── NOTES.md │ └── README.md ├── 0692-top-k-frequent-words │ ├── 0692-top-k-frequent-words.cpp │ ├── NOTES.md │ └── README.md ├── 0695-max-area-of-island │ ├── 0695-max-area-of-island.cpp │ ├── NOTES.md │ └── README.md ├── 0707-design-linked-list │ ├── 0707-design-linked-list.cpp │ ├── NOTES.md │ └── README.md ├── 0720-longest-word-in-dictionary │ ├── 0720-longest-word-in-dictionary.cpp │ ├── NOTES.md │ └── README.md ├── 0729-my-calendar-i │ ├── 0729-my-calendar-i.cpp │ ├── NOTES.md │ └── README.md ├── 0735-asteroid-collision │ ├── 0735-asteroid-collision.cpp │ └── README.md ├── 0739-daily-temperatures │ ├── 0739-daily-temperatures.cpp │ ├── NOTES.md │ └── README.md ├── 0787-cheapest-flights-within-k-stops │ ├── 0787-cheapest-flights-within-k-stops.cpp │ ├── NOTES.md │ └── README.md ├── 0792-number-of-matching-subsequences │ ├── 0792-number-of-matching-subsequences.cpp │ ├── NOTES.md │ └── README.md ├── 0838-push-dominoes │ ├── 0838-push-dominoes.cpp │ ├── NOTES.md │ └── README.md ├── 0841-keys-and-rooms │ ├── 0841-keys-and-rooms.cpp │ ├── NOTES.md │ └── README.md ├── 0860-lemonade-change │ ├── 0860-lemonade-change.cpp │ ├── NOTES.md │ └── README.md ├── 0875-koko-eating-bananas │ ├── 0875-koko-eating-bananas.cpp │ ├── NOTES.md │ └── README.md ├── 0881-boats-to-save-people │ ├── 0881-boats-to-save-people.cpp │ └── README.md ├── 0910-smallest-range-ii │ ├── 0910-smallest-range-ii.cpp │ └── README.md ├── 0947-most-stones-removed-with-same-row-or-column │ ├── 0947-most-stones-removed-with-same-row-or-column.cpp │ ├── NOTES.md │ └── README.md ├── 0973-k-closest-points-to-origin │ ├── 0973-k-closest-points-to-origin.cpp │ ├── NOTES.md │ └── README.md ├── 0983-minimum-cost-for-tickets │ ├── 0983-minimum-cost-for-tickets.cpp │ ├── NOTES.md │ └── README.md ├── 0994-rotting-oranges │ ├── 0994-rotting-oranges.cpp │ ├── NOTES.md │ └── README.md ├── 0997-find-the-town-judge │ ├── 0997-find-the-town-judge.cpp │ ├── NOTES.md │ └── README.md ├── 1143-longest-common-subsequence │ ├── 1143-longest-common-subsequence.cpp │ └── README.md ├── 1189. Maximum Number of Balloons.cpp ├── 1249-minimum-remove-to-make-valid-parentheses │ ├── 1249-minimum-remove-to-make-valid-parentheses.cpp │ ├── NOTES.md │ └── README.md ├── 1319-number-of-operations-to-make-network-connected │ ├── 1319-number-of-operations-to-make-network-connected.cpp │ └── README.md ├── 14. Longest Common Prefix.cpp ├── 1448-count-good-nodes-in-binary-tree │ ├── 1448-count-good-nodes-in-binary-tree.cpp │ ├── NOTES.md │ └── README.md ├── 1461-check-if-a-string-contains-all-binary-codes-of-size-k │ ├── 1461-check-if-a-string-contains-all-binary-codes-of-size-k.cpp │ ├── NOTES.md │ └── README.md ├── 1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero │ ├── 1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.cpp │ └── README.md ├── 1472-design-browser-history │ ├── 1472-design-browser-history.cpp │ └── README.md ├── 1498-number-of-subsequences-that-satisfy-the-given-sum-condition │ ├── 1498-number-of-subsequences-that-satisfy-the-given-sum-condition.cpp │ └── NOTES.md ├── 1557-minimum-number-of-vertices-to-reach-all-nodes │ ├── 1557-minimum-number-of-vertices-to-reach-all-nodes.cpp │ ├── NOTES.md │ └── README.md ├── 1797-design-authentication-manager │ ├── 1797-design-authentication-manager.cpp │ ├── NOTES.md │ └── README.md ├── 1823-find-the-winner-of-the-circular-game │ ├── 1823-find-the-winner-of-the-circular-game.cpp │ ├── NOTES.md │ └── README.md ├── 1838-frequency-of-the-most-frequent-element │ ├── 1838-frequency-of-the-most-frequent-element.cpp │ ├── NOTES.md │ └── README.md ├── 1845-seat-reservation-manager │ ├── 1845-seat-reservation-manager.cpp │ ├── NOTES.md │ └── README.md ├── 1888-minimum-number-of-flips-to-make-the-binary-string-alternating │ ├── 1888-minimum-number-of-flips-to-make-the-binary-string-alternating.cpp │ ├── NOTES.md │ └── README.md ├── 1930-unique-length-3-palindromic-subsequences │ ├── 1930-unique-length-3-palindromic-subsequences.cpp │ ├── NOTES.md │ └── README.md ├── 1968-array-with-elements-not-equal-to-average-of-neighbors │ ├── 1968-array-with-elements-not-equal-to-average-of-neighbors.cpp │ └── NOTES.md ├── 2002-maximum-product-of-the-length-of-two-palindromic-subsequences │ ├── 2002-maximum-product-of-the-length-of-two-palindromic-subsequences.cpp │ ├── NOTES.md │ └── README.md ├── 2009-minimum-number-of-operations-to-make-array-continuous │ ├── 2009-minimum-number-of-operations-to-make-array-continuous.cpp │ ├── NOTES.md │ └── README.md ├── 2017-grid-game │ ├── 2017-grid-game.cpp │ ├── NOTES.md │ └── README.md ├── 2126-destroying-asteroids │ ├── 2126-destroying-asteroids.cpp │ ├── NOTES.md │ └── README.md ├── 2276-count-integers-in-intervals │ ├── 2276-count-integers-in-intervals.cpp │ ├── NOTES.md │ └── README.md ├── 2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph │ ├── 2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph.cpp │ ├── NOTES.md │ └── README.md ├── 2328-number-of-increasing-paths-in-a-grid │ ├── 2328-number-of-increasing-paths-in-a-grid.cpp │ ├── NOTES.md │ └── README.md ├── 2348-number-of-zero-filled-subarrays │ ├── 2348-number-of-zero-filled-subarrays.cpp │ ├── NOTES.md │ └── README.md ├── 2492-minimum-score-of-a-path-between-two-cities │ ├── 2492-minimum-score-of-a-path-between-two-cities.cpp │ ├── NOTES.md │ └── README.md ├── 2591-distribute-money-to-maximum-children │ ├── 2591-distribute-money-to-maximum-children.cpp │ ├── NOTES.md │ └── README.md ├── 2594-minimum-time-to-repair-cars │ ├── 2594-minimum-time-to-repair-cars.cpp │ ├── NOTES.md │ └── README.md ├── 27.Remove-Element.cpp ├── 287. Find the Duplicate Number.cpp ├── 344. Reverse String.cpp ├── 448. Find All Numbers Disappeared in an Array.cpp ├── 704. Binary Search.cpp ├── 88. Merge Sorted Array.cpp ├── 977. Squares of a Sorted Array.cpp └── README.md ├── C ├── 1-Two-Sum.c ├── 118-Pascal's-Triangle.c ├── 217-Contains-Duplicate.c ├── 242-Valid-Anagram.c ├── 27-Remove-Element.c ├── 448-Find-All-Numbers-Disappeared-in-an-Array.c ├── 58-Length-of-Last-Word.c └── 724-Find-Pivot-Index.c ├── Java ├── 1-two-sum.java ├── 125-valid-palindrome.java ├── 20-valid-paranthesis.java ├── 217-contains-duplicate.java ├── 242-valid-anagram.java └── 70-climbing-stairs.java ├── JavaScript ├── 1. Two Sum.js ├── 102.binary-tree-level-order-traversal.js ├── 105.construct-binary-tree-from-preorder-and-inorder-traversal.js ├── 11. Container With Most Water.js ├── 121. Best Time to Buy and Sell Stock.js ├── 124.binary-tree-maximum-path-sum.js ├── 125. Valid Palindrome.js ├── 128. Longest Consecutive Sequence.js ├── 141.linked-list-cycle.js ├── 143.reorder-list.js ├── 15. 3Sum.js ├── 153.find-minimum-in-rotated-sorted-array.js ├── 19.remove-nth-node-from-end-of-list.js ├── 20. Valid Parentheses.js ├── 206.reverse-linked-list.js ├── 21.merge-two-sorted-lists.js ├── 217. Contains Duplicate.js ├── 226.invert-binary-tree.js ├── 23.merge-k-sorted-lists.js ├── 230.kth-smallest-element-in-a-bst.js ├── 235.lowest-common-ancestor-of-a-binary-search-tree.js ├── 238. Product of Array Except Self.js ├── 242. Valid Anagram.js ├── 297.serialize-and-deserialize-binary-tree.js ├── 3. Longest Substring Without Repeating Characters.js ├── 33.search-in-rotated-sorted-array.js ├── 347. Top K Frequent Elements.js ├── 424.longest-repeating-character-replacement.js ├── 49. Group Anagrams.js ├── 76.minimum-window-substring.js └── 98.validate-binary-search-tree.js ├── Kotlin ├── 1-two-sum.kt ├── 217-Contains Duplicate.kt ├── 242-valid-anagram.kt └── 49-group-anagrams.kt └── python3 ├── 1-two-sum.py ├── 100-same-tree.py ├── 102-binary-tree-level.py ├── 104-maximum-depth-tree.py ├── 105-construct-binary-tree.py ├── 108.py ├── 11-Container-water.py ├── 110.py ├── 113.py ├── 1143-longest-common-subsequence.py ├── 118.py ├── 1189.py ├── 121-sell-and-buy.py ├── 122.py ├── 124-maximum-path.py ├── 125-valid-palindrome.py ├── 128-longest-sequence.py ├── 129.py ├── 1299.py ├── 133-clone-graph.py ├── 134.py ├── 1343.py ├── 139-word-break.py ├── 14-Longest-Prefix.py ├── 141-linked-cycle.py ├── 143-reorder-list.py ├── 1448.py ├── 1461.py ├── 147.py ├── 1498.py ├── 15-3-Sum.py ├── 150.py ├── 152-maximum-product-subarray.py ├── 153-minimum-window.py ├── 155.py ├── 160.py ├── 167-Two-Sum.py ├── 169-Majority-Element.py ├── 179.py ├── 1838.py ├── 187.py ├── 1888.py ├── 189.py ├── 19-remove-node.py ├── 190-Reverse-Bits.py ├── 191-Number-of-Bits.py ├── 1930.py ├── 1968.py ├── 198-house-robber.py ├── 2.py ├── 20-valid-parentheses.py ├── 200-number-islands.py ├── 2002.py ├── 2017.py ├── 203.py ├── 205-Isomorphic-Strings.py ├── 206-reverse-linkedlist.py ├── 207-course-schedule.py ├── 208-implement-trie.py ├── 209.py ├── 21-merge-linkedlist.py ├── 211-design-search.py ├── 212-word-search-ii.py ├── 213-house-robber_2.py ├── 215.py ├── 217-contains-duplicate.py ├── 219-Contains-Duplicate.py ├── 22.py ├── 225.py ├── 226-invert-binary-tree.py ├── 23-merge-Ksorted.py ├── 230-kth-smallest.py ├── 235-lowest-common-ancestor.py ├── 238-Product-except.py ├── 24.py ├── 242-valid-anagram.py ├── 252-meeting-rooms.py ├── 253-meeting-rooms-ii.py ├── 26-Remove-Duplicates.py ├── 261-valid-tree.py ├── 268-Missing-Number.py ├── 269-alien-dictionary.py ├── 27.py ├── 283-Move-Zeroes.py ├── 287.py ├── 290-Word-Pattern.py ├── 295-find-median.py ├── 297-serialize-and-deserialize.py ├── 3-longest-substring.py ├── 300-longest-increasing-subsequence.py ├── 303.py ├── 322-coin-change.py ├── 323-connected-components.py ├── 33-Search-rotated.py ├── 338-Counting-Bits.py ├── 34.py ├── 344-Reverse-String.py ├── 347-K-frequent.py ├── 35-Search-Insert-Position.py ├── 36-valid.sudoku.py ├── 367.py ├── 371-Sum-Two-Integers.py ├── 374.py ├── 380.py ├── 39-combination-sum.py ├── 392-Is-Subsequence.py ├── 402.py ├── 416.py ├── 417-pacific-atlantic.py ├── 424-longest-replacement.py ├── 43.py ├── 435-Non-overlapping-Intervals.py ├── 438.py ├── 441-Arranging-Coins.py ├── 448.py ├── 45.py ├── 48-Rotate-Image.py ├── 49-Group-anagrams.py ├── 494.py ├── 496-Next-Greater-Element.py ├── 5-longest-palindromic-substring.py ├── 523.py ├── 53-maximum-subarray.py ├── 54-Spiral-Matrix.py ├── 543.py ├── 55-jump-game.py ├── 554.py ├── 56-merge-Intervals.py ├── 560.py ├── 567.py ├── 57-Insert-Interval.py ├── 572-subtree-another-tree.py ├── 58.py ├── 605-Can-Place-Flowers.py ├── 62-unique-paths.py ├── 621.py ├── 647-palindromic-substrings.py ├── 658.py ├── 659-decode-encode.py ├── 665.py ├── 680-Valid-Palindrome.py ├── 682-Baseball-Game.py ├── 685.py ├── 692.py ├── 7.py ├── 70-climbing-stairs.py ├── 704-Binary-Search.py ├── 720.py ├── 724.py ├── 73-Set-Matrix-Zeroes.py ├── 739.py ├── 74.py ├── 75-Sort-Colors.py ├── 76-Minimum-Window.py ├── 767.py ├── 78.py ├── 787.py ├── 79-word-search.py ├── 792.py ├── 83.py ├── 838.py ├── 857.py ├── 876.py ├── 88-merge-sorted.py ├── 881.py ├── 91-decode-ways.py ├── 92.py ├── 929-Unique-Email.py ├── 94.py ├── 973.py ├── 977.py ├── 98-validate-binary-search.py ├── 983.py └── 994.py /Solutions/C++/0001-two-sum/0001-two-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector& nums, int target) { 4 | map > mp ; 5 | for (int i =0 ; i < nums.size();i++) 6 | { 7 | mp[ nums[i] ].push_back(i) ; 8 | } 9 | sort (nums.begin(),nums.end()); 10 | for (int i =0 , j = nums.size()-1; i < j ;) 11 | { 12 | if (nums[i]+nums[j] == target) 13 | { 14 | if (nums[i] != nums[j]) 15 | return {mp[nums[i]][0],mp[nums[j]][0]}; 16 | else 17 | return {mp[nums[i]][0],mp[nums[j]][1]}; 18 | 19 | }else if (nums[i]+nums[j] > target) 20 | j--; 21 | else 22 | i++; 23 | } 24 | return {}; 25 | } 26 | }; -------------------------------------------------------------------------------- /Solutions/C++/0001-two-sum/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0002-add-two-numbers/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0003-longest-substring-without-repeating-characters/0003-longest-substring-without-repeating-characters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLongestSubstring(string s) { 4 | if (s.size() == 0)return 0; 5 | int answer = 1; 6 | int l = 0, r = 0; 7 | map mp; 8 | mp[s[0]]++; 9 | while(r < s.size()) 10 | { 11 | while(r + 1 < s.size() && mp[s[r+1]] == 0) 12 | { 13 | r++; 14 | mp[s[r]]++; 15 | } 16 | answer = max(answer, r - l + 1); 17 | if (l == r) 18 | { 19 | mp[s[l]]--; 20 | l++;r++; 21 | if (l < s.size())mp[s[l]]++; 22 | }else 23 | mp[s[l++]]--; 24 | } 25 | return answer; 26 | 27 | 28 | } 29 | }; -------------------------------------------------------------------------------- /Solutions/C++/0003-longest-substring-without-repeating-characters/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0004-median-of-two-sorted-arrays/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0005-longest-palindromic-substring/0005-longest-palindromic-substring.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string longestPalindrome(string s) { 4 | int pos = -1, sz = 0, n = s.size(); 5 | for (int i = 0; i < n; i++) 6 | { 7 | // odd 8 | int l = i-1, r = i + 1; 9 | while(l >= 0 && r < n && s[l] == s[r]) 10 | l--,r++; 11 | l++,r--; 12 | if (r - l + 1 > sz) 13 | { 14 | sz = r - l + 1; 15 | pos = l; 16 | } 17 | // even 18 | l = i, r = i + 1; 19 | while(l >= 0 && r < n && s[l] == s[r]) 20 | l--,r++; 21 | l++,r--; 22 | if (r - l + 1 > sz) 23 | { 24 | sz = r - l + 1; 25 | pos = l; 26 | } 27 | } 28 | return s.substr(pos, sz); 29 | } 30 | }; -------------------------------------------------------------------------------- /Solutions/C++/0005-longest-palindromic-substring/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0007-reverse-integer/0007-reverse-integer.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int reverse(int x) { 4 | long long ans = 0; 5 | int si = (x < 0? -1: 1); 6 | x = abs(x); 7 | while (x) 8 | { 9 | ans = ans * 10 + x % 10; 10 | x/=10; 11 | } 12 | ans *= si; 13 | if (ans > (1LL<<31)-1 || ans < -1*((1LL<<31))) 14 | return 0 ; 15 | return ans ; 16 | } 17 | }; -------------------------------------------------------------------------------- /Solutions/C++/0007-reverse-integer/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0011-container-with-most-water/0011-container-with-most-water.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int area (vector& height , int i , int j ) 4 | { 5 | return (1LL*(j-i)*min(height[i],height[j])); 6 | } 7 | int maxArea(vector& height) { 8 | int ans =0 ; 9 | for (int i =0 , j = height.size()-1; i < j;) 10 | { 11 | ans = max (ans , area(height,i,j)); 12 | if (height[i] <= height[j]) 13 | i++; 14 | else 15 | j--; 16 | } 17 | 18 | return ans ; 19 | } 20 | }; -------------------------------------------------------------------------------- /Solutions/C++/0011-container-with-most-water/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0015-3sum/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0016-3sum-closest/0016-3sum-closest.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int threeSumClosest(vector& nums, int target) { 4 | sort(nums.begin(), nums.end()); 5 | int ans = 1e9; 6 | for(int i = 0; i < nums.size(); i++) 7 | { 8 | for(int j = i+1, k = nums.size()-1; j < k;) 9 | { 10 | int sum = nums[i] + nums[j] + nums[k]; 11 | if (abs(target - sum) < abs(target - ans)) 12 | ans = sum; 13 | if (sum == target) 14 | { 15 | return target; 16 | }else if (sum > target) 17 | { 18 | k--; 19 | }else 20 | { 21 | j++; 22 | } 23 | } 24 | } 25 | return ans; 26 | } 27 | }; -------------------------------------------------------------------------------- /Solutions/C++/0016-3sum-closest/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0019-remove-nth-node-from-end-of-list/0019-remove-nth-node-from-end-of-list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* removeNthFromEnd(ListNode* head, int n) { 12 | ListNode* tem = head ;ListNode* prv = head ; 13 | int sz = 0 ; 14 | while (tem!= NULL)tem = tem->next , sz++ ; 15 | 16 | int rm = sz - n + 1; 17 | tem = head ; 18 | if (rm == 1 )return head->next ; 19 | while (--rm) 20 | { 21 | prv = tem ; 22 | tem = tem->next ; 23 | } 24 | 25 | prv -> next = tem -> next ; 26 | return head ; 27 | } 28 | }; -------------------------------------------------------------------------------- /Solutions/C++/0019-remove-nth-node-from-end-of-list/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0020-valid-parentheses/0020-valid-parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isValid(string s) { 4 | stack stk; 5 | unordered_map fliped; 6 | fliped[']'] = '['; 7 | fliped['}'] = '{'; 8 | fliped[')'] = '('; 9 | for (int i = 0; i < s.size(); i++) 10 | { 11 | if (s[i] == ']' || s[i] == ')' || s[i] == '}') 12 | { 13 | if (stk.empty() || stk.top() != fliped[s[i]]) return 0; 14 | stk.pop(); 15 | }else 16 | stk.push(s[i]); 17 | } 18 | return stk.empty(); 19 | } 20 | }; -------------------------------------------------------------------------------- /Solutions/C++/0020-valid-parentheses/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0021-merge-two-sorted-lists/0021-merge-two-sorted-lists.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { 14 | if (list1 == nullptr) return list2; 15 | if (list2 == nullptr) return list1; 16 | if (list1->val < list2->val){ 17 | list1->next = mergeTwoLists(list1->next, list2); 18 | return list1; 19 | }else { 20 | list2->next = mergeTwoLists(list1, list2->next); 21 | return list2; 22 | } 23 | } 24 | }; -------------------------------------------------------------------------------- /Solutions/C++/0021-merge-two-sorted-lists/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0022-generate-parentheses/README.md: -------------------------------------------------------------------------------- 1 |

22. Generate Parentheses

Medium


Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

2 | 3 |

 

4 |

Example 1:

5 |
Input: n = 3
 6 | Output: ["((()))","(()())","(())()","()(())","()()()"]
 7 | 

Example 2:

8 |
Input: n = 1
 9 | Output: ["()"]
10 | 
11 |

 

12 |

Constraints:

13 | 14 |
    15 |
  • 1 <= n <= 8
  • 16 |
17 |
-------------------------------------------------------------------------------- /Solutions/C++/0023-merge-k-sorted-lists/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0024-swap-nodes-in-pairs/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0033-search-in-rotated-sorted-array/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0034-find-first-and-last-position-of-element-in-sorted-array/0034-find-first-and-last-position-of-element-in-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector searchRange(vector& nums, int target) { 4 | int l = 0, r = nums.size() - 1, mid, F = -1, L = -1; 5 | while(l <= r) 6 | { 7 | mid = (l+r) >> 1; 8 | if (nums[mid] >= target) 9 | F = mid, r = mid - 1; 10 | else 11 | l = mid + 1; 12 | } 13 | if (F == -1 || nums[F] != target) 14 | return {-1, -1}; 15 | l = F, r = nums.size() - 1; 16 | while(l <= r) 17 | { 18 | mid = (l+r) >> 1; 19 | if (nums[mid] <= target) 20 | L = mid, l = mid + 1; 21 | else 22 | r = mid - 1; 23 | } 24 | return {F, L}; 25 | } 26 | }; -------------------------------------------------------------------------------- /Solutions/C++/0034-find-first-and-last-position-of-element-in-sorted-array/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0039-combination-sum/0039-combination-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector current; 4 | vector> ret; 5 | void take_or_leave(vector& candidates, int target, int msk, int cnt, int idx) 6 | { 7 | if (target == 0) 8 | { 9 | ret.push_back(current); 10 | return; 11 | } 12 | if (target < 0 || idx >= candidates.size())return; 13 | current.push_back(candidates[idx]); 14 | take_or_leave(candidates, target - candidates[idx], msk ^ (1<<(idx)), cnt+1, idx); 15 | current.pop_back(); 16 | take_or_leave(candidates, target, msk, cnt, idx + 1); 17 | } 18 | vector> combinationSum(vector& candidates, int target) { 19 | ret.clear(); 20 | current.clear(); 21 | take_or_leave(candidates, target, 0, 0, 0); 22 | return ret; 23 | } 24 | }; -------------------------------------------------------------------------------- /Solutions/C++/0039-combination-sum/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0043-multiply-strings/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0045-jump-game-ii/0045-jump-game-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int jump(vector& nums) { 4 | vector mnJumps(nums.size(), (int)1e9); 5 | mnJumps[nums.size()-1] = 0; 6 | for (int i = nums.size()-2; i >= 0; i--){ 7 | for (int j = min((int)nums.size()-1, nums[i] + i); j > i; j--){ 8 | mnJumps[i] = min(mnJumps[i], 1 + mnJumps[j]); 9 | } 10 | } 11 | return mnJumps[0]; 12 | } 13 | }; -------------------------------------------------------------------------------- /Solutions/C++/0045-jump-game-ii/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0046-permutations/0046-permutations.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> permute(vector& nums) { 4 | sort(nums.begin() , nums.end()); 5 | vector > ans ; 6 | do 7 | { 8 | ans.push_back(nums); 9 | }while (next_permutation(nums.begin() , nums.end())); 10 | return ans ; 11 | } 12 | }; -------------------------------------------------------------------------------- /Solutions/C++/0046-permutations/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0048-rotate-image/0048-rotate-image.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void rotate(vector>& mat) { 4 | int n = mat.size(); 5 | for(int rep = 0; rep < 3; rep++) 6 | { 7 | for(int i = 0; i < n; i++) 8 | { 9 | for(int j = 0; j < n - j - 1; j++) 10 | swap(mat[i][j], mat[i][n-j-1]); 11 | } 12 | for(int i = 0; i < n; i++) 13 | for(int j = i; j < n; j++) 14 | swap(mat[i][j], mat[j][i]); 15 | } 16 | } 17 | }; -------------------------------------------------------------------------------- /Solutions/C++/0048-rotate-image/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0049-group-anagrams/0049-group-anagrams.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> groupAnagrams(vector& strs) { 4 | vector> tem; 5 | 6 | for (int i = 0; i < strs.size(); i++) 7 | { 8 | string cur = strs[i]; 9 | sort(cur.begin(), cur.end()); 10 | tem.push_back({cur, strs[i]}); 11 | } 12 | sort(tem.begin(), tem.end()); 13 | vector> ret; 14 | vector cur; 15 | for (int i = 0; i < strs.size(); i++) 16 | { 17 | cur.clear(); 18 | cur.push_back(tem[i].second); 19 | int j = i+1; 20 | while(j < strs.size() && tem[j].first == tem[i].first) 21 | { 22 | cur.push_back(tem[j].second); 23 | j++; 24 | } 25 | i = j-1; 26 | ret.push_back(cur); 27 | } 28 | return ret; 29 | } 30 | }; -------------------------------------------------------------------------------- /Solutions/C++/0049-group-anagrams/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0053-maximum-subarray/0053-maximum-subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxSubArray(vector& nums) { 4 | vector dp(nums.size()); 5 | int ans = nums[0]; 6 | dp[0] = nums[0]; 7 | for (int i = 1; i < nums.size() ;i++) 8 | { 9 | dp[i] = max (dp[i-1] + nums[i] , nums[i]); 10 | ans = max (dp[i] , ans ); 11 | } 12 | return ans ; 13 | } 14 | }; -------------------------------------------------------------------------------- /Solutions/C++/0053-maximum-subarray/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0054-spiral-matrix/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0055-jump-game/0055-jump-game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canJump(vector& nums) { 4 | int idx = nums.size() - 1; 5 | for (int i = nums.size() - 2; i >= 0; i--) 6 | { 7 | if (idx <= i + nums[i]) 8 | idx = i; 9 | } 10 | return idx == 0; 11 | } 12 | }; -------------------------------------------------------------------------------- /Solutions/C++/0055-jump-game/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0056-merge-intervals/0056-merge-intervals.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> merge(vector>& intervals) { 4 | sort(intervals.begin(), intervals.end()); 5 | vector> ret; 6 | for(int i = 0; i < intervals.size(); i++) 7 | { 8 | if (ret.empty() || intervals[i][0] > ret.back()[1]) 9 | ret.push_back(intervals[i]); 10 | else 11 | ret.back()[1] = max(ret.back()[1], intervals[i][1]); 12 | } 13 | return ret; 14 | } 15 | }; -------------------------------------------------------------------------------- /Solutions/C++/0056-merge-intervals/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0057-insert-interval/0057-insert-interval.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> insert(vector>& intervals, vector& newInterval) { 4 | intervals.push_back(newInterval); 5 | sort(intervals.begin(), intervals.end()); 6 | stack> stk; 7 | stk.push(intervals[0]); 8 | for (int i = 1; i < intervals.size(); i++) 9 | { 10 | if (intervals[i][0] > stk.top()[1]) 11 | stk.push(intervals[i]); 12 | else 13 | stk.top()[1] = max(stk.top()[1], intervals[i][1]); 14 | } 15 | intervals.clear(); 16 | while(!stk.empty()) 17 | intervals.push_back(stk.top()), stk.pop(); 18 | reverse(intervals.begin(), intervals.end()); 19 | return intervals; 20 | } 21 | }; -------------------------------------------------------------------------------- /Solutions/C++/0057-insert-interval/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0061-rotate-list/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0062-unique-paths/0062-unique-paths.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int C[200][100]; 4 | int PC (int x , int y ) 5 | { 6 | if (x < 0 || y < 0 )return 0 ; 7 | if (x == 0 && x == y )return 1 ; 8 | int &ret = C [x][y]; 9 | if (ret != -1 )return ret ; 10 | return ret = PC (x-1 , y ) + PC (x , y-1 ); 11 | } 12 | int uniquePaths(int m, int n) { 13 | memset (C , -1 , sizeof C ); 14 | C[0][0] = 1; 15 | n--; 16 | m--; 17 | PC (n , m ); 18 | 19 | return C[n][m]; 20 | } 21 | }; -------------------------------------------------------------------------------- /Solutions/C++/0062-unique-paths/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0070-climbing-stairs/0070-climbing-stairs.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int climbStairs(int n) { 4 | if (n <= 2) return n; 5 | int prv = 2, prvPrv = 1, cur; 6 | n-=2; 7 | while(n--){ 8 | cur = prv + prvPrv; 9 | prvPrv = prv; 10 | prv = cur; 11 | } 12 | return cur; 13 | } 14 | }; -------------------------------------------------------------------------------- /Solutions/C++/0070-climbing-stairs/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0073-set-matrix-zeroes/0073-set-matrix-zeroes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void setZeroes(vector>& matrix) { 4 | set row , col ; 5 | for (int i =0 ; i < matrix.size();i++) 6 | for (int j =0 ; j < matrix[i].size();j++) 7 | { 8 | if (matrix[i][j] == 0) 9 | { 10 | row.insert(i); 11 | col.insert(j); 12 | } 13 | } 14 | for (int r : row ) 15 | { 16 | for (int j =0 ; j < matrix[r].size() ; j++) 17 | matrix[r][j] = 0 ; 18 | } 19 | 20 | for (int c : col ) 21 | { 22 | for (int i =0 ; i < matrix.size(); i++) 23 | matrix[i][c] =0; 24 | } 25 | } 26 | }; -------------------------------------------------------------------------------- /Solutions/C++/0073-set-matrix-zeroes/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0076-minimum-window-substring/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0078-subsets/0078-subsets.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> subsets(vector& nums) { 4 | vector> ret; 5 | int n = nums.size(); 6 | for(int i = 0; i < (1< cur; 9 | for(int j = 0; j < n; j++) 10 | if (i & (1<val != q->val) return 0; 18 | if (!check(p->left, q->left)) return 0; 19 | if (!check(p->right, q->right)) return 0; 20 | return 1; 21 | } 22 | public: 23 | bool isSameTree(TreeNode* p, TreeNode* q) { 24 | return check(p, q); 25 | } 26 | }; -------------------------------------------------------------------------------- /Solutions/C++/0100-same-tree/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0101-symmetric-tree/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0102-binary-tree-level-order-traversal/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0103-binary-tree-zigzag-level-order-traversal/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0104-maximum-depth-of-binary-tree/0104-maximum-depth-of-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int maxDepth(TreeNode* root) { 15 | if (root == nullptr) return 0; 16 | return 1 + max(maxDepth(root->left), maxDepth(root->right)); 17 | } 18 | }; -------------------------------------------------------------------------------- /Solutions/C++/0104-maximum-depth-of-binary-tree/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0105-construct-binary-tree-from-preorder-and-inorder-traversal/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0106-construct-binary-tree-from-inorder-and-postorder-traversal/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0108-convert-sorted-array-to-binary-search-tree/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0113-path-sum-ii/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0121-best-time-to-buy-and-sell-stock/0121-best-time-to-buy-and-sell-stock.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | int mx = 0, mn = 1e9, n = prices.size(); 5 | for (int i = 0; i < n; i++){ 6 | mx = max(mx, prices[i] - mn); 7 | mn = min(mn, prices[i]); 8 | } 9 | return mx; 10 | } 11 | }; -------------------------------------------------------------------------------- /Solutions/C++/0121-best-time-to-buy-and-sell-stock/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0122-best-time-to-buy-and-sell-stock-ii/0122-best-time-to-buy-and-sell-stock-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | int answer = 0; 5 | for (int i = 1; i < prices.size(); i++) 6 | answer += max(0, prices[i]-prices[i-1]); 7 | return answer; 8 | } 9 | }; -------------------------------------------------------------------------------- /Solutions/C++/0122-best-time-to-buy-and-sell-stock-ii/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0124-binary-tree-maximum-path-sum/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0125-valid-palindrome/0125-valid-palindrome.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool valid_alpha(char c){ 4 | return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'); 5 | } 6 | char to_lower(char c){ 7 | if (c >= 'A' && c <= 'Z') return c + 32; 8 | return c; 9 | } 10 | bool isPalindrome(string s) { 11 | int l = 0, r = s.size()-1; 12 | while (l < r){ 13 | while (l < r && !valid_alpha(s[l])) 14 | l++; 15 | while (r >= l && !valid_alpha(s[r])) 16 | r--; 17 | s[l] = to_lower(s[l]); 18 | s[r] = to_lower(s[r]); 19 | if (l >= r) break; 20 | if (s[l] != s[r]) return 0; 21 | l++; 22 | r--; 23 | } 24 | return 1; 25 | } 26 | }; -------------------------------------------------------------------------------- /Solutions/C++/0125-valid-palindrome/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0126-word-ladder-ii/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0128-longest-consecutive-sequence/0128-longest-consecutive-sequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestConsecutive(vector& nums) { 4 | int longest = 0; 5 | unordered_set st; 6 | for (int i = 0; i < nums.size(); i++){ 7 | st.insert(nums[i]); 8 | } 9 | for (int i = 0; i < nums.size(); i++){ 10 | // check if this is the begining of the streak 11 | if (st.count(nums[i] - 1) == 0){ 12 | int cur = 1; 13 | int num = nums[i] + 1; 14 | while (st.count(num)){ 15 | cur++; 16 | num++; 17 | } 18 | longest = max(longest, cur); 19 | } 20 | } 21 | return longest; 22 | } 23 | }; -------------------------------------------------------------------------------- /Solutions/C++/0128-longest-consecutive-sequence/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0129-sum-root-to-leaf-numbers/0129-sum-root-to-leaf-numbers.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int sum(TreeNode* root, int val) 15 | { 16 | if (root == nullptr) return 0; 17 | if (root->left == nullptr && root->right == nullptr) 18 | return val * 10 + root->val; 19 | int cur = (root->val); 20 | return sum(root->left, val * 10 + cur) + sum(root->right, val * 10 + cur); 21 | } 22 | int sumNumbers(TreeNode* root) { 23 | return sum(root, 0); 24 | } 25 | }; -------------------------------------------------------------------------------- /Solutions/C++/0129-sum-root-to-leaf-numbers/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0133-clone-graph/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0134-gas-station/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0136-single-number/0136-single-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int singleNumber(vector& nums) { 4 | int x = 0; 5 | for(int i: nums) 6 | x ^= i; 7 | return x; 8 | } 9 | }; -------------------------------------------------------------------------------- /Solutions/C++/0136-single-number/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0138-copy-list-with-random-pointer/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0139-word-break/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0141-linked-list-cycle/0141-linked-list-cycle.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | bool hasCycle(ListNode *head) { 12 | ListNode* slow = head; 13 | ListNode* fast = head; 14 | while (slow && fast && fast->next){ 15 | slow = slow->next; 16 | fast = fast->next->next; 17 | if (slow == fast) return 1; 18 | } 19 | return 0; 20 | } 21 | }; -------------------------------------------------------------------------------- /Solutions/C++/0141-linked-list-cycle/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0143-reorder-list/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0150-evaluate-reverse-polish-notation/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0152-maximum-product-subarray/0152-maximum-product-subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProduct(vector& nums) { 4 | int answer, mx, mn; 5 | answer = mx = mn = nums[0]; 6 | for (int i = 1; i < nums.size(); i++) 7 | { 8 | int p1 = nums[i] * mx; 9 | int p2 = nums[i] * mn; 10 | mx = max({nums[i], p1, p2}); 11 | mn = min({nums[i], p1, p2}); 12 | answer = max(mx, answer); 13 | } 14 | return answer; 15 | } 16 | }; -------------------------------------------------------------------------------- /Solutions/C++/0152-maximum-product-subarray/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0153-find-minimum-in-rotated-sorted-array/0153-find-minimum-in-rotated-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMin(vector& nums) { 4 | int n = nums.size(); 5 | int rootingPoint = (n > 1? 1: 0); 6 | 7 | int l = 0, r = n-1, m; 8 | while (l <= r){ 9 | m = (l+r) >> 1; 10 | if (nums[m] >= nums[0]){ 11 | // first half 12 | rootingPoint = (m + 1) % n; 13 | l = m + 1; 14 | }else 15 | r = m - 1; 16 | } 17 | 18 | return min(nums[0], nums[rootingPoint]); 19 | } 20 | }; 21 | /* 22 | 0 1 2 3 4 5 23 | 5 0 1 2 3 4 24 | 4 5 0 1 2 3 25 | 3 4 5 0 1 2 26 | */ -------------------------------------------------------------------------------- /Solutions/C++/0153-find-minimum-in-rotated-sorted-array/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0155-min-stack/0155-min-stack.cpp: -------------------------------------------------------------------------------- 1 | class MinStack { 2 | public: 3 | stack> s1; 4 | MinStack() { 5 | s1 = stack>(); 6 | } 7 | 8 | void push(int val) { 9 | int mn = (s1.size()? min(val,s1.top()[1]): val); 10 | s1.push({val, mn}); 11 | } 12 | 13 | void pop() { 14 | s1.pop(); 15 | } 16 | 17 | int top() { 18 | return s1.top()[0]; 19 | } 20 | 21 | int getMin() { 22 | return s1.top()[1]; 23 | } 24 | }; 25 | 26 | /** 27 | * Your MinStack object will be instantiated and called as such: 28 | * MinStack* obj = new MinStack(); 29 | * obj->push(val); 30 | * obj->pop(); 31 | * int param_3 = obj->top(); 32 | * int param_4 = obj->getMin(); 33 | */ -------------------------------------------------------------------------------- /Solutions/C++/0155-min-stack/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0173-binary-search-tree-iterator/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0179-largest-number/0179-largest-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string largestNumber(vector& nums) { 4 | sort(nums.begin(), nums.end(), [](int a, int b){ 5 | string x = to_string(a); 6 | string y = to_string(b); 7 | return x+y > y+x; 8 | }); 9 | string ret = ""; 10 | for (int i = 0; i < nums.size(); i++) 11 | ret += to_string(nums[i]); 12 | while (ret[0] == '0' && ret.size() > 1) 13 | ret = ret.substr(1); 14 | return ret; 15 | } 16 | }; -------------------------------------------------------------------------------- /Solutions/C++/0179-largest-number/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0187-repeated-dna-sequences/0187-repeated-dna-sequences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findRepeatedDnaSequences(string s) { 4 | map seen; 5 | vector ret; 6 | for(int i = 0; i + 10 <= s.size(); i++) 7 | { 8 | string cur = s.substr(i, 10); 9 | if (++seen[cur] == 2) 10 | ret.push_back(cur); 11 | } 12 | return ret; 13 | } 14 | }; -------------------------------------------------------------------------------- /Solutions/C++/0187-repeated-dna-sequences/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0189-rotate-array/0189-rotate-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void rotate(vector& nums, int k) { 4 | int n = nums.size(); 5 | k %= n; 6 | vector temp = nums; 7 | for (int i = 0; i < n; i++){ 8 | nums[i] = temp[(i + n-k)%n]; 9 | } 10 | } 11 | }; -------------------------------------------------------------------------------- /Solutions/C++/0189-rotate-array/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0190-reverse-bits/0190-reverse-bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | uint32_t reverseBits(uint32_t n) { 4 | for (int i = 0, j = 31; i < j; i++, j--){ 5 | if (!!(n & (1LL<& nums) { 4 | int numberOfHouses = nums.size(); 5 | int maxWithOutLastHouse = 0; 6 | int maxWithLastHouse = nums[0]; 7 | for (int i = 1; i < numberOfHouses; i++){ 8 | int newMaxWithLastHouse = nums[i] + maxWithOutLastHouse; 9 | int newMaxWithOutLastHouse = max(maxWithOutLastHouse, maxWithLastHouse); 10 | maxWithLastHouse = newMaxWithLastHouse; 11 | maxWithOutLastHouse = newMaxWithOutLastHouse; 12 | } 13 | return max(maxWithOutLastHouse, maxWithLastHouse); 14 | } 15 | }; -------------------------------------------------------------------------------- /Solutions/C++/0198-house-robber/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0199-binary-tree-right-side-view/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0200-number-of-islands/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0206-reverse-linked-list/0206-reverse-linked-list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution { 12 | public: 13 | ListNode* reverseList(ListNode* head) { 14 | ListNode* prv = nullptr; 15 | while(head) 16 | { 17 | ListNode* nxt = head->next; 18 | head->next = prv; 19 | prv = head; 20 | head = nxt; 21 | } 22 | return prv; 23 | } 24 | }; -------------------------------------------------------------------------------- /Solutions/C++/0206-reverse-linked-list/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0207-course-schedule/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0208-implement-trie-prefix-tree/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0209-minimum-size-subarray-sum/0209-minimum-size-subarray-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minSubArrayLen(int target, vector& nums) { 4 | int n = nums.size(), len = 0; 5 | int l = 1, r = n, m; 6 | while (l <= r){ 7 | m = (l+r) >> 1; 8 | bool ok = 0; 9 | int sum = 0; 10 | for (int i = 0; i < m-1; i++) 11 | sum += nums[i]; 12 | for (int i = 0, j = m-1; j < n; i++, j++){ 13 | sum += nums[j]; 14 | if (sum >= target){ 15 | ok = 1;break; 16 | } 17 | sum -= nums[i]; 18 | } 19 | if (ok){ 20 | len = m; 21 | r = m - 1; 22 | }else 23 | l = m + 1; 24 | } 25 | return len; 26 | } 27 | }; -------------------------------------------------------------------------------- /Solutions/C++/0209-minimum-size-subarray-sum/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0211-design-add-and-search-words-data-structure/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0212-word-search-ii/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0213-house-robber-ii/0213-house-robber-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int dp[101][2]; 4 | int solve(vector& nums, int indx, bool takeFirstHouse){ 5 | if (indx >= nums.size()) 6 | return 0; 7 | int& ret = dp[indx][takeFirstHouse]; 8 | if (~ret) return ret; 9 | ret = 0; 10 | if (indx == nums.size() - 1){ 11 | if (!takeFirstHouse) 12 | ret = nums[indx] + solve(nums, indx + 2, takeFirstHouse); 13 | }else 14 | { 15 | ret = max(solve(nums, indx + 1, takeFirstHouse), 16 | nums[indx] + solve(nums, indx + 2, takeFirstHouse | (indx == 0))); 17 | } 18 | return ret; 19 | } 20 | int rob(vector& nums) { 21 | memset(dp, -1, sizeof dp); 22 | return solve(nums, 0, 0); 23 | } 24 | }; -------------------------------------------------------------------------------- /Solutions/C++/0213-house-robber-ii/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0215-kth-largest-element-in-an-array/0215-kth-largest-element-in-an-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int frq[20001], delta = 1e4; 4 | int findKthLargest(vector& nums, int k) { 5 | memset(frq, 0, sizeof frq); 6 | for (int i = 0; i < nums.size(); i++) 7 | frq[nums[i] + delta]++; 8 | for (int i = 20000; i >= 0; i--){ 9 | k -= frq[i]; 10 | if (k <= 0) return i - delta; 11 | } 12 | return -1; 13 | } 14 | }; -------------------------------------------------------------------------------- /Solutions/C++/0215-kth-largest-element-in-an-array/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0217-contains-duplicate/0217-contains-duplicate.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool containsDuplicate(vector& nums) { 4 | unordered_map mp; 5 | for (int i = 0; i < nums.size(); i++){ 6 | if (++mp[nums[i]] == 2) 7 | return 1; 8 | } 9 | return 0; 10 | } 11 | }; -------------------------------------------------------------------------------- /Solutions/C++/0217-contains-duplicate/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0226-invert-binary-tree/0226-invert-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | void dfs(TreeNode* root){ 15 | if (root == nullptr) return; 16 | dfs(root->left); 17 | dfs(root->right); 18 | swap(root->left, root->right); 19 | } 20 | TreeNode* invertTree(TreeNode* root) { 21 | dfs(root); 22 | return root; 23 | } 24 | }; -------------------------------------------------------------------------------- /Solutions/C++/0226-invert-binary-tree/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0227-basic-calculator-ii/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0230-kth-smallest-element-in-a-bst/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0231-power-of-two/0231-power-of-two.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPowerOfTwo(int n) { 4 | return n && n != -2147483648 && (n & (n-1)) == 0; 5 | } 6 | }; -------------------------------------------------------------------------------- /Solutions/C++/0231-power-of-two/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0232-implement-queue-using-stacks/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0235-lowest-common-ancestor-of-a-binary-search-tree/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0236-lowest-common-ancestor-of-a-binary-tree/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0238-product-of-array-except-self/0238-product-of-array-except-self.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector productExceptSelf(vector& nums) { 4 | vector ret(nums.size(), 1); 5 | for(int _ = 0; _ < 2; _++) 6 | { 7 | int prd = 1; 8 | for(int i = 0; i < nums.size(); i++) 9 | { 10 | ret[_? nums.size()-1-i: i] *= prd; 11 | prd *= nums[_? nums.size()-1-i: i]; 12 | } 13 | } 14 | return ret; 15 | } 16 | }; -------------------------------------------------------------------------------- /Solutions/C++/0238-product-of-array-except-self/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0242-valid-anagram/0242-valid-anagram.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isAnagram(string s, string t) { 4 | if (s.size() != t.size() || !t.size())return !t.size(); 5 | int frq[26] = {0}; 6 | for (int i =0 ; i< t.size() ;i++) 7 | { 8 | frq[ s[i] - 'a' ]++; 9 | frq[ t[i] -'a']--; 10 | } 11 | for (int i =0 ; i < 26 ;i++)if (frq[i] != 0 )return 0; 12 | return 1 ; 13 | } 14 | }; -------------------------------------------------------------------------------- /Solutions/C++/0242-valid-anagram/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0268-missing-number/0268-missing-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int missingNumber(vector& nums) { 4 | int sum = (nums.size() * (nums.size() + 1)) / 2; 5 | for (int i = 0; i < nums.size(); i++) 6 | sum -= nums[i]; 7 | return sum; 8 | } 9 | }; -------------------------------------------------------------------------------- /Solutions/C++/0268-missing-number/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0295-find-median-from-data-stream/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0297-serialize-and-deserialize-binary-tree/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0300-longest-increasing-subsequence/0300-longest-increasing-subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLIS(vector& nums) { 4 | vector LIS(nums.size(), 1); 5 | int mx = 1; 6 | for (int i = 0; i < nums.size(); i++){ 7 | for (int j = 0; j < i; j++){ 8 | if (nums[i] > nums[j]) 9 | LIS[i] = max(LIS[i], LIS[j] + 1); 10 | } 11 | mx = max(mx, LIS[i]); 12 | } 13 | return mx; 14 | } 15 | }; -------------------------------------------------------------------------------- /Solutions/C++/0300-longest-increasing-subsequence/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0303-range-sum-query-immutable/0303-range-sum-query-immutable.cpp: -------------------------------------------------------------------------------- 1 | class NumArray { 2 | public: 3 | vector prefix; 4 | NumArray(vector& nums) { 5 | prefix = vector (nums.size(), 0); 6 | for (int i = 0; i < nums.size(); i++){ 7 | prefix[i] = nums[i] + (i? prefix[i-1]: 0); 8 | } 9 | } 10 | 11 | int sumRange(int left, int right) { 12 | return prefix[right] - (left? prefix[left - 1]: 0); 13 | } 14 | }; 15 | 16 | /** 17 | * Your NumArray object will be instantiated and called as such: 18 | * NumArray* obj = new NumArray(nums); 19 | * int param_1 = obj->sumRange(left,right); 20 | */ -------------------------------------------------------------------------------- /Solutions/C++/0304-range-sum-query-2d-immutable/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0322-coin-change/0322-coin-change.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int coinChange(vector& coins, int amount) { 4 | int inf = 1e9; 5 | vector minCoins(amount+1, inf); 6 | minCoins[0] = 0; 7 | for (int curAmount = 1; curAmount <= amount; curAmount++){ 8 | for (int& coin: coins){ 9 | if (coin > curAmount) continue; 10 | minCoins[curAmount] = min(minCoins[curAmount], 11 | 1 + minCoins[curAmount-coin]); 12 | } 13 | } 14 | if (minCoins[amount] == inf) 15 | return -1; 16 | return minCoins[amount]; 17 | } 18 | }; -------------------------------------------------------------------------------- /Solutions/C++/0322-coin-change/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0323-number-of-connected-components-in-an-undirected-graph/0323-number-of-connected-components-in-an-undirected-graph.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector parent; 4 | int getParent(int u){ 5 | return parent[u] == u? u: parent[u] = getParent(parent[u]); 6 | } 7 | void merge(int u, int v){ 8 | u = getParent(u); 9 | v = getParent(v); 10 | if (parent[u] != parent[v]) 11 | parent[u] = v; 12 | } 13 | int countComponents(int n, vector> edges) { 14 | parent = vector(n); 15 | for (int i = 0; i < n; i++) 16 | parent[i] = i; 17 | for (int i = 0; i < edges.size(); i++) { 18 | merge(edges[i][0], edges[i][1]); 19 | } 20 | set parents; 21 | for (int i = 0; i < n; i++) { 22 | parents.insert(getParent(i)); 23 | } 24 | return (int) parents.size(); 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Solutions/C++/0338-counting-bits/0338-counting-bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector countBits(int n) { 4 | vector count(n + 1, 0); 5 | count[0] = 0; 6 | for (int i = 1; i <= n; i++){ 7 | count[i] = (count[i>>1] + (i&1)); 8 | } 9 | return count; 10 | } 11 | }; -------------------------------------------------------------------------------- /Solutions/C++/0338-counting-bits/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0341-flatten-nested-list-iterator/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0347-top-k-frequent-elements/0347-top-k-frequent-elements.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector topKFrequent(vector& nums, int k) { 4 | int delta = 1e4; 5 | vector frq(2 * delta + 2, 0); 6 | for (int i = 0; i < nums.size(); i++) 7 | { 8 | frq[nums[i] + delta]++; 9 | } 10 | priority_queue> pq; 11 | for (int i = 0; i <= 2 * delta; i++){ 12 | if (frq[i] > 0){ 13 | pq.push({-frq[i], i - delta}); 14 | } 15 | while (pq.size() > k){ 16 | pq.pop(); 17 | } 18 | } 19 | vector topK; 20 | while (pq.size()){ 21 | topK.push_back(pq.top()[1]); 22 | pq.pop(); 23 | } 24 | return topK; 25 | } 26 | }; 27 | // time N Log(K) -------------------------------------------------------------------------------- /Solutions/C++/0347-top-k-frequent-elements/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0371-sum-of-two-integers/0371-sum-of-two-integers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int getSum(int a, int b) { 4 | return a + b; 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /Solutions/C++/0371-sum-of-two-integers/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0371-sum-of-two-integers/README.md: -------------------------------------------------------------------------------- 1 |

371. Sum of Two Integers

Medium


Given two integers a and b, return the sum of the two integers without using the operators + and -.

2 | 3 |

 

4 |

Example 1:

5 |
Input: a = 1, b = 2
 6 | Output: 3
 7 | 

Example 2:

8 |
Input: a = 2, b = 3
 9 | Output: 5
10 | 
11 |

 

12 |

Constraints:

13 | 14 |
    15 |
  • -1000 <= a, b <= 1000
  • 16 |
17 |
-------------------------------------------------------------------------------- /Solutions/C++/0380-insert-delete-getrandom-o1/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0402-remove-k-digits/0402-remove-k-digits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string removeKdigits(string num, int k) { 4 | stack stk; 5 | stk.push(num[0]); 6 | for (int i = 1; i < num.size(); i++){ 7 | while (k && !stk.empty() && num[i] < stk.top()){ 8 | stk.pop(); 9 | k--; 10 | } 11 | stk.push(num[i]); 12 | } 13 | while (stk.size() && k){ 14 | k--; 15 | stk.pop(); 16 | } 17 | string ret = ""; 18 | while (!stk.empty()){ 19 | ret += stk.top(); 20 | stk.pop(); 21 | } 22 | while (ret.size() > 0 && ret.back() == '0') 23 | ret.pop_back(); 24 | reverse(ret.begin(), ret.end()); 25 | if (ret.size() == 0) ret += "0"; 26 | return ret; 27 | } 28 | }; -------------------------------------------------------------------------------- /Solutions/C++/0402-remove-k-digits/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0416-partition-equal-subset-sum/0416-partition-equal-subset-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int dp[201][10001]; 4 | int solve(vector& nums, int i, int rem){ 5 | if (rem == 0) return 1; 6 | if (i == nums.size() || rem < 0) return 0; 7 | int &ret = dp[i][rem]; 8 | if (~ret) return ret; 9 | ret = max(solve(nums, i + 1, rem), solve(nums, i + 1, rem - nums[i])); 10 | return ret; 11 | } 12 | bool canPartition(vector& nums) { 13 | int sum = 0; 14 | for (int i = 0; i < nums.size(); i++) 15 | sum += nums[i]; 16 | if (sum & 1) return 0; 17 | sum /= 2; 18 | memset(dp, -1, sizeof dp); 19 | return solve(nums, 0, sum); 20 | } 21 | }; -------------------------------------------------------------------------------- /Solutions/C++/0416-partition-equal-subset-sum/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0417-pacific-atlantic-water-flow/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0421-maximum-xor-of-two-numbers-in-an-array/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0435-non-overlapping-intervals/0435-non-overlapping-intervals.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int eraseOverlapIntervals(vector>& intervals) { 4 | sort(intervals.begin(), intervals.end(), 5 | [](vector&a, vector&b) 6 | { 7 | return a[0] < b[0]; 8 | }); 9 | int ans = 0; 10 | int r = -1e9; 11 | for(int i = 0; i < intervals.size(); i++) 12 | { 13 | if (intervals[i][0] >= r) 14 | { 15 | r = intervals[i][1]; 16 | }else 17 | { 18 | ans++; 19 | r = min(r, intervals[i][1]); 20 | } 21 | } 22 | return ans; 23 | } 24 | }; -------------------------------------------------------------------------------- /Solutions/C++/0435-non-overlapping-intervals/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0438-find-all-anagrams-in-a-string/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0445-add-two-numbers-ii/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0449-serialize-and-deserialize-bst/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0450-delete-node-in-a-bst/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0451-sort-characters-by-frequency/0451-sort-characters-by-frequency.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string frequencySort(string s) { 4 | vector frq(128, 0); 5 | for (int i = 0; i < s.size(); i++) 6 | frq[s[i]]++; 7 | sort(s.begin(), s.end(),[&](char& a, char& b){ 8 | if (frq[a] != frq[b]) return frq[a] > frq[b]; 9 | return a > b; 10 | }); 11 | return s; 12 | } 13 | }; -------------------------------------------------------------------------------- /Solutions/C++/0451-sort-characters-by-frequency/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0494-target-sum/0494-target-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int ways[20][40000]; 4 | int countWays(vector&nums, int index, int curSum, int target){ 5 | if (index == nums.size()){ 6 | return (curSum == target); 7 | } 8 | int& ret = ways[index][curSum]; 9 | if (~ret) 10 | return ret; 11 | ret = countWays(nums, index + 1, curSum + nums[index], target) + 12 | countWays(nums, index + 1, curSum - nums[index], target); 13 | return ret; 14 | } 15 | int findTargetSumWays(vector& nums, int target) { 16 | memset(ways, -1, sizeof ways); 17 | return countWays(nums, 0, 20000, target + 20000); 18 | } 19 | }; -------------------------------------------------------------------------------- /Solutions/C++/0494-target-sum/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0523-continuous-subarray-sum/0523-continuous-subarray-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkSubarraySum(vector& nums, int k) { 4 | map mp; 5 | mp[0] = 0; 6 | int pre = 0; 7 | for (int i = 0; i < nums.size(); i++){ 8 | pre = (pre + nums[i])%k; 9 | if (mp.find(pre) == mp.end()) 10 | mp[pre] = i + 1; 11 | else if (mp[pre] < i) 12 | return 1; 13 | } 14 | return 0; 15 | } 16 | }; -------------------------------------------------------------------------------- /Solutions/C++/0547-number-of-provinces/0547-number-of-provinces.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int vis[200]; 4 | void dfs(vector>& isConnected, int node){ 5 | vis[node] = 1; 6 | for (int i = 0; i < isConnected.size(); i++){ 7 | if (isConnected[node][i] && !vis[i]) 8 | dfs(isConnected, i); 9 | } 10 | } 11 | int findCircleNum(vector>& isConnected) { 12 | memset(vis, 0, sizeof vis); 13 | int cnt = 0; 14 | for (int i = 0; i < isConnected.size(); i++){ 15 | if (vis[i] == 0){ 16 | cnt++; 17 | dfs(isConnected, i); 18 | } 19 | } 20 | return cnt; 21 | } 22 | }; -------------------------------------------------------------------------------- /Solutions/C++/0547-number-of-provinces/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0554-brick-wall/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0560-subarray-sum-equals-k/0560-subarray-sum-equals-k.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int subarraySum(vector& nums, int k) { 4 | map mp; 5 | mp[0] = 1; 6 | int cnt = 0; 7 | int pre = 0; 8 | for(int i = 0; i < nums.size(); i++) 9 | { 10 | pre += nums[i]; 11 | cnt += mp[pre - k]; 12 | mp[pre]++; 13 | 14 | } 15 | return cnt; 16 | } 17 | }; -------------------------------------------------------------------------------- /Solutions/C++/0560-subarray-sum-equals-k/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0567-permutation-in-string/0567-permutation-in-string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool checkInclusion(string s1, string s2) { 4 | if (s1.size() > s2.size()) return 0; 5 | vector frq(26, 0), frq2(26, 0); 6 | for (int i = 0; i < s1.size(); i++) frq[s1[i] - 'a']++; 7 | for (int i = 0; i < s1.size()-1; i++)frq2[s2[i] - 'a']++; 8 | for (int i = 0, j = s1.size()-1; j < s2.size(); j++, i++){ 9 | frq2[s2[j] - 'a']++; 10 | bool ok = 1; 11 | for (int k = 0; ok && k < 26; k++) 12 | if (frq[k] != frq2[k]) 13 | ok = 0; 14 | if (ok) return 1; 15 | frq2[s2[i]-'a']--; 16 | } 17 | return 0; 18 | } 19 | }; -------------------------------------------------------------------------------- /Solutions/C++/0567-permutation-in-string/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0572-subtree-of-another-tree/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0605-can-place-flowers/0605-can-place-flowers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canPlaceFlowers(vector& flowerbed, int n) { 4 | for (int i = 0; i < flowerbed.size(); i++){ 5 | if (flowerbed[i]) continue; 6 | if (i && flowerbed[i-1]) continue; 7 | if (i+1 < flowerbed.size() && flowerbed[i+1]) continue; 8 | n--; 9 | flowerbed[i] = 1; 10 | } 11 | return n <= 0; 12 | } 13 | }; -------------------------------------------------------------------------------- /Solutions/C++/0621-task-scheduler/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0647-palindromic-substrings/0647-palindromic-substrings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countSubstrings(string s) { 4 | int cnt = 0, n = s.size(); 5 | for (int i = 0; i < n; i++){ 6 | int l = i - 1, r = i + 1; 7 | cnt++; 8 | while (l >= 0 && r < n && s[l] == s[r]){ 9 | cnt++; 10 | l--; 11 | r++; 12 | } 13 | l = i, r = i + 1; 14 | while (l >= 0 && r < n && s[l] == s[r]){ 15 | cnt++; 16 | l--; 17 | r++; 18 | } 19 | } 20 | return cnt; 21 | } 22 | }; -------------------------------------------------------------------------------- /Solutions/C++/0647-palindromic-substrings/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0658-find-k-closest-elements/0658-find-k-closest-elements.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findClosestElements(vector& arr, int k, int x) { 4 | sort(arr.begin(), arr.end(), [&](int A, int B){ 5 | if (abs(A - x) != abs(B - x)) return abs(A - x) < abs(B - x); 6 | return A < B; 7 | }); 8 | arr.erase(arr.begin() + k, arr.end()); 9 | sort(arr.begin(), arr.end()); 10 | return arr; 11 | } 12 | }; -------------------------------------------------------------------------------- /Solutions/C++/0658-find-k-closest-elements/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0665-non-decreasing-array/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0692-top-k-frequent-words/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0695-max-area-of-island/0695-max-area-of-island.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int dfs(vector>& grid, int r, int c) 4 | { 5 | grid[r][c] = 0; 6 | int dx[] = {1, -1, 0, 0}; 7 | int dy[] = {0, 0, 1, -1}; 8 | int cur = 1; 9 | for (int i = 0; i < 4; i++) 10 | { 11 | int nr = dx[i] + r; 12 | int nc = dy[i] + c; 13 | if (nr >= 0 && nc >= 0 && nr < grid.size() 14 | && nc < grid[0].size() && grid[nr][nc] == 1) 15 | cur += dfs(grid, nr, nc); 16 | } 17 | return cur; 18 | } 19 | int maxAreaOfIsland(vector>& grid) { 20 | int mx = 0; 21 | for (int i = 0; i < grid.size(); i++) 22 | for (int j = 0; j < grid[i].size(); j++) 23 | if (grid[i][j]) 24 | mx = max(mx, dfs(grid, i, j)); 25 | return mx; 26 | } 27 | }; -------------------------------------------------------------------------------- /Solutions/C++/0695-max-area-of-island/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0707-design-linked-list/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0720-longest-word-in-dictionary/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0729-my-calendar-i/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0739-daily-temperatures/0739-daily-temperatures.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector dailyTemperatures(vector& T) { 4 | stack> stk; 5 | vector answer(T.size(), 0); 6 | for (int i = T.size()-1; ~i; i--) 7 | { 8 | while(!stk.empty() && stk.top().first <= T[i]) 9 | stk.pop(); 10 | if (!stk.empty()) 11 | answer[i] = stk.top().second - i; 12 | stk.push({T[i], i}); 13 | } 14 | return answer; 15 | 16 | } 17 | }; -------------------------------------------------------------------------------- /Solutions/C++/0739-daily-temperatures/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0787-cheapest-flights-within-k-stops/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0792-number-of-matching-subsequences/0792-number-of-matching-subsequences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numMatchingSubseq(string s, vector& words) { 4 | vector> nxt((int)s.size()); 5 | nxt[s.size()-1] = vector(26, -1); 6 | nxt[s.size()-1][s.back()-'a'] = s.size()-1; 7 | for (int i = s.size()-2; i >= 0; i--){ 8 | nxt[i] = nxt[i+1]; 9 | nxt[i][s[i]-'a'] = i; 10 | } 11 | int cnt = 0; 12 | for (int i = 0; i < words.size(); i++){ 13 | int index = 0; 14 | int j = 0; 15 | while (j < words[i].size() && index < s.size()){ 16 | index = nxt[index][words[i][j] - 'a']; 17 | if (index == -1) break; 18 | index++; 19 | j++; 20 | } 21 | cnt += j == words[i].size(); 22 | } 23 | return cnt; 24 | } 25 | }; -------------------------------------------------------------------------------- /Solutions/C++/0792-number-of-matching-subsequences/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0838-push-dominoes/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0841-keys-and-rooms/0841-keys-and-rooms.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool vis[1001]; 4 | bool canVisitAllRooms(vector>& rooms) { 5 | memset(vis, 0, sizeof vis); 6 | queue q; 7 | q.push(0); 8 | int visited = 1; 9 | vis[0] = 1; 10 | while (!q.empty()){ 11 | int cur = q.front(); 12 | q.pop(); 13 | for (int i = 0; i < rooms[cur].size(); i++){ 14 | if (!vis[rooms[cur][i]]){ 15 | vis[rooms[cur][i]] = 1; 16 | q.push(rooms[cur][i]); 17 | visited++; 18 | } 19 | } 20 | } 21 | return visited == rooms.size(); 22 | } 23 | }; -------------------------------------------------------------------------------- /Solutions/C++/0841-keys-and-rooms/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0860-lemonade-change/0860-lemonade-change.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool lemonadeChange(vector& bills) { 4 | int rem5 = 0, rem10 = 0; 5 | for (int i = 0; i < bills.size(); i++){ 6 | if (bills[i] == 5){ 7 | rem5++; 8 | }else if (bills[i] == 10){ 9 | if (rem5) 10 | rem5--,rem10++; 11 | else 12 | return 0; 13 | }else { 14 | if (rem10 && rem5) 15 | rem10--,rem5--; 16 | else if (rem5 >= 3) 17 | rem5 -= 3; 18 | else 19 | return 0; 20 | } 21 | } 22 | return 1; 23 | } 24 | }; -------------------------------------------------------------------------------- /Solutions/C++/0860-lemonade-change/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0875-koko-eating-bananas/0875-koko-eating-bananas.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minEatingSpeed(vector& piles, int h) { 4 | int l = 1, r = 1e9 + 1, m, k = -1; 5 | while (l <= r){ 6 | m = (l+r) >> 1; 7 | long long need = 0; 8 | for (int i = 0; i < piles.size(); i++){ 9 | need += (1LL * piles[i] + m - 1) / m; 10 | } 11 | if (need <= h) 12 | k = m, r = m - 1; 13 | else 14 | l = m + 1; 15 | } 16 | return k; 17 | } 18 | }; -------------------------------------------------------------------------------- /Solutions/C++/0875-koko-eating-bananas/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0881-boats-to-save-people/0881-boats-to-save-people.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numRescueBoats(vector& people, int limit) { 4 | sort(people.begin(), people.end()); 5 | int l = 0, r = people.size()-1; 6 | int boats = 0; 7 | while (l <= r){ 8 | if (people[r] + people[l] <= limit){ 9 | boats++; 10 | r--; 11 | l++; 12 | }else { 13 | r--; 14 | boats++; 15 | } 16 | } 17 | return boats; 18 | } 19 | }; -------------------------------------------------------------------------------- /Solutions/C++/0947-most-stones-removed-with-same-row-or-column/0947-most-stones-removed-with-same-row-or-column.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool vis[1001]; 4 | int dfs(vector>& stones, int point){ 5 | vis[point] = 1; 6 | int removed = 0; 7 | for (int i = 0; i < stones.size(); i++){ 8 | if (vis[i]) continue; 9 | if (stones[i][0] == stones[point][0] || stones[i][1] == stones[point][1]){ 10 | removed += 1 + dfs(stones, i); 11 | } 12 | } 13 | return removed; 14 | } 15 | int removeStones(vector>& stones) { 16 | memset(vis, 0, sizeof vis); 17 | int ans = 0; 18 | for (int i = 0; i < stones.size(); i++){ 19 | if (!vis[i]) 20 | ans += dfs(stones, i); 21 | } 22 | return ans; 23 | } 24 | }; -------------------------------------------------------------------------------- /Solutions/C++/0947-most-stones-removed-with-same-row-or-column/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0973-k-closest-points-to-origin/0973-k-closest-points-to-origin.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> kClosest(vector>& points, int k) { 4 | priority_queue> pq; 5 | auto GetDist = [&](int index){ 6 | int sum = 0; 7 | for (int i = 0; i < 2; i++) 8 | sum += points[index][i] * points[index][i]; 9 | return sum; 10 | }; 11 | for (int i = 0; i < points.size(); i++){ 12 | pq.push({GetDist(i),i}); 13 | while (pq.size() > k) 14 | pq.pop(); 15 | } 16 | vector> ret; 17 | while (pq.size() > 0){ 18 | int index = pq.top()[1]; 19 | ret.push_back(points[index]); 20 | pq.pop(); 21 | } 22 | return ret; 23 | 24 | } 25 | }; -------------------------------------------------------------------------------- /Solutions/C++/0973-k-closest-points-to-origin/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0983-minimum-cost-for-tickets/0983-minimum-cost-for-tickets.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minCost[366]; 4 | int minSpend(vector& days, vector& costs, int day){ 5 | if (day > days.back()) return 0; 6 | int& ret = minCost[day]; 7 | if (~ret) return ret; 8 | int index = 0; 9 | while (index < days.size() && days[index] < day) 10 | index++; 11 | day = days[index]; 12 | ret = 1e9; 13 | int period[] = {1, 7, 30}; 14 | for (int i = 0; i < 3; i++){ 15 | ret = min(ret, costs[i] + minSpend(days, costs, day + period[i])); 16 | } 17 | return ret; 18 | } 19 | int mincostTickets(vector& days, vector& costs) { 20 | memset(minCost, -1, sizeof minCost); 21 | return minSpend(days, costs, 1); 22 | } 23 | }; -------------------------------------------------------------------------------- /Solutions/C++/0983-minimum-cost-for-tickets/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0994-rotting-oranges/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/0997-find-the-town-judge/0997-find-the-town-judge.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findJudge(int n, vector>& trust) { 4 | 5 | vector trustCount(n, 0); 6 | for (int i = 0; i < trust.size(); i++) 7 | { 8 | trustCount[trust[i][1]-1]++; 9 | trustCount[trust[i][0]-1]--; 10 | } 11 | for (int i = 0; i < n; i++){ 12 | if (trustCount[i] == n-1){ 13 | return i + 1; 14 | } 15 | } 16 | return -1; 17 | 18 | } 19 | }; -------------------------------------------------------------------------------- /Solutions/C++/0997-find-the-town-judge/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/1143-longest-common-subsequence/1143-longest-common-subsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int dp[1001][1001]; 4 | int solve(string& a, string& b, int i = 0, int j = 0){ 5 | if (i == a.size() || j == b.size()) return 0; 6 | int& ret = dp[i][j]; 7 | if (~ret) return ret; 8 | ret = 0; 9 | if (a[i] == b[j]) ret = 1 + solve(a, b, i + 1, j + 1); 10 | ret = max(ret, solve(a, b, i + 1, j)); 11 | ret = max(ret, solve(a, b, i, j + 1)); 12 | ret = max(ret, solve(a, b, i+1, j+1)); 13 | return ret; 14 | } 15 | int longestCommonSubsequence(string text1, string text2) { 16 | memset(dp, -1, sizeof dp); 17 | return solve(text1, text2, 0, 0); 18 | } 19 | }; -------------------------------------------------------------------------------- /Solutions/C++/1189. Maximum Number of Balloons.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxNumberOfBalloons(string text) { 4 | int freq[27] = {0}; 5 | int i ; 6 | for(char c: text){ 7 | freq[c-'a']++; 8 | } 9 | // Since "L" and "O" are repeated twice we need to normalize them to 1 10 | freq[11]/=2; // Divide "L" by half 11 | freq[14]/=2; // Divide "O" by half 12 | int minOccurence = min(freq[0],min(freq[1],min(freq[11], min(freq[13],freq[14])))); 13 | return minOccurence; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /Solutions/C++/1249-minimum-remove-to-make-valid-parentheses/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/14. Longest Common Prefix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string longestCommonPrefix(vector& strs) { 4 | string common = ""; 5 | char current; 6 | int i, j; 7 | int firstStringLength = strs[0].size(); // take First Word Length as reference 8 | for(i = 0; i < firstStringLength; i++){ 9 | current = strs[0][i]; // take First Word characters as reference 10 | for(j = 1; j < strs.size(); j++){ 11 | if(current != strs[j][i]) 12 | return common; 13 | } 14 | common+=current; 15 | } 16 | return common; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /Solutions/C++/1448-count-good-nodes-in-binary-tree/1448-count-good-nodes-in-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 | * }; 11 | */ 12 | class Solution { 13 | public: 14 | int goodNodesHelper(TreeNode* root, int pathMax){ 15 | if (root == nullptr) return 0; 16 | int val = root->val; 17 | return (val >= pathMax) + goodNodesHelper(root->left, max(pathMax, val))+ 18 | goodNodesHelper(root->right, max(pathMax, val)); 19 | } 20 | int goodNodes(TreeNode* root) { 21 | return goodNodesHelper(root, -1e9); 22 | } 23 | }; -------------------------------------------------------------------------------- /Solutions/C++/1448-count-good-nodes-in-binary-tree/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/1461-check-if-a-string-contains-all-binary-codes-of-size-k/1461-check-if-a-string-contains-all-binary-codes-of-size-k.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool hasAllCodes(string s, int k) { 4 | if (k > s.size()) return 0; 5 | unordered_set masks; 6 | int hashValue = 0; 7 | for (int i = 0; i < k-1; i++){ 8 | hashValue = (hashValue << 1) | (s[i] == '1'); 9 | } 10 | for (int i = 0, j = k-1; j < s.size(); i++, j++){ 11 | hashValue = (hashValue << 1) | (s[j] == '1'); 12 | hashValue &= ((1<& nums, int target) { 4 | sort(nums.begin(), nums.end()); 5 | int ans = 0, n = nums.size(), mod = 1e9 + 7; 6 | vector pow2(n+1, 0); 7 | pow2[0] = 1; 8 | for (int i = 1; i <= n; i++) 9 | pow2[i] = (pow2[i-1] << 1) % mod; 10 | n--; 11 | for (int i = 0; i <= n; i++){ 12 | while (i <= n && nums[i] + nums[n] > target) 13 | n--; 14 | int len = n - i; 15 | if (len >= 0) 16 | ans = (ans + pow2[len] % mod) % mod; 17 | } 18 | return ans; 19 | } 20 | }; -------------------------------------------------------------------------------- /Solutions/C++/1498-number-of-subsequences-that-satisfy-the-given-sum-condition/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/1557-minimum-number-of-vertices-to-reach-all-nodes/1557-minimum-number-of-vertices-to-reach-all-nodes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findSmallestSetOfVertices(int n, vector>& edges) { 4 | vector inDegree(n); 5 | vector nodes; 6 | for (int i = 0; i < edges.size(); i++){ 7 | inDegree[edges[i][1]]++; 8 | } 9 | for (int i = 0; i < n; i++){ 10 | if (inDegree[i] == 0){ 11 | nodes.push_back(i); 12 | } 13 | } 14 | if (nodes.size() == 0) 15 | nodes.push_back(0); 16 | return nodes; 17 | } 18 | }; -------------------------------------------------------------------------------- /Solutions/C++/1557-minimum-number-of-vertices-to-reach-all-nodes/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/1797-design-authentication-manager/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/1823-find-the-winner-of-the-circular-game/1823-find-the-winner-of-the-circular-game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findTheWinner(int n, int k) { 4 | queue q; 5 | for (int i = 1; i <= n; i++) 6 | q.push(i); 7 | while (q.size() > 1){ 8 | int rem = k-1; 9 | while (rem--){ 10 | q.push(q.front()); 11 | q.pop(); 12 | } 13 | q.pop(); 14 | } 15 | return q.front(); 16 | } 17 | }; -------------------------------------------------------------------------------- /Solutions/C++/1823-find-the-winner-of-the-circular-game/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/1838-frequency-of-the-most-frequent-element/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/1845-seat-reservation-manager/1845-seat-reservation-manager.cpp: -------------------------------------------------------------------------------- 1 | class SeatManager { 2 | public: 3 | set unlocked; 4 | int toTake = 1; 5 | SeatManager(int n) {} 6 | 7 | int reserve() { 8 | if (unlocked.size()){ 9 | int val = *unlocked.begin(); 10 | unlocked.erase(val); 11 | return val; 12 | } 13 | return toTake++; 14 | } 15 | 16 | void unreserve(int seatNumber) { 17 | unlocked.insert(seatNumber); 18 | } 19 | }; 20 | 21 | /** 22 | * Your SeatManager object will be instantiated and called as such: 23 | * SeatManager* obj = new SeatManager(n); 24 | * int param_1 = obj->reserve(); 25 | * obj->unreserve(seatNumber); 26 | */ -------------------------------------------------------------------------------- /Solutions/C++/1845-seat-reservation-manager/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/1888-minimum-number-of-flips-to-make-the-binary-string-alternating/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/1930-unique-length-3-palindromic-subsequences/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/1968-array-with-elements-not-equal-to-average-of-neighbors/1968-array-with-elements-not-equal-to-average-of-neighbors.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector rearrangeArray(vector& nums) { 4 | int n = nums.size(); 5 | sort(nums.begin(), nums.end()); 6 | for (int i = 1; i + 1 < n; i++){ 7 | if (nums[i-1] + nums[i+1] == 2 * nums[i]){ 8 | swap(nums[i], nums[i+1]); 9 | } 10 | } 11 | for (int i = n-2; i > 0; i--){ 12 | if (nums[i-1] + nums[i+1] == 2 * nums[i]){ 13 | swap(nums[i], nums[i+1]); 14 | } 15 | } 16 | return nums; 17 | } 18 | }; -------------------------------------------------------------------------------- /Solutions/C++/1968-array-with-elements-not-equal-to-average-of-neighbors/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/2002-maximum-product-of-the-length-of-two-palindromic-subsequences/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/2009-minimum-number-of-operations-to-make-array-continuous/2009-minimum-number-of-operations-to-make-array-continuous.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minOperations(vector& nums) { 4 | int mn = 1e9, n = nums.size(); 5 | sort(nums.begin(), nums.end()); 6 | nums.erase(unique(nums.begin(), nums.end()), nums.end()); 7 | 8 | for (int i = 0; i < nums.size(); i++){ 9 | int lst = nums[i] + n - 1; 10 | int l = i, r = nums.size()-1, m, index = i; 11 | while (l <= r){ 12 | m = (l+r) >> 1; 13 | if (nums[m] <= lst){ 14 | index = m; 15 | l = m + 1; 16 | }else 17 | r = m - 1; 18 | } 19 | mn = min(mn, n - (index - i + 1)); 20 | } 21 | return mn; 22 | } 23 | }; -------------------------------------------------------------------------------- /Solutions/C++/2009-minimum-number-of-operations-to-make-array-continuous/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/2017-grid-game/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/2126-destroying-asteroids/2126-destroying-asteroids.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool asteroidsDestroyed(int mass, vector& asteroids) { 4 | int N = 100001; 5 | vector frq(N, 0); 6 | long long curMass = mass; 7 | for (int i = 0; i < asteroids.size(); i++) 8 | frq[asteroids[i]]++; 9 | for (int i = 1; i < N && curMass < N-1; i++){ 10 | if (frq[i] == 0) continue; 11 | if (i > curMass) return 0; 12 | curMass += 1LL * frq[i] * i; 13 | } 14 | return 1; 15 | } 16 | }; -------------------------------------------------------------------------------- /Solutions/C++/2126-destroying-asteroids/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/2276-count-integers-in-intervals/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/2328-number-of-increasing-paths-in-a-grid/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/2348-number-of-zero-filled-subarrays/2348-number-of-zero-filled-subarrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long zeroFilledSubarray(vector& nums) { 4 | long long ans = 0; 5 | for (int i = 0; i < nums.size(); i++){ 6 | if (nums[i] != 0) continue; 7 | int j = i + 1; 8 | while (j < nums.size() && nums[j] == 0) 9 | j++; 10 | int len = j - i; 11 | ans += 1LL * len * (len + 1) / 2; 12 | i = j; 13 | } 14 | return ans; 15 | } 16 | }; -------------------------------------------------------------------------------- /Solutions/C++/2348-number-of-zero-filled-subarrays/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/2492-minimum-score-of-a-path-between-two-cities/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/2591-distribute-money-to-maximum-children/2591-distribute-money-to-maximum-children.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | int distMoney(int money, int children) { 5 | if (money < children) return -1; 6 | int ret = 0; 7 | for (int i = 1; i <= children; i++){ 8 | int take = i * 8; 9 | if (take > money) break; 10 | int rem = money - take; 11 | int remC = children - i; 12 | if (rem == 0 && remC == 0){ 13 | ret = i; 14 | continue; 15 | } 16 | if (rem == 0) continue; 17 | if (remC == 0) continue; 18 | if (rem >= remC) { 19 | if (remC == 1 && rem == 4) continue; 20 | ret = max(ret, i); 21 | } 22 | } 23 | return ret; 24 | } 25 | }; -------------------------------------------------------------------------------- /Solutions/C++/2591-distribute-money-to-maximum-children/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/2594-minimum-time-to-repair-cars/NOTES.md: -------------------------------------------------------------------------------- 1 | ​ -------------------------------------------------------------------------------- /Solutions/C++/27.Remove-Element.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeElement(vector& nums, int val) { 4 | int occurence = count(nums.begin(),nums.end(),val); 5 | remove(nums.begin(),nums.end(),val); 6 | return nums.size()-occurence; 7 | 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /Solutions/C++/287. Find the Duplicate Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findDuplicate(vector& nums) { 4 | bitset<100001> frequency= {0}; 5 | int i; 6 | for(int num: nums){ 7 | if(frequency[num]) 8 | return num; 9 | else 10 | frequency[num] = 1; 11 | } 12 | return 0; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /Solutions/C++/344. Reverse String.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void reverseString(vector& s) { 4 | int i,j; 5 | char temp; 6 | for(i = 0, j = s.size() - 1; i < j; i++,j--){ 7 | temp = s[i]; 8 | s[i] = s[j]; 9 | s[j] = temp; 10 | } 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /Solutions/C++/448. Find All Numbers Disappeared in an Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findDisappearedNumbers(vector& nums) { 4 | bitset<100002> bt = {0}; 5 | vector diss; 6 | int i; 7 | for(i=0;i& nums, int target) { 4 | int index = lower_bound(nums.begin(),nums.end(),target)-nums.begin(); 5 | if(index < nums.size()) 6 | if(nums[index] == target) 7 | return index; 8 | return -1; 9 | } 10 | 11 | }; 12 | -------------------------------------------------------------------------------- /Solutions/C++/88. Merge Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void merge(vector& nums1, int m, vector& nums2, int n) { 4 | int i, j = 0; 5 | for(i = m, j = 0; j < n; i++,j++){ 6 | nums1[i] = nums2[j]; 7 | } 8 | sort(nums1.begin(), nums1.end()); 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /Solutions/C++/977. Squares of a Sorted Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector sortedSquares(vector& nums) { 4 | for(int i = 0; i < nums.size(); i++){ 5 | nums[i] = abs(nums[i] * nums[i]); 6 | } 7 | sort(nums.begin(), nums.end()); 8 | return nums; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /Solutions/C++/README.md: -------------------------------------------------------------------------------- 1 | # LeetCode -------------------------------------------------------------------------------- /Solutions/C/1-Two-Sum.c: -------------------------------------------------------------------------------- 1 | int *twoSum(int *nums, int numsSize, int target, int *returnSize) 2 | { 3 | *returnSize = 2; 4 | int *ptr = (int *)malloc(2 * sizeof(int)); 5 | if (NULL == ptr) 6 | { 7 | } 8 | else 9 | { 10 | int temp = 0; 11 | for (int i = 0; i < numsSize - 1; i++) 12 | { 13 | temp = target - *(nums + i); 14 | for (int j = i + 1; j < numsSize; j++) 15 | { 16 | if (temp == *(nums + j)) 17 | { 18 | *ptr = i; 19 | *(ptr + 1) = j; 20 | } 21 | else 22 | { 23 | } 24 | } 25 | } 26 | } 27 | return ptr; 28 | } -------------------------------------------------------------------------------- /Solutions/C/217-Contains-Duplicate.c: -------------------------------------------------------------------------------- 1 | #include 2 | bool containsDuplicate(int *nums, int numsSize) 3 | { 4 | qsort(nums, numsSize, sizeof(int), compare); 5 | for (int i = 0; i < numsSize - 1; i++) 6 | { 7 | if (*(nums + i) == *(nums + i + 1)) 8 | { 9 | return true; 10 | } 11 | } 12 | return false; 13 | } 14 | int compare(const void *a, const void *b) 15 | { 16 | return (*((int *)a) - *((int *)b)); 17 | } 18 | -------------------------------------------------------------------------------- /Solutions/C/242-Valid-Anagram.c: -------------------------------------------------------------------------------- 1 | bool isAnagram(char * s, char * t){ 2 | bool retVal = true; 3 | int *s_map = (int*)calloc(26,sizeof(int)); 4 | int *t_map = (int*)calloc(26,sizeof(int)); 5 | if(strlen(s) == strlen(t)) 6 | { 7 | for(int i = 0 ; i = 0 && *(s + str_size - 1 - num_spaces) == ' ') 11 | { 12 | num_spaces++; 13 | } 14 | 15 | int len = 0; 16 | while ((str_size - 1 - num_spaces - len) >= 0 && *(s + str_size - 1 - num_spaces - len) != ' ') 17 | { 18 | len++; 19 | } 20 | return len; 21 | } -------------------------------------------------------------------------------- /Solutions/C/724-Find-Pivot-Index.c: -------------------------------------------------------------------------------- 1 | int pivotIndex(int *nums, int numsSize) 2 | { 3 | int leftArraySum = 0; 4 | int rightArraySum = 0; 5 | 6 | for (int i = 1; i < numsSize; i++) 7 | { 8 | rightArraySum += *(nums + i); 9 | } 10 | 11 | for (int i = 0; i < numsSize - 1; i++) 12 | { 13 | if (leftArraySum == rightArraySum) 14 | { 15 | return i; 16 | } 17 | else 18 | { 19 | leftArraySum += *(nums + i); 20 | rightArraySum -= *(nums + i + 1); 21 | } 22 | } 23 | if (leftArraySum == rightArraySum) 24 | { 25 | return numsSize - 1; 26 | } 27 | return -1; 28 | } -------------------------------------------------------------------------------- /Solutions/Java/1-two-sum.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int[] twoSum(int[] nums, int target) { 3 | int[] result = new int[2]; 4 | for (int i = 0; i < nums.length; i++) { 5 | for (int j = i+1 ; j < nums.length; j++) { 6 | if((nums[i] + nums[j]) == target) { 7 | result[0] = i; 8 | result[1] = j; 9 | } 10 | } 11 | } 12 | return result; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Solutions/Java/125-valid-palindrome.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isPalindrome(String s) { 3 | boolean isPalindrome = true; 4 | int i = 0; 5 | s = (s.replaceAll("[^a-zA-Z0-9]", "")).toLowerCase(); 6 | int j = s.length()-1; 7 | while((isPalindrome) && (i set = new HashSet<>(); 4 | 5 | for(int num : nums) { 6 | if(set.contains(num)) { 7 | return true; 8 | } 9 | set.add(num); 10 | } 11 | 12 | return false; 13 | } 14 | } -------------------------------------------------------------------------------- /Solutions/Java/70-climbing-stairs.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public static int climbStairs(int n) { 3 | if (n <= 2) { 4 | return n; 5 | } 6 | int[] dp = new int[n+1]; 7 | dp[1] = 1; 8 | dp[2] = 2; 9 | for (int i = 3; i <= n; i++) { 10 | dp[i] = dp[i-1] + dp[i-2]; 11 | } 12 | return dp[n]; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Solutions/JavaScript/11. Container With Most Water.js: -------------------------------------------------------------------------------- 1 | /* 2 | ------------------- Hint ---------------------------- 3 | 4 | We want to find the maximum amount of stored water. 5 | Solved by using Two Pointers . complexity O(N). 6 | 7 | */ 8 | 9 | /** 10 | * @param {number[]} height 11 | * @return {number} 12 | */ 13 | var maxArea = function (height) { 14 | let l = 0, 15 | r = height.length - 1, 16 | mx = 0; 17 | 18 | while (l < r) { 19 | mx = Math.max(mx, Math.min(height[l], height[r]) * (r - l)); 20 | if (height[l] < height[r]) l++; 21 | else r--; 22 | } 23 | 24 | return mx; 25 | }; 26 | -------------------------------------------------------------------------------- /Solutions/JavaScript/121. Best Time to Buy and Sell Stock.js: -------------------------------------------------------------------------------- 1 | /* 2 | ------------------- Hint ---------------------------- 3 | 4 | We want to find min and max number from the array 5 | Solved by using Two Pointers . complexity O(N). 6 | 7 | */ 8 | 9 | /** 10 | * @param {number[]} prices 11 | * @return {number} 12 | */ 13 | var maxProfit = function (prices) { 14 | let l = 0, r = 1, mx = 0; 15 | 16 | while (r < prices.length) { 17 | 18 | if (prices[l] < prices[r]) { 19 | mx = Math.max(mx, prices[r] - prices[l]); 20 | } else { 21 | l = r; 22 | } 23 | r++; 24 | 25 | } 26 | return mx; 27 | }; -------------------------------------------------------------------------------- /Solutions/JavaScript/153.find-minimum-in-rotated-sorted-array.js: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=153 lang=javascript 3 | * 4 | * [153] Find Minimum in Rotated Sorted Array 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * @param {number[]} nums 10 | * @return {number} 11 | */ 12 | 13 | var findMin = function(nums) { 14 | let left = 0; 15 | let right = nums.length - 1; 16 | let mid = 0; 17 | while (left < right) { 18 | mid = Math.floor((left + right) / 2); 19 | if (nums[mid] > nums[right]) { 20 | left = mid + 1; 21 | } 22 | else { 23 | right = mid; 24 | } 25 | } 26 | return nums[left]; 27 | }; 28 | // @lc code=end 29 | 30 | 31 | // @after-stub-for-debug-begin 32 | module.exports = findMin; 33 | // @after-stub-for-debug-end -------------------------------------------------------------------------------- /Solutions/JavaScript/20. Valid Parentheses.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {string} s 3 | * @return {boolean} 4 | */ 5 | var isValid = function(s) { 6 | let stack = [] //uses only push and pop (FILO) 7 | let pairs = { 8 | '(':')', 9 | '[':']', 10 | '{':'}' 11 | } 12 | for(let i = 0; i < s.length; i++){ 13 | if (s[i] in pairs){ 14 | stack.push(s[i]) 15 | } 16 | else if (stack.length == 0 || s[i] != pairs[stack.pop()]){ 17 | return false 18 | } 19 | } 20 | return stack.length == 0 21 | } -------------------------------------------------------------------------------- /Solutions/JavaScript/297.serialize-and-deserialize-binary-tree.js: -------------------------------------------------------------------------------- 1 | /* 2 | * @lc app=leetcode id=297 lang=javascript 3 | * 4 | * [297] Serialize and Deserialize Binary Tree 5 | */ 6 | 7 | // @lc code=start 8 | /** 9 | * Definition for a binary tree node. 10 | * function TreeNode(val) { 11 | * this.val = val; 12 | * this.left = this.right = null; 13 | * } 14 | */ 15 | 16 | /** 17 | * Encodes a tree to a single string. 18 | * 19 | * @param {TreeNode} root 20 | * @return {string} 21 | */ 22 | var serialize = function (root) { 23 | return JSON.stringify(root); 24 | }; 25 | 26 | /** 27 | * Decodes your encoded data to tree. 28 | * 29 | * @param {string} data 30 | * @return {TreeNode} 31 | */ 32 | var deserialize = function (data) { 33 | return JSON.parse(data); 34 | }; 35 | 36 | /** 37 | * Your functions will be called as such: 38 | * deserialize(serialize(root)); 39 | */ 40 | // @lc code=end 41 | -------------------------------------------------------------------------------- /Solutions/Kotlin/217-Contains Duplicate.kt: -------------------------------------------------------------------------------- 1 | 2 | /**When we change the array to "Set". The new Set will implicitly remove duplicate elements. 3 | We check the size of the Array and the size of the Set, if the size of the array bigger then it means it has duplicates.**/ 4 | 5 | class Solution { 6 | fun containsDuplicate(nums: IntArray) = nums.size > nums.toSet().size 7 | } 8 | -------------------------------------------------------------------------------- /Solutions/python3/1-two-sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, nums: List[int], target: int) -> List[int]: 3 | d = {} # val -> index 4 | 5 | for i, n in enumerate(nums): 6 | diff = target - n 7 | if diff in d: 8 | return [d[diff], i] 9 | d[n] = i 10 | 11 | #Time Complexity : O(N) 12 | #Space Complexity : O(N) 13 | -------------------------------------------------------------------------------- /Solutions/python3/100-same-tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: 3 | 4 | def rec(node1,node2): 5 | if not node1 and not node2: 6 | return True 7 | elif not node1 and node2 or not node2 and node1: 8 | return False 9 | elif node1.val != node2.val : 10 | return False 11 | else: 12 | return rec(node1.left,node2.left ) and rec(node1.right,node2.right) 13 | return(rec(p,q)) 14 | 15 | #Time Complexity :O(N) 16 | #Space Complexity:O(1) 17 | -------------------------------------------------------------------------------- /Solutions/python3/102-binary-tree-level.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: 3 | 4 | q=collections.deque() 5 | q.append(root) 6 | result=[] 7 | while q: 8 | qlen=len(q) 9 | level=[] 10 | for i in range(qlen): 11 | node=q.popleft() 12 | 13 | if node: 14 | level.append(node.val) 15 | if node.left: 16 | q.append(node.left) 17 | if node.right: 18 | q.append(node.right) 19 | if level: 20 | result.append(level) 21 | return result 22 | 23 | #Time Complexity :O(N) 24 | #Space Complexity:O(N) 25 | 26 | -------------------------------------------------------------------------------- /Solutions/python3/104-maximum-depth-tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxDepth(self, root: Optional[TreeNode]) -> int: 3 | def rec(node,s): 4 | if node is None: 5 | return s 6 | return max(rec(node.left,s+1),rec(node.right,s+1)) 7 | maxs=rec(root,0) 8 | return maxs 9 | #Time Complexity :O(N) 10 | #Space Complexity:O(1) 11 | -------------------------------------------------------------------------------- /Solutions/python3/105-construct-binary-tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]: 3 | if not preorder or not inorder: 4 | return None 5 | 6 | root = TreeNode(preorder[0]) 7 | mid = inorder.index(preorder[0]) 8 | root.left = self.buildTree(preorder[1 : mid + 1], inorder[:mid]) 9 | root.right = self.buildTree(preorder[mid + 1 :], inorder[mid + 1 :]) 10 | return root 11 | 12 | 13 | #Time Complexity :O(N) 14 | #Space Complexity:O(1) 15 | 16 | -------------------------------------------------------------------------------- /Solutions/python3/108.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortedArrayToBST(self, nums: List[int]) -> TreeNode: 3 | if not nums: 4 | return None 5 | mid = len(nums) // 2 6 | root = TreeNode(nums[mid]) 7 | root.left = self.sortedArrayToBST(nums[:mid]) 8 | root.right = self.sortedArrayToBST(nums[mid+1:]) 9 | return root 10 | -------------------------------------------------------------------------------- /Solutions/python3/11-Container-water.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxArea(self, height: List[int]) -> int: 3 | left,right=0,len(height)-1 4 | maxValue=0 5 | while left < right: 6 | value=((min(height[left],height[right])) * (right-left) ) 7 | maxValue=max(maxValue,value) 8 | 9 | if height[left]<=height[right]: 10 | left+=1 11 | else: 12 | right-=1 13 | return(maxValue) 14 | 15 | 16 | #Time Complexity : O(N) 17 | #Space Complexity : O(1) 18 | -------------------------------------------------------------------------------- /Solutions/python3/110.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def isBalanced(self, root: Optional[TreeNode]) -> bool: 9 | def dfs(root): 10 | if not root: 11 | return [True, 0] 12 | 13 | left, right = dfs(root.left), dfs(root.right) 14 | balanced = left[0] and right[0] and abs(left[1] - right[1]) <= 1 15 | return [balanced, 1 + max(left[1], right[1])] 16 | 17 | return dfs(root)[0] 18 | -------------------------------------------------------------------------------- /Solutions/python3/113.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | 4 | def helper(self, node, visited): 5 | if node is None: 6 | return None 7 | 8 | newNode = Node(node.val) 9 | visited[node.val] = newNode 10 | 11 | for adjNode in node.neighbors: 12 | if adjNode.val not in visited: 13 | newNode.neighbors.append(self.helper(adjNode, visited)) 14 | else: 15 | newNode.neighbors.append(visited[adjNode.val]) 16 | 17 | return newNode 18 | 19 | def cloneGraph(self, node: 'Node') -> 'Node': 20 | return self.helper(node, {}) 21 | -------------------------------------------------------------------------------- /Solutions/python3/1143-longest-common-subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestCommonSubsequence(self, text1: str, text2: str) -> int: 3 | dp = [[0 for j in range(len(text2)+1)] for i in range(len(text1)+1)] 4 | 5 | for i in range(len(text1)-1,-1,-1): 6 | for j in range(len(text2)-1,-1,-1): 7 | if text1[i] == text2[j]: 8 | dp[i][j] = 1 + dp[i+1][j+1] 9 | else: 10 | dp[i][j] = max(dp[i][j+1],dp[i+1][j]) 11 | return dp[0][0] 12 | -------------------------------------------------------------------------------- /Solutions/python3/118.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def generate(self, numRows: int) -> List[List[int]]: 3 | Pascal = [[0 for j in range(i)] for i in range(1, numRows+1)] 4 | for i in range(numRows): 5 | row = [1] * (i+1) 6 | for j in range(1, i): 7 | row[j] = Pascal[i-1][j-1] + Pascal[i-1][j] 8 | Pascal[i] = row 9 | return Pascal 10 | -------------------------------------------------------------------------------- /Solutions/python3/1189.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxNumberOfBalloons(self, text: str) -> int: 3 | d={} 4 | wordCnt={} 5 | word="balloon" 6 | for i in text: 7 | d[i]=1+d.get(i,0) 8 | for i in word: 9 | if i in d: 10 | wordCnt[i]=d[i] 11 | if sum(wordCnt.values())>=len(word): 12 | return((min(wordCnt['b'],wordCnt['a'],wordCnt['l']//2,wordCnt['o']//2,wordCnt['n']))) 13 | else: 14 | return(0) 15 | 16 | -------------------------------------------------------------------------------- /Solutions/python3/121-sell-and-buy.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices: List[int]) -> int: 3 | res = 0 4 | 5 | lowest = prices[0] 6 | for price in prices: 7 | if price < lowest: 8 | lowest = price 9 | res = max(res, price - lowest) 10 | return res 11 | 12 | #Time complexity: O(N) 13 | #Space Complexity : O(1) 14 | -------------------------------------------------------------------------------- /Solutions/python3/122.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices: List[int]) -> int: 3 | l,r=0,1 4 | profit=0 5 | while r < len(prices): 6 | if prices[l] int: 3 | res = [root.val] 4 | 5 | # return max path sum without split 6 | def dfs(root): 7 | if not root: 8 | return 0 9 | 10 | leftMax = dfs(root.left) 11 | rightMax = dfs(root.right) 12 | leftMax = max(leftMax, 0) 13 | rightMax = max(rightMax, 0) 14 | 15 | # compute max path sum WITH split 16 | res[0] = max(res[0], root.val + leftMax + rightMax) 17 | return root.val + max(leftMax, rightMax) 18 | 19 | dfs(root) 20 | return res[0] 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /Solutions/python3/128-longest-sequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestConsecutive(self, nums: List[int]) -> int: 3 | maximum = 0 4 | setNm = set(nums) 5 | for n in nums: 6 | if n-1 not in setNm: 7 | i = 0 8 | while n+i in setNm: 9 | setNm.remove(n+i) 10 | i+=1 11 | maximum = max(maximum,i) 12 | return maximum 13 | 14 | #Time Complexity : O(N) 15 | #Space Complexity : O(N) 16 | -------------------------------------------------------------------------------- /Solutions/python3/129.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def sumNumbers(self, root: Optional[TreeNode] , val = 0) -> int: 9 | if not root: 10 | return 0 11 | q = [root] 12 | sum = 0 13 | while(q): 14 | node = q.pop() 15 | if not node.left and not node.right: 16 | sum+=node.val 17 | 18 | if node.left: 19 | node.left.val += node.val*10 20 | q.append(node.left) 21 | if node.right: 22 | node.right.val += node.val*10 23 | q.append(node.right) 24 | return sum 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /Solutions/python3/1299.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def replaceElements(self, arr: List[int]) -> List[int]: 3 | rightMax=-1 4 | for i in range(len(arr)-1,-1,-1): 5 | intialValue=arr[i] 6 | arr[i]=rightMax 7 | rightMax=max(intialValue,arr[i]) 8 | return(arr) 9 | -------------------------------------------------------------------------------- /Solutions/python3/133-clone-graph.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def cloneGraph(self, node: "Node") -> "Node": 3 | oldToNew = {} 4 | 5 | def dfs(node): 6 | if node in oldToNew: 7 | return oldToNew[node] 8 | 9 | copy = Node(node.val) 10 | oldToNew[node] = copy 11 | for nei in node.neighbors: 12 | copy.neighbors.append(dfs(nei)) 13 | return copy 14 | 15 | return dfs(node) if node else None 16 | -------------------------------------------------------------------------------- /Solutions/python3/134.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: 3 | 4 | 5 | if sum(gas) < sum(cost): 6 | return -1 7 | 8 | gas_tank, start_index = 0, 0 9 | 10 | for i in range(len(gas)): 11 | 12 | gas_tank += gas[i] - cost[i] 13 | 14 | 15 | if gas_tank < 0: 16 | 17 | start_index = i + 1 18 | gas_tank = 0 19 | 20 | return start_index 21 | 22 | -------------------------------------------------------------------------------- /Solutions/python3/1343.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int: 3 | windSum=0 4 | MaxC=0 5 | for i in range(k): 6 | windSum+=arr[i] 7 | if windSum//k >=threshold: 8 | MaxC+=1 9 | for i in range(k,len(arr)): 10 | windSum=windSum-arr[i-k]+arr[i] 11 | if windSum//k >=threshold: 12 | MaxC+=1 13 | continue 14 | return(MaxC) 15 | -------------------------------------------------------------------------------- /Solutions/python3/139-word-break.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def wordBreak(self, s: str, wordDict: List[str]) -> bool: 3 | 4 | dp = [False] * (len(s) + 1) 5 | dp[len(s)] = True 6 | 7 | for i in range(len(s) - 1, -1, -1): 8 | for w in wordDict: 9 | if (i + len(w)) <= len(s) and s[i : i + len(w)] == w: 10 | dp[i] = dp[i + len(w)] 11 | if dp[i]: 12 | break 13 | 14 | return dp[0] 15 | -------------------------------------------------------------------------------- /Solutions/python3/14-Longest-Prefix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestCommonPrefix(self, strs: List[str]) -> str: 3 | res="" 4 | for i in range(len(strs[0])): 5 | for s in strs: 6 | if i==len(s) or s[i] != strs[0][i]: 7 | return res 8 | res+=strs[0][i] 9 | return res 10 | 11 | 12 | -------------------------------------------------------------------------------- /Solutions/python3/141-linked-cycle.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hasCycle(self, head: ListNode) -> bool: 3 | slow, fast = head, head 4 | 5 | while fast and fast.next: 6 | slow = slow.next 7 | fast = fast.next.next 8 | if slow == fast: 9 | return True 10 | return False 11 | #Time Complexity :O(N) 12 | #Space Complexity:O(1) 13 | -------------------------------------------------------------------------------- /Solutions/python3/1448.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def goodNodes(self, root: TreeNode) -> int: 9 | maxval=root.val 10 | count=0 11 | def isgood(root,maxval): 12 | nonlocal count 13 | if root is None: 14 | return 15 | if root.val>= maxval: 16 | count+=1 17 | maxval=root.val 18 | isgood(root.left,maxval) 19 | isgood(root.right,maxval) 20 | isgood(root,maxval) 21 | return count 22 | -------------------------------------------------------------------------------- /Solutions/python3/1461.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hasAllCodes(self, s: str, k: int) -> bool: 3 | codeSet=set() 4 | for i in range(len(s)-k+1): 5 | codeSet.add(s[i:i+k]) 6 | if len(codeSet)==2**k: 7 | return(True) 8 | else: 9 | return(False) 10 | -------------------------------------------------------------------------------- /Solutions/python3/147.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]: 8 | dummy=ListNode(0,head) 9 | prev=head 10 | cur=head.next 11 | 12 | while cur : 13 | if cur.val >= prev.val: 14 | prev=cur 15 | cur=cur.next 16 | continue 17 | temp=dummy 18 | while cur.val >temp.next.val: 19 | temp=temp.next 20 | prev.next=cur.next 21 | cur.next=temp.next 22 | temp.next=cur 23 | cur=prev.next 24 | return(dummy.next) 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /Solutions/python3/1498.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numSubseq(self, nums: List[int], target: int) -> int: 3 | i,j=0,len(nums)-1 4 | c,mod=0,(10**9+7) 5 | nums.sort() 6 | while i<=j: 7 | if nums[i]+nums[j]<=target: 8 | c+=pow(2,(j-i),mod) 9 | i+=1 10 | else: 11 | j-=1 12 | return c%mod 13 | -------------------------------------------------------------------------------- /Solutions/python3/150.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def evalRPN(self, tokens: List[str]) -> int: 3 | stack=[] 4 | for c in tokens: 5 | if c =="+": 6 | num1=stack.pop() 7 | num2=stack.pop() 8 | stack.append(num2+num1) 9 | elif c =="-": 10 | num1=stack.pop() 11 | num2=stack.pop() 12 | stack.append(num2-num1) 13 | elif c =="*": 14 | num1=stack.pop() 15 | num2=stack.pop() 16 | stack.append(num2*num1) 17 | elif c =="/": 18 | num1=stack.pop() 19 | num2=stack.pop() 20 | stack.append(int(num2/num1)) 21 | else: 22 | stack.append(int(c)) 23 | return (stack.pop()) 24 | -------------------------------------------------------------------------------- /Solutions/python3/152-maximum-product-subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProduct(self, nums: List[int]) -> int: 3 | if len(nums)==0: 4 | return 0 5 | 6 | max_pro , min_pro = nums[0], nums[0] 7 | 8 | #result will store the final max product 9 | result = max_pro 10 | 11 | for i in range(1, len(nums)): 12 | current = nums[i] 13 | 14 | temp_max = max( current , max_pro*current, current*min_pro) 15 | 16 | min_pro = min( current , max_pro*current, current*min_pro) 17 | 18 | max_pro = temp_max 19 | 20 | result = max(result, max_pro) 21 | 22 | return result 23 | -------------------------------------------------------------------------------- /Solutions/python3/153-minimum-window.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findMin(self, nums: List[int]) -> int: 3 | left, right = 0, len(nums) - 1 4 | while left < right: 5 | mid = left + (right - left) // 2 6 | if nums[mid] > nums[right]: 7 | left = mid + 1 8 | else: 9 | right = mid 10 | return nums[left] 11 | 12 | #Time complexity:O(logN) 13 | #Space complexity:O(1) 14 | -------------------------------------------------------------------------------- /Solutions/python3/155.py: -------------------------------------------------------------------------------- 1 | class MinStack: 2 | def __init__(self): 3 | self.minStack = [] 4 | def push(self, val: int) -> None: 5 | self.minStack.append(val) 6 | 7 | def pop(self) -> None: 8 | if self.minStack: 9 | self.minStack.pop() 10 | 11 | def top(self) -> int: 12 | return(self.minStack[-1]) 13 | 14 | def getMin(self) -> int: 15 | return(min(self.minStack)) 16 | # Your MinStack object will be instantiated and called as such: 17 | # obj = MinStack() 18 | # obj.push(val) 19 | # obj.pop() 20 | # param_3 = obj.top() 21 | # param_4 = obj.getMin() 22 | -------------------------------------------------------------------------------- /Solutions/python3/160.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | 8 | class Solution: 9 | def getIntersectionNode( 10 | self, headA: ListNode, headB: ListNode 11 | ) -> Optional[ListNode]: 12 | l1, l2 = headA, headB 13 | while l1 != l2: 14 | l1 = l1.next if l1 else headB 15 | l2 = l2.next if l2 else headA 16 | return l1 17 | -------------------------------------------------------------------------------- /Solutions/python3/167-Two-Sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def twoSum(self, numbers: List[int], target: int) -> List[int]: 3 | low=0 4 | high=len(numbers)-1 5 | while lowtarget: 10 | high-=1 11 | elif numSum int: 3 | count = 0 4 | candidate = None 5 | 6 | for num in nums: 7 | if count == 0: 8 | candidate = num 9 | count += (1 if num == candidate else -1) 10 | 11 | return candidate 12 | -------------------------------------------------------------------------------- /Solutions/python3/179.py: -------------------------------------------------------------------------------- 1 | class LargerNumKey(str): 2 | def __lt__(x, y): 3 | # Compare x+y with y+x in reverse order to get descending order 4 | return x+y > y+x 5 | 6 | class Solution: 7 | def largestNumber(self, nums: List[int]) -> str: 8 | # Convert the list of numbers to list of strings 9 | nums = [str(num) for num in nums] 10 | 11 | # Sort the list of strings using our custom sorting function 12 | nums.sort(key=LargerNumKey) 13 | 14 | # Join the sorted list of strings to form the final result 15 | largest_num = ''.join(nums) 16 | 17 | # If the largest number is 0, return "0" 18 | # Otherwise, return the largest number 19 | return "0" if largest_num[0] == "0" else largest_num 20 | -------------------------------------------------------------------------------- /Solutions/python3/1838.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxFrequency(self, nums: List[int], k: int) -> int: 3 | nums.sort() 4 | n = len(nums) 5 | sum_s_w = nums[0] 6 | fin = 1 7 | i=0 8 | for j in range(1,n): 9 | sum_s_w+=nums[j] 10 | mx = nums[j] 11 | while sum_s_w+k List[str]: 3 | freq = {} 4 | for i in range(len(s) - 9): 5 | substring = s[i:i+10] 6 | freq[substring] = freq.get(substring, 0) + 1 7 | return [substring for substring in freq if freq[substring] > 1] 8 | -------------------------------------------------------------------------------- /Solutions/python3/189.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rotate(self, nums: List[int], k: int) -> None: 3 | for i in range(k): 4 | temp=nums[-1] 5 | nums.pop(len(nums)-1) 6 | nums.insert(0,temp) 7 | return(nums) 8 | -------------------------------------------------------------------------------- /Solutions/python3/19-remove-node.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: 3 | dummy = ListNode() 4 | dummy.next = head 5 | 6 | pnt1, pnt2 = dummy, head 7 | for _ in range(n): 8 | pnt2 = pnt2.next 9 | 10 | while pnt2: 11 | pnt1, pnt2 = pnt1.next, pnt2.next 12 | 13 | pnt1.next = pnt1.next.next 14 | return dummy.next 15 | 16 | #Time Complexity :O(N) 17 | #Space Complexity:O(1) 18 | -------------------------------------------------------------------------------- /Solutions/python3/190-Reverse-Bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseBits(self, n: int) -> int: 3 | res = 0 4 | for i in range(32): 5 | bit = (n >> i) & 1 6 | res += (bit << (31 - i)) 7 | return res 8 | -------------------------------------------------------------------------------- /Solutions/python3/191-Number-of-Bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def hammingWeight(self, n: int) -> int: 3 | return(bin(n).count('1')) 4 | 5 | -------------------------------------------------------------------------------- /Solutions/python3/1930.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def countPalindromicSubsequence(self, s): 3 | d=defaultdict(list) 4 | for i,c in enumerate(s): 5 | d[c].append(i) 6 | ans=0 7 | for el in d: 8 | if len(d[el])<2: 9 | continue 10 | a=d[el][0] 11 | b=d[el][-1] 12 | ans+=len(set(s[a+1:b])) 13 | return(ans) 14 | 15 | -------------------------------------------------------------------------------- /Solutions/python3/1968.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rearrangeArray(self, nums: List[int]) -> List[int]: 3 | nums.sort() 4 | for i in range(1, len(nums), 2): 5 | nums[i], nums[i - 1] = nums[i - 1], nums[i] 6 | 7 | return nums 8 | -------------------------------------------------------------------------------- /Solutions/python3/198-house-robber.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rob(self, nums: List[int]) -> int: 3 | rob1, rob2 = 0, 0 4 | 5 | for n in nums: 6 | temp = max(n + rob1, rob2) 7 | rob1 = rob2 8 | rob2 = temp 9 | return rob2 10 | -------------------------------------------------------------------------------- /Solutions/python3/2.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: 8 | dummy=ListNode() 9 | head=dummy 10 | val,carry=0,0 11 | 12 | while l1 or l2 or carry: 13 | val1=l1.val if l1 else 0 14 | val2=l2.val if l2 else 0 15 | 16 | val=val1+val2+carry 17 | 18 | carry=val//10 19 | val=val%10 20 | head.next=ListNode(val) 21 | 22 | head=head.next 23 | 24 | if l1 : l1=l1.next 25 | if l2 : l2=l2.next 26 | return dummy.next 27 | -------------------------------------------------------------------------------- /Solutions/python3/20-valid-parentheses.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isValid(self, s: str) -> bool: 3 | Map = {")": "(", "]": "[", "}": "{"} 4 | stack = [] 5 | 6 | for c in s: 7 | if c not in Map: 8 | stack.append(c) 9 | continue 10 | if not stack or stack[-1] != Map[c]: 11 | return False 12 | stack.pop() 13 | 14 | return not stack 15 | 16 | #Time:O(N) 17 | #Space:O(N) 18 | -------------------------------------------------------------------------------- /Solutions/python3/200-number-islands.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numIslands(self, grid: List[List[str]]) -> int: 3 | islands = 0 4 | visit = set() 5 | rows, cols = len(grid), len(grid[0]) 6 | 7 | def dfs(r, c): 8 | if ( 9 | r not in range(rows) 10 | or c not in range(cols) 11 | or grid[r][c] == "0" 12 | or (r, c) in visit 13 | ): 14 | return 15 | 16 | visit.add((r, c)) 17 | directions = [[0, 1], [0, -1], [1, 0], [-1, 0]] 18 | for dr, dc in directions: 19 | dfs(r + dr, c + dc) 20 | 21 | for r in range(rows): 22 | for c in range(cols): 23 | if grid[r][c] == "1" and (r, c) not in visit: 24 | islands += 1 25 | dfs(r, c) 26 | return islands 27 | 28 | -------------------------------------------------------------------------------- /Solutions/python3/2002.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProduct(self, s: str) -> int: 3 | subs = [] 4 | n = len(s) 5 | def dfs(curr, ind, inds): 6 | if ind == n: 7 | if curr == curr[::-1]: 8 | subs.append((curr, inds)) 9 | return 10 | dfs(curr+s[ind], ind+1, inds|{ind}) 11 | dfs(curr, ind+1, inds) 12 | 13 | dfs('', 0, set()) 14 | 15 | res = 0 16 | n = len(subs) 17 | for i in range(n): 18 | s1, i1 = subs[i] 19 | for j in range(i+1, n): 20 | s2, i2 = subs[j] 21 | if len(i1 & i2) == 0: 22 | res = max(res, len(s1)*len(s2)) 23 | return res 24 | -------------------------------------------------------------------------------- /Solutions/python3/2017.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def gridGame(self, grid): 3 | 4 | top, bottom = grid 5 | top_sum = sum(top) 6 | bottom_sum = 0 7 | res = float('inf') 8 | 9 | for i in range(len(top)): 10 | top_sum -= top[i] 11 | res = min(res, max(top_sum, bottom_sum)) 12 | bottom_sum += bottom[i] 13 | 14 | return res 15 | -------------------------------------------------------------------------------- /Solutions/python3/203.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]: 8 | cur = head 9 | while cur and cur.next: 10 | if cur.next.val == val: 11 | cur.next = cur.next.next 12 | else: 13 | cur = cur.next 14 | if head and head.val == val: 15 | return head.next 16 | return head 17 | 18 | -------------------------------------------------------------------------------- /Solutions/python3/205-Isomorphic-Strings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isIsomorphic(self, s: str, t: str) -> bool: 3 | ds,dt={},{} 4 | 5 | for i in range(len(s)): 6 | 7 | if (s[i] in ds and ds[s[i]]!=t[i]) or (t[i] in dt and dt[t[i]] != s[i]): 8 | return False 9 | 10 | ds[s[i]]=t[i] 11 | dt[t[i]]=s[i] 12 | return True 13 | -------------------------------------------------------------------------------- /Solutions/python3/206-reverse-linkedlist.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseList(self, head: ListNode) -> ListNode: 3 | prev, curr = None, head 4 | 5 | while curr: 6 | temp = curr.next 7 | curr.next = prev 8 | prev = curr 9 | curr = temp 10 | return prev 11 | 12 | #Time Complexity :O(1) 13 | #Space Complexity:O(1) 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /Solutions/python3/207-course-schedule.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: 3 | # dfs 4 | preMap = {i: [] for i in range(numCourses)} 5 | 6 | # map each course to : prereq list 7 | for crs, pre in prerequisites: 8 | preMap[crs].append(pre) 9 | 10 | visiting = set() 11 | 12 | def dfs(crs): 13 | if crs in visiting: 14 | return False 15 | if preMap[crs] == []: 16 | return True 17 | 18 | visiting.add(crs) 19 | for pre in preMap[crs]: 20 | if not dfs(pre): 21 | return False 22 | visiting.remove(crs) 23 | preMap[crs] = [] 24 | return True 25 | 26 | for c in range(numCourses): 27 | if not dfs(c): 28 | return False 29 | return True 30 | -------------------------------------------------------------------------------- /Solutions/python3/209.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minSubArrayLen(self, target: int, nums: List[int]) -> int: 3 | n=len(nums) 4 | i=j=0 5 | s=nums[0] 6 | m=9999999 7 | while j=target: 9 | m=min(m,j-i+1) 10 | s-=nums[i] 11 | i+=1 12 | else: 13 | j+=1 14 | if j ListNode: 3 | dummy = ListNode() 4 | tail = dummy 5 | 6 | while list1 and list2: 7 | if list1.val < list2.val: 8 | tail.next = list1 9 | list1 = list1.next 10 | else: 11 | tail.next = list2 12 | list2 = list2.next 13 | tail = tail.next 14 | 15 | if list1: 16 | tail.next = list1 17 | elif list2: 18 | tail.next = list2 19 | 20 | return dummy.next 21 | 22 | #Time Complexity :O(N) 23 | #Space Complexity:O(N) 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /Solutions/python3/213-house-robber_2.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def rob(self, nums: List[int]) -> int: 3 | return max(nums[0], self.helper(nums[1:]), self.helper(nums[:-1])) 4 | 5 | def helper(self, nums): 6 | rob1, rob2 = 0, 0 7 | 8 | for n in nums: 9 | newRob = max(rob1 + n, rob2) 10 | rob1 = rob2 11 | rob2 = newRob 12 | return rob2 13 | -------------------------------------------------------------------------------- /Solutions/python3/215.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | class Solution: 3 | def findKthLargest(self, nums: List[int], k: int) -> int: 4 | heapq.heapify(nums) 5 | res=heapq.nlargest(k,nums) 6 | return(res[-1]) 7 | -------------------------------------------------------------------------------- /Solutions/python3/217-contains-duplicate.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def containsDuplicate(self, nums: List[int]) -> bool: 3 | hashSet=set() 4 | 5 | for n in nums : 6 | if n in hashSet: 7 | return True 8 | hashSet.add(n) 9 | return False 10 | 11 | #Time complexity : O(N) 12 | #Space complexity : O(N) 13 | -------------------------------------------------------------------------------- /Solutions/python3/219-Contains-Duplicate.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: 3 | d={} 4 | for i in range(len(nums)): 5 | if nums[i] in d: 6 | if i -d[nums[i]] <= k: 7 | return(True) 8 | d[nums[i]]=i 9 | return(False) 10 | -------------------------------------------------------------------------------- /Solutions/python3/22.py: -------------------------------------------------------------------------------- 1 | def generateParenthesis(self, n: int) -> List[str]: 2 | def dfs(left, right, s): 3 | if len(s) == n * 2: 4 | res.append(s) 5 | return 6 | 7 | if left < n: 8 | dfs(left + 1, right, s + '(') 9 | 10 | if right < left: 11 | dfs(left, right + 1, s + ')') 12 | 13 | res = [] 14 | dfs(0, 0, '') 15 | return res 16 | -------------------------------------------------------------------------------- /Solutions/python3/225.py: -------------------------------------------------------------------------------- 1 | class MyStack: 2 | 3 | def __init__(self): 4 | self.q=deque() 5 | def push(self, x: int) -> None: 6 | self.q.append(x) 7 | 8 | def pop(self) -> int: 9 | for i in range(len(self.q)-1): 10 | self.push(self.q.popleft()) 11 | return(self.q.popleft()) 12 | 13 | def top(self) -> int: 14 | return(self.q[-1]) 15 | 16 | def empty(self) -> bool: 17 | return (len(self.q))==0 18 | 19 | # Your MyStack object will be instantiated and called as such: 20 | # obj = MyStack() 21 | # obj.push(x) 22 | # param_2 = obj.pop() 23 | # param_3 = obj.top() 24 | # param_4 = obj.empty() 25 | -------------------------------------------------------------------------------- /Solutions/python3/226-invert-binary-tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: 3 | 4 | def rec(node): 5 | if node is None: 6 | return 7 | tempnode=node.left 8 | node.left=node.right 9 | node.right=tempnode 10 | rec(node.left) 11 | rec(node.right) 12 | rec(root) 13 | return root 14 | 15 | #Time Complexity :O(N) 16 | #Space Complexity:O(1) 17 | -------------------------------------------------------------------------------- /Solutions/python3/230-kth-smallest.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: 3 | l=[] 4 | def node(root): 5 | if root is None: 6 | return 7 | nonlocal l 8 | node(root.left) 9 | l.append(root.val) 10 | node(root.right) 11 | node(root) 12 | return(l[k-1]) 13 | 14 | #Time Complexity :O(N) 15 | #Space Complexity:O(N) 16 | -------------------------------------------------------------------------------- /Solutions/python3/235-lowest-common-ancestor.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 4 | if (p.val == root.val) or (q.val == root.val) or (p.val < root.val and root.val < q.val) or (q.val < root.val and root.val < p.val): 5 | return root 6 | if p.val < root.val and q.val < root.val: 7 | return self.lowestCommonAncestor(root.left, p, q) 8 | else: 9 | return self.lowestCommonAncestor(root.right, p, q) 10 | 11 | 12 | #Time Complexity :O(logN) 13 | #Space Complexity:O(1) 14 | 15 | 16 | -------------------------------------------------------------------------------- /Solutions/python3/238-Product-except.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def productExceptSelf(self, nums: List[int]) -> List[int]: 3 | res = [1] * (len(nums)) 4 | 5 | prefix = 1 6 | for i in range(len(nums)): 7 | res[i] = prefix 8 | prefix *= nums[i] 9 | postfix = 1 10 | for i in range(len(nums) - 1, -1, -1): 11 | res[i] *= postfix 12 | postfix *= nums[i] 13 | return res 14 | 15 | 16 | #Time Complexity : O(N) 17 | #Space Complexity : O(N) 18 | -------------------------------------------------------------------------------- /Solutions/python3/24.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: 8 | 9 | 10 | dummy=ListNode(0,head) 11 | prev=dummy 12 | while prev.next and prev.next.next: 13 | a,b=prev.next,prev.next.next 14 | temp= a 15 | prev.next = b 16 | a.next,b.next=b.next,a 17 | prev=temp 18 | return dummy.next 19 | -------------------------------------------------------------------------------- /Solutions/python3/242-valid-anagram.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isAnagram(self, s: str, t: str) -> bool: 3 | if len(s) != len(t): 4 | return False 5 | 6 | ds, dt = {}, {} 7 | 8 | for i in range(len(s)): 9 | ds[s[i]] = 1 + ds.get(s[i], 0) 10 | dt[t[i]] = 1 + dt.get(t[i], 0) 11 | return ds == dt 12 | 13 | #Time Complexity : O(N) 14 | #Space Complexity : O(N) 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /Solutions/python3/252-meeting-rooms.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param intervals: an array of meeting time intervals 4 | @return: if a person could attend all meetings 5 | """ 6 | 7 | def canAttendMeetings(self, intervals): 8 | intervals.sort(key=lambda i: i[0]) 9 | 10 | for i in range(1, len(intervals)): 11 | i1 = intervals[i - 1] 12 | i2 = intervals[i] 13 | 14 | if i1[1] > i2[0]: 15 | return False 16 | return True 17 | -------------------------------------------------------------------------------- /Solutions/python3/253-meeting-rooms-ii.py: -------------------------------------------------------------------------------- 1 | def minMeetingRooms(self, intervals: List[List[int]]) -> int: 2 | time = [] 3 | for start, end in intervals: 4 | time.append((start, 1)) 5 | time.append((end, -1)) 6 | 7 | time.sort(key=lambda x: (x[0], x[1])) 8 | 9 | count = 0 10 | max_count = 0 11 | for t in time: 12 | count += t[1] 13 | max_count = max(max_count, count) 14 | return max_count 15 | -------------------------------------------------------------------------------- /Solutions/python3/26-Remove-Duplicates.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeDuplicates(self, nums: List[int]) -> int: 3 | end =len(nums) 4 | i=1 5 | while True: 6 | if(i==end): 7 | break 8 | if(nums[i]==nums[i-1]): 9 | nums.remove(nums[i]) 10 | i-=1 11 | end=len(nums) 12 | i+=1 13 | return(len(nums)) 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /Solutions/python3/261-valid-tree.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param n: An integer 4 | @param edges: a list of undirected edges 5 | @return: true if it's a valid tree, or false 6 | """ 7 | 8 | def validTree(self, n, edges): 9 | if not n: 10 | return True 11 | adj = {i: [] for i in range(n)} 12 | for n1, n2 in edges: 13 | adj[n1].append(n2) 14 | adj[n2].append(n1) 15 | 16 | visit = set() 17 | 18 | def dfs(i, prev): 19 | if i in visit: 20 | return False 21 | 22 | visit.add(i) 23 | for j in adj[i]: 24 | if j == prev: 25 | continue 26 | if not dfs(j, i): 27 | return False 28 | return True 29 | 30 | return dfs(0, -1) and n == len(visit) 31 | -------------------------------------------------------------------------------- /Solutions/python3/268-Missing-Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def missingNumber(self, nums: List[int]) -> int: 3 | n = len(nums) 4 | for i in range(n+1): 5 | if i not in nums: return i 6 | return n+1 7 | -------------------------------------------------------------------------------- /Solutions/python3/27.py: -------------------------------------------------------------------------------- 1 | def removeElement(self, nums: List[int], val: int) -> int: 2 | while val in nums: 3 | nums.remove(val) 4 | -------------------------------------------------------------------------------- /Solutions/python3/283-Move-Zeroes.py: -------------------------------------------------------------------------------- 1 | def moveZeroes(self, nums: List[int]) -> None: 2 | """ 3 | Do not return anything, modify nums in-place instead. 4 | """ 5 | l=0 6 | 7 | for r in range(len(nums)): 8 | if nums[r]: 9 | nums[r],nums[l]=nums[l],nums[r] 10 | l+=1 11 | 12 | -------------------------------------------------------------------------------- /Solutions/python3/287.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDuplicate(self, nums: List[int]) -> int: 3 | nums.sort() 4 | for i in range(len(nums)-1): 5 | if nums[i]==nums[i+1]: 6 | return (nums[i]) 7 | return(nums[0]) 8 | -------------------------------------------------------------------------------- /Solutions/python3/290-Word-Pattern.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def wordPattern(self, pattern: str, s: str) -> bool: 3 | dp,ds={},{} 4 | s=s.split() 5 | if len(pattern)!=len(s): 6 | return False 7 | for i in range(len(pattern)) : 8 | if pattern[i] in dp and dp[pattern[i]] != s[i] or s[i] in ds and ds[s[i]]!=pattern[i]: 9 | return False 10 | dp[pattern[i]]=s[i] 11 | ds[s[i]]=pattern[i] 12 | return True 13 | 14 | 15 | -------------------------------------------------------------------------------- /Solutions/python3/3-longest-substring.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLongestSubstring(self, s: str) -> int: 3 | HashSet = set() 4 | l = 0 5 | res = 0 6 | 7 | for r in range(len(s)): 8 | while s[r] in HashSet: 9 | HashSet.remove(s[l]) 10 | l += 1 11 | HashSet.add(s[r]) 12 | res = max(res, r - l + 1) 13 | return res 14 | 15 | #Time Complexity: O(N) 16 | #Space Complexity: O(N) 17 | -------------------------------------------------------------------------------- /Solutions/python3/300-longest-increasing-subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLIS(self, nums: List[int]) -> int: 3 | LIS = [1] * len(nums) 4 | 5 | for i in range(len(nums) - 1, -1, -1): 6 | for j in range(i + 1, len(nums)): 7 | if nums[i] < nums[j]: 8 | LIS[i] = max(LIS[i], 1 + LIS[j]) 9 | return max(LIS) 10 | -------------------------------------------------------------------------------- /Solutions/python3/303.py: -------------------------------------------------------------------------------- 1 | class NumArray: 2 | 3 | def __init__(self, nums: List[int]): 4 | self.nums=[0]+list(accumulate(nums)) 5 | print(self.nums) 6 | 7 | def sumRange(self, left: int, right: int) -> int: 8 | return self.nums[right+1]-self.nums[left] 9 | 10 | # Your NumArray object will be instantiated and called as such: 11 | # obj = NumArray(nums) 12 | # param_1 = obj.sumRange(left,right) 13 | -------------------------------------------------------------------------------- /Solutions/python3/322-coin-change.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def coinChange(self, coins: List[int], amount: int) -> int: 3 | 4 | dp = [amount+1 for i in range(amount+1)] 5 | 6 | dp[0] = 0 7 | 8 | for i in range(1,amount+1): 9 | for j in coins: 10 | 11 | if i==j: 12 | dp[i]=1 13 | break 14 | 15 | else: 16 | if i-j>=0: 17 | dp[i]= min(dp[i],1+dp[i-j]) 18 | 19 | if dp[amount]==amount+1: 20 | return -1 21 | return dp[amount] 22 | -------------------------------------------------------------------------------- /Solutions/python3/323-connected-components.py: -------------------------------------------------------------------------------- 1 | class UnionFind: 2 | def __init__(self): 3 | self.f = {} 4 | 5 | def findParent(self, x): 6 | y = self.f.get(x, x) 7 | if x != y: 8 | y = self.f[x] = self.findParent(y) 9 | return y 10 | 11 | def union(self, x, y): 12 | self.f[self.findParent(x)] = self.findParent(y) 13 | 14 | 15 | class Solution: 16 | def countComponents(self, n: int, edges: List[List[int]]) -> int: 17 | dsu = UnionFind() 18 | for a, b in edges: 19 | dsu.union(a, b) 20 | return len(set(dsu.findParent(x) for x in range(n))) 21 | -------------------------------------------------------------------------------- /Solutions/python3/33-Search-rotated.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def search(self, nums: List[int], target: int) -> int: 3 | def binarySearch(left, right, pivot) -> int: 4 | while left <= right: 5 | mid = left + (right - left) // 2 6 | if nums[(mid + pivot) % len(nums)] > target: 7 | right = mid - 1 8 | elif nums[(mid + pivot) % len(nums)] < target: 9 | left = mid + 1 10 | else: 11 | return (mid + pivot) % len(nums) 12 | return -1 13 | pivot = nums.index(min(nums)) 14 | left, right = 0, len(nums) - 1 15 | index = binarySearch(left, right, pivot) 16 | return index 17 | 18 | 19 | #Time:O(logN) 20 | #Space:O(1) 21 | -------------------------------------------------------------------------------- /Solutions/python3/338-Counting-Bits.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countBits(self, n: int) -> List[int]: 3 | arr=[0] 4 | for i in range(1,n+1): 5 | value=bin(i).count('1') 6 | arr.append(value) 7 | return arr 8 | -------------------------------------------------------------------------------- /Solutions/python3/344-Reverse-String.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverseString(self, s: List[str]) -> None: 3 | """ 4 | Do not return anything, modify s in-place instead. 5 | """ 6 | l = 0 7 | r = len(s) - 1 8 | while l <= r: 9 | s[l],s[r] = s[r],s[l] 10 | l += 1 11 | r -= 1 12 | -------------------------------------------------------------------------------- /Solutions/python3/347-K-frequent.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def topKFrequent(self, nums: List[int], k: int) -> List[int]: 3 | count =Counter(nums) 4 | freq = [[] for i in range(len(nums) + 1)] 5 | 6 | for n, c in count.items(): 7 | freq[c].append(n) 8 | 9 | res = [] 10 | for i in range(len(freq) - 1, 0, -1): 11 | for n in freq[i]: 12 | res.append(n) 13 | if len(res) == k: 14 | return res 15 | 16 | #Time Complexity : O(N) 17 | #Space Complexity : O(N) 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /Solutions/python3/35-Search-Insert-Position.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def searchInsert(self, nums: List[int], target: int) -> int: 3 | low=0 4 | high=len(nums)-1 5 | while low<=high: 6 | mid=int((low+high)/2) 7 | if(nums[mid]==target): 8 | return mid 9 | elif(nums[mid]target): 12 | high=mid-1 13 | if(target>nums[mid] and target bool: 3 | rows=collections.defaultdict(set) 4 | cols=collections.defaultdict(set) 5 | squares=collections.defaultdict(set) 6 | 7 | for i in range(9): 8 | for j in range(9): 9 | if board[i][j]==".": 10 | continue 11 | 12 | if board[i][j] in rows[i] or board[i][j] in cols[j] or board[i][j] in squares[(i//3,j//3)]: 13 | return False 14 | 15 | rows[i].add(board[i][j]) 16 | cols[j].add(board[i][j]) 17 | squares[(i//3,j//3)].add(board[i][j]) 18 | return True 19 | -------------------------------------------------------------------------------- /Solutions/python3/367.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isPerfectSquare(self, num: int) -> bool: 3 | num=num**0.5 4 | while(num>=1): 5 | if(num%1==0): 6 | return(True) 7 | else: 8 | return(False) 9 | 10 | -------------------------------------------------------------------------------- /Solutions/python3/371-Sum-Two-Integers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getSum(self, a: int, b: int) -> int: 3 | if a == 0 : 4 | return b 5 | 6 | if b == 0: 7 | return a 8 | 9 | 10 | carry = 0 11 | 12 | while b != 0 : 13 | carry = (a & b) << 1 14 | 15 | a = a ^ b 16 | b = carry 17 | 18 | return a 19 | 20 | -------------------------------------------------------------------------------- /Solutions/python3/374.py: -------------------------------------------------------------------------------- 1 | # The guess API is already defined for you. 2 | # @param num, your guess 3 | # @return -1 if num is higher than the picked number 4 | # 1 if num is lower than the picked number 5 | # otherwise return 0 6 | # def guess(num: int) -> int: 7 | 8 | class Solution: 9 | def guessNumber(self, n: int) -> int: 10 | 11 | low=0 12 | high=n 13 | while low<=high: 14 | mid=int((low+high)/2) 15 | if(guess(mid)==0): 16 | return mid 17 | elif(guess(mid)==1): 18 | low=mid+1 19 | elif(guess(mid)==-1): 20 | high=mid-1 21 | 22 | 23 | -------------------------------------------------------------------------------- /Solutions/python3/380.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | class RandomizedSet: 4 | 5 | def __init__(self): 6 | # Initialize Set 7 | self.sets = set() 8 | 9 | def insert(self, val: int) -> bool: 10 | # If n is present in set then return false 11 | if val in self.sets : 12 | return False 13 | 14 | # If n is not present in set then add it to the set. 15 | self.sets.add(val) 16 | return True 17 | 18 | def remove(self, val: int) -> bool: 19 | # If n is in set then remove n else return false 20 | if val in self.sets: 21 | self.sets.remove(val) 22 | return True 23 | return False 24 | 25 | def getRandom(self) -> int: 26 | # Return random number using random module 27 | return random.choice(list(self.sets)) 28 | -------------------------------------------------------------------------------- /Solutions/python3/39-combination-sum.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: 3 | result=[] 4 | 5 | def dfs(total,subset): 6 | if total==target: 7 | subset.sort() 8 | if (subset) not in result: 9 | result.append(subset) 10 | return True 11 | if total > target: 12 | return False 13 | diff=target-total 14 | for num in candidates: 15 | if num>diff: 16 | continue 17 | level=subset.copy() 18 | level.append(num) 19 | dfs(total+num,level) 20 | dfs(0,[]) 21 | return result 22 | 23 | -------------------------------------------------------------------------------- /Solutions/python3/392-Is-Subsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isSubsequence(self, s: str, t: str) -> bool: 3 | i=0 4 | for j in range(len(t)): 5 | if i < len(s) and s[i]==t[j]: 6 | i+=1 7 | return i==len(s) 8 | -------------------------------------------------------------------------------- /Solutions/python3/402.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def removeKdigits(self, num: str, k: int) -> str: 3 | stack = [] 4 | for n in num: 5 | while( stack and int(stack[-1]) > int(n) and k): 6 | stack.pop() 7 | k -= 1 8 | stack.append(str(n)) 9 | 10 | # If no elements are removed, pop last elements, (increasing order) 11 | while(k): 12 | stack.pop() 13 | k -= 1 14 | 15 | # removing leading zeros 16 | i = 0 17 | while( i 0) else "0" 21 | 22 | -------------------------------------------------------------------------------- /Solutions/python3/416.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canPartition(self, nums: List[int]) -> bool: 3 | summ = sum(nums) 4 | if summ%2: 5 | return False 6 | 7 | self.cache = {} 8 | 9 | return self.check(nums, 0, summ//2) 10 | 11 | 12 | def check(self, nums, i, target): 13 | if (i, target) in self.cache: 14 | return self.cache[(i, target)] 15 | 16 | if nums[i] == target: 17 | return True 18 | if target < 0 or i == len(nums)-1: 19 | return False 20 | 21 | result = self.check(nums, i+1, target - nums[i]) or self.check(nums, i+1, target) 22 | self.cache[(i, target)] = result 23 | 24 | return result 25 | -------------------------------------------------------------------------------- /Solutions/python3/424-longest-replacement.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def characterReplacement(self, s: str, k: int) -> int: 3 | count = {} 4 | res = 0 5 | 6 | l = 0 7 | maxf = 0 8 | for r in range(len(s)): 9 | count[s[r]] = 1 + count.get(s[r], 0) 10 | maxf = max(maxf, count[s[r]]) 11 | 12 | if (r - l + 1) - maxf > k: 13 | count[s[l]] -= 1 14 | l += 1 15 | 16 | res = max(res, r - l + 1) 17 | return res 18 | 19 | #Time Complexty : O(N) 20 | #Space Complexity: O(N) 21 | -------------------------------------------------------------------------------- /Solutions/python3/43.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def multiply(self, num1: str, num2: str) -> str: 3 | dic={ 4 | '1':1, 5 | '2':2, 6 | '3':3, 7 | '4':4, 8 | '5':5, 9 | '6':6, 10 | '7':7, 11 | '8':8, 12 | '9':9, 13 | '0':0 14 | } 15 | h=list(num1) 16 | l=list(num2) 17 | s=len(num1)-1 18 | s1=len(l)-1 19 | k=0 20 | k1=0 21 | p=0 22 | p1=0 23 | while h: 24 | r=h.pop(s) 25 | p1+=(10**k)*dic[r] 26 | k+=1 27 | s-=1 28 | while l: 29 | r=l.pop(s1) 30 | p+=(10**k1)*dic[r] 31 | k1+=1 32 | s1-=1 33 | return str((p1*p)) 34 | 35 | -------------------------------------------------------------------------------- /Solutions/python3/435-Non-overlapping-Intervals.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: 3 | intervals.sort(key = lambda x: x[1]) 4 | countDeleted, currEnd = 0, intervals[0][1] 5 | for start, end in intervals[1:]: 6 | if (start >= currEnd): 7 | currEnd = end 8 | else: 9 | countDeleted += 1 10 | return countDeleted 11 | -------------------------------------------------------------------------------- /Solutions/python3/438.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findAnagrams(self, s: str, p: str) -> List[int]: 3 | dp=Counter(p) 4 | ds={} 5 | 6 | l,r=0,0 7 | ans=[] 8 | 9 | while r int: 3 | l = 1 4 | h = n 5 | while l<=h: 6 | mid = l + (h-l)//2 7 | temp = int(mid*(mid+1)/2) 8 | if temp == n: 9 | return mid 10 | if temp < n: 11 | l = mid + 1 12 | else: 13 | h = mid - 1 14 | return h 15 | 16 | -------------------------------------------------------------------------------- /Solutions/python3/448.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDisappearedNumbers(self, nums: List[int]) -> List[int]: 3 | for n in nums: 4 | i=abs(n)-1 5 | nums[i]=-1*abs(nums[i]) 6 | res=[] 7 | for i ,n in enumerate(nums): 8 | if n>0: 9 | res.append(i+1) 10 | return(res) 11 | -------------------------------------------------------------------------------- /Solutions/python3/45.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def jump(self, nums: List[int]) -> int: 3 | n = len(nums) 4 | jumps = 0 5 | maxReach = 0 6 | curReach = 0 7 | for i in range(n - 1): 8 | maxReach = max(maxReach, i + nums[i]) 9 | if i == curReach: 10 | jumps += 1 11 | curReach = maxReach 12 | if curReach >= n - 1: 13 | return jumps 14 | if i >= maxReach: 15 | return 0 16 | return jumps 17 | -------------------------------------------------------------------------------- /Solutions/python3/49-Group-anagrams.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 3 | res = collections.defaultdict(list) 4 | 5 | for s in strs: 6 | count = [0] * 26 7 | for c in s: 8 | count[ord(c) - ord("a")] += 1 9 | res[tuple(count)].append(s) 10 | return res.values() 11 | 12 | #Time Complexity : O(N*m) 13 | #Space Complexity : O(N*m) 14 | -------------------------------------------------------------------------------- /Solutions/python3/494.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findTargetSumWays(self, nums: List[int], target: int) -> int: 3 | n = len(nums) 4 | cache = {} 5 | 6 | def dp(i, curr): 7 | if (i, curr) in cache: 8 | return cache[(i, curr)] 9 | if i == n: 10 | return int(curr == target) 11 | 12 | cache[(i,curr)] = dp(i+1, curr + nums[i]) + dp(i+1, curr - nums[i]) 13 | return cache[(i, curr)] 14 | 15 | return dp(0, 0) 16 | -------------------------------------------------------------------------------- /Solutions/python3/496-Next-Greater-Element.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]: 3 | ans={} 4 | res=[] 5 | stack=[] 6 | for num in nums2: 7 | while stack and num > stack[-1] : 8 | ans[stack.pop()]=num 9 | stack.append(num) 10 | for num in nums1: 11 | res.append(ans.get(num,-1)) 12 | return res 13 | -------------------------------------------------------------------------------- /Solutions/python3/5-longest-palindromic-substring.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestPalindrome(self, s: str) -> str: 3 | res = "" 4 | resLen = 0 5 | 6 | for i in range(len(s)): 7 | # odd length 8 | l, r = i, i 9 | while l >= 0 and r < len(s) and s[l] == s[r]: 10 | if (r - l + 1) > resLen: 11 | res = s[l : r + 1] 12 | resLen = r - l + 1 13 | l -= 1 14 | r += 1 15 | 16 | # even length 17 | l, r = i, i + 1 18 | while l >= 0 and r < len(s) and s[l] == s[r]: 19 | if (r - l + 1) > resLen: 20 | res = s[l : r + 1] 21 | resLen = r - l + 1 22 | l -= 1 23 | r += 1 24 | 25 | return res 26 | -------------------------------------------------------------------------------- /Solutions/python3/523.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkSubarraySum(self, nums: List[int], k: int) -> bool: 3 | n=len(nums) 4 | s=0 5 | d={0:-1} 6 | for i in range(n): 7 | s=(s+nums[i])%k 8 | if s not in d: 9 | d[s]=i 10 | else: 11 | if i-d[s]>1: 12 | return True 13 | return False 14 | -------------------------------------------------------------------------------- /Solutions/python3/53-maximum-subarray.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxSubArray(self, nums: List[int]) -> int: 3 | maxsub=float("-Inf") 4 | count=0 5 | for n in nums: 6 | count+=n 7 | maxsub=max(maxsub,count) 8 | if count<0: 9 | count=0 10 | return maxsub 11 | -------------------------------------------------------------------------------- /Solutions/python3/54-Spiral-Matrix.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def spiralOrder(self, matrix: List[List[int]]) -> List[int]: 3 | result = list() 4 | while len(matrix) > 0: 5 | try: 6 | result += matrix.pop(0) #remove the first nested list (top row) 7 | result += [x.pop(-1) for x in matrix] #remove every last element of the lists (right row) 8 | result += matrix.pop(-1)[::-1] #remove last nested list in reverse order (bottom row) 9 | result += [x.pop(0) for x in matrix][::-1] #remove every last element of the lists (left row) 10 | except: 11 | break #if at any moment the matrix is empty, break the loop and return the result array 12 | return result 13 | -------------------------------------------------------------------------------- /Solutions/python3/543.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int: 9 | res = 0 10 | 11 | def dfs(root): 12 | nonlocal res 13 | 14 | if not root: 15 | return 0 16 | left = dfs(root.left) 17 | right = dfs(root.right) 18 | res = max(res, left + right) 19 | 20 | return 1 + max(left, right) 21 | 22 | dfs(root) 23 | return res 24 | -------------------------------------------------------------------------------- /Solutions/python3/55-jump-game.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canJump(self, nums: List[int]) -> bool: 3 | goal = len(nums) - 1 4 | 5 | for i in range(len(nums) - 2, -1, -1): 6 | if i + nums[i] >= goal: 7 | goal = i 8 | return goal == 0 9 | -------------------------------------------------------------------------------- /Solutions/python3/554.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def leastBricks(self, wall: List[List[int]]) -> int: 3 | hm = {0:0} #Ensure hashmap isn't empty at end 4 | for row in wall: 5 | s = 0 6 | for brick in row[:-1]: 7 | s+=brick 8 | if not s in hm: 9 | hm[s] = 0 10 | hm[s] += 1 11 | return len(wall) - max(hm.values()) 12 | 13 | -------------------------------------------------------------------------------- /Solutions/python3/56-merge-Intervals.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def merge(self, intervals: List[List[int]]) -> List[List[int]]: 3 | intervals.sort(key=lambda pair: pair[0]) 4 | output = [intervals[0]] 5 | 6 | for start, end in intervals: 7 | lastEnd = output[-1][1] 8 | 9 | if start <= lastEnd: 10 | # merge 11 | output[-1][1] = max(lastEnd, end) 12 | else: 13 | output.append([start, end]) 14 | return output 15 | -------------------------------------------------------------------------------- /Solutions/python3/560.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subarraySum(self, nums: List[int], k: int) -> int: 3 | ans=0 4 | prefsum=0 5 | d={0:1} 6 | 7 | for num in nums: 8 | prefsum=prefsum+num 9 | 10 | if prefsum-k in d: 11 | ans+=d[prefsum-k] 12 | if prefsum not in d: 13 | d[prefsum]=1 14 | else: 15 | d[prefsum]= d[prefsum]+1 16 | return ans56 17 | -------------------------------------------------------------------------------- /Solutions/python3/567.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkInclusion(self, s1: str, s2: str) -> bool: 3 | if len(s1)>len(s2): 4 | return False 5 | d1={} 6 | d2={} 7 | for i in range(len(s1)): 8 | d1[s1[i]]= d1.get(s1[i],0)+1 9 | d2[s2[i]]= d2.get(s2[i],0)+1 10 | l=0 11 | if len(s1)==len(s2): 12 | return d1==d2 13 | for r in range(len(s1),len(s2)): 14 | if d1==d2: 15 | return True 16 | d2[s2[l]]-=1 17 | if d2[s2[l]] == 0: 18 | del d2[s2[l]] 19 | l+=1 20 | d2[s2[r]] = 1+d2.get(s2[r],0) 21 | if d1==d2: 22 | return True 23 | return False 24 | 25 | -------------------------------------------------------------------------------- /Solutions/python3/57-Insert-Interval.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def insert( 3 | self, intervals: List[List[int]], newInterval: List[int] 4 | ) -> List[List[int]]: 5 | res = [] 6 | 7 | for i in range(len(intervals)): 8 | if newInterval[1] < intervals[i][0]: 9 | res.append(newInterval) 10 | return res + intervals[i:] 11 | elif newInterval[0] > intervals[i][1]: 12 | res.append(intervals[i]) 13 | else: 14 | newInterval = [ 15 | min(newInterval[0], intervals[i][0]), 16 | max(newInterval[1], intervals[i][1]), 17 | ] 18 | res.append(newInterval) 19 | return res 20 | -------------------------------------------------------------------------------- /Solutions/python3/58.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def lengthOfLastWord(self, s: str) -> int: 3 | s=s.split() 4 | return len(s[-1]) 5 | -------------------------------------------------------------------------------- /Solutions/python3/605-Can-Place-Flowers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: 3 | flowerbed=[0]+flowerbed+[0] 4 | 5 | for i in range(1,len(flowerbed)-1): 6 | if flowerbed[i-1] == 0 and flowerbed[i]==0 and flowerbed[i+1] ==0: 7 | n-=1 8 | flowerbed[i]=1 9 | if n <= 0 : 10 | return True 11 | return False 12 | 13 | 14 | -------------------------------------------------------------------------------- /Solutions/python3/62-unique-paths.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def uniquePaths(self, m: int, n: int) -> int: 3 | dp=[[0 for i in range(n)] for i in range(m)] 4 | if(m==1 and n==1): 5 | return 1 6 | for i in range(m-1,-1,-1): 7 | for j in range(n-1,-1,-1): 8 | if(i==m-1 and j==n-1): 9 | dp[i][j]=0 10 | #last position in the grid set it to zero.. 11 | elif(i==m-1): 12 | dp[i][j]=1 13 | #check the edge cases... 14 | elif(j==n-1): 15 | dp[i][j]=1 16 | #check the edge cases... 17 | else: 18 | dp[i][j]=dp[i+1][j]+dp[i][j+1] 19 | return dp[0][0] 20 | 21 | -------------------------------------------------------------------------------- /Solutions/python3/621.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | class Solution: 3 | def leastInterval(self, tasks: List[str], n: int) -> int: 4 | ans, hashMap, heap = 0, Counter(tasks), [] 5 | 6 | for key in hashMap: 7 | heappush(heap, -hashMap[key]) 8 | 9 | 10 | while len(heap): 11 | 12 | tt, arr = 0, [] 13 | for i in range(n + 1): 14 | if len(heap): 15 | arr.append(-heappop(heap) - 1) 16 | tt += 1 17 | 18 | for i in arr: 19 | if i > 0: 20 | heappush(heap, -i) 21 | 22 | if not len(heap): 23 | ans += tt 24 | else: 25 | ans += (n + 1) 26 | return ans 27 | -------------------------------------------------------------------------------- /Solutions/python3/647-palindromic-substrings.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def countSubstrings(self, s: str) -> int: 3 | L, r = len(s), 0 4 | for i in range(L): 5 | for a,b in [(i,i),(i,i+1)]: 6 | while a >= 0 and b < L and s[a] == s[b]: a -= 1; b += 1 7 | r += (b-a)//2 8 | return r 9 | -------------------------------------------------------------------------------- /Solutions/python3/658.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | class Solution: 3 | def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: 4 | heap=[] 5 | for num in arr : 6 | heapq.heappush(heap,[num,abs(num-x)]) 7 | heap.sort(key = lambda x: x[1]) 8 | result=heap[:k] 9 | ans=[] 10 | for num in result: 11 | ans.append(num[0]) 12 | return(sorted(ans)) 13 | -------------------------------------------------------------------------------- /Solutions/python3/659-decode-encode.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param: strs: a list of strings 4 | @return: encodes a list of strings to a single string. 5 | """ 6 | 7 | def encode(self, strs): 8 | res = "" 9 | for s in strs: 10 | res += str(len(s)) + "#" + s 11 | return res 12 | 13 | """ 14 | @param: s: A string 15 | @return: decodes a single string to a list of strings 16 | """ 17 | 18 | def decode(self, s): 19 | res, i = [], 0 20 | 21 | while i < len(s): 22 | j = i 23 | while s[j] != "#": 24 | j += 1 25 | length = int(s[i:j]) 26 | res.append(s[j + 1 : j + 1 + length]) 27 | i = j + 1 + length 28 | return res 29 | -------------------------------------------------------------------------------- /Solutions/python3/665.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkPossibility(self, nums: List[int]) -> bool: 3 | cnt=0 4 | for i in range(1,len(nums)): 5 | if nums[i-1]>nums[i]: 6 | cnt+=1 7 | if i >= 2 and i+11: 11 | return(False) 12 | return(True) 13 | -------------------------------------------------------------------------------- /Solutions/python3/680-Valid-Palindrome.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def validPalindrome(self, s: str) -> bool: 3 | def ispalindrome(s): 4 | l,r=0,len(s)-1 5 | while l int: 3 | stack=[] 4 | for i in ops: 5 | if i=='+' and len(stack)>1: 6 | num1=stack[-1] 7 | num2=stack[-2] 8 | stack.append((num1)+(num2)) 9 | elif i=="C" and stack: 10 | stack.pop() 11 | elif i=='D' and stack: 12 | num1=stack[-1] 13 | stack.append((num1)*2) 14 | else: 15 | stack.append(int(i)) 16 | return(sum(stack)) 17 | -------------------------------------------------------------------------------- /Solutions/python3/685.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxAreaOfIsland(self, grid: List[List[int]]) -> int: 3 | rows,cols=len(grid),len(grid[0]) 4 | visit=set() 5 | def dfs(i,j): 6 | if i <0 or i==rows or j <0 or j==cols or grid[i][j]==0 or (i,j) in visit: 7 | return 0 8 | visit.add((i,j)) 9 | return(1+ dfs(i+1,j) + dfs(i-1,j) + dfs(i,j+1) + dfs(i,j-1)) 10 | area=0 11 | for m in range(rows): 12 | for n in range(cols): 13 | area=max(area,dfs(m,n)) 14 | return area 15 | 16 | -------------------------------------------------------------------------------- /Solutions/python3/692.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def topKFrequent(self, words: List[str], k: int) -> List[str]: 3 | words.sort() 4 | d={} 5 | for word in words: 6 | d[word]=1+d.get(word,0) 7 | d=list(dict(sorted(d.items(), key=lambda x:x[1],reverse=True)))[:k] 8 | return(d) 9 | 10 | 11 | -------------------------------------------------------------------------------- /Solutions/python3/7.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverse(self, x: int) -> int: 3 | MIN= -2147483648 4 | MAX= 2147483647 5 | res=0 6 | while x: 7 | digit=int(math.fmod(x,10)) 8 | x=int(x/10) 9 | if (res > MAX //10 or ( res==MAX//10 and digit >= MAX%10)) : 10 | return(0) 11 | if (res< MIN //10 or( res==MIN//10 and digit<=MIN%10)): 12 | return(0) 13 | res= (res*10)+digit 14 | return(res) 15 | -------------------------------------------------------------------------------- /Solutions/python3/70-climbing-stairs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def climbStairs(self, n: int) -> int: 3 | one,two=1,1 4 | 5 | for i in range(n-1): 6 | temp=one 7 | one=one+two 8 | two=temp 9 | return one 10 | -------------------------------------------------------------------------------- /Solutions/python3/704-Binary-Search.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def search(self, nums: List[int], target: int) -> int: 3 | low=0 4 | high=len(nums)-1 5 | while low<=high: 6 | mid=int((low+high)/2) 7 | if(nums[mid]==target): 8 | return mid 9 | elif(nums[mid]target): 12 | high=mid-1 13 | return -1 14 | -------------------------------------------------------------------------------- /Solutions/python3/720.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestWord(self, words: List[str]) -> str: 3 | words.sort() 4 | visited ={""} 5 | res="" 6 | 7 | for word in words: 8 | print(word[:-1]) 9 | if word[:-1] in visited: 10 | visited.add(word) 11 | if len(word)>len(res): 12 | res=word 13 | return res 14 | 15 | -------------------------------------------------------------------------------- /Solutions/python3/724.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def pivotIndex(self, nums: List[int]) -> int: 3 | total=sum(nums) #O(n) 4 | left=0 5 | 6 | for i in range(len(nums)) : 7 | 8 | right=total-nums[i]-left 9 | if left==right: 10 | return i 11 | left+=nums[i] 12 | return -1 13 | 14 | 15 | #O(N) 16 | -------------------------------------------------------------------------------- /Solutions/python3/73-Set-Matrix-Zeroes.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def setZeroes(self, matrix: List[List[int]]) -> None: 3 | d={} 4 | row=len(matrix) 5 | col=len(matrix[0]) 6 | cols=[] 7 | rows=[] 8 | for r in range(row): 9 | for c in range(col): 10 | if matrix[r][c]==0: 11 | rows.append(r) 12 | cols.append(c) 13 | 14 | for r in range(row): 15 | for c in range(col): 16 | if r in rows or c in cols: 17 | matrix[r][c]=0 18 | 19 | 20 | -------------------------------------------------------------------------------- /Solutions/python3/739.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def dailyTemperatures(self, temperatures: List[int]) -> List[int]: 3 | res=[0]*len(temperatures) 4 | 5 | stack=[] 6 | 7 | for i ,t in enumerate (temperatures): 8 | while stack and stack[-1][0] bool: 3 | rows, cols = len(matrix), len(matrix[0]) 4 | 5 | low,high=0,rows-1 6 | 7 | while low<=high: 8 | row=(low+high)//2 9 | 10 | if target > matrix[row][-1]: 11 | low=row+1 12 | elif target < matrix[row][0]: 13 | high=row-1 14 | else : 15 | break 16 | if high target: 26 | high=mid-1 27 | elif matrix[row][mid] < target: 28 | low=mid+1 29 | return False 30 | -------------------------------------------------------------------------------- /Solutions/python3/75-Sort-Colors.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortColors(self, nums: List[int]) -> None: 3 | left = i = 0 4 | right = len(nums) - 1 5 | while i <= right : 6 | while(nums[i] == 2 and i < right): 7 | nums[i], nums[right] = nums[right], nums[i] 8 | right -= 1 9 | while(nums[i] == 0 and i > left): 10 | nums[i], nums[left] = nums[left], nums[i] 11 | left +=1 12 | i += 1 13 | 14 | -------------------------------------------------------------------------------- /Solutions/python3/767.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | class Solution: 3 | def reorganizeString(self, s: str) -> str: 4 | res="" 5 | d={} 6 | heap=[] 7 | for c in s: 8 | d[c]=1+d.get(c,0) 9 | for c in d: 10 | heapq.heappush(heap,(-d[c],c)) 11 | 12 | while heap: 13 | arr=[] 14 | for ch in range(2): 15 | if len(heap): 16 | c,s=heapq.heappop(heap) 17 | c*=-1 18 | res+=s 19 | c-=1 20 | if c>0: 21 | arr.append([-c,s]) 22 | for c,s in arr: 23 | heapq.heappush(heap,(c,s)) 24 | if len(res)>2 and res[-1]==res[-2]: 25 | return ("") 26 | return(res) 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /Solutions/python3/78.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def subsets(self, nums: List[int]) -> List[List[int]]: 3 | res=[] 4 | subset=[] 5 | 6 | 7 | def backtrack(i): 8 | if i >= len(nums): 9 | res.append(subset.copy()) 10 | return 11 | subset.append(nums[i]) 12 | backtrack(i+1) 13 | subset.pop() 14 | backtrack(i+1) 15 | backtrack(0) 16 | return(res) 17 | -------------------------------------------------------------------------------- /Solutions/python3/787.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findCheapestPrice( 3 | self, n: int, flights: List[List[int]], src: int, dst: int, k: int 4 | ) -> int: 5 | prices = [float("inf")] * n 6 | prices[src] = 0 7 | 8 | for i in range(k + 1): 9 | tmpPrices = prices.copy() 10 | 11 | for s, d, p in flights: # s=source, d=dest, p=price 12 | if prices[s] == float("inf"): 13 | continue 14 | if prices[s] + p < tmpPrices[d]: 15 | tmpPrices[d] = prices[s] + p 16 | prices = tmpPrices 17 | return -1 if prices[dst] == float("inf") else prices[dst] 18 | -------------------------------------------------------------------------------- /Solutions/python3/792.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numMatchingSubseq(self, s: str, words: List[str]) -> int: 3 | word_count={} 4 | for word in words: 5 | word_count[word]=word_count.get(word,0)+1 6 | 7 | def is_subsequence(s,word): 8 | i=0 9 | for char in word: 10 | i=s.find(char,i)+1 11 | if not i : 12 | return False 13 | return True 14 | res=0 15 | for word in word_count: 16 | if is_subsequence(s,word): 17 | res+=word_count[word] 18 | return res 19 | -------------------------------------------------------------------------------- /Solutions/python3/83.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]: 8 | curr=head 9 | while curr and curr.next: 10 | if curr.val==curr.next.val: 11 | curr.next=curr.next.next 12 | else: 13 | curr=curr.next 14 | return head 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /Solutions/python3/857.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minEatingSpeed(self, piles: List[int], h: int) -> int: 3 | ans = float('inf') 4 | start = 1 5 | end = max(piles) + 1 6 | while start <= end: 7 | mid = (start + end)//2 8 | hour = 0 9 | for i in piles: 10 | if i%mid==0: 11 | hour += i//mid 12 | else: 13 | hour += i//mid + 1 14 | print(hour) 15 | if hour > h: 16 | start = mid + 1 17 | else: 18 | ans = min(mid, ans) 19 | end = mid - 1 20 | return ans 21 | -------------------------------------------------------------------------------- /Solutions/python3/876.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: 8 | fast=head 9 | slow=head 10 | 11 | while fast and fast.next: 12 | fast=fast.next.next 13 | slow=slow.next 14 | return slow 15 | -------------------------------------------------------------------------------- /Solutions/python3/88-merge-sorted.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: 3 | """ 4 | Do not return anything, modify nums1 in-place instead. 5 | """ 6 | while m>0 and n>0 : 7 | if nums1[m-1] >= nums2[n-1]: 8 | nums1[m+n-1]=nums1[m-1] 9 | m-=1 10 | else: 11 | nums1[m+n-1]=nums2[n-1] 12 | n-=1 13 | if n >0 : 14 | nums1[:n]=nums2[:n] 15 | 16 | 17 | -------------------------------------------------------------------------------- /Solutions/python3/881.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numRescueBoats(self, people: List[int], limit: int) -> int: 3 | c,n=0,len(people) 4 | i,j=0,n-1 5 | people.sort() 6 | while i<=j: 7 | if people[i]+people[j]<=limit: 8 | i+=1 9 | j-=1 10 | else: 11 | j-=1 12 | c+=1 13 | return c 14 | -------------------------------------------------------------------------------- /Solutions/python3/91-decode-ways.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numDecodings(self, s: str) -> int: 3 | dp=[0]*(len(s)+1) 4 | if not s or s[0] == '0': return 0 5 | dp[0] = dp[1] = 1 6 | for i in range(2, len(s)+1): 7 | v = int(s[i-1:i]) 8 | if v >= 1 and v < 10: dp[i] += dp[i-1] 9 | v = int(s[i-2: i]) 10 | if v > 9 and v <= 26: dp[i] += dp[i-2] 11 | return dp[-1] 12 | 13 | -------------------------------------------------------------------------------- /Solutions/python3/92.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode: 3 | # def __init__(self, val=0, next=None): 4 | # self.val = val 5 | # self.next = next 6 | class Solution: 7 | def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]: 8 | dummy = ListNode(0, head) 9 | leftPrev = dummy 10 | cur = head 11 | 12 | for i in range(left - 1): 13 | leftPrev, cur = cur, cur.next 14 | 15 | prev = None 16 | for i in range(right - left + 1): 17 | tmp_next = cur.next 18 | cur.next = prev 19 | prev, cur = cur, tmp_next 20 | 21 | leftPrev.next.next = cur 22 | leftPrev.next = prev 23 | 24 | return dummy.next 25 | -------------------------------------------------------------------------------- /Solutions/python3/929-Unique-Email.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numUniqueEmails(self, emails: List[str]) -> int: 3 | seen = set() 4 | for email in emails: 5 | local,domain=email.split('@') 6 | local=local.split('+')[0] 7 | local=local.replace('.',"") 8 | seen.add(local+"@"+domain) 9 | return(len(seen)) 10 | -------------------------------------------------------------------------------- /Solutions/python3/94.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: 9 | result=[] 10 | def dfs(root): 11 | if root is None: 12 | return 13 | dfs(root.left) 14 | result.append(root.val) 15 | dfs(root.right) 16 | dfs(root) 17 | return(result) 18 | -------------------------------------------------------------------------------- /Solutions/python3/973.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: 3 | heap=[] 4 | for x,y in points: 5 | ans=(abs(x - 0) ** 2) + (abs(y - 0) ** 2) 6 | heap.append([ans,x,y]) 7 | heapq.heapify(heap) 8 | res=[] 9 | for i in range(k): 10 | dist, x, y = heapq.heappop(heap) 11 | res.append([x, y]) 12 | return res 13 | -------------------------------------------------------------------------------- /Solutions/python3/977.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sortedSquares(self, nums: List[int]) -> List[int]: 3 | for i in range(len(nums)): 4 | nums[i]=pow(nums[i],2) 5 | return(sorted(nums)) 6 | 7 | -------------------------------------------------------------------------------- /Solutions/python3/98-validate-binary-search.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isValidBST(self, root: Optional[TreeNode]) -> bool: 3 | lastvalue=float('-inf') 4 | statment=True 5 | def dfs(node): 6 | nonlocal statment,lastvalue 7 | if node is None: 8 | return 9 | dfs(node.left) 10 | if node.val > lastvalue: 11 | lastvalue=node.val 12 | else: 13 | statment=False 14 | dfs(node.right) 15 | dfs(root) 16 | return statment 17 | 18 | #Time Complexity :O(N) 19 | #Space Complexity:O(1) 20 | -------------------------------------------------------------------------------- /Solutions/python3/983.py: -------------------------------------------------------------------------------- 1 | def mincostTickets(self, days: List[int], costs: List[int]) -> int: 2 | dp=[0 for i in range(days[-1]+1)] 3 | dy = set(days) 4 | for i in range(days[-1]+1): 5 | if i not in dy: dp[i]=dp[i-1] 6 | else: dp[i]=min(dp[max(0,i-7)]+costs[1],dp[max(0,i-1)]+costs[0],dp[max(0,i-30)]+costs[2]) 7 | return dp[-1] 8 | --------------------------------------------------------------------------------