├── .gitignore ├── .vscode └── settings.json ├── Grind75.md ├── LICENSE ├── README.md ├── Screen Recording 2025-06-02 at 13.42.55_4k.mov ├── __pycache__ ├── logger.cpython-312.pyc └── logger.cpython-38.pyc ├── blog ├── images │ ├── leetcode-algorithm-109.jpg │ ├── leetcode-algorithm-11.png │ ├── leetcode-algorithm-110-1.jpg │ ├── leetcode-algorithm-110-2.jpg │ ├── leetcode-algorithm-111.jpg │ ├── leetcode-algorithm-112-1.jpg │ ├── leetcode-algorithm-112-2.jpg │ ├── leetcode-algorithm-113-1.jpg │ ├── leetcode-algorithm-113-2.jpg │ ├── leetcode-algorithm-114.jpg │ ├── leetcode-algorithm-116.png │ ├── leetcode-algorithm-117.png │ ├── leetcode-algorithm-118.gif │ ├── leetcode-algorithm-124-1.jpg │ ├── leetcode-algorithm-124-2.jpg │ ├── leetcode-algorithm-129-1.jpg │ ├── leetcode-algorithm-129-2.jpg │ ├── leetcode-algorithm-130.jpg │ ├── leetcode-algorithm-142-1.png │ ├── leetcode-algorithm-142-2.png │ ├── leetcode-algorithm-142-3.png │ ├── leetcode-algorithm-17.png │ ├── leetcode-algorithm-36.png │ ├── leetcode-algorithm-37.png │ ├── leetcode-algorithm-42.png │ ├── leetcode-algorithm-48-1.jpg │ ├── leetcode-algorithm-48-2.jpg │ ├── leetcode-algorithm-51.png │ ├── leetcode-algorithm-547-1.jpg │ ├── leetcode-algorithm-547-2.jpg │ ├── leetcode-algorithm-62.png │ ├── leetcode-algorithm-73-1.jpg │ ├── leetcode-algorithm-73-2.jpg │ ├── leetcode-algorithm-74-1.jpg │ ├── leetcode-algorithm-74-2.jpg │ ├── leetcode-algorithm-79.jpg │ ├── leetcode-algorithm-84-1.png │ ├── leetcode-algorithm-84-2.png │ ├── leetcode-algorithm-85.jpg │ ├── leetcode-algorithm-94-1.jpg │ ├── leetcode-algorithm-94-2.jpg │ ├── leetcode-algorithm-94-3.jpg │ ├── leetcode-algorithm-97.jpg │ ├── leetcode-algorithm-99-1.jpg │ ├── leetcode-algorithm-99-2.jpg │ ├── leetcode-sketch-algorithm-10.png │ ├── leetcode-sketch-algorithm-123.png │ ├── leetcode-sketch-algorithm-17.png │ ├── leetcode-sketch-algorithm-22.jpg │ ├── leetcode-sketch-algorithm-23.jpg │ ├── leetcode-sketch-algorithm-36.png │ ├── leetcode-sketch-algorithm-39.jpg │ ├── leetcode-sketch-algorithm-44.jpg │ ├── leetcode-sketch-algorithm-59.png │ └── leetcode-sketch-algorithm-69.png ├── leetcode-1.md ├── leetcode-10.md ├── leetcode-100.md ├── leetcode-101.md ├── leetcode-102.md ├── leetcode-103.md ├── leetcode-104.md ├── leetcode-105.md ├── leetcode-106.md ├── leetcode-107.md ├── leetcode-108.md ├── leetcode-109.md ├── leetcode-11.md ├── leetcode-110.md ├── leetcode-111.md ├── leetcode-112.md ├── leetcode-113.md ├── leetcode-114.md ├── leetcode-115.md ├── leetcode-116.md ├── leetcode-117.md ├── leetcode-118.md ├── leetcode-119.md ├── leetcode-12.md ├── leetcode-120.md ├── leetcode-121.md ├── leetcode-122.md ├── leetcode-123.md ├── leetcode-124.md ├── leetcode-125.md ├── leetcode-126.md ├── leetcode-127.md ├── leetcode-128.md ├── leetcode-129.md ├── leetcode-13.md ├── leetcode-130.md ├── leetcode-131.md ├── leetcode-135.md ├── leetcode-136.md ├── leetcode-14.md ├── leetcode-142.md ├── leetcode-15.md ├── leetcode-153.md ├── leetcode-154.md ├── leetcode-16.md ├── leetcode-167.md ├── leetcode-17.md ├── leetcode-1700.md ├── leetcode-1704.md ├── leetcode-1708.md ├── leetcode-1710.md ├── leetcode-1716.md ├── leetcode-1720.md ├── leetcode-1725.md ├── leetcode-1732.md ├── leetcode-1736.md ├── leetcode-1742.md ├── leetcode-18.md ├── leetcode-19.md ├── leetcode-190.md ├── leetcode-198.md ├── leetcode-2.md ├── leetcode-20.md ├── leetcode-21.md ├── leetcode-22.md ├── leetcode-23.md ├── leetcode-24.md ├── leetcode-25.md ├── leetcode-26.md ├── leetcode-27.md ├── leetcode-28.md ├── leetcode-29.md ├── leetcode-3.md ├── leetcode-30.md ├── leetcode-31.md ├── leetcode-318.md ├── leetcode-32.md ├── leetcode-33.md ├── leetcode-338.md ├── leetcode-34.md ├── leetcode-340.md ├── leetcode-342.md ├── leetcode-35.md ├── leetcode-36.md ├── leetcode-37.md ├── leetcode-38.md ├── leetcode-39.md ├── leetcode-4.md ├── leetcode-40.md ├── leetcode-406.md ├── leetcode-41.md ├── leetcode-413.md ├── leetcode-42.md ├── leetcode-43.md ├── leetcode-435.md ├── leetcode-44.md ├── leetcode-45.md ├── leetcode-452.md ├── leetcode-455.md ├── leetcode-46.md ├── leetcode-461.md ├── leetcode-47.md ├── leetcode-48.md ├── leetcode-49.md ├── leetcode-5.md ├── leetcode-50.md ├── leetcode-51.md ├── leetcode-52.md ├── leetcode-524.md ├── leetcode-53.md ├── leetcode-54.md ├── leetcode-540.md ├── leetcode-542.md ├── leetcode-547.md ├── leetcode-55.md ├── leetcode-56.md ├── leetcode-57.md ├── leetcode-58.md ├── leetcode-59.md ├── leetcode-6.md ├── leetcode-60.md ├── leetcode-605.md ├── leetcode-61.md ├── leetcode-62.md ├── leetcode-63.md ├── leetcode-633.md ├── leetcode-64.md ├── leetcode-65.md ├── leetcode-66.md ├── leetcode-665.md ├── leetcode-67.md ├── leetcode-68.md ├── leetcode-680.md ├── leetcode-69.md ├── leetcode-695.md ├── leetcode-7.md ├── leetcode-70.md ├── leetcode-71.md ├── leetcode-72.md ├── leetcode-73.md ├── leetcode-74.md ├── leetcode-75.md ├── leetcode-76.md ├── leetcode-763.md ├── leetcode-77.md ├── leetcode-78.md ├── leetcode-79.md ├── leetcode-8.md ├── leetcode-80.md ├── leetcode-81.md ├── leetcode-82.md ├── leetcode-83.md ├── leetcode-84.md ├── leetcode-85.md ├── leetcode-86.md ├── leetcode-87.md ├── leetcode-88.md ├── leetcode-89.md ├── leetcode-9.md ├── leetcode-90.md ├── leetcode-91.md ├── leetcode-92.md ├── leetcode-93.md ├── leetcode-94.md ├── leetcode-95.md ├── leetcode-96.md ├── leetcode-97.md ├── leetcode-98.md └── leetcode-99.md ├── learning ├── design-linked-list.py ├── sorting.cpp └── sorting.py ├── leetcode ├── 1.two-sum.cpp ├── 1.two-sum.py ├── 10.regular-expression-matching.cpp ├── 10.regular-expression-matching.py ├── 100.same-tree.cpp ├── 100.same-tree.py ├── 1004.max-consecutive-ones-iii.cpp ├── 1004.max-consecutive-ones-iii.py ├── 1007.minimum-domino-rotations-for-equal-row.cpp ├── 1007.minimum-domino-rotations-for-equal-row.py ├── 101.symmetric-tree.cpp ├── 101.symmetric-tree.py ├── 1016.binary-string-with-substrings-representing-1-to-n.cpp ├── 1016.binary-string-with-substrings-representing-1-to-n.py ├── 102.binary-tree-level-order-traversal.cpp ├── 102.binary-tree-level-order-traversal.py ├── 1028.recover-a-tree-from-preorder-traversal.cpp ├── 1028.recover-a-tree-from-preorder-traversal.py ├── 103.binary-tree-zigzag-level-order-traversal.cpp ├── 103.binary-tree-zigzag-level-order-traversal.py ├── 1033.moving-stones-until-consecutive.cpp ├── 1033.moving-stones-until-consecutive.py ├── 104.maximum-depth-of-binary-tree.cpp ├── 104.maximum-depth-of-binary-tree.py ├── 1040.moving-stones-until-consecutive-ii.cpp ├── 1040.moving-stones-until-consecutive-ii.py ├── 1046.last-stone-weight.cpp ├── 1046.last-stone-weight.py ├── 105.construct-binary-tree-from-preorder-and-inorder-traversal.cpp ├── 105.construct-binary-tree-from-preorder-and-inorder-traversal.py ├── 1052.grumpy-bookstore-owner.cpp ├── 1052.grumpy-bookstore-owner.py ├── 1059.all-paths-from-source-lead-to-destination.vip ├── 106.construct-binary-tree-from-inorder-and-postorder-traversal.cpp ├── 106.construct-binary-tree-from-inorder-and-postorder-traversal.py ├── 107.binary-tree-level-order-traversal-ii.cpp ├── 107.binary-tree-level-order-traversal-ii.py ├── 1079.letter-tile-possibilities.cpp ├── 1079.letter-tile-possibilities.py ├── 108.convert-sorted-array-to-binary-search-tree.cpp ├── 108.convert-sorted-array-to-binary-search-tree.py ├── 1089.duplicate-zeros.cpp ├── 1089.duplicate-zeros.py ├── 109.convert-sorted-list-to-binary-search-tree.cpp ├── 109.convert-sorted-list-to-binary-search-tree.py ├── 1092.shortest-common-supersequence.cpp ├── 1092.shortest-common-supersequence.py ├── 1094.car-pooling.cpp ├── 1094.car-pooling.py ├── 11.container-with-most-water.cpp ├── 11.container-with-most-water.py ├── 110.balanced-binary-tree.cpp ├── 110.balanced-binary-tree.py ├── 1100.find-k-length-substrings-with-no-repeated-characters.vip ├── 111.minimum-depth-of-binary-tree.cpp ├── 111.minimum-depth-of-binary-tree.py ├── 1110.delete-nodes-and-return-forest.cpp ├── 1110.delete-nodes-and-return-forest.py ├── 1123.lowest-common-ancestor-of-deepest-leaves.cpp ├── 1123.lowest-common-ancestor-of-deepest-leaves.py ├── 1128.number-of-equivalent-domino-pairs.cpp ├── 1128.number-of-equivalent-domino-pairs.py ├── 113.path-sum-ii.cpp ├── 113.path-sum-ii.py ├── 114.flatten-binary-tree-to-linked-list.cpp ├── 114.flatten-binary-tree-to-linked-list.py ├── 1143.longest-common-subsequence.cpp ├── 1143.longest-common-subsequence.py ├── 115.distinct-subsequences.cpp ├── 115.distinct-subsequences.py ├── 1150.check-if-a-number-is-majority-element-in-a-sorted-array.cpp ├── 1150.check-if-a-number-is-majority-element-in-a-sorted-array.py ├── 1156.swap-for-longest-repeated-character-substring.cpp ├── 1156.swap-for-longest-repeated-character-substring.py ├── 1176.diet-plan-performance.vip ├── 118.pascals-triangle.cpp ├── 118.pascals-triangle.py ├── 119.pascals-triangle-ii.cpp ├── 119.pascals-triangle-ii.py ├── 1197.minimum-knight-moves.vip ├── 12.integer-to-roman.cpp ├── 12.integer-to-roman.py ├── 120.triangle.cpp ├── 120.triangle.py ├── 1208.get-equal-substrings-within-budget.cpp ├── 1208.get-equal-substrings-within-budget.py ├── 121.best-time-to-buy-and-sell-stock.cpp ├── 121.best-time-to-buy-and-sell-stock.py ├── 122.best-time-to-buy-and-sell-stock-ii.cpp ├── 122.best-time-to-buy-and-sell-stock-ii.py ├── 123.best-time-to-buy-and-sell-stock-iii.cpp ├── 123.best-time-to-buy-and-sell-stock-iii.py ├── 1234.replace-the-substring-for-balanced-string.cpp ├── 1234.replace-the-substring-for-balanced-string.py ├── 1235.maximum-profit-in-job-scheduling.cpp ├── 1235.maximum-profit-in-job-scheduling.py ├── 124.binary-tree-maximum-path-sum.cpp ├── 124.binary-tree-maximum-path-sum.py ├── 1248.count-number-of-nice-subarrays.cpp ├── 1248.count-number-of-nice-subarrays.py ├── 1249.minimum-remove-to-make-valid-parentheses.cpp ├── 1249.minimum-remove-to-make-valid-parentheses.py ├── 125.valid-palindrome.cpp ├── 125.valid-palindrome.py ├── 126.word-ladder-ii.cpp ├── 126.word-ladder-ii.py ├── 1261.find-elements-in-a-contaminated-binary-tree.cpp ├── 1261.find-elements-in-a-contaminated-binary-tree.py ├── 127.word-ladder.cpp ├── 127.word-ladder.py ├── 128.longest-consecutive-sequence.cpp ├── 128.longest-consecutive-sequence.py ├── 1288.remove-covered-intervals.cpp ├── 1288.remove-covered-intervals.py ├── 1295.find-numbers-with-even-number-of-digits.cpp ├── 1295.find-numbers-with-even-number-of-digits.py ├── 1297.maximum-number-of-occurrences-of-a-substring.cpp ├── 1297.maximum-number-of-occurrences-of-a-substring.py ├── 1298.maximum-candies-you-can-get-from-boxes.cpp ├── 1298.maximum-candies-you-can-get-from-boxes.py ├── 13.roman-to-integer.cpp ├── 13.roman-to-integer.py ├── 130.surrounded-regions.cpp ├── 130.surrounded-regions.py ├── 131.palindrome-partitioning.cpp ├── 131.palindrome-partitioning.py ├── 132.palindrome-partitioning-ii.cpp ├── 132.palindrome-partitioning-ii.py ├── 1326.minimum-number-of-taps-to-open-to-water-a-garden.cpp ├── 1326.minimum-number-of-taps-to-open-to-water-a-garden.py ├── 133.clone-graph.cpp ├── 133.clone-graph.py ├── 134.gas-station.cpp ├── 134.gas-station.py ├── 1343.number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.cpp ├── 1343.number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.py ├── 135.candy.cpp ├── 135.candy.py ├── 1352.product-of-the-last-k-numbers.cpp ├── 1352.product-of-the-last-k-numbers.py ├── 1353.maximum-number-of-events-that-can-be-attended.cpp ├── 1353.maximum-number-of-events-that-can-be-attended.py ├── 1358.number-of-substrings-containing-all-three-characters.cpp ├── 1358.number-of-substrings-containing-all-three-characters.py ├── 136.single-number.cpp ├── 136.single-number.py ├── 138.copy-list-with-random-pointer.py ├── 1385.find-the-distance-value-between-two-arrays.cpp ├── 1385.find-the-distance-value-between-two-arrays.py ├── 139.word-break.cpp ├── 139.word-break.py ├── 1399.count-largest-group.cpp ├── 1399.count-largest-group.py ├── 14.longest-common-prefix.cpp ├── 14.longest-common-prefix.py ├── 141.linked-list-cycle.cpp ├── 141.linked-list-cycle.py ├── 1415.the-k-th-lexicographical-string-of-all-happy-strings-of-length-n.cpp ├── 1415.the-k-th-lexicographical-string-of-all-happy-strings-of-length-n.py ├── 142.linked-list-cycle-ii.cpp ├── 142.linked-list-cycle-ii.py ├── 1423.maximum-points-you-can-obtain-from-cards.cpp ├── 1423.maximum-points-you-can-obtain-from-cards.py ├── 143.reorder-list.py ├── 1438.longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.cpp ├── 1438.longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.py ├── 144.binary-tree-preorder-traversal.cpp ├── 144.binary-tree-preorder-traversal.py ├── 145.binary-tree-postorder-traversal.cpp ├── 145.binary-tree-postorder-traversal.py ├── 1456.maximum-number-of-vowels-in-a-substring-of-given-length.cpp ├── 1456.maximum-number-of-vowels-in-a-substring-of-given-length.py ├── 146.lru-cache.cpp ├── 146.lru-cache.py ├── 1461.check-if-a-string-contains-all-binary-codes-of-size-k.cpp ├── 1461.check-if-a-string-contains-all-binary-codes-of-size-k.py ├── 1471.the-k-strongest-values-in-an-array.cpp ├── 1471.the-k-strongest-values-in-an-array.py ├── 148.sort-list.cpp ├── 148.sort-list.py ├── 149.max-points-on-a-line.cpp ├── 149.max-points-on-a-line.py ├── 1493.longest-subarray-of-1s-after-deleting-one-element.cpp ├── 1493.longest-subarray-of-1s-after-deleting-one-element.py ├── 1498.number-of-subsequences-that-satisfy-the-given-sum-condition.cpp ├── 1498.number-of-subsequences-that-satisfy-the-given-sum-condition.py ├── 15.3sum.cpp ├── 15.3sum.py ├── 150.evaluate-reverse-polish-notation.cpp ├── 150.evaluate-reverse-polish-notation.py ├── 1514.path-with-maximum-probability.cpp ├── 1514.path-with-maximum-probability.py ├── 152.maximum-product-subarray.cpp ├── 152.maximum-product-subarray.py ├── 1524.number-of-sub-arrays-with-odd-sum.cpp ├── 1524.number-of-sub-arrays-with-odd-sum.py ├── 153.find-minimum-in-rotated-sorted-array.cpp ├── 153.find-minimum-in-rotated-sorted-array.py ├── 1534.count-good-triplets.cpp ├── 1534.count-good-triplets.py ├── 154.find-minimum-in-rotated-sorted-array-ii.cpp ├── 154.find-minimum-in-rotated-sorted-array-ii.py ├── 155.min-stack.cpp ├── 155.min-stack.py ├── 1550.three-consecutive-odds.cpp ├── 1550.three-consecutive-odds.py ├── 156.binary-tree-upside-down.cpp ├── 156.binary-tree-upside-down.py ├── 1574.shortest-subarray-to-be-removed-to-make-array-sorted.cpp ├── 1574.shortest-subarray-to-be-removed-to-make-array-sorted.py ├── 1577.number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers.cpp ├── 1577.number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers.py ├── 1589.maximum-sum-obtained-of-any-permutation.cpp ├── 1589.maximum-sum-obtained-of-any-permutation.py ├── 16.3sum-closest.cpp ├── 16.3sum-closest.py ├── 160.intersection-of-two-linked-lists.cpp ├── 160.intersection-of-two-linked-lists.py ├── 1610.maximum-number-of-visible-points.cpp ├── 1610.maximum-number-of-visible-points.py ├── 1616.split-two-strings-to-make-palindrome.cpp ├── 1616.split-two-strings-to-make-palindrome.py ├── 162.find-peak-element.cpp ├── 162.find-peak-element.py ├── 1631.path-with-minimum-effort.cpp ├── 1631.path-with-minimum-effort.py ├── 1652.defuse-the-bomb.cpp ├── 1652.defuse-the-bomb.py ├── 1658.minimum-operations-to-reduce-x-to-zero.cpp ├── 1658.minimum-operations-to-reduce-x-to-zero.py ├── 167.two-sum-ii-input-array-is-sorted.cpp ├── 167.two-sum-ii-input-array-is-sorted.py ├── 1674.minimum-moves-to-make-array-complementary.cpp ├── 1674.minimum-moves-to-make-array-complementary.py ├── 168.excel-sheet-column-title.cpp ├── 168.excel-sheet-column-title.py ├── 169.majority-element.cpp ├── 169.majority-element.py ├── 1695.maximum-erasure-value.cpp ├── 1695.maximum-erasure-value.py ├── 17.letter-combinations-of-a-phone-number.cpp ├── 17.letter-combinations-of-a-phone-number.py ├── 170.two-sum-iii-data-structure-design.cpp ├── 170.two-sum-iii-data-structure-design.py ├── 1712.ways-to-split-array-into-three-subarrays.cpp ├── 1712.ways-to-split-array-into-three-subarrays.py ├── 1718.construct-the-lexicographically-largest-valid-sequence.cpp ├── 1718.construct-the-lexicographically-largest-valid-sequence.py ├── 172.factorial-trailing-zeroes.cpp ├── 172.factorial-trailing-zeroes.py ├── 1726.tuple-with-same-product.cpp ├── 1726.tuple-with-same-product.py ├── 173.binary-search-tree-iterator.cpp ├── 173.binary-search-tree-iterator.py ├── 1730.shortest-path-to-get-food.vip ├── 1749.maximum-absolute-sum-of-any-subarray.cpp ├── 1749.maximum-absolute-sum-of-any-subarray.py ├── 175.combine-two-tables.sql ├── 1750.minimum-length-of-string-after-deleting-similar-ends.cpp ├── 1750.minimum-length-of-string-after-deleting-similar-ends.py ├── 1763.longest-nice-substring.cpp ├── 1763.longest-nice-substring.py ├── 1780.check-if-number-is-a-sum-of-powers-of-three.cpp ├── 1780.check-if-number-is-a-sum-of-powers-of-three.py ├── 1782.count-pairs-of-nodes.cpp ├── 1782.count-pairs-of-nodes.py ├── 179.largest-number.cpp ├── 179.largest-number.py ├── 1793.maximum-score-of-a-good-subarray.cpp ├── 1793.maximum-score-of-a-good-subarray.py ├── 18.4sum.cpp ├── 18.4sum.py ├── 1838.frequency-of-the-most-frequent-element.cpp ├── 1838.frequency-of-the-most-frequent-element.py ├── 1851.minimum-interval-to-include-each-query.cpp ├── 1851.minimum-interval-to-include-each-query.py ├── 1854.maximum-population-year.cpp ├── 1854.maximum-population-year.py ├── 1855.maximum-distance-between-a-pair-of-values.cpp ├── 1855.maximum-distance-between-a-pair-of-values.py ├── 1857.largest-color-value-in-a-directed-graph.cpp ├── 1857.largest-color-value-in-a-directed-graph.py ├── 1863.sum-of-all-subset-xor-totals.cpp ├── 1863.sum-of-all-subset-xor-totals.py ├── 188.best-time-to-buy-and-sell-stock-iv.cpp ├── 188.best-time-to-buy-and-sell-stock-iv.py ├── 1888.minimum-number-of-flips-to-make-the-binary-string-alternating.cpp ├── 1888.minimum-number-of-flips-to-make-the-binary-string-alternating.py ├── 189.rotate-array.cpp ├── 189.rotate-array.py ├── 1893.check-if-all-the-integers-in-a-range-are-covered.cpp ├── 1893.check-if-all-the-integers-in-a-range-are-covered.py ├── 19.remove-nth-node-from-end-of-list.cpp ├── 19.remove-nth-node-from-end-of-list.py ├── 190.reverse-bits.cpp ├── 190.reverse-bits.py ├── 1901.find-a-peak-element-ii.cpp ├── 1901.find-a-peak-element-ii.py ├── 191.number-of-1-bits.cpp ├── 191.number-of-1-bits.py ├── 1910.remove-all-occurrences-of-a-substring.cpp ├── 1910.remove-all-occurrences-of-a-substring.py ├── 1920.build-array-from-permutation.cpp ├── 1920.build-array-from-permutation.py ├── 1922.count-good-numbers.cpp ├── 1922.count-good-numbers.py ├── 1926.nearest-exit-from-entrance-in-maze.cpp ├── 1926.nearest-exit-from-entrance-in-maze.py ├── 1931.painting-a-grid-with-three-different-colors.cpp ├── 1931.painting-a-grid-with-three-different-colors.py ├── 1943.describe-the-painting.cpp ├── 1943.describe-the-painting.py ├── 1976.number-of-ways-to-arrive-at-destination.cpp ├── 1976.number-of-ways-to-arrive-at-destination.py ├── 198.house-robber.cpp ├── 198.house-robber.py ├── 1980.find-unique-binary-string.cpp ├── 1980.find-unique-binary-string.py ├── 1984.minimum-difference-between-highest-and-lowest-of-k-scores.cpp ├── 1984.minimum-difference-between-highest-and-lowest-of-k-scores.py ├── 199.binary-tree-right-side-view.cpp ├── 199.binary-tree-right-side-view.py ├── 2.add-two-numbers.cpp ├── 2.add-two-numbers.py ├── 20.valid-parentheses.cpp ├── 20.valid-parentheses.py ├── 200.number-of-islands.cpp ├── 200.number-of-islands.py ├── 2009.minimum-number-of-operations-to-make-array-continuous.cpp ├── 2009.minimum-number-of-operations-to-make-array-continuous.py ├── 202.happy-number.cpp ├── 202.happy-number.py ├── 2024.maximize-the-confusion-of-an-exam.cpp ├── 2024.maximize-the-confusion-of-an-exam.py ├── 203.remove-linked-list-elements.py ├── 2033.minimum-operations-to-make-a-uni-value-grid.cpp ├── 2033.minimum-operations-to-make-a-uni-value-grid.py ├── 204.count-primes.cpp ├── 204.count-primes.py ├── 2040.kth-smallest-product-of-two-sorted-arrays.cpp ├── 2040.kth-smallest-product-of-two-sorted-arrays.py ├── 205.isomorphic-strings.cpp ├── 205.isomorphic-strings.py ├── 206.reverse-linked-list.cpp ├── 206.reverse-linked-list.py ├── 207.course-schedule.cpp ├── 207.course-schedule.py ├── 2071.maximum-number-of-tasks-you-can-assign.cpp ├── 2071.maximum-number-of-tasks-you-can-assign.py ├── 2079.watering-plants.cpp ├── 2079.watering-plants.py ├── 208.implement-trie-prefix-tree.cpp ├── 208.implement-trie-prefix-tree.py ├── 209.minimum-size-subarray-sum.cpp ├── 209.minimum-size-subarray-sum.py ├── 2090.k-radius-subarray-averages.cpp ├── 2090.k-radius-subarray-averages.py ├── 2094.finding-3-digit-even-numbers.cpp ├── 2094.finding-3-digit-even-numbers.py ├── 21.merge-two-sorted-lists.cpp ├── 21.merge-two-sorted-lists.py ├── 210.course-schedule-ii.cpp ├── 210.course-schedule-ii.py ├── 2105.watering-plants-ii.cpp ├── 2105.watering-plants-ii.py ├── 2106.maximum-fruits-harvested-after-at-most-k-steps.cpp ├── 2106.maximum-fruits-harvested-after-at-most-k-steps.py ├── 211.design-add-and-search-words-data-structure.cpp ├── 211.design-add-and-search-words-data-structure.py ├── 2115.find-all-possible-recipes-from-given-supplies.cpp ├── 2115.find-all-possible-recipes-from-given-supplies.py ├── 212.word-search-ii.cpp ├── 212.word-search-ii.py ├── 2122.recover-the-original-array.cpp ├── 2122.recover-the-original-array.py ├── 213.house-robber-ii.cpp ├── 213.house-robber-ii.py ├── 2131.longest-palindrome-by-concatenating-two-letter-words.cpp ├── 2131.longest-palindrome-by-concatenating-two-letter-words.py ├── 2134.minimum-swaps-to-group-all-1s-together-ii.cpp ├── 2134.minimum-swaps-to-group-all-1s-together-ii.py ├── 2140.solving-questions-with-brainpower.cpp ├── 2140.solving-questions-with-brainpower.py ├── 2145.count-the-hidden-sequences.cpp ├── 2145.count-the-hidden-sequences.py ├── 215.kth-largest-element-in-an-array.cpp ├── 215.kth-largest-element-in-an-array.py ├── 2156.find-substring-with-given-hash-value.cpp ├── 2156.find-substring-with-given-hash-value.py ├── 2161.partition-array-according-to-given-pivot.cpp ├── 2161.partition-array-according-to-given-pivot.py ├── 217.contains-duplicate.cpp ├── 217.contains-duplicate.py ├── 2176.count-equal-and-divisible-pairs-in-an-array.cpp ├── 2176.count-equal-and-divisible-pairs-in-an-array.py ├── 2179.count-good-triplets-in-an-array.cpp ├── 2179.count-good-triplets-in-an-array.py ├── 218.the-skyline-problem.cpp ├── 218.the-skyline-problem.py ├── 219.contains-duplicate-ii.cpp ├── 22.generate-parentheses.cpp ├── 22.generate-parentheses.py ├── 220.contains-duplicate-iii.cpp ├── 220.contains-duplicate-iii.py ├── 2206.divide-array-into-equal-pairs.cpp ├── 2206.divide-array-into-equal-pairs.py ├── 221.maximal-square.cpp ├── 221.maximal-square.py ├── 2210.count-hills-and-valleys-in-an-array.cpp ├── 2210.count-hills-and-valleys-in-an-array.py ├── 2226.maximum-candies-allocated-to-k-children.cpp ├── 2226.maximum-candies-allocated-to-k-children.py ├── 2234.maximum-total-beauty-of-the-gardens.cpp ├── 2234.maximum-total-beauty-of-the-gardens.py ├── 224.basic-calculator.cpp ├── 224.basic-calculator.py ├── 225.implement-stack-using-queues.cpp ├── 225.implement-stack-using-queues.py ├── 2251.number-of-flowers-in-full-bloom.cpp ├── 2251.number-of-flowers-in-full-bloom.py ├── 226.invert-binary-tree.cpp ├── 226.invert-binary-tree.py ├── 2269.find-the-k-beauty-of-a-number.cpp ├── 2269.find-the-k-beauty-of-a-number.py ├── 227.basic-calculator-ii.cpp ├── 227.basic-calculator-ii.py ├── 2270.number-of-ways-to-split-array.cpp ├── 2270.number-of-ways-to-split-array.py ├── 2271.maximum-white-tiles-covered-by-a-carpet.cpp ├── 2271.maximum-white-tiles-covered-by-a-carpet.py ├── 228.summary-ranges.py ├── 229.majority-element-ii.cpp ├── 229.majority-element-ii.py ├── 23.merge-k-sorted-lists.cpp ├── 23.merge-k-sorted-lists.py ├── 230.kth-smallest-element-in-a-bst.cpp ├── 230.kth-smallest-element-in-a-bst.py ├── 2302.count-subarrays-with-score-less-than-k.cpp ├── 2302.count-subarrays-with-score-less-than-k.py ├── 231.power-of-two.cpp ├── 231.power-of-two.py ├── 232.implement-queue-using-stacks.cpp ├── 232.implement-queue-using-stacks.py ├── 2337.move-pieces-to-obtain-a-string.cpp ├── 2337.move-pieces-to-obtain-a-string.py ├── 2338.count-the-number-of-ideal-arrays.cpp ├── 2338.count-the-number-of-ideal-arrays.py ├── 234.palindrome-linked-list.cpp ├── 234.palindrome-linked-list.py ├── 2342.max-sum-of-a-pair-with-equal-sum-of-digits.cpp ├── 2342.max-sum-of-a-pair-with-equal-sum-of-digits.py ├── 2349.design-a-number-container-system.cpp ├── 2349.design-a-number-container-system.py ├── 235.lowest-common-ancestor-of-a-binary-search-tree.cpp ├── 235.lowest-common-ancestor-of-a-binary-search-tree.py ├── 2359.find-closest-node-to-given-two-nodes.cpp ├── 2359.find-closest-node-to-given-two-nodes.py ├── 236.lowest-common-ancestor-of-a-binary-tree.cpp ├── 236.lowest-common-ancestor-of-a-binary-tree.py ├── 2364.count-number-of-bad-pairs.cpp ├── 2364.count-number-of-bad-pairs.py ├── 237.delete-node-in-a-linked-list.py ├── 2375.construct-smallest-number-from-di-string.cpp ├── 2375.construct-smallest-number-from-di-string.py ├── 2379.minimum-recolors-to-get-k-consecutive-black-blocks.cpp ├── 2379.minimum-recolors-to-get-k-consecutive-black-blocks.py ├── 238.product-of-array-except-self.cpp ├── 238.product-of-array-except-self.py ├── 239.sliding-window-maximum.cpp ├── 239.sliding-window-maximum.py ├── 24.swap-nodes-in-pairs.cpp ├── 24.swap-nodes-in-pairs.py ├── 240.search-a-2d-matrix-ii.cpp ├── 240.search-a-2d-matrix-ii.py ├── 2401.longest-nice-subarray.cpp ├── 2401.longest-nice-subarray.py ├── 241.different-ways-to-add-parentheses.cpp ├── 241.different-ways-to-add-parentheses.py ├── 242.valid-anagram.cpp ├── 242.valid-anagram.py ├── 2444.count-subarrays-with-fixed-bounds.cpp ├── 2444.count-subarrays-with-fixed-bounds.py ├── 246.strobogrammatic-number.cpp ├── 246.strobogrammatic-number.py ├── 2460.apply-operations-to-an-array.cpp ├── 2460.apply-operations-to-an-array.py ├── 2461.maximum-sum-of-distinct-subarrays-with-length-k.cpp ├── 2461.maximum-sum-of-distinct-subarrays-with-length-k.py ├── 2467.most-profitable-path-in-a-tree.cpp ├── 2467.most-profitable-path-in-a-tree.py ├── 2468.split-message-based-on-limit.cpp ├── 2468.split-message-based-on-limit.py ├── 249.group-shifted-strings.cpp ├── 25.reverse-nodes-in-k-group.cpp ├── 25.reverse-nodes-in-k-group.py ├── 2503.maximum-number-of-points-from-grid-queries.cpp ├── 2503.maximum-number-of-points-from-grid-queries.py ├── 251.flatten-2d-vector.py ├── 2516.take-k-of-each-character-from-left-and-right.cpp ├── 2516.take-k-of-each-character-from-left-and-right.py ├── 2523.closest-prime-numbers-in-range.cpp ├── 2523.closest-prime-numbers-in-range.py ├── 2524.maximum-frequency-score-of-a-subarray.vip ├── 2529.maximum-count-of-positive-integer-and-negative-integer.cpp ├── 2529.maximum-count-of-positive-integer-and-negative-integer.py ├── 2537.count-the-number-of-good-subarrays.cpp ├── 2537.count-the-number-of-good-subarrays.py ├── 2540.minimum-common-value.cpp ├── 2540.minimum-common-value.py ├── 2551.put-marbles-in-bags.cpp ├── 2551.put-marbles-in-bags.py ├── 2555.maximize-win-from-two-segments.cpp ├── 2555.maximize-win-from-two-segments.py ├── 2560.house-robber-iv.cpp ├── 2560.house-robber-iv.py ├── 2563.count-the-number-of-fair-pairs.cpp ├── 2563.count-the-number-of-fair-pairs.py ├── 257.binary-tree-paths.cpp ├── 257.binary-tree-paths.py ├── 2570.merge-two-2d-arrays-by-summing-values.cpp ├── 2570.merge-two-2d-arrays-by-summing-values.py ├── 2579.count-total-number-of-colored-cells.cpp ├── 2579.count-total-number-of-colored-cells.py ├── 2594.minimum-time-to-repair-cars.cpp ├── 2594.minimum-time-to-repair-cars.py ├── 26.remove-duplicates-from-sorted-array.cpp ├── 26.remove-duplicates-from-sorted-array.py ├── 260.single-number-iii.cpp ├── 260.single-number-iii.py ├── 263.ugly-number.cpp ├── 263.ugly-number.py ├── 2653.sliding-subarray-beauty.cpp ├── 2653.sliding-subarray-beauty.py ├── 268.missing-number.cpp ├── 268.missing-number.py ├── 2685.count-the-number-of-complete-components.cpp ├── 2685.count-the-number-of-complete-components.py ├── 269.alien-dictionary.py ├── 2698.find-the-punishment-number-of-an-integer.cpp ├── 2698.find-the-punishment-number-of-an-integer.py ├── 27.remove-element.cpp ├── 27.remove-element.py ├── 270.closest-binary-search-tree-value.cpp ├── 270.closest-binary-search-tree-value.py ├── 273.integer-to-english-words.py ├── 2730.find-the-longest-semi-repetitive-substring.cpp ├── 2730.find-the-longest-semi-repetitive-substring.py ├── 2743.count-substrings-without-repeating-character.vip ├── 276.paint-fence.cpp ├── 276.paint-fence.py ├── 2762.continuous-subarrays.cpp ├── 2762.continuous-subarrays.py ├── 2779.maximum-beauty-of-an-array-after-applying-operation.cpp ├── 2779.maximum-beauty-of-an-array-after-applying-operation.py ├── 278.first-bad-version.cpp ├── 278.first-bad-version.py ├── 2780.minimum-index-of-a-valid-split.cpp ├── 2780.minimum-index-of-a-valid-split.py ├── 2781.length-of-the-longest-valid-substring.cpp ├── 2781.length-of-the-longest-valid-substring.py ├── 279.perfect-squares.cpp ├── 279.perfect-squares.py ├── 2799.count-complete-subarrays-in-an-array.cpp ├── 2799.count-complete-subarrays-in-an-array.py ├── 28.find-the-index-of-the-first-occurrence-in-a-string.cpp ├── 28.find-the-index-of-the-first-occurrence-in-a-string.py ├── 2818.apply-operations-to-maximize-score.cpp ├── 2818.apply-operations-to-maximize-score.py ├── 282.expression-add-operators.cpp ├── 282.expression-add-operators.py ├── 2824.count-pairs-whose-sum-is-less-than-target.cpp ├── 2824.count-pairs-whose-sum-is-less-than-target.py ├── 283.move-zeroes.cpp ├── 283.move-zeroes.py ├── 2831.find-the-longest-equal-subarray.cpp ├── 2831.find-the-longest-equal-subarray.py ├── 2841.maximum-sum-of-almost-unique-subarray.cpp ├── 2841.maximum-sum-of-almost-unique-subarray.py ├── 2843.count-symmetric-integers.cpp ├── 2843.count-symmetric-integers.py ├── 2845.count-of-interesting-subarrays.cpp ├── 2845.count-of-interesting-subarrays.py ├── 2848.points-that-intersect-with-cars.cpp ├── 2848.points-that-intersect-with-cars.py ├── 286.walls-and-gates.cpp ├── 286.walls-and-gates.py ├── 287.find-the-duplicate-number.cpp ├── 287.find-the-duplicate-number.py ├── 2873.maximum-value-of-an-ordered-triplet-i.cpp ├── 2873.maximum-value-of-an-ordered-triplet-i.py ├── 2874.maximum-value-of-an-ordered-triplet-ii.cpp ├── 2874.maximum-value-of-an-ordered-triplet-ii.py ├── 2875.minimum-size-subarray-in-infinite-array.cpp ├── 2875.minimum-size-subarray-in-infinite-array.py ├── 2877.create-a-dataframe-from-list.py ├── 2878.get-the-size-of-a-dataframe.py ├── 2879.display-the-first-three-rows.py ├── 2880.select-data.py ├── 2881.create-a-new-column.py ├── 289.game-of-life.py ├── 2894.divisible-and-non-divisible-sums-difference.cpp ├── 2894.divisible-and-non-divisible-sums-difference.py ├── 29.divide-two-integers.cpp ├── 29.divide-two-integers.py ├── 2900.longest-unequal-adjacent-groups-subsequence-i.cpp ├── 2900.longest-unequal-adjacent-groups-subsequence-i.py ├── 2901.longest-unequal-adjacent-groups-subsequence-ii.cpp ├── 2901.longest-unequal-adjacent-groups-subsequence-ii.py ├── 2904.shortest-and-lexicographically-smallest-beautiful-string.cpp ├── 2904.shortest-and-lexicographically-smallest-beautiful-string.py ├── 2918.minimum-equal-sum-of-two-arrays-after-replacing-zeros.cpp ├── 2918.minimum-equal-sum-of-two-arrays-after-replacing-zeros.py ├── 2929.distribute-candies-among-children-ii.cpp ├── 2929.distribute-candies-among-children-ii.py ├── 2942.find-words-containing-character.cpp ├── 2942.find-words-containing-character.py ├── 295.find-median-from-data-stream.cpp ├── 295.find-median-from-data-stream.py ├── 2953.count-complete-substrings.cpp ├── 2953.count-complete-substrings.py ├── 2958.length-of-longest-subarray-with-at-most-k-frequency.cpp ├── 2958.length-of-longest-subarray-with-at-most-k-frequency.py ├── 2962.count-subarrays-where-max-element-appears-at-least-k-times.cpp ├── 2962.count-subarrays-where-max-element-appears-at-least-k-times.py ├── 2965.find-missing-and-repeated-values.cpp ├── 2965.find-missing-and-repeated-values.py ├── 2968.apply-operations-to-maximize-frequency-score.cpp ├── 2968.apply-operations-to-maximize-frequency-score.py ├── 297.serialize-and-deserialize-binary-tree.cpp ├── 297.serialize-and-deserialize-binary-tree.py ├── 2970.count-the-number-of-incremovable-subarrays-i.cpp ├── 2970.count-the-number-of-incremovable-subarrays-i.py ├── 2972.count-the-number-of-incremovable-subarrays-ii.cpp ├── 2972.count-the-number-of-incremovable-subarrays-ii.py ├── 2999.count-the-number-of-powerful-integers.cpp ├── 2999.count-the-number-of-powerful-integers.py ├── 3.longest-substring-without-repeating-characters.cpp ├── 3.longest-substring-without-repeating-characters.py ├── 30.substring-with-concatenation-of-all-words.cpp ├── 30.substring-with-concatenation-of-all-words.py ├── 300.longest-increasing-subsequence.cpp ├── 300.longest-increasing-subsequence.py ├── 3024.type-of-triangle.cpp ├── 3024.type-of-triangle.py ├── 303.range-sum-query-immutable.cpp ├── 303.range-sum-query-immutable.py ├── 304.range-sum-query-2d-immutable.cpp ├── 304.range-sum-query-2d-immutable.py ├── 3048.earliest-second-to-mark-indices-i.cpp ├── 3048.earliest-second-to-mark-indices-i.py ├── 3066.minimum-operations-to-exceed-threshold-value-ii.cpp ├── 3066.minimum-operations-to-exceed-threshold-value-ii.py ├── 3068.find-the-maximum-sum-of-node-values.cpp ├── 3068.find-the-maximum-sum-of-node-values.py ├── 307.range-sum-query-mutable.cpp ├── 307.range-sum-query-mutable.py ├── 309.best-time-to-buy-and-sell-stock-with-cooldown.cpp ├── 309.best-time-to-buy-and-sell-stock-with-cooldown.py ├── 3090.maximum-length-substring-with-two-occurrences.cpp ├── 3090.maximum-length-substring-with-two-occurrences.py ├── 31.next-permutation.cpp ├── 31.next-permutation.py ├── 310.minimum-height-trees.cpp ├── 310.minimum-height-trees.py ├── 3108.minimum-cost-walk-in-weighted-graph.cpp ├── 3108.minimum-cost-walk-in-weighted-graph.py ├── 312.burst-balloons.cpp ├── 312.burst-balloons.py ├── 313.super-ugly-number.cpp ├── 313.super-ugly-number.py ├── 3134.find-the-median-of-the-uniqueness-array.cpp ├── 3134.find-the-median-of-the-uniqueness-array.py ├── 3160.find-the-number-of-distinct-colors-among-the-balls.cpp ├── 3160.find-the-number-of-distinct-colors-among-the-balls.py ├── 3169.count-days-without-meetings.cpp ├── 3169.count-days-without-meetings.py ├── 3174.clear-digits.cpp ├── 3174.clear-digits.py ├── 318.maximum-product-of-word-lengths.cpp ├── 318.maximum-product-of-word-lengths.py ├── 3191.minimum-operations-to-make-binary-array-elements-equal-to-one-i.cpp ├── 3191.minimum-operations-to-make-binary-array-elements-equal-to-one-i.py ├── 32.longest-valid-parentheses.cpp ├── 32.longest-valid-parentheses.py ├── 3206.alternating-groups-i.cpp ├── 3206.alternating-groups-i.py ├── 3208.alternating-groups-ii.cpp ├── 3208.alternating-groups-ii.py ├── 322.coin-change.cpp ├── 322.coin-change.py ├── 323.number-of-connected-components-in-an-undirected-graph.cpp ├── 323.number-of-connected-components-in-an-undirected-graph.py ├── 324.wiggle-sort-ii.cpp ├── 324.wiggle-sort-ii.py ├── 3258.count-substrings-that-satisfy-k-constraint-i.cpp ├── 3258.count-substrings-that-satisfy-k-constraint-i.py ├── 326.power-of-three.cpp ├── 326.power-of-three.py ├── 3261.count-substrings-that-satisfy-k-constraint-ii.cpp ├── 3261.count-substrings-that-satisfy-k-constraint-ii.py ├── 3272.find-the-count-of-good-integers.cpp ├── 3272.find-the-count-of-good-integers.py ├── 3274.check-if-two-chessboard-squares-have-the-same-color.cpp ├── 3274.check-if-two-chessboard-squares-have-the-same-color.py ├── 3275.k-th-nearest-obstacle-queries.cpp ├── 3275.k-th-nearest-obstacle-queries.py ├── 3276.select-cells-in-grid-with-maximum-score.cpp ├── 3276.select-cells-in-grid-with-maximum-score.py ├── 3277.maximum-xor-score-subarray-queries.cpp ├── 3277.maximum-xor-score-subarray-queries.py ├── 328.odd-even-linked-list.cpp ├── 328.odd-even-linked-list.py ├── 3280.convert-date-to-binary.cpp ├── 3280.convert-date-to-binary.py ├── 3281.maximize-score-of-numbers-in-ranges.cpp ├── 3281.maximize-score-of-numbers-in-ranges.py ├── 3282.reach-end-of-array-with-max-score.cpp ├── 3282.reach-end-of-array-with-max-score.py ├── 3283.maximum-number-of-moves-to-kill-all-pawns.cpp ├── 3283.maximum-number-of-moves-to-kill-all-pawns.py ├── 3285.find-indices-of-stable-mountains.cpp ├── 3285.find-indices-of-stable-mountains.py ├── 3286.find-a-safe-walk-through-a-grid.cpp ├── 3286.find-a-safe-walk-through-a-grid.py ├── 329.longest-increasing-path-in-a-matrix.cpp ├── 329.longest-increasing-path-in-a-matrix.py ├── 3298.count-substrings-that-can-be-rearranged-to-contain-a-string-ii.cpp ├── 3298.count-substrings-that-can-be-rearranged-to-contain-a-string-ii.py ├── 33.search-in-rotated-sorted-array.cpp ├── 33.search-in-rotated-sorted-array.py ├── 3306.count-of-substrings-containing-every-vowel-and-k-consonants-ii.cpp ├── 3306.count-of-substrings-containing-every-vowel-and-k-consonants-ii.py ├── 332.reconstruct-itinerary.cpp ├── 332.reconstruct-itinerary.py ├── 3323.minimize-connected-groups-by-inserting-interval.vip ├── 3325.count-substrings-with-k-frequency-characters-i.cpp ├── 3325.count-substrings-with-k-frequency-characters-i.py ├── 3335.total-characters-in-string-after-transformations-i.cpp ├── 3335.total-characters-in-string-after-transformations-i.py ├── 3337.total-characters-in-string-after-transformations-ii.cpp ├── 3337.total-characters-in-string-after-transformations-ii.py ├── 3340.check-balanced-string.cpp ├── 3340.check-balanced-string.py ├── 3341.find-minimum-time-to-reach-last-room-i.cpp ├── 3341.find-minimum-time-to-reach-last-room-i.py ├── 3342.find-minimum-time-to-reach-last-room-ii.cpp ├── 3342.find-minimum-time-to-reach-last-room-ii.py ├── 3343.count-number-of-balanced-permutations.cpp ├── 3343.count-number-of-balanced-permutations.py ├── 3355.zero-array-transformation-i.cpp ├── 3355.zero-array-transformation-i.py ├── 3356.zero-array-transformation-ii.cpp ├── 3356.zero-array-transformation-ii.py ├── 336.palindrome-pairs.py ├── 3362.zero-array-transformation-iii.cpp ├── 3362.zero-array-transformation-iii.py ├── 337.house-robber-iii.cpp ├── 337.house-robber-iii.py ├── 3372.maximize-the-number-of-target-nodes-after-connecting-trees-i.cpp ├── 3372.maximize-the-number-of-target-nodes-after-connecting-trees-i.py ├── 3373.maximize-the-number-of-target-nodes-after-connecting-trees-ii.cpp ├── 3373.maximize-the-number-of-target-nodes-after-connecting-trees-ii.py ├── 3375.minimum-operations-to-make-array-values-equal-to-k.cpp ├── 3375.minimum-operations-to-make-array-values-equal-to-k.py ├── 338.counting-bits.cpp ├── 338.counting-bits.py ├── 3386.button-with-longest-push-time.cpp ├── 3386.button-with-longest-push-time.py ├── 3387.maximize-amount-after-two-days-of-conversions.cpp ├── 3387.maximize-amount-after-two-days-of-conversions.py ├── 3392.count-subarrays-of-length-three-with-a-condition.cpp ├── 3392.count-subarrays-of-length-three-with-a-condition.py ├── 3394.check-if-grid-can-be-cut-into-sections.cpp ├── 3394.check-if-grid-can-be-cut-into-sections.py ├── 3396.minimum-number-of-operations-to-make-elements-in-array-distinct.cpp ├── 3396.minimum-number-of-operations-to-make-elements-in-array-distinct.py ├── 34.find-first-and-last-position-of-element-in-sorted-array.cpp ├── 34.find-first-and-last-position-of-element-in-sorted-array.py ├── 3403.find-the-lexicographically-largest-string-from-the-box-i.cpp ├── 3403.find-the-lexicographically-largest-string-from-the-box-i.py ├── 341.flatten-nested-list-iterator.cpp ├── 341.flatten-nested-list-iterator.py ├── 3411.maximum-subarray-with-equal-products.cpp ├── 3411.maximum-subarray-with-equal-products.py ├── 3413.maximum-coins-from-k-consecutive-bags.cpp ├── 3413.maximum-coins-from-k-consecutive-bags.py ├── 342.power-of-four.cpp ├── 342.power-of-four.py ├── 343.integer-break.cpp ├── 343.integer-break.py ├── 3439.reschedule-meetings-for-maximum-free-time-i.cpp ├── 3439.reschedule-meetings-for-maximum-free-time-i.py ├── 344.reverse-string.cpp ├── 344.reverse-string.py ├── 345.reverse-vowels-of-a-string.cpp ├── 345.reverse-vowels-of-a-string.py ├── 346.moving-average-from-data-stream.cpp ├── 346.moving-average-from-data-stream.py ├── 3467.transform-array-by-parity.cpp ├── 3467.transform-array-by-parity.py ├── 347.top-k-frequent-elements.cpp ├── 347.top-k-frequent-elements.py ├── 349.intersection-of-two-arrays.cpp ├── 349.intersection-of-two-arrays.py ├── 35.search-insert-position.cpp ├── 35.search-insert-position.py ├── 350.intersection-of-two-arrays-ii.cpp ├── 350.intersection-of-two-arrays-ii.py ├── 354.russian-doll-envelopes.cpp ├── 354.russian-doll-envelopes.py ├── 359.logger-rate-limiter.cpp ├── 36.valid-sudoku.cpp ├── 36.valid-sudoku.py ├── 360.sort-transformed-array.vip ├── 366.find-leaves-of-binary-tree.cpp ├── 366.find-leaves-of-binary-tree.py ├── 367.valid-perfect-square.cpp ├── 367.valid-perfect-square.py ├── 368.largest-divisible-subset.cpp ├── 368.largest-divisible-subset.py ├── 37.sudoku-solver.cpp ├── 37.sudoku-solver.py ├── 370.range-addition.vip ├── 371.sum-of-two-integers.cpp ├── 371.sum-of-two-integers.py ├── 374.guess-number-higher-or-lower.cpp ├── 374.guess-number-higher-or-lower.py ├── 375.guess-number-higher-or-lower-ii.cpp ├── 375.guess-number-higher-or-lower-ii.py ├── 376.wiggle-subsequence.cpp ├── 376.wiggle-subsequence.py ├── 377.combination-sum-iv.cpp ├── 377.combination-sum-iv.py ├── 378.kth-smallest-element-in-a-sorted-matrix.cpp ├── 378.kth-smallest-element-in-a-sorted-matrix.py ├── 38.count-and-say.cpp ├── 38.count-and-say.py ├── 380.insert-delete-getrandom-o1.cpp ├── 380.insert-delete-getrandom-o1.py ├── 382.linked-list-random-node.cpp ├── 382.linked-list-random-node.py ├── 383.ransom-note.cpp ├── 383.ransom-note.py ├── 384.shuffle-an-array.cpp ├── 384.shuffle-an-array.py ├── 387.first-unique-character-in-a-string.cpp ├── 387.first-unique-character-in-a-string.py ├── 388.longest-absolute-file-path.cpp ├── 388.longest-absolute-file-path.py ├── 39.combination-sum.cpp ├── 39.combination-sum.py ├── 393.utf-8-validation.cpp ├── 393.utf-8-validation.py ├── 394.decode-string.cpp ├── 394.decode-string.py ├── 395.longest-substring-with-at-least-k-repeating-characters.cpp ├── 395.longest-substring-with-at-least-k-repeating-characters.py ├── 4.median-of-two-sorted-arrays.cpp ├── 4.median-of-two-sorted-arrays.py ├── 40.combination-sum-ii.cpp ├── 40.combination-sum-ii.py ├── 403.frog-jump.cpp ├── 403.frog-jump.py ├── 404.sum-of-left-leaves.cpp ├── 404.sum-of-left-leaves.py ├── 406.queue-reconstruction-by-height.cpp ├── 406.queue-reconstruction-by-height.py ├── 407.trapping-rain-water-ii.cpp ├── 407.trapping-rain-water-ii.py ├── 408.valid-word-abbreviation.cpp ├── 408.valid-word-abbreviation.py ├── 409.longest-palindrome.cpp ├── 409.longest-palindrome.py ├── 41.first-missing-positive.cpp ├── 41.first-missing-positive.py ├── 413.arithmetic-slices.cpp ├── 413.arithmetic-slices.py ├── 415.add-strings.cpp ├── 415.add-strings.py ├── 416.partition-equal-subset-sum.cpp ├── 416.partition-equal-subset-sum.py ├── 417.pacific-atlantic-water-flow.cpp ├── 417.pacific-atlantic-water-flow.py ├── 42.trapping-rain-water.cpp ├── 42.trapping-rain-water.py ├── 424.longest-repeating-character-replacement.cpp ├── 424.longest-repeating-character-replacement.py ├── 43.multiply-strings.cpp ├── 43.multiply-strings.py ├── 432.all-oone-data-structure.cpp ├── 432.all-oone-data-structure.py ├── 433.minimum-genetic-mutation.cpp ├── 433.minimum-genetic-mutation.py ├── 435.non-overlapping-intervals.cpp ├── 435.non-overlapping-intervals.py ├── 437.path-sum-iii.cpp ├── 437.path-sum-iii.py ├── 438.find-all-anagrams-in-a-string.cpp ├── 438.find-all-anagrams-in-a-string.py ├── 44.wildcard-matching.cpp ├── 44.wildcard-matching.py ├── 442.find-all-duplicates-in-an-array.cpp ├── 442.find-all-duplicates-in-an-array.py ├── 444.sequence-reconstruction.cpp ├── 444.sequence-reconstruction.py ├── 447.number-of-boomerangs.cpp ├── 447.number-of-boomerangs.py ├── 448.find-all-numbers-disappeared-in-an-array.cpp ├── 448.find-all-numbers-disappeared-in-an-array.py ├── 449.serialize-and-deserialize-bst.cpp ├── 449.serialize-and-deserialize-bst.py ├── 45.jump-game-ii.cpp ├── 45.jump-game-ii.py ├── 450.delete-node-in-a-bst.cpp ├── 450.delete-node-in-a-bst.py ├── 451.sort-characters-by-frequency.cpp ├── 451.sort-characters-by-frequency.py ├── 452.minimum-number-of-arrows-to-burst-balloons.cpp ├── 452.minimum-number-of-arrows-to-burst-balloons.py ├── 454.4sum-ii.cpp ├── 455.assign-cookies.cpp ├── 455.assign-cookies.py ├── 46.permutations.cpp ├── 46.permutations.py ├── 461.hamming-distance.cpp ├── 461.hamming-distance.py ├── 462.minimum-moves-to-equal-array-elements-ii.cpp ├── 462.minimum-moves-to-equal-array-elements-ii.py ├── 463.island-perimeter.py ├── 47.permutations-ii.cpp ├── 47.permutations-ii.py ├── 470.implement-rand10-using-rand7.cpp ├── 470.implement-rand10-using-rand7.py ├── 474.ones-and-zeroes.cpp ├── 474.ones-and-zeroes.py ├── 476.number-complement.cpp ├── 476.number-complement.py ├── 48.rotate-image.cpp ├── 48.rotate-image.py ├── 480.sliding-window-median.cpp ├── 480.sliding-window-median.py ├── 485.max-consecutive-ones.cpp ├── 49.group-anagrams.cpp ├── 49.group-anagrams.py ├── 494.target-sum.cpp ├── 494.target-sum.py ├── 498.diagonal-traverse.cpp ├── 5.longest-palindromic-substring.cpp ├── 5.longest-palindromic-substring.py ├── 50.powx-n.cpp ├── 50.powx-n.py ├── 503.next-greater-element-ii.cpp ├── 503.next-greater-element-ii.py ├── 504.base-7.cpp ├── 504.base-7.py ├── 51.n-queens.cpp ├── 51.n-queens.py ├── 513.find-bottom-left-tree-value.cpp ├── 513.find-bottom-left-tree-value.py ├── 516.longest-palindromic-subsequence.cpp ├── 516.longest-palindromic-subsequence.py ├── 518.coin-change-ii.cpp ├── 518.coin-change-ii.py ├── 52.n-queens-ii.cpp ├── 52.n-queens-ii.py ├── 524.longest-word-in-dictionary-through-deleting.cpp ├── 524.longest-word-in-dictionary-through-deleting.py ├── 525.contiguous-array.cpp ├── 525.contiguous-array.py ├── 528.random-pick-with-weight.cpp ├── 528.random-pick-with-weight.py ├── 53.maximum-subarray.cpp ├── 53.maximum-subarray.py ├── 530.minimum-absolute-difference-in-bst.cpp ├── 530.minimum-absolute-difference-in-bst.py ├── 532.k-diff-pairs-in-an-array.cpp ├── 532.k-diff-pairs-in-an-array.py ├── 535.encode-and-decode-tinyurl.cpp ├── 535.encode-and-decode-tinyurl.py ├── 538.convert-bst-to-greater-tree.cpp ├── 538.convert-bst-to-greater-tree.py ├── 54.spiral-matrix.cpp ├── 54.spiral-matrix.py ├── 540.single-element-in-a-sorted-array.cpp ├── 540.single-element-in-a-sorted-array.py ├── 542.01-matrix.cpp ├── 542.01-matrix.py ├── 543.diameter-of-binary-tree.cpp ├── 543.diameter-of-binary-tree.py ├── 547.number-of-provinces.cpp ├── 547.number-of-provinces.py ├── 55.jump-game.cpp ├── 55.jump-game.py ├── 56.merge-intervals.cpp ├── 56.merge-intervals.py ├── 560.subarray-sum-equals-k.cpp ├── 560.subarray-sum-equals-k.py ├── 561.array-partition-i.cpp ├── 566.reshape-the-matrix.cpp ├── 566.reshape-the-matrix.py ├── 567.permutation-in-string.cpp ├── 567.permutation-in-string.py ├── 57.insert-interval.cpp ├── 57.insert-interval.py ├── 572.subtree-of-another-tree.cpp ├── 572.subtree-of-another-tree.py ├── 581.shortest-unsorted-continuous-subarray.cpp ├── 581.shortest-unsorted-continuous-subarray.py ├── 583.delete-operation-for-two-strings.cpp ├── 583.delete-operation-for-two-strings.py ├── 588.design-in-memory-file-system.vip ├── 594.longest-harmonious-subsequence.cpp ├── 594.longest-harmonious-subsequence.py ├── 599.minimum-index-sum-of-two-lists.cpp ├── 6.zigzag-conversion.py ├── 605.can-place-flowers.cpp ├── 605.can-place-flowers.py ├── 61.rotate-list.py ├── 611.valid-triangle-number.cpp ├── 611.valid-triangle-number.py ├── 617.merge-two-binary-trees.cpp ├── 617.merge-two-binary-trees.py ├── 62.unique-paths.cpp ├── 62.unique-paths.py ├── 621.task-scheduler.cpp ├── 621.task-scheduler.py ├── 63.unique-paths-ii.cpp ├── 63.unique-paths-ii.py ├── 632.smallest-range-covering-elements-from-k-lists.cpp ├── 632.smallest-range-covering-elements-from-k-lists.py ├── 633.sum-of-square-numbers.cpp ├── 633.sum-of-square-numbers.py ├── 637.average-of-levels-in-binary-tree.cpp ├── 637.average-of-levels-in-binary-tree.py ├── 64.minimum-path-sum.cpp ├── 64.minimum-path-sum.py ├── 643.maximum-average-subarray-i.cpp ├── 643.maximum-average-subarray-i.py ├── 645.set-mismatch.cpp ├── 645.set-mismatch.py ├── 646.maximum-length-of-pair-chain.cpp ├── 646.maximum-length-of-pair-chain.py ├── 647.palindromic-substrings.cpp ├── 647.palindromic-substrings.py ├── 650.2-keys-keyboard.cpp ├── 650.2-keys-keyboard.py ├── 652.find-duplicate-subtrees.cpp ├── 653.two-sum-iv-input-is-a-bst.cpp ├── 653.two-sum-iv-input-is-a-bst.py ├── 654.maximum-binary-tree.cpp ├── 654.maximum-binary-tree.py ├── 657.robot-return-to-origin.py ├── 658.find-k-closest-elements.cpp ├── 658.find-k-closest-elements.py ├── 66.plus-one.cpp ├── 66.plus-one.py ├── 662.maximum-width-of-binary-tree.cpp ├── 662.maximum-width-of-binary-tree.py ├── 665.non-decreasing-array.cpp ├── 665.non-decreasing-array.py ├── 669.trim-a-binary-search-tree.cpp ├── 669.trim-a-binary-search-tree.py ├── 67.add-binary.cpp ├── 67.add-binary.py ├── 674.longest-continuous-increasing-subsequence.cpp ├── 674.longest-continuous-increasing-subsequence.py ├── 677.map-sum-pairs.cpp ├── 677.map-sum-pairs.py ├── 68.text-justification.py ├── 680.valid-palindrome-ii.cpp ├── 680.valid-palindrome-ii.py ├── 684.redundant-connection.cpp ├── 684.redundant-connection.py ├── 687.longest-univalue-path.cpp ├── 687.longest-univalue-path.py ├── 69.sqrtx.cpp ├── 69.sqrtx.py ├── 692.top-k-frequent-words.cpp ├── 692.top-k-frequent-words.py ├── 693.binary-number-with-alternating-bits.cpp ├── 693.binary-number-with-alternating-bits.py ├── 695.max-area-of-island.cpp ├── 695.max-area-of-island.py ├── 696.count-binary-substrings.cpp ├── 696.count-binary-substrings.py ├── 697.degree-of-an-array.cpp ├── 697.degree-of-an-array.py ├── 7.reverse-integer.cpp ├── 7.reverse-integer.py ├── 70.climbing-stairs.cpp ├── 70.climbing-stairs.py ├── 701.insert-into-a-binary-search-tree.cpp ├── 701.insert-into-a-binary-search-tree.py ├── 702.search-in-a-sorted-array-of-unknown-size.cpp ├── 702.search-in-a-sorted-array-of-unknown-size.py ├── 703.kth-largest-element-in-a-stream.cpp ├── 703.kth-largest-element-in-a-stream.py ├── 704.binary-search.cpp ├── 704.binary-search.py ├── 713.subarray-product-less-than-k.cpp ├── 713.subarray-product-less-than-k.py ├── 714.best-time-to-buy-and-sell-stock-with-transaction-fee.cpp ├── 714.best-time-to-buy-and-sell-stock-with-transaction-fee.py ├── 718.maximum-length-of-repeated-subarray.cpp ├── 718.maximum-length-of-repeated-subarray.py ├── 72.edit-distance.cpp ├── 72.edit-distance.py ├── 721.accounts-merge.cpp ├── 721.accounts-merge.py ├── 724.find-pivot-index.cpp ├── 729.my-calendar-i.cpp ├── 729.my-calendar-i.py ├── 73.set-matrix-zeroes.cpp ├── 73.set-matrix-zeroes.py ├── 731.my-calendar-ii.cpp ├── 731.my-calendar-ii.py ├── 732.my-calendar-iii.cpp ├── 732.my-calendar-iii.py ├── 733.flood-fill.cpp ├── 733.flood-fill.py ├── 735.asteroid-collision.cpp ├── 735.asteroid-collision.py ├── 739.daily-temperatures.cpp ├── 739.daily-temperatures.py ├── 74.search-a-2d-matrix.cpp ├── 74.search-a-2d-matrix.py ├── 743.network-delay-time.cpp ├── 743.network-delay-time.py ├── 747.largest-number-at-least-twice-of-others.cpp ├── 75.sort-colors.cpp ├── 75.sort-colors.py ├── 751.ip-to-cidr.py ├── 755.pour-water.py ├── 76.minimum-window-substring.cpp ├── 76.minimum-window-substring.py ├── 760.find-anagram-mappings.py ├── 763.partition-labels.cpp ├── 763.partition-labels.py ├── 769.max-chunks-to-make-sorted.cpp ├── 769.max-chunks-to-make-sorted.py ├── 77.combinations.cpp ├── 77.combinations.py ├── 771.jewels-and-stones.cpp ├── 773.sliding-puzzle.py ├── 777.swap-adjacent-in-lr-string.cpp ├── 777.swap-adjacent-in-lr-string.py ├── 778.swim-in-rising-water.cpp ├── 778.swim-in-rising-water.py ├── 78.subsets.cpp ├── 78.subsets.py ├── 781.rabbits-in-forest.cpp ├── 781.rabbits-in-forest.py ├── 785.is-graph-bipartite.cpp ├── 785.is-graph-bipartite.py ├── 787.cheapest-flights-within-k-stops.cpp ├── 787.cheapest-flights-within-k-stops.py ├── 79.word-search.cpp ├── 79.word-search.py ├── 790.domino-and-tromino-tiling.cpp ├── 790.domino-and-tromino-tiling.py ├── 796.rotate-string.cpp ├── 796.rotate-string.py ├── 8.string-to-integer-atoi.cpp ├── 8.string-to-integer-atoi.py ├── 80.remove-duplicates-from-sorted-array-ii.cpp ├── 80.remove-duplicates-from-sorted-array-ii.py ├── 809.expressive-words.cpp ├── 809.expressive-words.py ├── 81.search-in-rotated-sorted-array-ii.cpp ├── 81.search-in-rotated-sorted-array-ii.py ├── 815.bus-routes.py ├── 825.friends-of-appropriate-ages.cpp ├── 825.friends-of-appropriate-ages.py ├── 829.consecutive-numbers-sum.py ├── 83.remove-duplicates-from-sorted-list.cpp ├── 83.remove-duplicates-from-sorted-list.py ├── 832.flipping-an-image.py ├── 836.rectangle-overlap.cpp ├── 836.rectangle-overlap.py ├── 838.push-dominoes.cpp ├── 838.push-dominoes.py ├── 84.largest-rectangle-in-histogram.cpp ├── 84.largest-rectangle-in-histogram.py ├── 844.backspace-string-compare.cpp ├── 844.backspace-string-compare.py ├── 846.hand-of-straights.cpp ├── 846.hand-of-straights.py ├── 85.maximal-rectangle.cpp ├── 85.maximal-rectangle.py ├── 852.peak-index-in-a-mountain-array.cpp ├── 852.peak-index-in-a-mountain-array.py ├── 853.car-fleet.cpp ├── 853.car-fleet.py ├── 859.buddy-strings.cpp ├── 86.partition-list.cpp ├── 86.partition-list.py ├── 860.lemonade-change.cpp ├── 860.lemonade-change.py ├── 863.all-nodes-distance-k-in-binary-tree.cpp ├── 863.all-nodes-distance-k-in-binary-tree.py ├── 865.smallest-subtree-with-all-the-deepest-nodes.cpp ├── 865.smallest-subtree-with-all-the-deepest-nodes.py ├── 87.scramble-string.cpp ├── 87.scramble-string.py ├── 870.advantage-shuffle.cpp ├── 870.advantage-shuffle.py ├── 873.length-of-longest-fibonacci-subsequence.cpp ├── 873.length-of-longest-fibonacci-subsequence.py ├── 874.walking-robot-simulation.cpp ├── 874.walking-robot-simulation.py ├── 875.koko-eating-bananas.cpp ├── 875.koko-eating-bananas.py ├── 876.middle-of-the-linked-list.cpp ├── 876.middle-of-the-linked-list.py ├── 877.stone-game.cpp ├── 877.stone-game.py ├── 88.merge-sorted-array.cpp ├── 88.merge-sorted-array.py ├── 882.reachable-nodes-in-subdivided-graph.cpp ├── 882.reachable-nodes-in-subdivided-graph.py ├── 889.construct-binary-tree-from-preorder-and-postorder-traversal.cpp ├── 889.construct-binary-tree-from-preorder-and-postorder-traversal.py ├── 895.maximum-frequency-stack.cpp ├── 895.maximum-frequency-stack.py ├── 897.increasing-order-search-tree.cpp ├── 897.increasing-order-search-tree.py ├── 9.palindrome-number.cpp ├── 9.palindrome-number.py ├── 90.subsets-ii.cpp ├── 90.subsets-ii.py ├── 904.fruit-into-baskets.cpp ├── 904.fruit-into-baskets.py ├── 905.sort-array-by-parity.cpp ├── 905.sort-array-by-parity.py ├── 909.snakes-and-ladders.cpp ├── 909.snakes-and-ladders.py ├── 91.decode-ways.cpp ├── 91.decode-ways.py ├── 92.reverse-linked-list-ii.cpp ├── 92.reverse-linked-list-ii.py ├── 922.sort-array-by-parity-ii.cpp ├── 922.sort-array-by-parity-ii.py ├── 923.3sum-with-multiplicity.cpp ├── 923.3sum-with-multiplicity.py ├── 924.minimize-malware-spread.py ├── 925.long-pressed-name.cpp ├── 925.long-pressed-name.py ├── 928.minimize-malware-spread-ii.py ├── 929.unique-email-addresses.py ├── 930.binary-subarrays-with-sum.cpp ├── 930.binary-subarrays-with-sum.py ├── 932.beautiful-array.cpp ├── 932.beautiful-array.py ├── 933.number-of-recent-calls.cpp ├── 933.number-of-recent-calls.py ├── 934.shortest-bridge.cpp ├── 934.shortest-bridge.py ├── 938.range-sum-of-bst.cpp ├── 938.range-sum-of-bst.py ├── 94.binary-tree-inorder-traversal.cpp ├── 94.binary-tree-inorder-traversal.py ├── 948.bag-of-tokens.cpp ├── 948.bag-of-tokens.py ├── 97.interleaving-string.cpp ├── 97.interleaving-string.py ├── 973.k-closest-points-to-origin.cpp ├── 973.k-closest-points-to-origin.py ├── 977.squares-of-a-sorted-array.cpp ├── 977.squares-of-a-sorted-array.py ├── 98.validate-binary-search-tree.cpp ├── 98.validate-binary-search-tree.py ├── 981.time-based-key-value-store.cpp ├── 981.time-based-key-value-store.py ├── 986.interval-list-intersections.cpp ├── 986.interval-list-intersections.py ├── 99.recover-binary-search-tree.cpp ├── 99.recover-binary-search-tree.py ├── 992.subarrays-with-k-different-integers.cpp ├── 992.subarrays-with-k-different-integers.py ├── 994.rotting-oranges.cpp └── 994.rotting-oranges.py ├── lintcode ├── 11.search-range-in-binary-search-tree.cpp ├── 11.search-range-in-binary-search-tree.py ├── 125.backpack-ii.cpp ├── 125.backpack-ii.py ├── 126.max-tree.vip ├── 138.subarray-sum.cpp ├── 138.subarray-sum.py ├── 139.subarray-sum-closest.vip ├── 1396.set-union.vip ├── 14.first-position-of-target.cpp ├── 14.first-position-of-target.py ├── 144.interleaving-positive-and-negative-numbers.cpp ├── 144.interleaving-positive-and-negative-numbers.py ├── 1534.convert-binary-search-tree-to-sorted-doubly-linked-list.cpp ├── 1534.convert-binary-search-tree-to-sorted-doubly-linked-list.py ├── 178.graph-valid-tree.cpp ├── 178.graph-valid-tree.py ├── 1790.rotate-string-ii.cpp ├── 1790.rotate-string-ii.py ├── 183.wood-cut.cpp ├── 183.wood-cut.py ├── 201.segment-tree-build.cpp ├── 201.segment-tree-build.py ├── 202.segment-tree-query.vip ├── 203.segment-tree-modify.cpp ├── 203.segment-tree-modify.py ├── 205.interval-minimum-number.cpp ├── 205.interval-minimum-number.py ├── 206.interval-sum.cpp ├── 206.interval-sum.py ├── 22.flatten-list.cpp ├── 22.flatten-list.py ├── 31.partition-array.py ├── 3622.read-n-characters-given-read4.cpp ├── 3622.read-n-characters-given-read4.py ├── 3630.two-sum-less-than-target.cpp ├── 3630.two-sum-less-than-target.py ├── 3653.meeting-scheduler.cpp ├── 3653.meeting-scheduler.py ├── 366.fibonacci.cpp ├── 366.fibonacci.py ├── 3662.design-hit-counter.cpp ├── 3662.design-hit-counter.py ├── 3665.inorder-successor-in-bst-ii.cpp ├── 3665.inorder-successor-in-bst-ii.py ├── 3672.connecting-cities-with-minimum-cost.cpp ├── 3672.connecting-cities-with-minimum-cost.py ├── 3675.minimum-swaps-to-group-all-1s-together.cpp ├── 3675.minimum-swaps-to-group-all-1s-together.py ├── 3678.delete-interval.cpp ├── 3678.delete-interval.py ├── 3724.distinct-numbers-in-each-subarray.cpp ├── 3724.distinct-numbers-in-each-subarray.py ├── 3736.kth-smallest-subarray-sum.cpp ├── 3736.kth-smallest-subarray-sum.py ├── 3745.brightest-position-on-street.cpp ├── 3745.brightest-position-on-street.py ├── 3751.number-of-equal-count-substrings.cpp ├── 3751.number-of-equal-count-substrings.py ├── 3756.number-of-unique-flavors-remaining-after-sharing-k-candies.cpp ├── 3756.number-of-unique-flavors-remaining-after-sharing-k-candies.py ├── 382.triangle-count.cpp ├── 382.triangle-count.py ├── 3827.merge-operations-to-turn-array-into-a-palindrome.cpp ├── 3827.merge-operations-to-turn-array-into-a-palindrome.py ├── 3847.number-of-subarrays-having-even-product.cpp ├── 3847.number-of-subarrays-having-even-product.py ├── 386.longest-substring-with-at-most-k-distinct-characters.cpp ├── 386.longest-substring-with-at-most-k-distinct-characters.py ├── 3889.amount-of-new-area-painted-each-day.cpp ├── 3889.amount-of-new-area-painted-each-day.py ├── 39.recover-rotated-sorted-array.cpp ├── 39.recover-rotated-sorted-array.py ├── 390.find-peak-element-ii.cpp ├── 390.find-peak-element-ii.py ├── 391.number-of-airplanes-in-the-sky.cpp ├── 391.number-of-airplanes-in-the-sky.py ├── 394.coins-in-a-line.cpp ├── 394.coins-in-a-line.py ├── 395.coins-in-a-line-ii.cpp ├── 395.coins-in-a-line-ii.py ├── 396.coins-in-a-line-iii.cpp ├── 396.coins-in-a-line-iii.py ├── 396.coins-in-a-line-iii.vip ├── 402.continuous-subarray-sum.cpp ├── 402.continuous-subarray-sum.py ├── 403.continuous-subarray-sum-ii.vip ├── 404.subarray-sum-ii.vip ├── 405.submatrix-sum.vip ├── 434.number-of-islands-ii.cpp ├── 434.number-of-islands-ii.py ├── 437.copy-books.cpp ├── 437.copy-books.py ├── 439.segment-tree-build-ii.cpp ├── 439.segment-tree-build-ii.py ├── 440.backpack-iii.cpp ├── 440.backpack-iii.py ├── 447.search-in-a-big-sorted-array.vip ├── 448.inorder-successor-in-bst.cpp ├── 448.inorder-successor-in-bst.py ├── 457.classical-binary-search.cpp ├── 457.classical-binary-search.py ├── 458.last-position-of-target.vip ├── 461.kth-smallest-numbers-in-unsorted-array.vip ├── 462.total-occurrence-of-target.vip ├── 465.kth-smallest-sum-in-two-sorted-arrays.vip ├── 508.wiggle-sort.cpp ├── 508.wiggle-sort.py ├── 515.paint-house.cpp ├── 515.paint-house.py ├── 516.paint-house-ii.cpp ├── 516.paint-house-ii.py ├── 526.load-balancer.cpp ├── 526.load-balancer.py ├── 543.kth-largest-in-n-arrays.vip ├── 553.bomb-enemy.cpp ├── 553.bomb-enemy.py ├── 562.backpack-iv.cpp ├── 562.backpack-iv.py ├── 563.backpack-v.cpp ├── 563.backpack-v.py ├── 585.maximum-number-in-mountain-sequence.cpp ├── 585.maximum-number-in-mountain-sequence.py ├── 586.sqrtx-ii.vip ├── 589.connecting-graph.vip ├── 590.connecting-graph-ii.vip ├── 591.connecting-graph-iii.cpp ├── 591.connecting-graph-iii.py ├── 598.zombie-in-matrix.cpp ├── 598.zombie-in-matrix.py ├── 600.smallest-rectangle-enclosing-black-pixels.cpp ├── 600.smallest-rectangle-enclosing-black-pixels.py ├── 601.flatten-2d-vector.cpp ├── 601.flatten-2d-vector.py ├── 611.knight-shortest-path.cpp ├── 611.knight-shortest-path.py ├── 617.maximum-average-subarray-ii.cpp ├── 617.maximum-average-subarray-ii.py ├── 618.search-graph-nodes.cpp ├── 618.search-graph-nodes.py ├── 623.k-edit-distance.vip ├── 628.maximum-subtree.vip ├── 629.minimum-spanning-tree.cpp ├── 629.minimum-spanning-tree.py ├── 631.maximal-square-ii.vip ├── 634.word-squares.cpp ├── 634.word-squares.py ├── 637.valid-word-abbreviation.cpp ├── 637.valid-word-abbreviation.py ├── 639.word-abbreviation.cpp ├── 639.word-abbreviation.py ├── 640.one-edit-distance.cpp ├── 640.one-edit-distance.py ├── 641.missing-ranges.cpp ├── 641.missing-ranges.py ├── 642.moving-average-from-data-stream.cpp ├── 642.moving-average-from-data-stream.py ├── 644.strobogrammatic-number.cpp ├── 644.strobogrammatic-number.py ├── 645.find-the-celebrity.cpp ├── 645.find-the-celebrity.py ├── 648.unique-word-abbreviation.cpp ├── 648.unique-word-abbreviation.py ├── 649.binary-tree-upside-down.cpp ├── 649.binary-tree-upside-down.py ├── 650.find-leaves-of-binary-tree.cpp ├── 650.find-leaves-of-binary-tree.py ├── 651.binary-tree-vertical-order-traversal.cpp ├── 651.binary-tree-vertical-order-traversal.py ├── 652.factorization.cpp ├── 652.factorization.py ├── 654.sparse-matrix-multiplication.cpp ├── 654.sparse-matrix-multiplication.py ├── 659.encode-and-decode-strings.cpp ├── 659.encode-and-decode-strings.py ├── 660.read-n-characters-given-read4-ii-call-multiple-times.cpp ├── 660.read-n-characters-given-read4-ii-call-multiple-times.py ├── 79.longest-common-substring.cpp ├── 79.longest-common-substring.py ├── 805.maximum-association-set.vip ├── 821.time-intersection.vip ├── 849.basic-calculator-iii.cpp ├── 849.basic-calculator-iii.py ├── 850.employee-free-time.cpp ├── 850.employee-free-time.py ├── 859.max-stack.cpp ├── 859.max-stack.py ├── 861.k-empty-slots.cpp ├── 861.k-empty-slots.py ├── 883.max-consecutive-ones-ii.cpp ├── 883.max-consecutive-ones-ii.py ├── 89.k-sum.cpp ├── 89.k-sum.py ├── 91.minimum-adjustment-cost.cpp ├── 91.minimum-adjustment-cost.py ├── 91.minimum-adjustment-cost.vip ├── 918.3sum-smaller.cpp ├── 918.3sum-smaller.py ├── 919.meeting-rooms-ii.cpp ├── 919.meeting-rooms-ii.py ├── 92.backpack.cpp ├── 92.backpack.py ├── 920.meeting-rooms.cpp ├── 920.meeting-rooms.py ├── 928.longest-substring-with-at-most-two-distinct-characters.cpp └── 928.longest-substring-with-at-most-two-distinct-characters.py ├── list ├── .vscode │ └── settings.json ├── 9c-advanced.md ├── 9c-basic.md ├── 9c-dp.md ├── 9c-top.md ├── blind75.md ├── endlesscheng.md ├── geekbang.md ├── grind102.md ├── grind169.md ├── grind75.md ├── leetcode-75.md ├── leetcode-discuss.md ├── leetcode-google.md ├── leetcode-top-100-liked.md ├── leetcode-top-interview-150.md ├── leetcode-topics.md ├── leetcode-trending.md ├── leetcode101.md ├── neetcode150.md ├── script │ ├── google.py │ ├── leetcode-companywise-interview-questions-google.csv │ └── reddit_leetcode_google.json └── test.md ├── logger.py ├── pre_commit_readme_update.py ├── problem.py ├── requirements.txt ├── test.mov └── test ├── cpp.xcodeproj ├── project.pbxproj └── project.xcworkspace │ ├── contents.xcworkspacedata │ └── xcshareddata │ └── IDEWorkspaceChecks.plist ├── cpp └── main.cpp └── python.py /.gitignore: -------------------------------------------------------------------------------- 1 | test/test.xcodeproj/project.xcworkspace/xcuserdata 2 | test/test.xcodeproj/xcshareddata 3 | test/test.xcodeproj/xcuserdata 4 | test/cpp.xcodeproj/xcuserdata 5 | test/cpp.xcodeproj/project.xcworkspace/xcuserdata 6 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "*.tcc": "cpp", 4 | "deque": "cpp", 5 | "string": "cpp", 6 | "unordered_map": "cpp", 7 | "vector": "cpp", 8 | "random": "cpp", 9 | "limits": "cpp", 10 | "ios": "cpp", 11 | "queue": "cpp", 12 | "__bit_reference": "cpp", 13 | "__node_handle": "cpp", 14 | "array": "cpp", 15 | "istream": "cpp", 16 | "optional": "cpp", 17 | "ostream": "cpp", 18 | "sstream": "cpp", 19 | "streambuf": "cpp", 20 | "string_view": "cpp", 21 | "tuple": "cpp", 22 | "variant": "cpp", 23 | "__hash_table": "cpp", 24 | "iosfwd": "cpp", 25 | "__split_buffer": "cpp", 26 | "list": "cpp", 27 | "__tree": "cpp", 28 | "bitset": "cpp", 29 | "initializer_list": "cpp", 30 | "set": "cpp", 31 | "stack": "cpp", 32 | "unordered_set": "cpp" 33 | } 34 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 渴望越狱的猫 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Screen Recording 2025-06-02 at 13.42.55_4k.mov: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/Screen Recording 2025-06-02 at 13.42.55_4k.mov -------------------------------------------------------------------------------- /__pycache__/logger.cpython-312.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/__pycache__/logger.cpython-312.pyc -------------------------------------------------------------------------------- /__pycache__/logger.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/__pycache__/logger.cpython-38.pyc -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-109.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-109.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-11.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-11.png -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-110-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-110-1.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-110-2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-110-2.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-111.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-111.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-112-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-112-1.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-112-2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-112-2.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-113-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-113-1.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-113-2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-113-2.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-114.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-114.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-116.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-116.png -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-117.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-117.png -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-118.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-118.gif -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-124-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-124-1.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-124-2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-124-2.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-129-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-129-1.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-129-2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-129-2.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-130.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-130.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-142-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-142-1.png -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-142-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-142-2.png -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-142-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-142-3.png -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-17.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-17.png -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-36.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-36.png -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-37.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-37.png -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-42.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-42.png -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-48-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-48-1.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-48-2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-48-2.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-51.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-51.png -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-547-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-547-1.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-547-2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-547-2.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-62.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-62.png -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-73-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-73-1.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-73-2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-73-2.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-74-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-74-1.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-74-2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-74-2.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-79.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-79.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-84-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-84-1.png -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-84-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-84-2.png -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-85.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-85.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-94-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-94-1.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-94-2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-94-2.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-94-3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-94-3.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-97.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-97.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-99-1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-99-1.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-algorithm-99-2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-algorithm-99-2.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-sketch-algorithm-10.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-sketch-algorithm-10.png -------------------------------------------------------------------------------- /blog/images/leetcode-sketch-algorithm-123.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-sketch-algorithm-123.png -------------------------------------------------------------------------------- /blog/images/leetcode-sketch-algorithm-17.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-sketch-algorithm-17.png -------------------------------------------------------------------------------- /blog/images/leetcode-sketch-algorithm-22.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-sketch-algorithm-22.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-sketch-algorithm-23.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-sketch-algorithm-23.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-sketch-algorithm-36.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-sketch-algorithm-36.png -------------------------------------------------------------------------------- /blog/images/leetcode-sketch-algorithm-39.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-sketch-algorithm-39.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-sketch-algorithm-44.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-sketch-algorithm-44.jpg -------------------------------------------------------------------------------- /blog/images/leetcode-sketch-algorithm-59.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-sketch-algorithm-59.png -------------------------------------------------------------------------------- /blog/images/leetcode-sketch-algorithm-69.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/blog/images/leetcode-sketch-algorithm-69.png -------------------------------------------------------------------------------- /blog/leetcode-136.md: -------------------------------------------------------------------------------- 1 | --- 2 | layout: post 3 | index: 136 4 | title: "LeetCode-136.只出现一次的数字(Single Number)" 5 | categories: Leetcode 6 | tags: Leetcode HashTable BitManipulation 7 | excerpt: "" 8 | --- 9 | 10 | * content 11 | {:toc} 12 | 13 | ## 136. 只出现一次的数字 14 | 15 | 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。 16 | 17 | 说明: 18 | 19 | 你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗? 20 | 21 | 示例 1: 22 | 23 | ``` 24 | 输入: [2,2,1] 25 | 输出: 1 26 | ``` 27 | 28 | 示例 2: 29 | 30 | ``` 31 | 输入: [4,1,2,1,2] 32 | 输出: 4 33 | ``` 34 | 35 | 来源:力扣(LeetCode) 36 | 37 | 链接:[https://leetcode-cn.com/problems/single-number/](https://leetcode-cn.com/problems/single-number/) 38 | 39 | Link:[https://leetcode.com/problems/single-number/](https://leetcode.com/problems/single-number/) 40 | 41 | ## 二进制 42 | 43 | O(N) 44 | 45 | ```python 46 | x ^ 0 = x 47 | x ^ x = 0 48 | ``` 49 | 50 | 利用上述特性, 0与任意bit异或,都等于bit值。所以初始化为0 51 | 52 | ```python 53 | class Solution: 54 | def singleNumber(self, nums: List[int]) -> int: 55 | res = 0 56 | for n in nums: 57 | res ^= n 58 | 59 | return res 60 | ``` 61 | 62 | --End-- 63 | 64 | 65 | -------------------------------------------------------------------------------- /leetcode/1016.binary-string-with-substrings-representing-1-to-n.py: -------------------------------------------------------------------------------- 1 | # Tag: String 2 | # Time: O(|S|) 3 | # Space: O(N) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given a binary string s and a positive integer n, return true if the binary representation of all the integers in the range [1, n] are substrings of s, or false otherwise. 8 | # A substring is a contiguous sequence of characters within a string. 9 | #   10 | # Example 1: 11 | # Input: s = "0110", n = 3 12 | # Output: true 13 | # Example 2: 14 | # Input: s = "0110", n = 4 15 | # Output: false 16 | # 17 | #   18 | # Constraints: 19 | # 20 | # 1 <= s.length <= 1000 21 | # s[i] is either '0' or '1'. 22 | # 1 <= n <= 109 23 | # 24 | # 25 | 26 | import math 27 | class Solution: 28 | def queryString(self, s: str, n: int) -> bool: 29 | bits = math.ceil(math.log2(n + 1)) 30 | table = set() 31 | mask = 0 32 | for k in range(1, bits + 1): # 32 times most 33 | mask = (mask << 1) + 1 34 | num = 0 35 | for i in range(len(s)): 36 | num = ((num << 1) + int(s[i])) & mask 37 | if i >= k - 1: 38 | if 0 <= num <= n: 39 | table.add(num) 40 | 41 | return len(table) == n -------------------------------------------------------------------------------- /leetcode/103.binary-tree-zigzag-level-order-traversal.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def zigzagLevelOrder(self, root): 10 | """ 11 | :type root: TreeNode 12 | :rtype: List[List[int]] 13 | """ 14 | 15 | if root is None: 16 | return [] 17 | 18 | res = [] 19 | q = [root] 20 | backward = False 21 | 22 | while len(q) > 0: 23 | 24 | ans = [] 25 | size = len(q) 26 | for i in range(size): 27 | tmp = q.pop(0) 28 | ans.append(tmp.val) 29 | 30 | if tmp.left is not None: 31 | q.append(tmp.left) 32 | 33 | if tmp.right is not None: 34 | q.append(tmp.right) 35 | 36 | if backward: 37 | ans = ans[::-1] 38 | 39 | res.append(ans) 40 | backward = not backward 41 | 42 | return res 43 | -------------------------------------------------------------------------------- /leetcode/1059.all-paths-from-source-lead-to-destination.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/leetcode/1059.all-paths-from-source-lead-to-destination.vip -------------------------------------------------------------------------------- /leetcode/107.binary-tree-level-order-traversal-ii.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def levelOrderBottom(self, root): 10 | """ 11 | :type root: TreeNode 12 | :rtype: List[List[int]] 13 | """ 14 | if root is None: 15 | return [] 16 | 17 | res = [] 18 | q = [root] 19 | 20 | while len(q) > 0: 21 | size = len(q) 22 | ans = [] 23 | for i in range(size): 24 | tmp = q[0] 25 | q.pop(0) 26 | 27 | ans.append(tmp.val) 28 | 29 | if tmp.left is not None: 30 | q.append(tmp.left) 31 | 32 | if tmp.right is not None: 33 | q.append(tmp.right) 34 | 35 | res.append(ans) 36 | 37 | return res[::-1] -------------------------------------------------------------------------------- /leetcode/1100.find-k-length-substrings-with-no-repeated-characters.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/leetcode/1100.find-k-length-substrings-with-no-repeated-characters.vip -------------------------------------------------------------------------------- /leetcode/1176.diet-plan-performance.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/leetcode/1176.diet-plan-performance.vip -------------------------------------------------------------------------------- /leetcode/118.pascals-triangle.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> generate(int numRows) { 4 | vector> res; 5 | for (auto r = 1; r <= numRows; ++r) 6 | { 7 | vector ans(r, 1); 8 | for (auto i = 1; i < r - 1; ++i) 9 | { 10 | vector previous = res[res.size() - 1]; 11 | ans[i] = previous[i - 1] + previous[i]; 12 | } 13 | 14 | res.push_back(ans); 15 | } 16 | 17 | return res; 18 | } 19 | }; -------------------------------------------------------------------------------- /leetcode/118.pascals-triangle.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def generate(self, numRows): 3 | """ 4 | :type numRows: int 5 | :rtype: List[List[int]] 6 | """ 7 | res = [] 8 | 9 | for i in range(numRows): 10 | row = [] 11 | 12 | for j in range(i + 1): 13 | if j == 0 or j == i: 14 | row.append(1) 15 | else: 16 | val = res[-1][j - 1] + res[-1][j] 17 | row.append(val) 18 | 19 | res.append(row) 20 | 21 | return res -------------------------------------------------------------------------------- /leetcode/119.pascals-triangle-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector getRow(int rowIndex) { 4 | 5 | vector row(rowIndex + 1, 0); 6 | 7 | for (auto i = 0; i < rowIndex + 1; ++i) 8 | { 9 | for (auto j = i; j >= 0; --j) 10 | { 11 | if (j == 0 || j == i) 12 | { 13 | row[j] = 1; 14 | } 15 | else 16 | { 17 | row[j] = row[j] + row[j - 1]; 18 | } 19 | } 20 | } 21 | 22 | return row; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /leetcode/119.pascals-triangle-ii.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def getRow(self, rowIndex): 3 | """ 4 | :type rowIndex: int 5 | :rtype: List[int] 6 | """ 7 | row = [0 for i in range(rowIndex + 1)] 8 | 9 | for i in range(rowIndex + 1): 10 | for j in range(i, -1, -1): 11 | if j == 0 or j == i: 12 | row[j] = 1 13 | else: 14 | row[j] = row[j - 1] + row[j] 15 | 16 | return row 17 | -------------------------------------------------------------------------------- /leetcode/1197.minimum-knight-moves.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/leetcode/1197.minimum-knight-moves.vip -------------------------------------------------------------------------------- /leetcode/1288.remove-covered-intervals.py: -------------------------------------------------------------------------------- 1 | # Tag: Array, Sorting 2 | # Time: O(NlogN) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given an array intervals where intervals[i] = [li, ri] represent the interval [li, ri), remove all intervals that are covered by another interval in the list. 8 | # The interval [a, b) is covered by the interval [c, d) if and only if c <= a and b <= d. 9 | # Return the number of remaining intervals. 10 | #   11 | # Example 1: 12 | # 13 | # Input: intervals = [[1,4],[3,6],[2,8]] 14 | # Output: 2 15 | # Explanation: Interval [3,6] is covered by [2,8], therefore it is removed. 16 | # 17 | # Example 2: 18 | # 19 | # Input: intervals = [[1,4],[2,3]] 20 | # Output: 1 21 | # 22 | #   23 | # Constraints: 24 | # 25 | # 1 <= intervals.length <= 1000 26 | # intervals[i].length == 2 27 | # 0 <= li < ri <= 105 28 | # All the given intervals are unique. 29 | # 30 | # 31 | 32 | class Solution: 33 | def removeCoveredIntervals(self, intervals: List[List[int]]) -> int: 34 | intervals.sort(key=lambda x: (x[0], -x[1])) 35 | right = 0 36 | res = 0 37 | for l, r in intervals: 38 | res += r > right 39 | right = max(right, r) 40 | 41 | return res -------------------------------------------------------------------------------- /leetcode/1295.find-numbers-with-even-number-of-digits.py: -------------------------------------------------------------------------------- 1 | # Tag: Array, Math 2 | # Time: O(N) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | # Video: https://youtu.be/ngriRz5ITf4 7 | 8 | # Given an array nums of integers, return how many of them contain an even number of digits. 9 | #   10 | # Example 1: 11 | # 12 | # Input: nums = [12,345,2,6,7896] 13 | # Output: 2 14 | # Explanation: 15 | # 12 contains 2 digits (even number of digits).  16 | # 345 contains 3 digits (odd number of digits).  17 | # 2 contains 1 digit (odd number of digits).  18 | # 6 contains 1 digit (odd number of digits).  19 | # 7896 contains 4 digits (even number of digits).  20 | # Therefore only 12 and 7896 contain an even number of digits. 21 | # 22 | # Example 2: 23 | # 24 | # Input: nums = [555,901,482,1771] 25 | # Output: 1 26 | # Explanation: 27 | # Only 1771 contains an even number of digits. 28 | # 29 | #   30 | # Constraints: 31 | # 32 | # 1 <= nums.length <= 500 33 | # 1 <= nums[i] <= 105 34 | # 35 | # 36 | 37 | class Solution: 38 | def findNumbers(self, nums: List[int]) -> int: 39 | res = 0 40 | for x in nums: 41 | count = 0 42 | while x > 0: 43 | count += 1 44 | x //= 10 45 | 46 | res += count % 2 == 0 47 | 48 | return res -------------------------------------------------------------------------------- /leetcode/133.clone-graph.py: -------------------------------------------------------------------------------- 1 | # Definition for a undirected graph node 2 | # class UndirectedGraphNode: 3 | # def __init__(self, x): 4 | # self.label = x 5 | # self.neighbors = [] 6 | 7 | class Solution: 8 | # @param node, a undirected graph node 9 | # @return a undirected graph node 10 | def cloneGraph(self, node): 11 | if node is None: 12 | return None 13 | 14 | mappings = {} 15 | queue = [node] 16 | visited = set([node]) 17 | 18 | while len(queue) > 0: 19 | cur = queue.pop(0) 20 | 21 | if cur not in mappings: 22 | mappings[cur] = UndirectedGraphNode(cur.label) 23 | 24 | for neighbor in cur.neighbors: 25 | if neighbor not in mappings: 26 | mappings[neighbor] = UndirectedGraphNode(neighbor.label) 27 | 28 | mappings[cur].neighbors.append(mappings[neighbor]) 29 | 30 | if neighbor not in visited: 31 | visited.add(neighbor) 32 | queue.append(neighbor) 33 | 34 | return mappings[node] -------------------------------------------------------------------------------- /leetcode/136.single-number.cpp: -------------------------------------------------------------------------------- 1 | // Tag: Array, Bit Manipulation 2 | // Time: O(N) 3 | // Space: O(1) 4 | // Ref: - 5 | // Note: - 6 | 7 | // Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. 8 | // You must implement a solution with a linear runtime complexity and use only constant extra space. 9 | //   10 | // Example 1: 11 | // Input: nums = [2,2,1] 12 | // Output: 1 13 | // Example 2: 14 | // Input: nums = [4,1,2,1,2] 15 | // Output: 4 16 | // Example 3: 17 | // Input: nums = [1] 18 | // Output: 1 19 | // 20 | //   21 | // Constraints: 22 | // 23 | // 1 <= nums.length <= 3 * 104 24 | // -3 * 104 <= nums[i] <= 3 * 104 25 | // Each element in the array appears twice except for one element which appears only once. 26 | // 27 | // 28 | 29 | class Solution { 30 | public: 31 | int singleNumber(vector& nums) { 32 | int res = 0; 33 | for (auto x: nums) { 34 | res = res ^ x; 35 | } 36 | return res; 37 | } 38 | }; -------------------------------------------------------------------------------- /leetcode/136.single-number.py: -------------------------------------------------------------------------------- 1 | # Tag: Array, Bit Manipulation 2 | # Time: O(N) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. 8 | # You must implement a solution with a linear runtime complexity and use only constant extra space. 9 | #   10 | # Example 1: 11 | # Input: nums = [2,2,1] 12 | # Output: 1 13 | # Example 2: 14 | # Input: nums = [4,1,2,1,2] 15 | # Output: 4 16 | # Example 3: 17 | # Input: nums = [1] 18 | # Output: 1 19 | # 20 | #   21 | # Constraints: 22 | # 23 | # 1 <= nums.length <= 3 * 104 24 | # -3 * 104 <= nums[i] <= 3 * 104 25 | # Each element in the array appears twice except for one element which appears only once. 26 | # 27 | # 28 | 29 | class Solution: 30 | def singleNumber(self, nums: List[int]) -> int: 31 | res = 0 32 | for x in nums: 33 | res = res ^ x 34 | return res -------------------------------------------------------------------------------- /leetcode/14.longest-common-prefix.py: -------------------------------------------------------------------------------- 1 | # 2 | # [14] Longest Common Prefix 3 | # 4 | # https://leetcode.com/problems/longest-common-prefix/description/ 5 | # 6 | # algorithms 7 | # Easy (32.11%) 8 | # Total Accepted: 641.9K 9 | # Total Submissions: 1.9M 10 | # Testcase Example: '["flower","flow","flight"]' 11 | # 12 | # Write a function to find the longest common prefix string amongst an array of 13 | # strings. 14 | # 15 | # If there is no common prefix, return an empty string "". 16 | # 17 | # Example 1: 18 | # 19 | # 20 | # Input: ["flower","flow","flight"] 21 | # Output: "fl" 22 | # 23 | # 24 | # Example 2: 25 | # 26 | # 27 | # Input: ["dog","racecar","car"] 28 | # Output: "" 29 | # Explanation: There is no common prefix among the input strings. 30 | # 31 | # 32 | # Note: 33 | # 34 | # All given inputs are in lowercase letters a-z. 35 | # 36 | # 37 | class Solution: 38 | def longestCommonPrefix(self, strs: List[str]) -> str: 39 | 40 | if len(strs) == 0 or len(strs[0]) == 0: 41 | return '' 42 | 43 | res = '' 44 | for i in range(len(strs[0])): 45 | for j in range(1, len(strs)): 46 | if i >= len(strs[j]) or strs[j][i] != strs[0][i]: 47 | return res 48 | 49 | res += strs[0][i] 50 | 51 | return res -------------------------------------------------------------------------------- /leetcode/1550.three-consecutive-odds.cpp: -------------------------------------------------------------------------------- 1 | // Tag: Array 2 | // Time: O(N) 3 | // Space: O(1) 4 | // Ref: - 5 | // Note: - 6 | // Video: https://youtu.be/23ecGZB559Y 7 | 8 | // Given an integer array arr, return true if there are three consecutive odd numbers in the array. Otherwise, return false. 9 | //   10 | // Example 1: 11 | // 12 | // Input: arr = [2,6,4,1] 13 | // Output: false 14 | // Explanation: There are no three consecutive odds. 15 | // 16 | // Example 2: 17 | // 18 | // Input: arr = [1,2,34,3,4,5,7,23,12] 19 | // Output: true 20 | // Explanation: [5,7,23] are three consecutive odds. 21 | // 22 | //   23 | // Constraints: 24 | // 25 | // 1 <= arr.length <= 1000 26 | // 1 <= arr[i] <= 1000 27 | // 28 | // 29 | 30 | class Solution { 31 | public: 32 | bool threeConsecutiveOdds(vector& arr) { 33 | int count = 0; 34 | for (auto &x: arr) { 35 | if (x % 2 == 1) { 36 | count += 1; 37 | } else { 38 | count = 0; 39 | } 40 | 41 | if (count == 3) { 42 | return true; 43 | } 44 | } 45 | return false; 46 | } 47 | }; -------------------------------------------------------------------------------- /leetcode/1550.three-consecutive-odds.py: -------------------------------------------------------------------------------- 1 | # Tag: Array 2 | # Time: O(N) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | # Video: https://youtu.be/23ecGZB559Y 7 | 8 | # Given an integer array arr, return true if there are three consecutive odd numbers in the array. Otherwise, return false. 9 | #   10 | # Example 1: 11 | # 12 | # Input: arr = [2,6,4,1] 13 | # Output: false 14 | # Explanation: There are no three consecutive odds. 15 | # 16 | # Example 2: 17 | # 18 | # Input: arr = [1,2,34,3,4,5,7,23,12] 19 | # Output: true 20 | # Explanation: [5,7,23] are three consecutive odds. 21 | # 22 | #   23 | # Constraints: 24 | # 25 | # 1 <= arr.length <= 1000 26 | # 1 <= arr[i] <= 1000 27 | # 28 | # 29 | 30 | class Solution: 31 | def threeConsecutiveOdds(self, arr: List[int]) -> bool: 32 | count = 0 33 | for x in arr: 34 | if x % 2 == 1: 35 | count += 1 36 | else: 37 | count = 0 38 | 39 | if count == 3: 40 | return True 41 | 42 | return False -------------------------------------------------------------------------------- /leetcode/156.binary-tree-upside-down.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | 12 | private: 13 | TreeNode *newRoot = NULL; 14 | 15 | void invert(TreeNode *cur) 16 | { 17 | if (cur == NULL) 18 | { 19 | return; 20 | } 21 | 22 | if (cur->left == NULL) 23 | { 24 | newRoot = cur; 25 | } 26 | else 27 | { 28 | invert(cur->left); 29 | cur->left->left = cur->right; 30 | cur->left->right = cur; 31 | cur->left = NULL; 32 | cur->right = NULL; 33 | } 34 | } 35 | public: 36 | TreeNode* upsideDownBinaryTree(TreeNode* root) { 37 | invert(root); 38 | return newRoot; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /leetcode/156.binary-tree-upside-down.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | 10 | def __init__(self, *args, **kwargs): 11 | self.newRoot = None 12 | 13 | def invert(self, node): 14 | if node is None: 15 | return 16 | 17 | if node.left is None: 18 | self.newRoot = node 19 | else: 20 | self.invert(node.left) 21 | 22 | node.left.left = node.right 23 | node.left.right = node 24 | node.left = None 25 | node.right = None 26 | 27 | def upsideDownBinaryTree(self, root): 28 | """ 29 | :type root: TreeNode 30 | :rtype: TreeNode 31 | """ 32 | self.invert(root) 33 | return self.newRoot 34 | -------------------------------------------------------------------------------- /leetcode/168.excel-sheet-column-title.cpp: -------------------------------------------------------------------------------- 1 | // Tag: Math, String 2 | // Time: O(logN) 3 | // Space: O(1) 4 | // Ref: - 5 | // Note: - 6 | 7 | // Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet. 8 | // For example: 9 | // 10 | // A -> 1 11 | // B -> 2 12 | // C -> 3 13 | // ... 14 | // Z -> 26 15 | // AA -> 27 16 | // AB -> 28 17 | // ... 18 | // 19 | //   20 | // Example 1: 21 | // 22 | // Input: columnNumber = 1 23 | // Output: "A" 24 | // 25 | // Example 2: 26 | // 27 | // Input: columnNumber = 28 28 | // Output: "AB" 29 | // 30 | // Example 3: 31 | // 32 | // Input: columnNumber = 701 33 | // Output: "ZY" 34 | // 35 | //   36 | // Constraints: 37 | // 38 | // 1 <= columnNumber <= 231 - 1 39 | // 40 | // 41 | 42 | class Solution { 43 | public: 44 | string convertToTitle(int columnNumber) { 45 | string res = ""; 46 | while (columnNumber > 0) { 47 | columnNumber -= 1; 48 | char alphabet = columnNumber % 26 + 'A'; 49 | columnNumber = columnNumber / 26; 50 | res = alphabet + res; 51 | } 52 | return res; 53 | } 54 | }; -------------------------------------------------------------------------------- /leetcode/168.excel-sheet-column-title.py: -------------------------------------------------------------------------------- 1 | # Tag: Math, String 2 | # Time: O(logN) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet. 8 | # For example: 9 | # 10 | # A -> 1 11 | # B -> 2 12 | # C -> 3 13 | # ... 14 | # Z -> 26 15 | # AA -> 27 16 | # AB -> 28 17 | # ... 18 | # 19 | #   20 | # Example 1: 21 | # 22 | # Input: columnNumber = 1 23 | # Output: "A" 24 | # 25 | # Example 2: 26 | # 27 | # Input: columnNumber = 28 28 | # Output: "AB" 29 | # 30 | # Example 3: 31 | # 32 | # Input: columnNumber = 701 33 | # Output: "ZY" 34 | # 35 | #   36 | # Constraints: 37 | # 38 | # 1 <= columnNumber <= 231 - 1 39 | # 40 | # 41 | 42 | class Solution: 43 | def convertToTitle(self, columnNumber: int) -> str: 44 | res = '' 45 | alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 46 | while columnNumber > 0: 47 | columnNumber -= 1 48 | i = (columnNumber) % 26 49 | columnNumber = (columnNumber) // 26 50 | res = alphabet[i] + res 51 | 52 | return res -------------------------------------------------------------------------------- /leetcode/170.two-sum-iii-data-structure-design.cpp: -------------------------------------------------------------------------------- 1 | class TwoSum { 2 | private: 3 | unordered_map table; 4 | public: 5 | /** Initialize your data structure here. */ 6 | TwoSum() { 7 | 8 | } 9 | 10 | /** Add the number to an internal data structure.. */ 11 | void add(int number) { 12 | table[number]++; 13 | } 14 | 15 | /** Find if there exists any pair of numbers which sum is equal to the value. */ 16 | bool find(int value) { 17 | 18 | for (auto it: table){ //:Fixme 19 | 20 | int count = table[value - it.first]; 21 | if (count > 1 || (count == 1 && it.first != value - it.first)) 22 | { 23 | return true; 24 | } 25 | } 26 | 27 | return false; 28 | } 29 | }; -------------------------------------------------------------------------------- /leetcode/170.two-sum-iii-data-structure-design.py: -------------------------------------------------------------------------------- 1 | class TwoSum(object): 2 | 3 | def __init__(self): 4 | """ 5 | Initialize your data structure here. 6 | """ 7 | self.hash_map = {} 8 | 9 | def add(self, number): 10 | """ 11 | Add the number to an internal data structure.. 12 | :type number: int 13 | :rtype: void 14 | """ 15 | self.hash_map[number] = self.hash_map.get(number, 0) + 1 16 | 17 | def find(self, value): 18 | """ 19 | Find if there exists any pair of numbers which sum is equal to the value. 20 | :type value: int 21 | :rtype: bool 22 | """ 23 | for num in self.hash_map: 24 | 25 | target = value - num 26 | count = self.hash_map.get(value - num) 27 | 28 | if (count > 1) or (count == 1 and num != target): 29 | return True 30 | 31 | return False 32 | 33 | # Your TwoSum object will be instantiated and called as such: 34 | # obj = TwoSum() 35 | # obj.add(number) 36 | # param_2 = obj.find(value) -------------------------------------------------------------------------------- /leetcode/1730.shortest-path-to-get-food.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/leetcode/1730.shortest-path-to-get-food.vip -------------------------------------------------------------------------------- /leetcode/179.largest-number.cpp: -------------------------------------------------------------------------------- 1 | // Tag: Array, String, Greedy, Sorting 2 | // Time: O(NlogN * K) 3 | // Space: O(N) 4 | // Ref: - 5 | // Note: - 6 | 7 | // Given a list of non-negative integers nums, arrange them such that they form the largest number and return it. 8 | // Since the result may be very large, so you need to return a string instead of an integer. 9 | //   10 | // Example 1: 11 | // 12 | // Input: nums = [10,2] 13 | // Output: "210" 14 | // 15 | // Example 2: 16 | // 17 | // Input: nums = [3,30,34,5,9] 18 | // Output: "9534330" 19 | // 20 | //   21 | // Constraints: 22 | // 23 | // 1 <= nums.length <= 100 24 | // 0 <= nums[i] <= 109 25 | // 26 | // 27 | 28 | class Solution { 29 | public: 30 | string largestNumber(vector& nums) { 31 | vector strs; 32 | for (int x: nums) { 33 | strs.push_back(to_string(x)); 34 | } 35 | 36 | sort(strs.begin(), strs.end(), [](string x, string y) { 37 | return x + y > y + x; 38 | }); 39 | 40 | string res; 41 | for (auto &s: strs) { 42 | res += s; 43 | } 44 | 45 | return res[0] == '0' ? "0" : res; 46 | } 47 | }; -------------------------------------------------------------------------------- /leetcode/203.remove-linked-list-elements.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | def removeElements(self, head, val): 9 | """ 10 | :type head: ListNode 11 | :type val: int 12 | :rtype: ListNode 13 | """ 14 | new_head = ListNode(0) 15 | new_head.next = head 16 | 17 | cur = new_head 18 | while(cur.next is not None): 19 | node = cur.next 20 | if node.val != val: 21 | cur = cur.next 22 | continue 23 | 24 | cur.next = node.next 25 | del node 26 | 27 | return new_head.next -------------------------------------------------------------------------------- /leetcode/207.course-schedule.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canFinish(int numCourses, vector>& prerequisites) { 4 | 5 | unordered_map> graph; 6 | unordered_map indegree; 7 | for (auto courses : prerequisites) { 8 | indegree[courses.first] += 1; 9 | graph[courses.second].push_back(courses.first); 10 | } 11 | 12 | queue starts; 13 | for (auto i = 0; i < numCourses; ++i) 14 | { 15 | if (indegree.count(i) == 0) 16 | { 17 | starts.push(i); 18 | } 19 | } 20 | 21 | while (!starts.empty()) { 22 | int course = starts.front(); 23 | starts.pop(); 24 | 25 | vector nodes = graph[course]; 26 | for (auto i = 0; i < nodes.size(); ++i) 27 | { 28 | indegree[nodes[i]] -= 1; 29 | if (indegree[nodes[i]] == 0) 30 | { 31 | starts.push(nodes[i]); 32 | indegree.erase(nodes[i]); 33 | } 34 | } 35 | } 36 | 37 | return indegree.empty(); 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /leetcode/207.course-schedule.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def canFinish(self, numCourses, prerequisites): 3 | """ 4 | :type numCourses: int 5 | :type prerequisites: List[List[int]] 6 | :rtype: bool 7 | """ 8 | indegree = {i:0 for i in range(numCourses)} 9 | graph = {i:[] for i in range(numCourses)} 10 | take = 0 11 | 12 | for pair in prerequisites: 13 | indegree[pair[0]] += 1 14 | graph[pair[1]].append(pair[0]) 15 | 16 | q = [] 17 | for i in range(numCourses): 18 | if indegree[i] == 0: 19 | q.append(i) 20 | 21 | while(len(q) > 0): 22 | c = q.pop(0) 23 | take += 1 24 | 25 | for neighbor in graph[c]: 26 | if indegree.get(neighbor, 0) > 0: 27 | indegree[neighbor] -= 1 28 | if indegree[neighbor] == 0: 29 | q.append(neighbor) 30 | del indegree[neighbor] 31 | 32 | return take == numCourses -------------------------------------------------------------------------------- /leetcode/217.contains-duplicate.cpp: -------------------------------------------------------------------------------- 1 | // Tag: Array, Hash Table, Sorting 2 | // Time: O(N) 3 | // Space: O(N) 4 | // Ref: - 5 | // Note: - 6 | 7 | // Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. 8 | //   9 | // Example 1: 10 | // Input: nums = [1,2,3,1] 11 | // Output: true 12 | // Example 2: 13 | // Input: nums = [1,2,3,4] 14 | // Output: false 15 | // Example 3: 16 | // Input: nums = [1,1,1,3,3,4,3,2,4,2] 17 | // Output: true 18 | // 19 | //   20 | // Constraints: 21 | // 22 | // 1 <= nums.length <= 105 23 | // -109 <= nums[i] <= 109 24 | // 25 | // 26 | 27 | class Solution { 28 | public: 29 | bool containsDuplicate(vector& nums) { 30 | unordered_set set; 31 | for (auto x: nums) { 32 | if (set.count(x) > 0) { 33 | return true; 34 | } 35 | set.insert(x); 36 | } 37 | 38 | return false; 39 | } 40 | }; 41 | 42 | class Solution { 43 | public: 44 | bool containsDuplicate(vector& nums) { 45 | unordered_set set(nums.begin(), nums.end()); 46 | return nums.size() != set.size(); 47 | } 48 | }; -------------------------------------------------------------------------------- /leetcode/217.contains-duplicate.py: -------------------------------------------------------------------------------- 1 | # Tag: Array, Hash Table, Sorting 2 | # Time: O(N) 3 | # Space: O(N) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. 8 | #   9 | # Example 1: 10 | # Input: nums = [1,2,3,1] 11 | # Output: true 12 | # Example 2: 13 | # Input: nums = [1,2,3,4] 14 | # Output: false 15 | # Example 3: 16 | # Input: nums = [1,1,1,3,3,4,3,2,4,2] 17 | # Output: true 18 | # 19 | #   20 | # Constraints: 21 | # 22 | # 1 <= nums.length <= 105 23 | # -109 <= nums[i] <= 109 24 | # 25 | # 26 | 27 | class Solution: 28 | def containsDuplicate(self, nums: List[int]) -> bool: 29 | return len(nums) != len(set(nums)) 30 | 31 | class Solution: 32 | def containsDuplicate(self, nums: List[int]) -> bool: 33 | table = set() 34 | for x in nums: 35 | if x in table: 36 | return True 37 | table.add(x) 38 | return False -------------------------------------------------------------------------------- /leetcode/219.contains-duplicate-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool containsNearbyDuplicate(vector& nums, int k) { 4 | unordered_map map; 5 | 6 | for (auto i = 0; i < nums.size(); ++i){ 7 | 8 | if (map.count(nums[i]) > 0){ 9 | if (abs(map[nums[i]] - i) <= k){ 10 | return true; 11 | } 12 | } 13 | 14 | map[nums[i]] = i; 15 | } 16 | 17 | return false; 18 | } 19 | }; -------------------------------------------------------------------------------- /leetcode/226.invert-binary-tree.py: -------------------------------------------------------------------------------- 1 | # Tag: Tree, Depth-First Search, Breadth-First Search, Binary Tree 2 | # Time: O(N) 3 | # Space: O(H) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given the root of a binary tree, invert the tree, and return its root. 8 | #   9 | # Example 1: 10 | # 11 | # 12 | # Input: root = [4,2,7,1,3,6,9] 13 | # Output: [4,7,2,9,6,3,1] 14 | # 15 | # Example 2: 16 | # 17 | # 18 | # Input: root = [2,1,3] 19 | # Output: [2,3,1] 20 | # 21 | # Example 3: 22 | # 23 | # Input: root = [] 24 | # Output: [] 25 | # 26 | #   27 | # Constraints: 28 | # 29 | # The number of nodes in the tree is in the range [0, 100]. 30 | # -100 <= Node.val <= 100 31 | # 32 | # 33 | 34 | # Definition for a binary tree node. 35 | # class TreeNode: 36 | # def __init__(self, val=0, left=None, right=None): 37 | # self.val = val 38 | # self.left = left 39 | # self.right = right 40 | class Solution: 41 | def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: 42 | if root is None: 43 | return None 44 | 45 | left = root.left 46 | right = root.right 47 | 48 | root.left = self.invertTree(right) 49 | root.right = self.invertTree(left) 50 | 51 | return root -------------------------------------------------------------------------------- /leetcode/228.summary-ranges.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def summaryRanges(self, nums): 3 | """ 4 | :type nums: List[int] 5 | :rtype: List[str] 6 | """ 7 | if len(nums) == 0: 8 | return [] 9 | 10 | start = 0 11 | res = [] 12 | 13 | for i in range(1, len(nums) + 1): 14 | if i == len(nums) or nums[i] - nums[i - 1] != 1: 15 | if start == i - 1: 16 | res.append(str(nums[start])) 17 | else: 18 | res.append(str(nums[start]) + '->' + str(nums[i - 1])) 19 | 20 | start = i 21 | 22 | return res -------------------------------------------------------------------------------- /leetcode/231.power-of-two.cpp: -------------------------------------------------------------------------------- 1 | // Tag: Math, Bit Manipulation, Recursion 2 | // Time: O(1) 3 | // Space: O(1) 4 | // Ref: - 5 | // Note: - 6 | 7 | // Given an integer n, return true if it is a power of two. Otherwise, return false. 8 | // An integer n is a power of two, if there exists an integer x such that n == 2x. 9 | //   10 | // Example 1: 11 | // 12 | // Input: n = 1 13 | // Output: true 14 | // Explanation: 20 = 1 15 | // 16 | // Example 2: 17 | // 18 | // Input: n = 16 19 | // Output: true 20 | // Explanation: 24 = 16 21 | // 22 | // Example 3: 23 | // 24 | // Input: n = 3 25 | // Output: false 26 | // 27 | //   28 | // Constraints: 29 | // 30 | // -231 <= n <= 231 - 1 31 | // 32 | //   33 | // Follow up: Could you solve it without loops/recursion? 34 | 35 | class Solution { 36 | public: 37 | bool isPowerOfTwo(int n) { 38 | return n > 0 && (n & (n - 1)) == 0; 39 | } 40 | }; -------------------------------------------------------------------------------- /leetcode/231.power-of-two.py: -------------------------------------------------------------------------------- 1 | # Tag: Math, Bit Manipulation, Recursion 2 | # Time: O(1) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given an integer n, return true if it is a power of two. Otherwise, return false. 8 | # An integer n is a power of two, if there exists an integer x such that n == 2x. 9 | #   10 | # Example 1: 11 | # 12 | # Input: n = 1 13 | # Output: true 14 | # Explanation: 20 = 1 15 | # 16 | # Example 2: 17 | # 18 | # Input: n = 16 19 | # Output: true 20 | # Explanation: 24 = 16 21 | # 22 | # Example 3: 23 | # 24 | # Input: n = 3 25 | # Output: false 26 | # 27 | #   28 | # Constraints: 29 | # 30 | # -231 <= n <= 231 - 1 31 | # 32 | #   33 | # Follow up: Could you solve it without loops/recursion? 34 | 35 | class Solution: 36 | def isPowerOfTwo(self, n: int) -> bool: 37 | return n > 0 and n & (n - 1) == 0 -------------------------------------------------------------------------------- /leetcode/237.delete-node-in-a-linked-list.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | def deleteNode(self, node): 9 | """ 10 | :type node: ListNode 11 | :rtype: void Do not return anything, modify node in-place instead. 12 | """ 13 | 14 | next = node.next 15 | if next is None: 16 | return 17 | 18 | node.val = next.val 19 | node.next = next.next 20 | del next 21 | 22 | 23 | -------------------------------------------------------------------------------- /leetcode/246.strobogrammatic-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isStrobogrammatic(string num) { 4 | // write your code here 5 | unordered_map mirrorMap; 6 | mirrorMap['1'] = '1'; 7 | mirrorMap['6'] = '9'; 8 | mirrorMap['8'] = '8'; 9 | mirrorMap['9'] = '6'; 10 | mirrorMap['0'] = '0'; 11 | 12 | int left = 0; 13 | int right = num.size() - 1; 14 | while (left <= right) 15 | { 16 | if (mirrorMap.count(num[left]) == 0 || mirrorMap[num[left]] != num[right]) 17 | { 18 | return false; 19 | } 20 | 21 | left++; 22 | right--; 23 | } 24 | 25 | return true; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /leetcode/246.strobogrammatic-number.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def isStrobogrammatic(self, num): 3 | """ 4 | :type num: str 5 | :rtype: bool 6 | """ 7 | if num is None or len(num) == 0: 8 | return True 9 | 10 | mirror_mapping = {'1': '1', '6': '9', '8': '8', '9': '6', '0': '0'} 11 | 12 | left = 0 13 | right = len(num) - 1 14 | 15 | while(left <= right): 16 | if num[left] not in mirror_mapping or mirror_mapping[num[left]] != num[right]: 17 | return False 18 | 19 | left += 1 20 | right -= 1 21 | 22 | return True 23 | -------------------------------------------------------------------------------- /leetcode/249.group-shifted-strings.cpp: -------------------------------------------------------------------------------- 1 | // O(N * K) k = length of string to be shift 2 | class Solution { 3 | private: 4 | // shift str to begin with 'a' for example 'xyz' -> 'abc' 5 | string shiftString(string str){ 6 | int offset = 'a' - str[0]; 7 | for(int i = 0; i < str.size(); ++i){ 8 | str[i] = 'a' + (str[i] + offset - 'a' + 26) % 26; 9 | } 10 | 11 | return str; 12 | } 13 | 14 | public: 15 | vector> groupStrings(vector& strings) { 16 | unordered_map map; 17 | vector> res; 18 | 19 | for (auto str: strings){ 20 | string tmp = shiftString(str); 21 | 22 | if (map.count(tmp) > 0){ 23 | res[map[tmp]].push_back(str); 24 | }else{ 25 | vector list; 26 | list.push_back(str); 27 | res.push_back(list); 28 | map[tmp] = res.size() - 1; 29 | } 30 | } 31 | 32 | return res; 33 | } 34 | }; -------------------------------------------------------------------------------- /leetcode/251.flatten-2d-vector.py: -------------------------------------------------------------------------------- 1 | class Vector2D(object): 2 | 3 | def __init__(self, vec2d): 4 | """ 5 | Initialize your data structure here. 6 | :type vec2d: List[List[int]] 7 | """ 8 | self.i = 0 9 | self.j = 0 10 | self.vector = vec2d 11 | 12 | 13 | def next(self): 14 | """ 15 | :rtype: int 16 | """ 17 | vec2d = self.vector 18 | res = vec2d[self.i][self.j] 19 | self.j += 1 20 | return res 21 | 22 | def hasNext(self): 23 | """ 24 | :rtype: bool 25 | """ 26 | vec2d = self.vector 27 | while self.i < len(vec2d) and self.j >= len(vec2d[self.i]): 28 | self.j = 0 29 | self.i += 1 30 | 31 | if self.i < len(vec2d) and self.j < len(vec2d[self.i]): 32 | return True 33 | 34 | return False 35 | 36 | 37 | # Your Vector2D object will be instantiated and called as such: 38 | # i, v = Vector2D(vec2d), [] 39 | # while i.hasNext(): v.append(i.next()) -------------------------------------------------------------------------------- /leetcode/2524.maximum-frequency-score-of-a-subarray.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/leetcode/2524.maximum-frequency-score-of-a-subarray.vip -------------------------------------------------------------------------------- /leetcode/270.closest-binary-search-tree-value.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int closestValue(TreeNode* root, double target) { 13 | TreeNode *cur = root; 14 | int closest = cur->val; 15 | 16 | while (cur) 17 | { 18 | if (abs(closest - target) > abs(cur->val - target)) 19 | { 20 | closest = cur->val; 21 | } 22 | 23 | if (cur->val - target > 0) 24 | { 25 | cur = cur->left; 26 | } 27 | else 28 | { 29 | cur = cur->right; 30 | } 31 | } 32 | 33 | return closest; 34 | } 35 | }; -------------------------------------------------------------------------------- /leetcode/270.closest-binary-search-tree-value.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def closestValue(self, root, target): 10 | """ 11 | :type root: TreeNode 12 | :type target: float 13 | :rtype: int 14 | """ 15 | cur = root 16 | closest = cur.val 17 | 18 | while cur is not None: 19 | if abs(closest - target) > abs(cur.val - target): 20 | closest = cur.val 21 | 22 | if cur.val - target > 0: 23 | cur = cur.left 24 | else: 25 | cur = cur.right 26 | 27 | return closest 28 | -------------------------------------------------------------------------------- /leetcode/273.integer-to-english-words.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numberToWords(self, num): 3 | """ 4 | :type num: int 5 | :rtype: str 6 | """ 7 | 8 | to19 = 'One Two Three Four Five Six Seven Eight Nine Ten Eleven Twelve ' \ 9 | 'Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen'.split() 10 | tens = 'Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety'.split() 11 | def words(n): 12 | if n < 20: 13 | return to19[n-1:n] 14 | if n < 100: 15 | return [tens[n/10-2]] + words(n%10) 16 | if n < 1000: 17 | return [to19[n/100-1]] + ['Hundred'] + words(n%100) 18 | for p, w in enumerate(('Thousand', 'Million', 'Billion'), 1): 19 | if n < 1000**(p+1): 20 | return words(n/1000**p) + [w] + words(n%1000**p) 21 | return ' '.join(words(num)) or 'Zero' 22 | 23 | -------------------------------------------------------------------------------- /leetcode/2743.count-substrings-without-repeating-character.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/leetcode/2743.count-substrings-without-repeating-character.vip -------------------------------------------------------------------------------- /leetcode/276.paint-fence.cpp: -------------------------------------------------------------------------------- 1 | // f[i] = (k - 1) * f[i - 1] + (k - 1) * f[i - 2] 2 | 3 | class Solution { 4 | public: 5 | int numWays(int n, int k) { 6 | 7 | if (n == 0 || k == 0) 8 | { 9 | return 0; 10 | } 11 | 12 | if (n == 1) 13 | { 14 | return k; 15 | } 16 | 17 | vector table(n + 1, 0); 18 | 19 | table[1] = k; 20 | table[2] = k * k; 21 | 22 | for (auto i = 3; i <= n; ++i) 23 | { 24 | table[i] = (k - 1) * table[i - 1] + (k - 1) * table[i - 2]; 25 | } 26 | 27 | return table[n]; 28 | 29 | } 30 | }; 31 | 32 | 33 | class Solution2 { 34 | public: 35 | int numWays(int n, int k) { 36 | 37 | if (n == 0 || k == 0) 38 | { 39 | return 0; 40 | } 41 | 42 | if (n == 1) 43 | { 44 | return k; 45 | } 46 | 47 | int same = k; 48 | int diff = k * (k - 1); 49 | 50 | for (auto i = 3; i <= n; ++i) 51 | { 52 | int tmp = diff; 53 | diff = (same + diff) * (k - 1); 54 | same = tmp; 55 | } 56 | 57 | return same + diff; 58 | } 59 | }; 60 | -------------------------------------------------------------------------------- /leetcode/276.paint-fence.py: -------------------------------------------------------------------------------- 1 | # f[i] = (k - 1) * f[i - 1] + (k - 1) * f[i - 2] 2 | class Solution(object): 3 | def numWays(self, n, k): 4 | """ 5 | :type n: int 6 | :type k: int 7 | :rtype: int 8 | """ 9 | 10 | if n == 0 or k == 0: 11 | return 0 12 | 13 | if n == 1: 14 | return k 15 | 16 | f = [0 for _ in range(n + 1)] 17 | f[1] = k 18 | f[2] = k * k 19 | 20 | for i in range(3, n + 1): 21 | f[i] = (k - 1) * f[i - 1] + (k - 1) * f[i - 2] 22 | 23 | return f[n] 24 | 25 | class Solution2(object): 26 | def numWays(self, n, k): 27 | """ 28 | :type n: int 29 | :type k: int 30 | :rtype: int 31 | """ 32 | 33 | if n == 0 or k == 0: 34 | return 0 35 | 36 | if n == 1: 37 | return k 38 | 39 | same = k 40 | diff = k * (k - 1) 41 | 42 | for i in range(3, n + 1): 43 | same, diff = diff, (same + diff) * (k - 1) 44 | 45 | return same + diff -------------------------------------------------------------------------------- /leetcode/2877.create-a-dataframe-from-list.py: -------------------------------------------------------------------------------- 1 | # Tag: Pandas 2 | # Time: N/A 3 | # Space: N/A 4 | # Ref: - 5 | # Note: - 6 | 7 | # Write a solution to create a DataFrame from a 2D list called student_data. This 2D list contains the IDs and ages of some students. 8 | # The DataFrame should have two columns, student_id and age, and be in the same order as the original 2D list. 9 | # The result format is in the following example. 10 | #   11 | # Example 1: 12 | # 13 | # Input: 14 | # student_data: 15 | # [ 16 | # [1, 15], 17 | # [2, 11], 18 | # [3, 11], 19 | # [4, 20] 20 | # ] 21 | # Output: 22 | # +------------+-----+ 23 | # | student_id | age | 24 | # +------------+-----+ 25 | # | 1 | 15 | 26 | # | 2 | 11 | 27 | # | 3 | 11 | 28 | # | 4 | 20 | 29 | # +------------+-----+ 30 | # Explanation: 31 | # A DataFrame was created on top of student_data, with two columns named student_id and age. 32 | # 33 | # 34 | 35 | import pandas as pd 36 | 37 | def createDataframe(student_data: List[List[int]]) -> pd.DataFrame: 38 | return pd.DataFrame(student_data, columns=['student_id', 'age']) -------------------------------------------------------------------------------- /leetcode/289.game-of-life.py: -------------------------------------------------------------------------------- 1 | import collections 2 | class Solution(object): 3 | def gameOfLife(self, board): 4 | """ 5 | :type board: List[List[int]] 6 | :rtype: void Do not return anything, modify board in-place instead. 7 | """ 8 | direction = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)] 9 | 10 | 11 | for i in range(len(board)): 12 | for j in range(len(board[i])): 13 | count = 0 14 | 15 | for x, y in direction: 16 | if 0 <= i + x < len(board) and 0 <= j + y < len(board[i]): 17 | count += (board[i + x][j + y] & 1) 18 | 19 | # condition 2 20 | if (board[i][j] & 1) == 1 and (count == 2 or count == 3): 21 | board[i][j] = 0b11 22 | 23 | # condition 4 24 | if (board[i][j] & 1) == 0 and count == 3: 25 | board[i][j] = 0b10 26 | 27 | 28 | for i in range(len(board)): 29 | for j in range(len(board[i])): 30 | board[i][j] >>= 1 -------------------------------------------------------------------------------- /leetcode/29.divide-two-integers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int divide(int dividend, int divisor) { 4 | if (dividend == INT_MIN && divisor == -1) { 5 | return INT_MAX; 6 | } 7 | 8 | bool minus = ((dividend > 0) ^ (divisor > 0)); 9 | 10 | long long number = labs(dividend); 11 | long long div = labs(divisor); 12 | 13 | long long res = 0; 14 | 15 | while (number >= div) { 16 | long long tmp = div; 17 | long long mul = 1; 18 | while(number >= (tmp << 1)) { 19 | mul <<= 1; 20 | tmp <<= 1; 21 | } 22 | 23 | res += mul; 24 | number -= tmp; 25 | } 26 | 27 | return (int)(minus ? -res: res); 28 | } 29 | }; -------------------------------------------------------------------------------- /leetcode/29.divide-two-integers.py: -------------------------------------------------------------------------------- 1 | MAX_INT = 2147483647 2 | MIN_INT = -2147483648 3 | 4 | class Solution: 5 | def divide(self, dividend: int, divisor: int) -> int: 6 | 7 | if dividend == MIN_INT and divisor == -1: 8 | return MAX_INT 9 | 10 | res = 0 11 | minus = (dividend > 0) ^ (divisor > 0) 12 | 13 | dividend = abs(dividend) 14 | divisor = abs(divisor) 15 | 16 | while dividend >= divisor: 17 | tmp = divisor 18 | scale = 1 19 | while (dividend >= (tmp << 1)): 20 | tmp = tmp << 1 21 | scale = scale << 1 22 | 23 | res += scale 24 | dividend -= tmp 25 | 26 | return -res if minus > 0 else res -------------------------------------------------------------------------------- /leetcode/2942.find-words-containing-character.py: -------------------------------------------------------------------------------- 1 | # Tag: Array, String 2 | # Time: O(N^2) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | 7 | # You are given a 0-indexed array of strings words and a character x. 8 | # Return an array of indices representing the words that contain the character x. 9 | # Note that the returned array may be in any order. 10 | #   11 | # Example 1: 12 | # 13 | # Input: words = ["leet","code"], x = "e" 14 | # Output: [0,1] 15 | # Explanation: "e" occurs in both words: "leet", and "code". Hence, we return indices 0 and 1. 16 | # 17 | # Example 2: 18 | # 19 | # Input: words = ["abc","bcd","aaaa","cbc"], x = "a" 20 | # Output: [0,2] 21 | # Explanation: "a" occurs in "abc", and "aaaa". Hence, we return indices 0 and 2. 22 | # 23 | # Example 3: 24 | # 25 | # Input: words = ["abc","bcd","aaaa","cbc"], x = "z" 26 | # Output: [] 27 | # Explanation: "z" does not occur in any of the words. Hence, we return an empty array. 28 | # 29 | #   30 | # Constraints: 31 | # 32 | # 1 <= words.length <= 50 33 | # 1 <= words[i].length <= 50 34 | # x is a lowercase English letter. 35 | # words[i] consists only of lowercase English letters. 36 | # 37 | # 38 | 39 | class Solution: 40 | def findWordsContaining(self, words: List[str], x: str) -> List[int]: 41 | return [i for i in range(len(words)) if x in words[i]] 42 | -------------------------------------------------------------------------------- /leetcode/3.longest-substring-without-repeating-characters.py: -------------------------------------------------------------------------------- 1 | # Tag: Hash Table, String, Sliding Window 2 | # Time: O(N) 3 | # Space: O(N) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given a string s, find the length of the longest substring without repeating characters. 8 | #   9 | # Example 1: 10 | # 11 | # Input: s = "abcabcbb" 12 | # Output: 3 13 | # Explanation: The answer is "abc", with the length of 3. 14 | # 15 | # Example 2: 16 | # 17 | # Input: s = "bbbbb" 18 | # Output: 1 19 | # Explanation: The answer is "b", with the length of 1. 20 | # 21 | # Example 3: 22 | # 23 | # Input: s = "pwwkew" 24 | # Output: 3 25 | # Explanation: The answer is "wke", with the length of 3. 26 | # Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. 27 | # 28 | #   29 | # Constraints: 30 | # 31 | # 0 <= s.length <= 5 * 104 32 | # s consists of English letters, digits, symbols and spaces. 33 | # 34 | # 35 | 36 | class Solution: 37 | def lengthOfLongestSubstring(self, s: str) -> int: 38 | n = len(s) 39 | i = 0 40 | seen = set() 41 | res = 0 42 | for j in range(n): 43 | while s[j] in seen: 44 | seen.remove(s[i]) 45 | i += 1 46 | 47 | seen.add(s[j]) 48 | res = max(res, j - i + 1) 49 | 50 | return res 51 | 52 | -------------------------------------------------------------------------------- /leetcode/3090.maximum-length-substring-with-two-occurrences.py: -------------------------------------------------------------------------------- 1 | # Tag: Hash Table, String, Sliding Window 2 | # Time: O(N) 3 | # Space: O(N) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given a string s, return the maximum length of a substring such that it contains at most two occurrences of each character. 8 | #   9 | # Example 1: 10 | # 11 | # Input: s = "bcbbbcba" 12 | # Output: 4 13 | # Explanation: 14 | # The following substring has a length of 4 and contains at most two occurrences of each character: "bcbbbcba". 15 | # Example 2: 16 | # 17 | # Input: s = "aaaa" 18 | # Output: 2 19 | # Explanation: 20 | # The following substring has a length of 2 and contains at most two occurrences of each character: "aaaa". 21 | #   22 | # Constraints: 23 | # 24 | # 2 <= s.length <= 100 25 | # s consists only of lowercase English letters. 26 | # 27 | # 28 | 29 | from collections import defaultdict 30 | class Solution: 31 | def maximumLengthSubstring(self, s: str) -> int: 32 | n = len(s) 33 | counter = defaultdict(int) 34 | i = 0 35 | res = 0 36 | for j in range(n): 37 | while counter[s[j]] == 2: 38 | counter[s[i]] -= 1 39 | i += 1 40 | 41 | counter[s[j]] += 1 42 | res = max(res, j - i + 1) 43 | 44 | return res -------------------------------------------------------------------------------- /leetcode/323.number-of-connected-components-in-an-undirected-graph.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def countComponents(self, n, edges): 3 | """ 4 | :type n: int 5 | :type edges: List[List[int]] 6 | :rtype: int 7 | """ 8 | graph = {i:[] for i in range(n)} 9 | 10 | for pair in edges: 11 | graph[pair[0]].append(pair[1]) 12 | graph[pair[1]].append(pair[0]) 13 | 14 | visited = set() 15 | count = 0 16 | for i in range(n): 17 | if i not in visited: 18 | count += 1 19 | self.dfs(graph, i, visited) 20 | 21 | return count 22 | 23 | def dfs(self, graph, start, visited): 24 | queue = [start] 25 | visited.add(start) 26 | 27 | while len(queue) > 0: 28 | tmp = queue.pop(0) 29 | 30 | for neighbor in graph[tmp]: 31 | if neighbor not in visited: 32 | visited.add(neighbor) 33 | queue.append(neighbor) -------------------------------------------------------------------------------- /leetcode/326.power-of-three.cpp: -------------------------------------------------------------------------------- 1 | // Tag: Math, Recursion 2 | // Time: O(1) 3 | // Space: O(1) 4 | // Ref: - 5 | // Note: - 6 | 7 | // Given an integer n, return true if it is a power of three. Otherwise, return false. 8 | // An integer n is a power of three, if there exists an integer x such that n == 3x. 9 | //   10 | // Example 1: 11 | // 12 | // Input: n = 27 13 | // Output: true 14 | // Explanation: 27 = 33 15 | // 16 | // Example 2: 17 | // 18 | // Input: n = 0 19 | // Output: false 20 | // Explanation: There is no x where 3x = 0. 21 | // 22 | // Example 3: 23 | // 24 | // Input: n = -1 25 | // Output: false 26 | // Explanation: There is no x where 3x = (-1). 27 | // 28 | //   29 | // Constraints: 30 | // 31 | // -231 <= n <= 231 - 1 32 | // 33 | //   34 | // Follow up: Could you solve it without loops/recursion? 35 | 36 | class Solution { 37 | public: 38 | bool isPowerOfThree(int n) { 39 | if (n <= 0) { 40 | return false; 41 | } 42 | 43 | while (n % 3 == 0) { 44 | n = n / 3; 45 | } 46 | 47 | return n == 1; 48 | } 49 | }; 50 | 51 | class Solution { 52 | public: 53 | bool isPowerOfThree(int n) { 54 | // 3^19 = 1162261467 55 | return n > 0 && 1162261467 % n == 0; 56 | } 57 | }; -------------------------------------------------------------------------------- /leetcode/326.power-of-three.py: -------------------------------------------------------------------------------- 1 | # Tag: Math, Recursion 2 | # Time: O(1) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given an integer n, return true if it is a power of three. Otherwise, return false. 8 | # An integer n is a power of three, if there exists an integer x such that n == 3x. 9 | #   10 | # Example 1: 11 | # 12 | # Input: n = 27 13 | # Output: true 14 | # Explanation: 27 = 33 15 | # 16 | # Example 2: 17 | # 18 | # Input: n = 0 19 | # Output: false 20 | # Explanation: There is no x where 3x = 0. 21 | # 22 | # Example 3: 23 | # 24 | # Input: n = -1 25 | # Output: false 26 | # Explanation: There is no x where 3x = (-1). 27 | # 28 | #   29 | # Constraints: 30 | # 31 | # -231 <= n <= 231 - 1 32 | # 33 | #   34 | # Follow up: Could you solve it without loops/recursion? 35 | 36 | class Solution: 37 | def isPowerOfThree(self, n: int) -> bool: 38 | 39 | if n <= 0: 40 | return False 41 | 42 | while n % 3 == 0: 43 | n = n // 3 44 | 45 | return n == 1 46 | 47 | class Solution(object): 48 | def isPowerOfThree(self, n): 49 | """ 50 | :type n: int 51 | :rtype: bool 52 | """ 53 | # 3 ** 19 < MAX_INT 54 | # 3 ** 20 > MAX_INT 55 | 56 | return n > 0 and (3 ** 19) % n == 0 -------------------------------------------------------------------------------- /leetcode/3323.minimize-connected-groups-by-inserting-interval.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/leetcode/3323.minimize-connected-groups-by-inserting-interval.vip -------------------------------------------------------------------------------- /leetcode/3392.count-subarrays-of-length-three-with-a-condition.cpp: -------------------------------------------------------------------------------- 1 | // Tag: Array 2 | // Time: O(N) 3 | // Space: O(1) 4 | // Ref: - 5 | // Note: - 6 | // Video: https://youtu.be/U5h-zgT1eYg 7 | 8 | // Given an integer array nums, return the number of subarrays of length 3 such that the sum of the first and third numbers equals exactly half of the second number. 9 | //   10 | // Example 1: 11 | // 12 | // Input: nums = [1,2,1,4,1] 13 | // Output: 1 14 | // Explanation: 15 | // Only the subarray [1,4,1] contains exactly 3 elements where the sum of the first and third numbers equals half the middle number. 16 | // 17 | // Example 2: 18 | // 19 | // Input: nums = [1,1,1] 20 | // Output: 0 21 | // Explanation: 22 | // [1,1,1] is the only subarray of length 3. However, its first and third numbers do not add to half the middle number. 23 | // 24 | //   25 | // Constraints: 26 | // 27 | // 3 <= nums.length <= 100 28 | // -100 <= nums[i] <= 100 29 | // 30 | // 31 | 32 | class Solution { 33 | public: 34 | int countSubarrays(vector& nums) { 35 | int n = nums.size(); 36 | int res = 0; 37 | for (int i = 0; i < n; i++) { 38 | if (i >= 2 && (nums[i] + nums[i - 2]) * 2 == nums[i - 1]) { 39 | res += 1; 40 | } 41 | } 42 | return res; 43 | } 44 | }; -------------------------------------------------------------------------------- /leetcode/3392.count-subarrays-of-length-three-with-a-condition.py: -------------------------------------------------------------------------------- 1 | # Tag: Array 2 | # Time: O(N) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | # Video: https://youtu.be/U5h-zgT1eYg 7 | 8 | # Given an integer array nums, return the number of subarrays of length 3 such that the sum of the first and third numbers equals exactly half of the second number. 9 | #   10 | # Example 1: 11 | # 12 | # Input: nums = [1,2,1,4,1] 13 | # Output: 1 14 | # Explanation: 15 | # Only the subarray [1,4,1] contains exactly 3 elements where the sum of the first and third numbers equals half the middle number. 16 | # 17 | # Example 2: 18 | # 19 | # Input: nums = [1,1,1] 20 | # Output: 0 21 | # Explanation: 22 | # [1,1,1] is the only subarray of length 3. However, its first and third numbers do not add to half the middle number. 23 | # 24 | #   25 | # Constraints: 26 | # 27 | # 3 <= nums.length <= 100 28 | # -100 <= nums[i] <= 100 29 | # 30 | # 31 | 32 | class Solution: 33 | def countSubarrays(self, nums: List[int]) -> int: 34 | n = len(nums) 35 | res = 0 36 | for i in range(n): 37 | if i >= 2 and (nums[i] + nums[i - 2]) * 2 == nums[i - 1]: 38 | res += 1 39 | 40 | return res -------------------------------------------------------------------------------- /leetcode/342.power-of-four.cpp: -------------------------------------------------------------------------------- 1 | // Tag: Math, Bit Manipulation, Recursion 2 | // Time: O(1) 3 | // Space: O(1) 4 | // Ref: - 5 | // Note: - 6 | 7 | // Given an integer n, return true if it is a power of four. Otherwise, return false. 8 | // An integer n is a power of four, if there exists an integer x such that n == 4x. 9 | //   10 | // Example 1: 11 | // Input: n = 16 12 | // Output: true 13 | // Example 2: 14 | // Input: n = 5 15 | // Output: false 16 | // Example 3: 17 | // Input: n = 1 18 | // Output: true 19 | // 20 | //   21 | // Constraints: 22 | // 23 | // -231 <= n <= 231 - 1 24 | // 25 | //   26 | // Follow up: Could you solve it without loops/recursion? 27 | 28 | class Solution { 29 | public: 30 | bool isPowerOfFour(int n) { 31 | return n > 0 && (n & (n - 1)) == 0 && n & 0x55555555; 32 | } 33 | }; 34 | 35 | class Solution { 36 | public: 37 | bool isPowerOfFour(int n) { 38 | if (n <= 0) { 39 | return false; 40 | } 41 | 42 | if (n == 1) { 43 | return true; 44 | } 45 | 46 | return n % 4 == 0 && isPowerOfFour(n / 4); 47 | } 48 | }; -------------------------------------------------------------------------------- /leetcode/342.power-of-four.py: -------------------------------------------------------------------------------- 1 | # Tag: Math, Bit Manipulation, Recursion 2 | # Time: O(1) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given an integer n, return true if it is a power of four. Otherwise, return false. 8 | # An integer n is a power of four, if there exists an integer x such that n == 4x. 9 | #   10 | # Example 1: 11 | # Input: n = 16 12 | # Output: true 13 | # Example 2: 14 | # Input: n = 5 15 | # Output: false 16 | # Example 3: 17 | # Input: n = 1 18 | # Output: true 19 | # 20 | #   21 | # Constraints: 22 | # 23 | # -231 <= n <= 231 - 1 24 | # 25 | #   26 | # Follow up: Could you solve it without loops/recursion? 27 | 28 | class Solution: 29 | def isPowerOfFour(self, n: int) -> bool: 30 | return n > 0 and (n & (n - 1)) == 0 and n & 0x55555555 31 | 32 | class Solution: 33 | def isPowerOfFour(self, n: int) -> bool: 34 | if n <= 0: 35 | return False 36 | 37 | if n == 1: 38 | return True 39 | 40 | return n % 4 == 0 and self.isPowerOfFour(n // 4) -------------------------------------------------------------------------------- /leetcode/344.reverse-string.cpp: -------------------------------------------------------------------------------- 1 | // Tag: Two Pointers, String 2 | // Time: O(N) 3 | // Space: O(1) 4 | // Ref: - 5 | // Note: - 6 | 7 | // Write a function that reverses a string. The input string is given as an array of characters s. 8 | // You must do this by modifying the input array in-place with O(1) extra memory. 9 | //   10 | // Example 1: 11 | // Input: s = ["h","e","l","l","o"] 12 | // Output: ["o","l","l","e","h"] 13 | // Example 2: 14 | // Input: s = ["H","a","n","n","a","h"] 15 | // Output: ["h","a","n","n","a","H"] 16 | // 17 | //   18 | // Constraints: 19 | // 20 | // 1 <= s.length <= 105 21 | // s[i] is a printable ascii character. 22 | // 23 | // 24 | 25 | class Solution { 26 | public: 27 | void reverseString(vector& s) { 28 | int l = 0; 29 | int r = s.size() - 1; 30 | 31 | while (l < r) { 32 | char tmp = s[l]; 33 | s[l] = s[r]; 34 | s[r] = tmp; 35 | 36 | l++; 37 | r--; 38 | } 39 | } 40 | }; -------------------------------------------------------------------------------- /leetcode/344.reverse-string.py: -------------------------------------------------------------------------------- 1 | # Tag: Two Pointers, String 2 | # Time: O(N) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Write a function that reverses a string. The input string is given as an array of characters s. 8 | # You must do this by modifying the input array in-place with O(1) extra memory. 9 | #   10 | # Example 1: 11 | # Input: s = ["h","e","l","l","o"] 12 | # Output: ["o","l","l","e","h"] 13 | # Example 2: 14 | # Input: s = ["H","a","n","n","a","h"] 15 | # Output: ["h","a","n","n","a","H"] 16 | # 17 | #   18 | # Constraints: 19 | # 20 | # 1 <= s.length <= 105 21 | # s[i] is a printable ascii character. 22 | # 23 | # 24 | 25 | class Solution: 26 | def reverseString(self, s: List[str]) -> None: 27 | """ 28 | Do not return anything, modify s in-place instead. 29 | """ 30 | l = 0 31 | r = len(s) - 1 32 | while l < r: 33 | s[l], s[r] = s[r], s[l] 34 | l += 1 35 | r -= 1 -------------------------------------------------------------------------------- /leetcode/345.reverse-vowels-of-a-string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string reverseVowels(string s) { 4 | 5 | int start = 0; 6 | int end = s.size() - 1; 7 | unordered_set vowels({'a', 'e', 'i', 'o', 'u'}); 8 | 9 | while(start < end) 10 | { 11 | while(start < end && vowels.count(tolower(s[start])) == 0) 12 | { 13 | start++; 14 | } 15 | 16 | while(start < end && vowels.count(tolower(s[end])) == 0) 17 | { 18 | end--; 19 | } 20 | 21 | if (start < end){ 22 | char tmp = s[start]; 23 | s[start] = s[end]; 24 | s[end] = tmp; 25 | } 26 | 27 | start++; 28 | end--; 29 | } 30 | 31 | return s; 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /leetcode/345.reverse-vowels-of-a-string.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def reverseVowels(self, s): 3 | """ 4 | :type s: str 5 | :rtype: str 6 | """ 7 | vowels = set("aeiouAEIOU") 8 | s = list(s) 9 | 10 | i = 0 11 | j = len(s) - 1 12 | 13 | while i < j: 14 | while i < j and s[i] not in vowels: 15 | i += 1 16 | 17 | while i < j and s[j] not in vowels: 18 | j -= 1 19 | 20 | if i < j: 21 | s[i], s[j] = s[j], s[i] 22 | 23 | i += 1 24 | j -= 1 25 | 26 | return ''.join(s) -------------------------------------------------------------------------------- /leetcode/346.moving-average-from-data-stream.cpp: -------------------------------------------------------------------------------- 1 | class MovingAverage { 2 | private: 3 | deque dq; 4 | int size; 5 | int sum; 6 | public: 7 | /** Initialize your data structure here. */ 8 | MovingAverage(int size) { 9 | this->size = size; 10 | this->sum = 0; 11 | } 12 | 13 | double next(int val) { 14 | 15 | dq.push_back(val); 16 | sum += val; 17 | 18 | if (dq.size() > size) 19 | { 20 | sum -= dq.front(); 21 | dq.pop_front(); 22 | } 23 | 24 | return double(sum) / dq.size(); 25 | } 26 | }; 27 | 28 | /** 29 | * Your MovingAverage object will be instantiated and called as such: 30 | * MovingAverage obj = new MovingAverage(size); 31 | * double param_1 = obj.next(val); 32 | */ -------------------------------------------------------------------------------- /leetcode/346.moving-average-from-data-stream.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | class MovingAverage(object): 3 | 4 | def __init__(self, size): 5 | """ 6 | Initialize your data structure here. 7 | :type size: int 8 | """ 9 | self.dq = deque() 10 | self.size = size 11 | self.sum = 0 12 | 13 | def next(self, val): 14 | """ 15 | :type val: int 16 | :rtype: float 17 | """ 18 | self.dq.append(val) 19 | self.sum += val 20 | if len(self.dq) > self.size: 21 | self.sum -= self.dq.popleft() 22 | 23 | return float(self.sum) / len(self.dq) 24 | 25 | 26 | # Your MovingAverage object will be instantiated and called as such: 27 | # obj = MovingAverage(size) 28 | # param_1 = obj.next(val) -------------------------------------------------------------------------------- /leetcode/350.intersection-of-two-arrays-ii.py: -------------------------------------------------------------------------------- 1 | # hash 2 | class Solution(object): 3 | def intersect(self, nums1, nums2): 4 | """ 5 | :type nums1: List[int] 6 | :type nums2: List[int] 7 | :rtype: List[int] 8 | """ 9 | count_map = {} 10 | res = [] 11 | for num in nums1: 12 | count_map[num] = count_map.get(num, 0) + 1 13 | 14 | for num in nums2: 15 | if count_map.get(num, 0) > 0: 16 | res.append(num) 17 | count_map[num] -= 1 18 | 19 | return res 20 | 21 | 22 | # tow-pointers 23 | class Solution2(object): 24 | def intersect(self, nums1, nums2): 25 | """ 26 | :type nums1: List[int] 27 | :type nums2: List[int] 28 | :rtype: List[int] 29 | """ 30 | 31 | nums1.sort() 32 | nums2.sort() 33 | 34 | left = 0 35 | right = 0 36 | res = [] 37 | while(left < len(nums1) and right < len(nums2)): 38 | if nums1[left] > nums2[right]: 39 | right += 1 40 | elif nums1[left] < nums2[right]: 41 | left += 1 42 | else: 43 | res.append(nums1[left]) 44 | left += 1 45 | right += 1 46 | 47 | return res -------------------------------------------------------------------------------- /leetcode/359.logger-rate-limiter.cpp: -------------------------------------------------------------------------------- 1 | class Logger { 2 | 3 | private: 4 | unordered_map map; 5 | 6 | public: 7 | /** Initialize your data structure here. */ 8 | Logger() { 9 | 10 | } 11 | 12 | /** Returns true if the message should be printed in the given timestamp, otherwise returns false. 13 | If this method returns false, the message will not be printed. 14 | The timestamp is in seconds granularity. */ 15 | bool shouldPrintMessage(int timestamp, string message) { 16 | 17 | if (timestamp < map[message]){ 18 | return false; 19 | } 20 | 21 | map[message] = timestamp + 10; 22 | return true; 23 | } 24 | }; 25 | 26 | /** 27 | * Your Logger object will be instantiated and called as such: 28 | * Logger obj = new Logger(); 29 | * bool param_1 = obj.shouldPrintMessage(timestamp,message); 30 | */ -------------------------------------------------------------------------------- /leetcode/360.sort-transformed-array.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/leetcode/360.sort-transformed-array.vip -------------------------------------------------------------------------------- /leetcode/366.find-leaves-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(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | 12 | private: 13 | unordered_map> heightMap; 14 | int nodeHeight(TreeNode* node) 15 | { 16 | if (node == NULL) 17 | { 18 | return 0; 19 | } 20 | 21 | int height = max(nodeHeight(node->left) + 1, nodeHeight(node->right) + 1); 22 | heightMap[height].push_back(node->val); 23 | 24 | return height; 25 | } 26 | 27 | public: 28 | vector> findLeaves(TreeNode* root) { 29 | int max_height = nodeHeight(root); 30 | 31 | vector> res; 32 | for(auto i = 1; i <= max_height; ++i) 33 | { 34 | res.push_back(heightMap[i]); 35 | } 36 | 37 | return res; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /leetcode/366.find-leaves-of-binary-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def __init__(self, *args, **kwargs): 10 | self.heightMap = {} 11 | 12 | def node_height(self, cur): 13 | if cur is None: 14 | return 0 15 | 16 | height = max(self.node_height(cur.left) + 1, self.node_height(cur.right) + 1) 17 | if height in self.heightMap: 18 | self.heightMap[height].append(cur.val) 19 | else: 20 | self.heightMap[height] = [cur.val] 21 | 22 | return height 23 | 24 | def findLeaves(self, root): 25 | """ 26 | :type root: TreeNode 27 | :rtype: List[List[int]] 28 | """ 29 | max_height = self.node_height(root) 30 | res = [] 31 | 32 | for i in range(1, max_height + 1): 33 | res.append(self.heightMap[i]) 34 | 35 | return res 36 | 37 | -------------------------------------------------------------------------------- /leetcode/367.valid-perfect-square.py: -------------------------------------------------------------------------------- 1 | # Tag: Math, Binary Search 2 | # Time: O(logN) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given a positive integer num, return true if num is a perfect square or false otherwise. 8 | # A perfect square is an integer that is the square of an integer. In other words, it is the product of some integer with itself. 9 | # You must not use any built-in library function, such as sqrt. 10 | #   11 | # Example 1: 12 | # 13 | # Input: num = 16 14 | # Output: true 15 | # Explanation: We return true because 4 * 4 = 16 and 4 is an integer. 16 | # 17 | # Example 2: 18 | # 19 | # Input: num = 14 20 | # Output: false 21 | # Explanation: We return false because 3.742 * 3.742 = 14 and 3.742 is not an integer. 22 | # 23 | #   24 | # Constraints: 25 | # 26 | # 1 <= num <= 231 - 1 27 | # 28 | # 29 | 30 | class Solution: 31 | def isPerfectSquare(self, num: int) -> bool: 32 | left = 0 33 | right = num 34 | 35 | while left < right: 36 | mid = left + (right - left) // 2 37 | if mid * mid == num: 38 | return True 39 | 40 | if mid * mid > num: 41 | right = mid 42 | else: 43 | left = mid + 1 44 | 45 | return left * left == num -------------------------------------------------------------------------------- /leetcode/370.range-addition.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/leetcode/370.range-addition.vip -------------------------------------------------------------------------------- /leetcode/371.sum-of-two-integers.cpp: -------------------------------------------------------------------------------- 1 | // Tag: Math, Bit Manipulation 2 | // Time: O(1) 3 | // Space: O(1) 4 | // Ref: - 5 | // Note: - 6 | 7 | // Given two integers a and b, return the sum of the two integers without using the operators + and -. 8 | //   9 | // Example 1: 10 | // Input: a = 1, b = 2 11 | // Output: 3 12 | // Example 2: 13 | // Input: a = 2, b = 3 14 | // Output: 5 15 | // 16 | //   17 | // Constraints: 18 | // 19 | // -1000 <= a, b <= 1000 20 | // 21 | // 22 | 23 | class Solution { 24 | public: 25 | int getSum(int a, int b) { 26 | return b==0? a:getSum(a^b, (a&b)<<1); 27 | } 28 | }; 29 | 30 | class Solution { 31 | public: 32 | int getSum(int a, int b) { 33 | while (b != 0) { 34 | int sum_without_carry = a ^ b; 35 | int carry = (a & b) << 1; 36 | a = sum_without_carry; 37 | b = carry; 38 | } 39 | return a; 40 | } 41 | }; -------------------------------------------------------------------------------- /leetcode/371.sum-of-two-integers.py: -------------------------------------------------------------------------------- 1 | # Tag: Math, Bit Manipulation 2 | # Time: O(1) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given two integers a and b, return the sum of the two integers without using the operators + and -. 8 | #   9 | # Example 1: 10 | # Input: a = 1, b = 2 11 | # Output: 3 12 | # Example 2: 13 | # Input: a = 2, b = 3 14 | # Output: 5 15 | # 16 | #   17 | # Constraints: 18 | # 19 | # -1000 <= a, b <= 1000 20 | # 21 | # 22 | 23 | class Solution: 24 | def getSum(self, a: int, b: int) -> int: 25 | mask = 0xffffffff 26 | if (b & mask) == 0: 27 | return (a & mask) if b > 0 else a 28 | else: 29 | return self.getSum(a ^ b, (a & b) << 1) 30 | 31 | class Solution: 32 | def getSum(self, a: int, b: int) -> int: 33 | mask = 0xffffffff 34 | while ((b & mask) != 0): 35 | sum_without_carry = a ^ b 36 | carry = (a & b) << 1 37 | 38 | a = sum_without_carry 39 | b = carry 40 | 41 | return (a & mask) if b > 0 else a 42 | -------------------------------------------------------------------------------- /leetcode/377.combination-sum-iv.cpp: -------------------------------------------------------------------------------- 1 | // f[i] = f[i - A1] + f[i - A2] ... + f[i - A(n-1)] 2 | class Solution { 3 | public: 4 | int combinationSum4(vector& nums, int target) { 5 | 6 | vector table(target + 1, 0); 7 | table[0] = 1; 8 | 9 | for(auto i = 1; i <= target; ++i) 10 | { 11 | int count = 0; 12 | 13 | for (auto j = 0; j < nums.size(); ++j) 14 | { 15 | if (i - nums[j] >= 0) 16 | { 17 | count += table[i - nums[j]]; 18 | } 19 | } 20 | 21 | table[i] = count; 22 | } 23 | 24 | return table[target]; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /leetcode/377.combination-sum-iv.py: -------------------------------------------------------------------------------- 1 | # f[i] = f[i - A1] + f[i - A2] ... + f[i - A(n-1)] 2 | class Solution(object): 3 | def combinationSum4(self, nums, target): 4 | """ 5 | :type nums: List[int] 6 | :type target: int 7 | :rtype: int 8 | """ 9 | 10 | table = [0 for _ in range(target + 1)] 11 | table[0] = 1 12 | 13 | for i in range(1, target + 1): 14 | count = 0 15 | 16 | for j in range(len(nums)): 17 | if i - nums[j] >= 0: 18 | count += table[i - nums[j]] 19 | 20 | table[i] = count 21 | 22 | return table[-1] -------------------------------------------------------------------------------- /leetcode/383.ransom-note.py: -------------------------------------------------------------------------------- 1 | # Tag: Hash Table, String, Counting 2 | # Time: O(N) 3 | # Space: O(N) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise. 8 | # Each letter in magazine can only be used once in ransomNote. 9 | #   10 | # Example 1: 11 | # Input: ransomNote = "a", magazine = "b" 12 | # Output: false 13 | # Example 2: 14 | # Input: ransomNote = "aa", magazine = "ab" 15 | # Output: false 16 | # Example 3: 17 | # Input: ransomNote = "aa", magazine = "aab" 18 | # Output: true 19 | # 20 | #   21 | # Constraints: 22 | # 23 | # 1 <= ransomNote.length, magazine.length <= 105 24 | # ransomNote and magazine consist of lowercase English letters. 25 | # 26 | # 27 | 28 | from collections import defaultdict 29 | class Solution: 30 | def canConstruct(self, ransomNote: str, magazine: str) -> bool: 31 | if len(ransomNote) > len(magazine): 32 | return False 33 | 34 | counter = defaultdict(int) 35 | for x in magazine: 36 | counter[x] += 1 37 | 38 | for x in ransomNote: 39 | if counter[x] == 0: 40 | return False 41 | 42 | counter[x] -= 1 43 | 44 | return True 45 | -------------------------------------------------------------------------------- /leetcode/39.combination-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | void helper(vector& candidates, int start, int sum, int target, vector& ans, vector>& res) 4 | { 5 | if (sum >= target) 6 | { 7 | if (sum == target) 8 | { 9 | res.push_back(ans); 10 | } 11 | return; 12 | } 13 | 14 | for (auto i = start; i < candidates.size(); ++i) 15 | { 16 | ans.push_back(candidates[i]); 17 | helper(candidates, i, sum + candidates[i], target, ans, res); 18 | ans.pop_back(); 19 | } 20 | 21 | } 22 | public: 23 | vector> combinationSum(vector& candidates, int target) { 24 | sort(candidates.begin(), candidates.end()); 25 | vector> res; 26 | vector ans; 27 | 28 | helper(candidates, 0, 0, target, ans, res); 29 | return res; 30 | } 31 | }; -------------------------------------------------------------------------------- /leetcode/39.combination-sum.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def combinationSum(self, candidates, target): 3 | """ 4 | :type candidates: List[int] 5 | :type target: int 6 | :rtype: List[List[int]] 7 | """ 8 | res = [] 9 | ans = [] 10 | candidates.sort() 11 | self.helper(candidates, 0, target, ans, 0, res) 12 | 13 | return res 14 | 15 | def helper(self, candidates, start, target, ans, total, res): 16 | if total == target: 17 | res.append(list(ans)) 18 | return 19 | 20 | for i in range(start, len(candidates)): 21 | 22 | number = candidates[i] 23 | 24 | if total + number <= target: 25 | ans.append(number) 26 | total += number 27 | 28 | self.helper(candidates, i, target, ans, total, res) 29 | 30 | total -= number 31 | ans.pop() -------------------------------------------------------------------------------- /leetcode/393.utf-8-validation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | int byteLength(int n) 4 | { 5 | if ((n >> 7) == 0b0) 6 | { 7 | return 1; 8 | } 9 | else if ((n >> 5) == 0b110) 10 | { 11 | return 2; 12 | } 13 | else if ((n >> 4) == 0b1110) 14 | { 15 | return 3; 16 | } 17 | else if ((n >> 3) == 0b11110) 18 | { 19 | return 4; 20 | } 21 | 22 | return 0; 23 | } 24 | public: 25 | bool validUtf8(vector& data) { 26 | 27 | if (data.size() == 0) 28 | { 29 | return false; 30 | } 31 | 32 | int i = 0; 33 | 34 | while (i < data.size()) 35 | { 36 | int n = data[i]; 37 | int len = byteLength(n); 38 | 39 | if (len == 0 || i + len - 1 >= data.size()) 40 | { 41 | return false; 42 | } 43 | 44 | for (auto j = i + 1; j <= i + len - 1; ++j) 45 | { 46 | if (data[j] >> 6 != 0b10) 47 | { 48 | return false; 49 | } 50 | } 51 | 52 | i = i + len; 53 | } 54 | 55 | return true; 56 | } 57 | }; -------------------------------------------------------------------------------- /leetcode/393.utf-8-validation.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def validUtf8(self, data): 3 | """ 4 | :type data: List[int] 5 | :rtype: bool 6 | """ 7 | if data is None or len(data) == 0: 8 | return False 9 | 10 | i = 0 11 | while i < len(data): 12 | n = self.byteLength(data[i]) 13 | if n == 0 or n + i - 1 >= len(data): 14 | return False 15 | 16 | for j in range(i + 1, n + i): 17 | if (data[j] >> 6) != 0b10: 18 | return False 19 | 20 | i = i + n 21 | 22 | return True 23 | 24 | def byteLength(self, n): 25 | if (n >> 7) == 0b0: 26 | return 1 27 | if (n >> 5) == 0b110: 28 | return 2 29 | if (n >> 4) == 0b1110: 30 | return 3 31 | if (n >> 3) == 0b11110: 32 | return 4 33 | return 0 -------------------------------------------------------------------------------- /leetcode/408.valid-word-abbreviation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool validWordAbbreviation(string word, string abbr) { 4 | 5 | int left = 0; 6 | int right = 0; 7 | 8 | while(left < word.size() && right < abbr.size()) 9 | { 10 | if (abbr[right] == '0') 11 | { 12 | return false; 13 | } 14 | else if (abbr[right] > '0' && abbr[right] <= '9') 15 | { 16 | int step = abbr[right] - '0'; 17 | while(right + 1 < abbr.size() && abbr[right + 1] >= '0' && abbr[right + 1] <= '9') 18 | { 19 | step = (step * 10) + (abbr[right + 1] - '0'); 20 | right++; 21 | } 22 | left += step; 23 | right += 1; 24 | continue; 25 | } 26 | else if(word[left] != abbr[right]) 27 | { 28 | return false; 29 | } 30 | 31 | left += 1; 32 | right += 1; 33 | } 34 | 35 | return (left == word.size() && right == abbr.size()); 36 | } 37 | }; -------------------------------------------------------------------------------- /leetcode/408.valid-word-abbreviation.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def validWordAbbreviation(self, word, abbr): 3 | """ 4 | :type word: str 5 | :type abbr: str 6 | :rtype: bool 7 | """ 8 | left = 0 9 | right = 0 10 | numbers = set(list("0123456789")) 11 | 12 | while(left < len(word) and right < len(abbr)): 13 | 14 | if abbr[right] == '0': 15 | return False 16 | 17 | elif abbr[right] in numbers: 18 | step = int(abbr[right]) 19 | while(right + 1 < len(abbr) and abbr[right + 1] in numbers): 20 | step = step * 10 + int(abbr[right + 1]) 21 | right += 1 22 | 23 | right += 1 24 | left += step 25 | continue 26 | 27 | elif word[left] != abbr[right]: 28 | return False 29 | 30 | left += 1 31 | right += 1 32 | 33 | return (left == len(word) and right == len(abbr)) 34 | -------------------------------------------------------------------------------- /leetcode/409.longest-palindrome.py: -------------------------------------------------------------------------------- 1 | # Tag: Hash Table, String, Greedy 2 | # Time: O(N) 3 | # Space: O(N) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. 8 | # Letters are case sensitive, for example, "Aa" is not considered a palindrome. 9 | #   10 | # Example 1: 11 | # 12 | # Input: s = "abccccdd" 13 | # Output: 7 14 | # Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7. 15 | # 16 | # Example 2: 17 | # 18 | # Input: s = "a" 19 | # Output: 1 20 | # Explanation: The longest palindrome that can be built is "a", whose length is 1. 21 | # 22 | #   23 | # Constraints: 24 | # 25 | # 1 <= s.length <= 2000 26 | # s consists of lowercase and/or uppercase English letters only. 27 | # 28 | # 29 | 30 | class Solution: 31 | def longestPalindrome(self, s: str) -> int: 32 | cache = set() 33 | res = 0 34 | for x in s: 35 | if x in cache: 36 | res += 2 37 | cache.remove(x) 38 | else: 39 | cache.add(x) 40 | 41 | if len(cache) > 0: 42 | res += 1 43 | 44 | return res 45 | -------------------------------------------------------------------------------- /leetcode/413.arithmetic-slices.py: -------------------------------------------------------------------------------- 1 | # Tag: Array, Dynamic Programming 2 | # Time: O(N) 3 | # Space: O(N) 4 | # Ref: - 5 | # Note: - 6 | 7 | # An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same. 8 | # 9 | # For example, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences. 10 | # 11 | # Given an integer array nums, return the number of arithmetic subarrays of nums. 12 | # A subarray is a contiguous subsequence of the array. 13 | #   14 | # Example 1: 15 | # 16 | # Input: nums = [1,2,3,4] 17 | # Output: 3 18 | # Explanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself. 19 | # 20 | # Example 2: 21 | # 22 | # Input: nums = [1] 23 | # Output: 0 24 | # 25 | #   26 | # Constraints: 27 | # 28 | # 1 <= nums.length <= 5000 29 | # -1000 <= nums[i] <= 1000 30 | # 31 | # 32 | 33 | class Solution: 34 | def numberOfArithmeticSlices(self, nums: List[int]) -> int: 35 | n = len(nums) 36 | if n < 3: 37 | return 0 38 | 39 | dp = [0 for i in range(n)] 40 | for i in range(2, n): 41 | if nums[i] - nums[i - 1] == nums[i - 1] - nums[i - 2]: 42 | dp[i] = dp[i - 1] + 1 43 | 44 | return sum(dp) -------------------------------------------------------------------------------- /leetcode/442.find-all-duplicates-in-an-array.py: -------------------------------------------------------------------------------- 1 | # Tag: Array, Hash Table, Index Sort 2 | # Time: O(N) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears at most twice, return an array of all the integers that appears twice. 8 | # You must write an algorithm that runs in O(n) time and uses only constant auxiliary space, excluding the space needed to store the output 9 | #   10 | # Example 1: 11 | # Input: nums = [4,3,2,7,8,2,3,1] 12 | # Output: [2,3] 13 | # Example 2: 14 | # Input: nums = [1,1,2] 15 | # Output: [1] 16 | # Example 3: 17 | # Input: nums = [1] 18 | # Output: [] 19 | # 20 | #   21 | # Constraints: 22 | # 23 | # n == nums.length 24 | # 1 <= n <= 105 25 | # 1 <= nums[i] <= n 26 | # Each element in nums appears once or twice. 27 | # 28 | # 29 | 30 | class Solution: 31 | def findDuplicates(self, nums: List[int]) -> List[int]: 32 | nums = [0] + nums 33 | res = [] 34 | for i in range(1, len(nums)): 35 | x = abs(nums[i]) 36 | if nums[x] < 0: 37 | res.append(x) 38 | else: 39 | nums[x] = -nums[x] 40 | 41 | return res -------------------------------------------------------------------------------- /leetcode/45.jump-game-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int jump(vector& nums) { 4 | 5 | int current = 0; 6 | int furthest = 0; 7 | int jumps = 0; 8 | 9 | for (auto i = 0; i < nums.size() - 1; ++i) 10 | { 11 | furthest = max(furthest, i + nums[i]); 12 | 13 | if (i == current) 14 | { 15 | current = furthest; 16 | jumps += 1; 17 | } 18 | } 19 | 20 | return jumps; 21 | } 22 | }; 23 | 24 | class Solution2 { 25 | public: 26 | int jump(vector& nums) { 27 | vector table(nums.size(), 0); 28 | 29 | for (auto i = 1; i < nums.size(); ++i) 30 | { 31 | int step = INT_MAX; 32 | for (auto j = 0; j < i; ++j) 33 | { 34 | if (i - j <= nums[j]) 35 | { 36 | step = min(step, table[j] + 1); 37 | } 38 | } 39 | table[i] = step; 40 | } 41 | 42 | return table[nums.size() - 1]; 43 | } 44 | }; 45 | -------------------------------------------------------------------------------- /leetcode/45.jump-game-ii.py: -------------------------------------------------------------------------------- 1 | # greedy 2 | class Solution(object): 3 | def jump(self, nums): 4 | """ 5 | :type nums: List[int] 6 | :rtype: int 7 | """ 8 | jumps = 0 9 | cur_end = 0 10 | cur_furthest = 0 11 | 12 | for i in range(len(nums) - 1): 13 | cur_furthest = max(cur_furthest, i + nums[i]) 14 | if (i == cur_end): 15 | jumps += 1 16 | cur_end = cur_furthest 17 | 18 | return jumps 19 | 20 | # DP O(N^2) Time Limit Exceeded 21 | class Solution2(object): 22 | def jump(self, nums): 23 | """ 24 | :type nums: List[int] 25 | :rtype: int 26 | """ 27 | if nums is None or len(nums) == 0: 28 | return 0 29 | 30 | table = [0 for i in range(len(nums))] 31 | table[0] = 0 32 | 33 | for i in range(1, len(nums)): 34 | jump_count = float('inf') 35 | for j in range(0, i): 36 | if nums[j] >= i - j: 37 | jump_count = min(jump_count, table[j] + 1) 38 | table[i] = jump_count 39 | 40 | return table[-1] -------------------------------------------------------------------------------- /leetcode/454.4sum-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int fourSumCount(vector& A, vector& B, vector& C, vector& D) { 4 | 5 | int res = 0; 6 | unordered_map abSum; 7 | 8 | for (auto a: A){ 9 | for (auto b: B){ 10 | abSum[a + b] += 1; 11 | } 12 | } 13 | 14 | for (auto c: C){ 15 | for (auto d: D){ 16 | int target = 0 - c - d; 17 | res += abSum[target]; 18 | } 19 | } 20 | 21 | return res; 22 | } 23 | }; -------------------------------------------------------------------------------- /leetcode/461.hamming-distance.cpp: -------------------------------------------------------------------------------- 1 | // Tag: Bit Manipulation 2 | // Time: O(1) 3 | // Space: O(1) 4 | // Ref: - 5 | // Note: - 6 | 7 | // The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 8 | // Given two integers x and y, return the Hamming distance between them. 9 | //   10 | // Example 1: 11 | // 12 | // Input: x = 1, y = 4 13 | // Output: 2 14 | // Explanation: 15 | // 1 (0 0 0 1) 16 | // 4 (0 1 0 0) 17 | // ↑ ↑ 18 | // The above arrows point to positions where the corresponding bits are different. 19 | // 20 | // Example 2: 21 | // 22 | // Input: x = 3, y = 1 23 | // Output: 1 24 | // 25 | //   26 | // Constraints: 27 | // 28 | // 0 <= x, y <= 231 - 1 29 | // 30 | // 31 | 32 | class Solution { 33 | public: 34 | int hammingDistance(int x, int y) { 35 | int n = x ^ y; 36 | int res = 0; 37 | while (n) { 38 | res += 1; 39 | n = n & (n - 1); 40 | } 41 | return res; 42 | } 43 | }; 44 | 45 | class Solution { 46 | public: 47 | int hammingDistance(int x, int y) { 48 | int diff = x ^ y; 49 | int res = 0; 50 | while (diff) { 51 | res += diff & 1; 52 | diff = diff >> 1; 53 | } 54 | return res; 55 | } 56 | }; -------------------------------------------------------------------------------- /leetcode/461.hamming-distance.py: -------------------------------------------------------------------------------- 1 | # Tag: Bit Manipulation 2 | # Time: O(1) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | 7 | # The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 8 | # Given two integers x and y, return the Hamming distance between them. 9 | #   10 | # Example 1: 11 | # 12 | # Input: x = 1, y = 4 13 | # Output: 2 14 | # Explanation: 15 | # 1 (0 0 0 1) 16 | # 4 (0 1 0 0) 17 | # ↑ ↑ 18 | # The above arrows point to positions where the corresponding bits are different. 19 | # 20 | # Example 2: 21 | # 22 | # Input: x = 3, y = 1 23 | # Output: 1 24 | # 25 | #   26 | # Constraints: 27 | # 28 | # 0 <= x, y <= 231 - 1 29 | # 30 | # 31 | 32 | class Solution: 33 | def hammingDistance(self, x: int, y: int) -> int: 34 | n = x ^ y 35 | res = 0 36 | while n > 0: 37 | n = n & (n - 1) 38 | res += 1 39 | return res 40 | 41 | class Solution: 42 | def hammingDistance(self, x: int, y: int) -> int: 43 | diff = x ^ y 44 | res = 0 45 | while diff > 0: 46 | res += diff & 1 47 | diff = diff >> 1 48 | return res -------------------------------------------------------------------------------- /leetcode/463.island-perimeter.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def islandPerimeter(self, grid): 3 | """ 4 | :type grid: List[List[int]] 5 | :rtype: int 6 | """ 7 | 8 | perimeter = 0 9 | 10 | for i in xrange(len(grid)): 11 | for j in xrange(len(grid[i])): 12 | if grid[i][j] == 1: 13 | perimeter += 4 14 | 15 | if i > 0 and grid[i - 1][j] == 1: 16 | perimeter -= 2 17 | 18 | if j > 0 and grid[i][j - 1] == 1: 19 | perimeter -= 2 20 | 21 | return perimeter 22 | -------------------------------------------------------------------------------- /leetcode/485.max-consecutive-ones.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMaxConsecutiveOnes(vector& nums) { 4 | int size = 0; 5 | int res = 0; 6 | 7 | for(auto i = 0; i < nums.size(); ++i) 8 | { 9 | if (nums[i] == 1) 10 | { 11 | size += 1; 12 | } 13 | else 14 | { 15 | res = max(res, size); 16 | size = 0; 17 | } 18 | } 19 | 20 | return max(res, size); 21 | } 22 | }; -------------------------------------------------------------------------------- /leetcode/49.group-anagrams.py: -------------------------------------------------------------------------------- 1 | # Tag: Array, Hash Table, String, Sorting 2 | # Time: O(NL) 3 | # Space: O(N) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given an array of strings strs, group the anagrams together. You can return the answer in any order. 8 | # An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. 9 | #   10 | # Example 1: 11 | # Input: strs = ["eat","tea","tan","ate","nat","bat"] 12 | # Output: [["bat"],["nat","tan"],["ate","eat","tea"]] 13 | # Example 2: 14 | # Input: strs = [""] 15 | # Output: [[""]] 16 | # Example 3: 17 | # Input: strs = ["a"] 18 | # Output: [["a"]] 19 | # 20 | #   21 | # Constraints: 22 | # 23 | # 1 <= strs.length <= 104 24 | # 0 <= strs[i].length <= 100 25 | # strs[i] consists of lowercase English letters. 26 | # 27 | # 28 | 29 | from collections import defaultdict 30 | class Solution: 31 | def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 32 | counter = defaultdict(list) 33 | for s in strs: 34 | key = "".join(sorted(s)) 35 | counter[key].append(s) 36 | 37 | return [counter[k] for k in counter] -------------------------------------------------------------------------------- /leetcode/504.base-7.cpp: -------------------------------------------------------------------------------- 1 | // Tag: Math 2 | // Time: O(N) 3 | // Space: O(1) 4 | // Ref: - 5 | // Note: - 6 | 7 | // Given an integer num, return a string of its base 7 representation. 8 | //   9 | // Example 1: 10 | // Input: num = 100 11 | // Output: "202" 12 | // Example 2: 13 | // Input: num = -7 14 | // Output: "-10" 15 | // 16 | //   17 | // Constraints: 18 | // 19 | // -107 <= num <= 107 20 | // 21 | // 22 | 23 | class Solution { 24 | public: 25 | string convertToBase7(int num) { 26 | if (num == 0) { 27 | return "0"; 28 | } 29 | 30 | string sign = num>=0 ? "" : "-"; 31 | string res = ""; 32 | num = abs(num); 33 | while (num > 0) { 34 | int d = num % 7; 35 | num = num / 7; 36 | 37 | res = to_string(d) + res; 38 | } 39 | 40 | return sign + res; 41 | } 42 | }; -------------------------------------------------------------------------------- /leetcode/504.base-7.py: -------------------------------------------------------------------------------- 1 | # Tag: Math 2 | # Time: O(N) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given an integer num, return a string of its base 7 representation. 8 | #   9 | # Example 1: 10 | # Input: num = 100 11 | # Output: "202" 12 | # Example 2: 13 | # Input: num = -7 14 | # Output: "-10" 15 | # 16 | #   17 | # Constraints: 18 | # 19 | # -107 <= num <= 107 20 | # 21 | # 22 | 23 | class Solution: 24 | def convertToBase7(self, num: int) -> str: 25 | 26 | if num == 0: 27 | return "0" 28 | 29 | res = "" 30 | sign = "" if num > 0 else "-" 31 | num = abs(num) 32 | while num > 0: 33 | d = num % 7 34 | num = num // 7 35 | 36 | res = str(d) + res 37 | 38 | return sign + res -------------------------------------------------------------------------------- /leetcode/525.contiguous-array.cpp: -------------------------------------------------------------------------------- 1 | // Tag: Array, Hash Table, Prefix Sum 2 | // Time: O(N) 3 | // Space: O(N) 4 | // Ref: - 5 | // Note: - 6 | 7 | // Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1. 8 | //   9 | // Example 1: 10 | // 11 | // Input: nums = [0,1] 12 | // Output: 2 13 | // Explanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1. 14 | // 15 | // Example 2: 16 | // 17 | // Input: nums = [0,1,0] 18 | // Output: 2 19 | // Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. 20 | // 21 | //   22 | // Constraints: 23 | // 24 | // 1 <= nums.length <= 105 25 | // nums[i] is either 0 or 1. 26 | // 27 | // 28 | 29 | class Solution { 30 | public: 31 | int findMaxLength(vector& nums) { 32 | unordered_map table; 33 | table[0] = -1; 34 | int preifx_sum = 0; 35 | int res = 0; 36 | int n = nums.size(); 37 | for (int i = 0; i < n; i++) { 38 | preifx_sum += nums[i] == 0 ? -1 : 1; 39 | if (table.count(preifx_sum) > 0) { 40 | res = max(res, i - table[preifx_sum]); 41 | } else { 42 | table[preifx_sum] = i; 43 | } 44 | } 45 | return res; 46 | } 47 | }; -------------------------------------------------------------------------------- /leetcode/525.contiguous-array.py: -------------------------------------------------------------------------------- 1 | # Tag: Array, Hash Table, Prefix Sum 2 | # Time: O(N) 3 | # Space: O(N) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1. 8 | #   9 | # Example 1: 10 | # 11 | # Input: nums = [0,1] 12 | # Output: 2 13 | # Explanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1. 14 | # 15 | # Example 2: 16 | # 17 | # Input: nums = [0,1,0] 18 | # Output: 2 19 | # Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1. 20 | # 21 | #   22 | # Constraints: 23 | # 24 | # 1 <= nums.length <= 105 25 | # nums[i] is either 0 or 1. 26 | # 27 | # 28 | 29 | class Solution: 30 | def findMaxLength(self, nums: List[int]) -> int: 31 | n = len(nums) 32 | preifx_sum = 0 33 | res = 0 34 | table = {0: -1} 35 | 36 | for i in range(n): 37 | if nums[i] == 0: 38 | preifx_sum -= 1 39 | else: 40 | preifx_sum += 1 41 | 42 | if preifx_sum in table: 43 | res = max(res, i - table[preifx_sum]) 44 | else: 45 | table[preifx_sum] = i 46 | 47 | return res -------------------------------------------------------------------------------- /leetcode/532.k-diff-pairs-in-an-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findPairs(vector& nums, int k) { 4 | sort(nums.begin(), nums.end()); 5 | int ans = 0; 6 | for (int i = 0; i < nums.size(); ++i) 7 | { 8 | int j = i + 1; 9 | 10 | while(j < nums.size() && nums[j] - nums[i] < k) 11 | { 12 | j++; 13 | } 14 | 15 | if (j < nums.size() && nums[j] - nums[i] == k) 16 | { 17 | ans += 1; 18 | 19 | // remove duplicate 20 | while(i + 1 < nums.size() && nums[i + 1] == nums[i]) 21 | { 22 | i++; 23 | } 24 | } 25 | } 26 | 27 | return ans; 28 | } 29 | }; -------------------------------------------------------------------------------- /leetcode/532.k-diff-pairs-in-an-array.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def findPairs(self, nums, k): 3 | """ 4 | :type nums: List[int] 5 | :type k: int 6 | :rtype: int 7 | """ 8 | 9 | if nums is None: 10 | return 0 11 | 12 | nums.sort() 13 | start = 0 14 | ans = 0 15 | 16 | while start < len(nums): 17 | end = start + 1 18 | 19 | while(end < len(nums) and nums[end] - nums[start] < k): 20 | end += 1 21 | 22 | if (end < len(nums) and nums[end] - nums[start] == k): 23 | ans += 1 24 | 25 | #remove duplicate 26 | while(start + 1 < len(nums) and nums[start + 1] == nums[start]): 27 | start += 1 28 | 29 | start += 1 30 | 31 | return ans 32 | -------------------------------------------------------------------------------- /leetcode/54.spiral-matrix.cpp: -------------------------------------------------------------------------------- 1 | static int xDirections[4] = {0, 1, 0, -1}; 2 | static int yDirections[4] = {1, 0, -1, 0}; 3 | static int shrinkBound[4] = {1, -1, -1, 1}; 4 | 5 | class Solution { 6 | public: 7 | vector spiralOrder(vector>& matrix) { 8 | int n = (int)matrix.size(); 9 | if (n == 0) 10 | { 11 | return vector(); 12 | } 13 | 14 | int m = (int)matrix[0].size(); 15 | vector res; 16 | int bounds[4] = {0, m - 1, n - 1, 0}; //top right, bottom left 17 | 18 | int x = 0; 19 | int y = 0; 20 | res.push_back(matrix[x][y]); 21 | 22 | while (bounds[3] <= bounds[1] && bounds[0] <= bounds[2]) { 23 | for (auto i = 0; i < 4; ++i) 24 | { 25 | while (x + xDirections[i] >= bounds[0] && x + xDirections[i] <= bounds[2] && y + yDirections[i] >= bounds[3] && y + yDirections[i] <= bounds[1]) { 26 | x = x + xDirections[i]; 27 | y = y + yDirections[i]; 28 | 29 | res.push_back(matrix[x][y]); 30 | } 31 | 32 | bounds[i] += shrinkBound[i]; 33 | } 34 | } 35 | 36 | return res; 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /leetcode/54.spiral-matrix.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def spiralOrder(self, matrix): 3 | """ 4 | :type matrix: List[List[int]] 5 | :rtype: List[int] 6 | """ 7 | 8 | if len(matrix) == 0 or len(matrix[0]) == 0: 9 | return [] 10 | 11 | x_directions = [0, 1, 0, -1] 12 | y_directions = [1, 0, -1, 0] 13 | shrink_bounds = [1, -1, -1, 1] 14 | 15 | top, left, bottom, right = 0, 0, len(matrix) - 1, len(matrix[0]) - 1 16 | bounds = [top, right, bottom, left] 17 | 18 | res = [] 19 | i, j = top, left 20 | res.append(matrix[i][j]) 21 | 22 | while bounds[0] <= bounds[2] and bounds[3] <= bounds[1]: 23 | 24 | for k in range(4): 25 | while bounds[0] <= i + x_directions[k] <= bounds[2] and bounds[3] <= j + y_directions[k] <= bounds[1]: 26 | i += x_directions[k] 27 | j += y_directions[k] 28 | res.append(matrix[i][j]) 29 | 30 | bounds[k] += shrink_bounds[k] 31 | 32 | return res -------------------------------------------------------------------------------- /leetcode/540.single-element-in-a-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | // Tag: Array, Binary Search 2 | // Time: O(logN) 3 | // Space: O(1) 4 | // Ref: - 5 | // Note: - 6 | 7 | // You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. 8 | // Return the single element that appears only once. 9 | // Your solution must run in O(log n) time and O(1) space. 10 | //   11 | // Example 1: 12 | // Input: nums = [1,1,2,3,3,4,4,8,8] 13 | // Output: 2 14 | // Example 2: 15 | // Input: nums = [3,3,7,7,10,11,11] 16 | // Output: 10 17 | // 18 | //   19 | // Constraints: 20 | // 21 | // 1 <= nums.length <= 105 22 | // 0 <= nums[i] <= 105 23 | // 24 | // 25 | 26 | class Solution { 27 | public: 28 | int singleNonDuplicate(vector& nums) { 29 | int left = 0; 30 | int right = nums.size() - 1; 31 | 32 | while (left < right) { 33 | int mid = left + (right - left) / 2; 34 | if ((mid % 2 == 0 && nums[mid] == nums[mid + 1]) || (mid % 2 == 1 && nums[mid] != nums[mid + 1])) { 35 | left = mid + 1; 36 | } else { 37 | right = mid; 38 | } 39 | } 40 | 41 | return nums[left]; 42 | } 43 | }; -------------------------------------------------------------------------------- /leetcode/540.single-element-in-a-sorted-array.py: -------------------------------------------------------------------------------- 1 | # Tag: Array, Binary Search 2 | # Time: O(logN) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | 7 | # You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. 8 | # Return the single element that appears only once. 9 | # Your solution must run in O(log n) time and O(1) space. 10 | #   11 | # Example 1: 12 | # Input: nums = [1,1,2,3,3,4,4,8,8] 13 | # Output: 2 14 | # Example 2: 15 | # Input: nums = [3,3,7,7,10,11,11] 16 | # Output: 10 17 | # 18 | #   19 | # Constraints: 20 | # 21 | # 1 <= nums.length <= 105 22 | # 0 <= nums[i] <= 105 23 | # 24 | # 25 | 26 | class Solution: 27 | def singleNonDuplicate(self, nums: List[int]) -> int: 28 | left = 0 29 | right = len(nums) - 1 30 | 31 | while left < right: 32 | mid = left + (right - left) // 2 33 | 34 | if (mid % 2 == 0 and nums[mid] == nums[mid + 1]) or (mid % 2 == 1 and nums[mid] != nums[mid + 1]): 35 | left = mid + 1 36 | else: 37 | right = mid 38 | 39 | return nums[left] 40 | -------------------------------------------------------------------------------- /leetcode/560.subarray-sum-equals-k.cpp: -------------------------------------------------------------------------------- 1 | // Tag: Array, Hash Table, Prefix Sum 2 | // Time: O(N) 3 | // Space: O(N) 4 | // Ref: - 5 | // Note: - 6 | 7 | // Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. 8 | // A subarray is a contiguous non-empty sequence of elements within an array. 9 | //   10 | // Example 1: 11 | // Input: nums = [1,1,1], k = 2 12 | // Output: 2 13 | // Example 2: 14 | // Input: nums = [1,2,3], k = 3 15 | // Output: 2 16 | // 17 | //   18 | // Constraints: 19 | // 20 | // 1 <= nums.length <= 2 * 104 21 | // -1000 <= nums[i] <= 1000 22 | // -107 <= k <= 107 23 | // 24 | // 25 | 26 | class Solution { 27 | public: 28 | int subarraySum(vector& nums, int k) { 29 | unordered_map mapping; 30 | mapping[0] = 1; 31 | int prefix = 0; 32 | int res = 0; 33 | for (auto n: nums) { 34 | prefix += n; 35 | res += mapping[prefix - k]; 36 | mapping[prefix]++; 37 | } 38 | return res; 39 | } 40 | }; -------------------------------------------------------------------------------- /leetcode/560.subarray-sum-equals-k.py: -------------------------------------------------------------------------------- 1 | # Tag: Array, Hash Table, Prefix Sum 2 | # Time: O(N) 3 | # Space: O(N) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. 8 | # A subarray is a contiguous non-empty sequence of elements within an array. 9 | #   10 | # Example 1: 11 | # Input: nums = [1,1,1], k = 2 12 | # Output: 2 13 | # Example 2: 14 | # Input: nums = [1,2,3], k = 3 15 | # Output: 2 16 | # 17 | #   18 | # Constraints: 19 | # 20 | # 1 <= nums.length <= 2 * 104 21 | # -1000 <= nums[i] <= 1000 22 | # -107 <= k <= 107 23 | # 24 | # 25 | 26 | from collections import defaultdict 27 | class Solution: 28 | def subarraySum(self, nums: List[int], k: int) -> int: 29 | n = len(nums) 30 | prefix = 0 31 | mapping = defaultdict(int) 32 | mapping[0] = 1 33 | 34 | res = 0 35 | for n in nums: 36 | prefix += n 37 | res += mapping[prefix - k] 38 | mapping[prefix] += 1 39 | 40 | return res -------------------------------------------------------------------------------- /leetcode/561.array-partition-i.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int arrayPairSum(vector& nums) { 4 | 5 | } 6 | }; 7 | -------------------------------------------------------------------------------- /leetcode/588.design-in-memory-file-system.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/leetcode/588.design-in-memory-file-system.vip -------------------------------------------------------------------------------- /leetcode/599.minimum-index-sum-of-two-lists.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findRestaurant(vector& list1, vector& list2) { 4 | 5 | unordered_map map; 6 | for (int i = 0; i < list1.size(); ++i){ 7 | map.insert(make_pair(list1[i], i)); 8 | } 9 | 10 | int sum = INT_MAX; 11 | vector res; 12 | for (int j = 0; j < list2.size(); ++j){ 13 | if (map.count(list2[j]) > 0){ 14 | int tmp = map[list2[j]] + j; 15 | 16 | if (tmp == sum){ 17 | res.push_back(list2[j]); 18 | }else if (tmp < sum){ 19 | res.clear(); 20 | sum = tmp; 21 | res.push_back(list2[j]); 22 | } 23 | } 24 | } 25 | 26 | return res; 27 | } 28 | }; -------------------------------------------------------------------------------- /leetcode/605.can-place-flowers.py: -------------------------------------------------------------------------------- 1 | # Tag: Greedy, Array 2 | # Time: O(N) 3 | # Space: O(N) 4 | # Ref: - 5 | # Note: - 6 | 7 | # You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots. 8 | # Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise. 9 | #   10 | # Example 1: 11 | # Input: flowerbed = [1,0,0,0,1], n = 1 12 | # Output: true 13 | # Example 2: 14 | # Input: flowerbed = [1,0,0,0,1], n = 2 15 | # Output: false 16 | # 17 | #   18 | # Constraints: 19 | # 20 | # 1 <= flowerbed.length <= 2 * 104 21 | # flowerbed[i] is 0 or 1. 22 | # There are no two adjacent flowers in flowerbed. 23 | # 0 <= n <= flowerbed.length 24 | # 25 | # 26 | 27 | class Solution: 28 | def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: 29 | 30 | count = 0 31 | flowerbed = [0] + flowerbed + [0] 32 | 33 | for i in range(1, len(flowerbed) - 1): 34 | if flowerbed[i] == 0 and flowerbed[i - 1] == 0 and flowerbed[i + 1] == 0: 35 | count += 1 36 | flowerbed[i] = 1 37 | 38 | return count >= n -------------------------------------------------------------------------------- /leetcode/61.rotate-list.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | def rotateRight(self, head, k): 9 | """ 10 | :type head: ListNode 11 | :type k: int 12 | :rtype: ListNode 13 | """ 14 | 15 | if head is None: 16 | return None 17 | 18 | new_head = ListNode(0) 19 | new_head.next = head 20 | 21 | total_count = self.count(head) 22 | step = k % total_count 23 | 24 | # find last k + 1 elements 25 | # start = start -> n1, n2..., nk 26 | start = head 27 | end = start 28 | count = 0 29 | while(head is not None): 30 | end = head 31 | 32 | if count > step: 33 | start = start.next 34 | count += 1 35 | head = head.next 36 | 37 | end.next = new_head.next 38 | new_head.next = start.next 39 | start.next = None 40 | 41 | return new_head.next 42 | 43 | def count(self, node): 44 | count = 0 45 | cur = node 46 | while (cur is not None): 47 | cur = cur.next 48 | count += 1 49 | 50 | return count -------------------------------------------------------------------------------- /leetcode/611.valid-triangle-number.py: -------------------------------------------------------------------------------- 1 | # Tag: Array, Two Pointers, Binary Search, Greedy, Sorting 2 | # Time: O(N^2) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle. 8 | #   9 | # Example 1: 10 | # 11 | # Input: nums = [2,2,3,4] 12 | # Output: 3 13 | # Explanation: Valid combinations are: 14 | # 2,3,4 (using the first 2) 15 | # 2,3,4 (using the second 2) 16 | # 2,2,3 17 | # 18 | # Example 2: 19 | # 20 | # Input: nums = [4,2,3,4] 21 | # Output: 4 22 | # 23 | #   24 | # Constraints: 25 | # 26 | # 1 <= nums.length <= 1000 27 | # 0 <= nums[i] <= 1000 28 | # 29 | # 30 | 31 | class Solution: 32 | def triangleNumber(self, nums: List[int]) -> int: 33 | n = len(nums) 34 | nums.sort() 35 | res = 0 36 | for k in range(2, n): 37 | r = k - 1 38 | l = 0 39 | while l < r: 40 | if nums[l] + nums[r] > nums[k]: 41 | res += r - l 42 | r -= 1 43 | else: 44 | l += 1 45 | 46 | return res -------------------------------------------------------------------------------- /leetcode/633.sum-of-square-numbers.cpp: -------------------------------------------------------------------------------- 1 | // Tag: Math, Two Pointers, Binary Search 2 | // Time: O(N) 3 | // Space: O(1) 4 | // Ref: - 5 | // Note: - 6 | 7 | // Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c. 8 | //   9 | // Example 1: 10 | // 11 | // Input: c = 5 12 | // Output: true 13 | // Explanation: 1 * 1 + 2 * 2 = 5 14 | // 15 | // Example 2: 16 | // 17 | // Input: c = 3 18 | // Output: false 19 | // 20 | //   21 | // Constraints: 22 | // 23 | // 0 <= c <= 231 - 1 24 | // 25 | // 26 | 27 | class Solution { 28 | public: 29 | bool judgeSquareSum(int c) { 30 | int l = 0; 31 | long r = sqrt(c); 32 | 33 | while (l <= r) { 34 | long res = l * l + r * r; 35 | if (res == c) { 36 | return true; 37 | } 38 | 39 | if (res > c) { 40 | r --; 41 | } else { 42 | l ++; 43 | } 44 | } 45 | 46 | return false; 47 | } 48 | }; -------------------------------------------------------------------------------- /leetcode/633.sum-of-square-numbers.py: -------------------------------------------------------------------------------- 1 | # Tag: Math, Two Pointers, Binary Search 2 | # Time: O(N) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c. 8 | #   9 | # Example 1: 10 | # 11 | # Input: c = 5 12 | # Output: true 13 | # Explanation: 1 * 1 + 2 * 2 = 5 14 | # 15 | # Example 2: 16 | # 17 | # Input: c = 3 18 | # Output: false 19 | # 20 | #   21 | # Constraints: 22 | # 23 | # 0 <= c <= 231 - 1 24 | # 25 | # 26 | 27 | import math 28 | class Solution: 29 | def judgeSquareSum(self, c: int) -> bool: 30 | l = 0 31 | r = math.floor(math.sqrt(c)) 32 | 33 | while l <= r: 34 | if l * l + r * r == c: 35 | return True 36 | 37 | if l * l + r * r > c: 38 | r -= 1 39 | else: 40 | l += 1 41 | return False 42 | -------------------------------------------------------------------------------- /leetcode/643.maximum-average-subarray-i.cpp: -------------------------------------------------------------------------------- 1 | // Tag: Array, Sliding Window 2 | // Time: O(N) 3 | // Space: O(1) 4 | // Ref: - 5 | // Note: - 6 | 7 | // You are given an integer array nums consisting of n elements, and an integer k. 8 | // Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10-5 will be accepted. 9 | //   10 | // Example 1: 11 | // 12 | // Input: nums = [1,12,-5,-6,50,3], k = 4 13 | // Output: 12.75000 14 | // Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75 15 | // 16 | // Example 2: 17 | // 18 | // Input: nums = [5], k = 1 19 | // Output: 5.00000 20 | // 21 | //   22 | // Constraints: 23 | // 24 | // n == nums.length 25 | // 1 <= k <= n <= 105 26 | // -104 <= nums[i] <= 104 27 | // 28 | // 29 | 30 | class Solution { 31 | public: 32 | double findMaxAverage(vector& nums, int k) { 33 | int n = nums.size(); 34 | int tmp = 0; 35 | int res = INT_MIN; 36 | for (int i = 0; i < n; i++) { 37 | tmp += nums[i]; 38 | if (i >= k - 1) { 39 | res = max(res, tmp); 40 | tmp -= nums[i - k + 1]; 41 | } 42 | } 43 | return double(res) / k; 44 | } 45 | }; -------------------------------------------------------------------------------- /leetcode/643.maximum-average-subarray-i.py: -------------------------------------------------------------------------------- 1 | # Tag: Array, Sliding Window 2 | # Time: O(N) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | 7 | # You are given an integer array nums consisting of n elements, and an integer k. 8 | # Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10-5 will be accepted. 9 | #   10 | # Example 1: 11 | # 12 | # Input: nums = [1,12,-5,-6,50,3], k = 4 13 | # Output: 12.75000 14 | # Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75 15 | # 16 | # Example 2: 17 | # 18 | # Input: nums = [5], k = 1 19 | # Output: 5.00000 20 | # 21 | #   22 | # Constraints: 23 | # 24 | # n == nums.length 25 | # 1 <= k <= n <= 105 26 | # -104 <= nums[i] <= 104 27 | # 28 | # 29 | 30 | class Solution: 31 | def findMaxAverage(self, nums: List[int], k: int) -> float: 32 | n = len(nums) 33 | res = float('-inf') 34 | tmp = 0 35 | for i in range(n): 36 | tmp += nums[i] 37 | 38 | if i >= k - 1: 39 | res = max(res, tmp) 40 | tmp -= nums[i - k + 1] 41 | 42 | return res / k -------------------------------------------------------------------------------- /leetcode/652.find-duplicate-subtrees.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | 12 | private: 13 | string postOrderTraverse(vector &res, unordered_map &map, TreeNode* node){ 14 | 15 | if (node == NULL){ 16 | return "#"; 17 | } 18 | 19 | string s = to_string(node->val) + "(" + postOrderTraverse(res, map, node->left) + "," + postOrderTraverse(res, map, node->right) + ")"; 20 | if (map[s] == 1){ 21 | res.push_back(node); 22 | } 23 | 24 | map[s] += 1; 25 | 26 | return s; 27 | } 28 | public: 29 | vector findDuplicateSubtrees(TreeNode* root) { 30 | vector res; 31 | unordered_map map; 32 | 33 | postOrderTraverse(res, map, root); 34 | 35 | return res; 36 | } 37 | }; -------------------------------------------------------------------------------- /leetcode/654.maximum-binary-tree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def constructMaximumBinaryTree(self, nums): 10 | """ 11 | :type nums: List[int] 12 | :rtype: TreeNode 13 | """ 14 | stack = [] 15 | 16 | for k in nums: 17 | node = TreeNode(k) 18 | 19 | while (stack and stack[-1].val <= k): 20 | node.left = stack.pop() 21 | 22 | if stack: 23 | stack[-1].right = node 24 | 25 | stack.append(node) 26 | 27 | return stack[0] 28 | -------------------------------------------------------------------------------- /leetcode/657.robot-return-to-origin.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def judgeCircle(self, moves): 3 | """ 4 | :type moves: str 5 | :rtype: bool 6 | """ 7 | return moves.count("U") == moves.count("D") and moves.count("L") == moves.count("R") -------------------------------------------------------------------------------- /leetcode/66.plus-one.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector plusOne(vector& digits) { 4 | 5 | vector res; 6 | int extra = 1; 7 | int count = (int)digits.size(); 8 | 9 | for(int i = count - 1; i >= 0; --i) 10 | { 11 | res.push_back((digits[i] + extra) % 10); 12 | extra = (digits[i] + extra) / 10; 13 | } 14 | 15 | if (extra > 0) 16 | { 17 | res.push_back(extra); 18 | } 19 | 20 | reverse(res.begin(), res.end()); 21 | return res; 22 | } 23 | }; -------------------------------------------------------------------------------- /leetcode/66.plus-one.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def plusOne(self, digits): 3 | """ 4 | :type digits: List[int] 5 | :rtype: List[int] 6 | """ 7 | ans = [] 8 | addon = 1 9 | i = len(digits) - 1 10 | 11 | while i >= 0 or addon > 0: 12 | number = digits[i] % 10 if i >= 0 else 0 13 | total = number + addon 14 | 15 | ans.append(total % 10) 16 | addon = total // 10 17 | 18 | i -= 1 19 | 20 | return ans[::-1] -------------------------------------------------------------------------------- /leetcode/665.non-decreasing-array.py: -------------------------------------------------------------------------------- 1 | # Tag: Array 2 | # Time: O(N) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element. 8 | # We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2). 9 | #   10 | # Example 1: 11 | # 12 | # Input: nums = [4,2,3] 13 | # Output: true 14 | # Explanation: You could modify the first 4 to 1 to get a non-decreasing array. 15 | # 16 | # Example 2: 17 | # 18 | # Input: nums = [4,2,1] 19 | # Output: false 20 | # Explanation: You cannot get a non-decreasing array by modifying at most one element. 21 | # 22 | #   23 | # Constraints: 24 | # 25 | # n == nums.length 26 | # 1 <= n <= 104 27 | # -105 <= nums[i] <= 105 28 | # 29 | # 30 | 31 | class Solution: 32 | def checkPossibility(self, nums: List[int]) -> bool: 33 | count = 0 34 | 35 | for i in range(1, len(nums)): 36 | if nums[i] < nums[i - 1]: 37 | count += 1 38 | if i - 2 >= 0 and nums[i - 2] > nums[i]: 39 | nums[i] = nums[i - 1] 40 | else: 41 | nums[i - 1] = nums[i] 42 | 43 | return count <= 1 44 | -------------------------------------------------------------------------------- /leetcode/67.add-binary.cpp: -------------------------------------------------------------------------------- 1 | // Tag: Math, String, Bit Manipulation, Simulation 2 | // Time: O(M+N) 3 | // Space: O(1) 4 | // Ref: - 5 | // Note: - 6 | 7 | // Given two binary strings a and b, return their sum as a binary string. 8 | //   9 | // Example 1: 10 | // Input: a = "11", b = "1" 11 | // Output: "100" 12 | // Example 2: 13 | // Input: a = "1010", b = "1011" 14 | // Output: "10101" 15 | // 16 | //   17 | // Constraints: 18 | // 19 | // 1 <= a.length, b.length <= 104 20 | // a and b consist only of '0' or '1' characters. 21 | // Each string does not contain leading zeros except for the zero itself. 22 | // 23 | // 24 | 25 | class Solution { 26 | public: 27 | string addBinary(string a, string b) { 28 | string res = ""; 29 | int carry = 0; 30 | int i = a.size() - 1; 31 | int j = b.size() - 1; 32 | while (i >= 0 || j >= 0 || carry) { 33 | int l = i >= 0 ? a[i] - '0' : 0; 34 | int r = j >= 0 ? b[j] - '0' : 0; 35 | int tmp = l + r + carry; 36 | char digit = tmp % 2; 37 | carry = tmp / 2; 38 | res = to_string(digit) + res; 39 | i--; 40 | j--; 41 | } 42 | 43 | return res; 44 | } 45 | }; -------------------------------------------------------------------------------- /leetcode/67.add-binary.py: -------------------------------------------------------------------------------- 1 | # Tag: Math, String, Bit Manipulation, Simulation 2 | # Time: O(M+N) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given two binary strings a and b, return their sum as a binary string. 8 | #   9 | # Example 1: 10 | # Input: a = "11", b = "1" 11 | # Output: "100" 12 | # Example 2: 13 | # Input: a = "1010", b = "1011" 14 | # Output: "10101" 15 | # 16 | #   17 | # Constraints: 18 | # 19 | # 1 <= a.length, b.length <= 104 20 | # a and b consist only of '0' or '1' characters. 21 | # Each string does not contain leading zeros except for the zero itself. 22 | # 23 | # 24 | 25 | class Solution: 26 | def addBinary(self, a: str, b: str) -> str: 27 | res = '' 28 | carry = 0 29 | i = len(a) - 1 30 | j = len(b) - 1 31 | 32 | while i >= 0 or j >= 0 or carry: 33 | l = int(a[i]) if i >= 0 else 0 34 | r = int(b[j]) if j >= 0 else 0 35 | tmp = l + r + carry 36 | digit = tmp % 2 37 | carry = tmp // 2 38 | res = str(digit) + res 39 | i -= 1 40 | j -= 1 41 | 42 | return res -------------------------------------------------------------------------------- /leetcode/680.valid-palindrome-ii.py: -------------------------------------------------------------------------------- 1 | # Tag: Two Pointers, String, Greedy 2 | # Time: O(N) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given a string s, return true if the s can be palindrome after deleting at most one character from it. 8 | #   9 | # Example 1: 10 | # 11 | # Input: s = "aba" 12 | # Output: true 13 | # 14 | # Example 2: 15 | # 16 | # Input: s = "abca" 17 | # Output: true 18 | # Explanation: You could delete the character 'c'. 19 | # 20 | # Example 3: 21 | # 22 | # Input: s = "abc" 23 | # Output: false 24 | # 25 | #   26 | # Constraints: 27 | # 28 | # 1 <= s.length <= 105 29 | # s consists of lowercase English letters. 30 | # 31 | # 32 | 33 | class Solution: 34 | def validPalindrome(self, s: str) -> bool: 35 | l = 0 36 | r = len(s) - 1 37 | 38 | while l < r: 39 | if s[l] != s[r]: 40 | return self.isPalindrome(s, l + 1, r) or self.isPalindrome(s, l, r - 1) 41 | 42 | l += 1 43 | r -= 1 44 | 45 | return True 46 | 47 | def isPalindrome(self, s: str, l: int, r:int) -> bool: 48 | while l < r: 49 | if s[l] != s[r]: 50 | return False 51 | 52 | l += 1 53 | r -= 1 54 | 55 | return True 56 | -------------------------------------------------------------------------------- /leetcode/687.longest-univalue-path.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | private: 12 | int ans = 0; 13 | 14 | int helper(TreeNode* cur) 15 | { 16 | if (cur == NULL) 17 | { 18 | return 0; 19 | } 20 | 21 | int left = helper(cur->left); 22 | int right = helper(cur->right); 23 | 24 | left = (cur->left && cur->left->val == cur->val) ? left + 1 : 0; 25 | right = (cur->right && cur->right->val == cur->val) ? right + 1 : 0; 26 | 27 | ans = max(ans, left + right); 28 | 29 | return max(left, right); 30 | } 31 | 32 | public: 33 | int longestUnivaluePath(TreeNode* root) { 34 | helper(root); 35 | return ans; 36 | } 37 | }; -------------------------------------------------------------------------------- /leetcode/687.longest-univalue-path.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.left = None 6 | # self.right = None 7 | 8 | class Solution(object): 9 | def __init__(self): 10 | self.res = 0 11 | 12 | def longestUnivaluePath(self, root): 13 | """ 14 | :type root: TreeNode 15 | :rtype: int 16 | """ 17 | self.helper(root) 18 | return self.res 19 | 20 | def helper(self, cur): 21 | if cur is None: 22 | return 0 23 | 24 | left = self.helper(cur.left) 25 | right = self.helper(cur.right) 26 | 27 | left = left + 1 if cur.left is not None and cur.left.val == cur.val else 0 28 | right = right + 1 if cur.right is not None and cur.right.val == cur.val else 0 29 | 30 | self.res = max(self.res, left + right) 31 | 32 | return max(left, right) 33 | -------------------------------------------------------------------------------- /leetcode/7.reverse-integer.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int reverse(int x) { 4 | int res = 0; 5 | while (x != 0) { 6 | int pop = x % 10; // gets last number 7 | x /= 10; 8 | if (res > INT_MAX / 10 || (res == INT_MAX / 10 && pop > 7)) return 0; 9 | if (res < INT_MIN / 10 || (res == INT_MIN / 10 && pop < -8)) return 0; 10 | res = res * 10 + pop; 11 | } 12 | 13 | return res; 14 | } 15 | }; 16 | 17 | class Solution2 { 18 | public: 19 | int reverse(int x) { 20 | 21 | int res = 0; 22 | while(x != 0) 23 | { 24 | int pop = x % 10; 25 | x = x / 10; 26 | 27 | int candidate = res * 10 + pop; 28 | 29 | if (candidate / 10 != res) 30 | { 31 | return 0; 32 | } 33 | 34 | res = candidate; 35 | } 36 | 37 | return res; 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /leetcode/7.reverse-integer.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def reverse(self, x: int) -> int: 3 | 4 | max_integer = 2 ** 31 - 1 5 | min_integer = - 2 ** 31 6 | 7 | sign = 1 if x >= 0 else -1 8 | x = abs(x) 9 | reverse = 0 10 | 11 | while x > 0: 12 | reverse = reverse * 10 + x % 10 13 | x = x // 10 14 | 15 | res = sign * reverse 16 | return res if res >= min_integer and res <= max_integer else 0 -------------------------------------------------------------------------------- /leetcode/70.climbing-stairs.py: -------------------------------------------------------------------------------- 1 | # Tag: Math, Dynamic Programming, Memoization 2 | # Time: O(N) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | 7 | # You are climbing a staircase. It takes n steps to reach the top. 8 | # Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 9 | #   10 | # Example 1: 11 | # 12 | # Input: n = 2 13 | # Output: 2 14 | # Explanation: There are two ways to climb to the top. 15 | # 1. 1 step + 1 step 16 | # 2. 2 steps 17 | # 18 | # Example 2: 19 | # 20 | # Input: n = 3 21 | # Output: 3 22 | # Explanation: There are three ways to climb to the top. 23 | # 1. 1 step + 1 step + 1 step 24 | # 2. 1 step + 2 steps 25 | # 3. 2 steps + 1 step 26 | # 27 | #   28 | # Constraints: 29 | # 30 | # 1 <= n <= 45 31 | # 32 | # 33 | 34 | class Solution: 35 | def climbStairs(self, n: int) -> int: 36 | cur = 1 37 | pre = 1 38 | 39 | for i in range(2, n + 1): 40 | new_cur = pre + cur 41 | pre = cur 42 | cur = new_cur 43 | 44 | return cur 45 | 46 | class Solution: 47 | def climbStairs(self, n: int) -> int: 48 | dp = [1 for i in range(n + 1)] 49 | for i in range(2, n + 1): 50 | dp[i] = dp[i - 1] + dp[i - 2] 51 | 52 | return dp[n] -------------------------------------------------------------------------------- /leetcode/702.search-in-a-sorted-array-of-unknown-size.cpp: -------------------------------------------------------------------------------- 1 | // Forward declaration of ArrayReader class. 2 | class ArrayReader; 3 | 4 | class Solution { 5 | public: 6 | int search(const ArrayReader& reader, int target) { 7 | int start = 0; 8 | int end = 1; 9 | 10 | int res = reader.get(end); 11 | while (res != INT_MAX && res < target) 12 | { 13 | start = end; 14 | end = end * 2; 15 | res = reader.get(end); 16 | } 17 | 18 | while (start + 1 < end) 19 | { 20 | int mid = start + (end - start) / 2; 21 | res = reader.get(mid); 22 | 23 | if (res < target) 24 | { 25 | start = mid; 26 | } 27 | else if (res > target) 28 | { 29 | end = mid; 30 | } 31 | else 32 | { 33 | return mid; 34 | } 35 | } 36 | 37 | if (reader.get(start) == target) 38 | { 39 | return start; 40 | } 41 | 42 | if (reader.get(end) == target) 43 | { 44 | return end; 45 | } 46 | 47 | return -1; 48 | } 49 | }; -------------------------------------------------------------------------------- /leetcode/702.search-in-a-sorted-array-of-unknown-size.py: -------------------------------------------------------------------------------- 1 | INT_MAX = 2147483647 2 | class Solution(object): 3 | def search(self, reader, target): 4 | """ 5 | :type reader: ArrayReader 6 | :type target: int 7 | :rtype: int 8 | """ 9 | 10 | start = 0 11 | end = 1 12 | res = reader.get(end) 13 | 14 | while(res != INT_MAX and res < target): 15 | start = end 16 | end = end * 2 17 | res = reader.get(end) 18 | 19 | while (start + 1 < end): 20 | mid = start + (end - start) // 2 21 | res = reader.get(mid) 22 | 23 | if res < target: 24 | start = mid 25 | elif res > target: 26 | end = mid 27 | else: 28 | return mid 29 | 30 | if reader.get(start) == target: 31 | return start 32 | 33 | if reader.get(end) == target: 34 | return end 35 | 36 | return -1 -------------------------------------------------------------------------------- /leetcode/713.subarray-product-less-than-k.py: -------------------------------------------------------------------------------- 1 | # Tag: Array, Binary Search, Sliding Window, Prefix Sum 2 | # Time: O(N) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k. 8 | #   9 | # Example 1: 10 | # 11 | # Input: nums = [10,5,2,6], k = 100 12 | # Output: 8 13 | # Explanation: The 8 subarrays that have product less than 100 are: 14 | # [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6] 15 | # Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k. 16 | # 17 | # Example 2: 18 | # 19 | # Input: nums = [1,2,3], k = 0 20 | # Output: 0 21 | # 22 | #   23 | # Constraints: 24 | # 25 | # 1 <= nums.length <= 3 * 104 26 | # 1 <= nums[i] <= 1000 27 | # 0 <= k <= 106 28 | # 29 | # 30 | 31 | class Solution: 32 | def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: 33 | n = len(nums) 34 | i = 0 35 | prod = 1 36 | res = 0 37 | for j in range(n): 38 | prod *= nums[j] 39 | while i <= j and prod >= k: 40 | prod //= nums[i] 41 | i += 1 42 | 43 | res += j - i + 1 44 | 45 | return res -------------------------------------------------------------------------------- /leetcode/724.find-pivot-index.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int pivotIndex(vector& nums) { 4 | 5 | int count = nums.size(); 6 | vector mem(count + 1, 0); // could use two variables instead 7 | for (auto i = 0; i < count; ++i) 8 | { 9 | mem[i + 1] = mem[i] + nums[i]; 10 | } 11 | 12 | for (auto i = 0; i < count; ++i) 13 | { 14 | if (mem[i] - mem[0] == mem[count] - mem[i + 1]) 15 | { 16 | return i; 17 | } 18 | } 19 | 20 | return -1; 21 | } 22 | }; -------------------------------------------------------------------------------- /leetcode/739.daily-temperatures.py: -------------------------------------------------------------------------------- 1 | # Tag: Array, Stack, Monotonic Stack 2 | # Time: O(N) 3 | # Space: O(N) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead. 8 | #   9 | # Example 1: 10 | # Input: temperatures = [73,74,75,71,69,72,76,73] 11 | # Output: [1,1,4,2,1,1,0,0] 12 | # Example 2: 13 | # Input: temperatures = [30,40,50,60] 14 | # Output: [1,1,1,0] 15 | # Example 3: 16 | # Input: temperatures = [30,60,90] 17 | # Output: [1,1,0] 18 | # 19 | #   20 | # Constraints: 21 | # 22 | # 1 <= temperatures.length <= 105 23 | # 30 <= temperatures[i] <= 100 24 | # 25 | # 26 | 27 | class Solution: 28 | def dailyTemperatures(self, temperatures: List[int]) -> List[int]: 29 | n = len(temperatures) 30 | res = [0 for i in range(n)] 31 | stack = [] 32 | 33 | for i in range(n): 34 | while len(stack) > 0 and temperatures[i] > temperatures[stack[-1]]: 35 | j = stack.pop() 36 | res[j] = i - j 37 | 38 | stack.append(i) 39 | 40 | return res -------------------------------------------------------------------------------- /leetcode/747.largest-number-at-least-twice-of-others.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int dominantIndex(vector& nums) { 4 | 5 | int maxIndex = 0; 6 | for (auto i = 1; i < nums.size(); ++i) 7 | { 8 | if (nums[maxIndex] < nums[i]) 9 | { 10 | maxIndex = i; 11 | } 12 | } 13 | 14 | for(auto i = 0; i < nums.size(); ++i) 15 | { 16 | if (i != maxIndex && nums[i] * 2 > nums[maxIndex]) 17 | { 18 | return -1; 19 | } 20 | } 21 | 22 | return maxIndex; 23 | } 24 | }; -------------------------------------------------------------------------------- /leetcode/751.ip-to-cidr.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def ipToCIDR(self, ip, n): 3 | """ 4 | :type ip: str 5 | :type n: int 6 | :rtype: List[str] 7 | """ 8 | ips = ip.split('.') 9 | x = 0 10 | for i in range(len(ips)): 11 | x = x * 256 + int(ips[i]) 12 | 13 | res = [] 14 | while n > 0: 15 | step = x & -x 16 | while step > n: 17 | step /= 2 18 | ans = self.numberToIp(x, step) 19 | res.append(ans) 20 | x += step 21 | n -= step 22 | return res 23 | 24 | def numberToIp(self, x, step): 25 | ans = [0 for i in range(4)] 26 | ans[0] = (x >> 24) & 255 27 | ans[1] = (x >> 16) & 255 28 | ans[2] = (x >> 8) & 255 29 | ans[3] = (x >> 0) & 255 30 | 31 | length = 33 32 | while step > 0: 33 | length -= 1 34 | step /= 2 35 | 36 | return '.'.join([str(item) for item in ans]) + '/' + str(length) -------------------------------------------------------------------------------- /leetcode/755.pour-water.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def pourWater(self, heights, V, K): 3 | """ 4 | :type heights: List[int] 5 | :type V: int 6 | :type K: int 7 | :rtype: List[int] 8 | """ 9 | 10 | for i in range(V): 11 | 12 | t = K 13 | 14 | #left peak [0: k] 15 | for left in range(K - 1, -1, -1): 16 | if heights[left] < heights[t]: 17 | t = left 18 | 19 | if heights[left] > heights[t]: 20 | break 21 | 22 | if t == K: 23 | # right peak [k + 1: ] 24 | for right in range(K + 1, len(heights)): 25 | if heights[right] < heights[t]: 26 | t = right 27 | 28 | if heights[right] > heights[t]: 29 | break 30 | 31 | heights[t] += 1 32 | 33 | return heights -------------------------------------------------------------------------------- /leetcode/760.find-anagram-mappings.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def anagramMappings(self, A, B): 3 | """ 4 | :type A: List[int] 5 | :type B: List[int] 6 | :rtype: List[int] 7 | """ 8 | mapping = {x: i for i, x in enumerate(B)} 9 | return [mapping[x] for x in A] -------------------------------------------------------------------------------- /leetcode/77.combinations.py: -------------------------------------------------------------------------------- 1 | # Tag: Backtracking 2 | # Time: O(k * C(n, k)) 3 | # Space: O(K) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n]. 8 | # You may return the answer in any order. 9 | #   10 | # Example 1: 11 | # 12 | # Input: n = 4, k = 2 13 | # Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] 14 | # Explanation: There are 4 choose 2 = 6 total combinations. 15 | # Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination. 16 | # 17 | # Example 2: 18 | # 19 | # Input: n = 1, k = 1 20 | # Output: [[1]] 21 | # Explanation: There is 1 choose 1 = 1 total combination. 22 | # 23 | #   24 | # Constraints: 25 | # 26 | # 1 <= n <= 20 27 | # 1 <= k <= n 28 | # 29 | # 30 | 31 | class Solution: 32 | def combine(self, n: int, k: int) -> List[List[int]]: 33 | res = [] 34 | tmp = [] 35 | self.dfs(n, k, 1, tmp, res) 36 | 37 | return res 38 | 39 | 40 | def dfs(self, n: int, k:int, start: int, tmp: list, ans: List[List[int]]): 41 | if len(tmp) == k: 42 | ans.append(tmp.copy()) 43 | return 44 | 45 | for i in range(start, n + 1): 46 | tmp.append(i) 47 | self.dfs(n, k, i + 1, tmp, ans) 48 | tmp.pop() -------------------------------------------------------------------------------- /leetcode/771.jewels-and-stones.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numJewelsInStones(string J, string S) { 4 | 5 | unordered_set set(J.begin(), J.end()); 6 | int count = 0; 7 | for (auto str: S){ 8 | if (set.count(str) > 0){ 9 | count += 1; 10 | } 11 | } 12 | 13 | return count; 14 | } 15 | }; -------------------------------------------------------------------------------- /leetcode/796.rotate-string.cpp: -------------------------------------------------------------------------------- 1 | // Tag: String, String Matching 2 | // Time: O(N) 3 | // Space: O(N) 4 | // Ref: - 5 | // Note: - 6 | 7 | // Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s. 8 | // A shift on s consists of moving the leftmost character of s to the rightmost position. 9 | // 10 | // For example, if s = "abcde", then it will be "bcdea" after one shift. 11 | // 12 | //   13 | // Example 1: 14 | // Input: s = "abcde", goal = "cdeab" 15 | // Output: true 16 | // Example 2: 17 | // Input: s = "abcde", goal = "abced" 18 | // Output: false 19 | // 20 | //   21 | // Constraints: 22 | // 23 | // 1 <= s.length, goal.length <= 100 24 | // s and goal consist of lowercase English letters. 25 | // 26 | // 27 | 28 | class Solution { 29 | public: 30 | bool rotateString(string s, string goal) { 31 | 32 | } 33 | }; -------------------------------------------------------------------------------- /leetcode/796.rotate-string.py: -------------------------------------------------------------------------------- 1 | # Tag: String, String Matching 2 | # Time: O(N) 3 | # Space: O(N) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s. 8 | # A shift on s consists of moving the leftmost character of s to the rightmost position. 9 | # 10 | # For example, if s = "abcde", then it will be "bcdea" after one shift. 11 | # 12 | #   13 | # Example 1: 14 | # Input: s = "abcde", goal = "cdeab" 15 | # Output: true 16 | # Example 2: 17 | # Input: s = "abcde", goal = "abced" 18 | # Output: false 19 | # 20 | #   21 | # Constraints: 22 | # 23 | # 1 <= s.length, goal.length <= 100 24 | # s and goal consist of lowercase English letters. 25 | # 26 | # 27 | 28 | class Solution: 29 | def rotateString(self, s: str, goal: str) -> bool: 30 | return len(s) == len(goal) and s in goal + goal -------------------------------------------------------------------------------- /leetcode/829.consecutive-numbers-sum.py: -------------------------------------------------------------------------------- 1 | import math 2 | class Solution(object): 3 | def consecutiveNumbersSum(self, N): 4 | """ 5 | :type N: int 6 | :rtype: int 7 | """ 8 | 9 | res = 1 10 | limit = int(math.sqrt(2 * N)) 11 | for k in range(2, limit): 12 | if (N - k * (k - 1) / 2) % k == 0: 13 | res += 1 14 | return res -------------------------------------------------------------------------------- /leetcode/83.remove-duplicates-from-sorted-list.py: -------------------------------------------------------------------------------- 1 | # Tag: Linked List 2 | # Time: O(N) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well. 8 | #   9 | # Example 1: 10 | # 11 | # 12 | # Input: head = [1,1,2] 13 | # Output: [1,2] 14 | # 15 | # Example 2: 16 | # 17 | # 18 | # Input: head = [1,1,2,3,3] 19 | # Output: [1,2,3] 20 | # 21 | #   22 | # Constraints: 23 | # 24 | # The number of nodes in the list is in the range [0, 300]. 25 | # -100 <= Node.val <= 100 26 | # The list is guaranteed to be sorted in ascending order. 27 | # 28 | # 29 | 30 | # Definition for singly-linked list. 31 | # class ListNode: 32 | # def __init__(self, val=0, next=None): 33 | # self.val = val 34 | # self.next = next 35 | class Solution: 36 | def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]: 37 | 38 | cur = head 39 | while cur and cur.next: 40 | tmp = cur.next 41 | if tmp.val == cur.val: 42 | cur.next = tmp.next 43 | else: 44 | cur = cur.next 45 | 46 | return head -------------------------------------------------------------------------------- /leetcode/832.flipping-an-image.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def flipAndInvertImage(self, A): 3 | """ 4 | :type A: List[List[int]] 5 | :rtype: List[List[int]] 6 | """ 7 | for i in range(len(A)): 8 | start = 0 9 | end = len(A[i]) - 1 10 | while (start <= end): 11 | A[i][start], A[i][end] = 1 - A[i][end], 1 - A[i][start] 12 | start += 1 13 | end -= 1 14 | 15 | if start == end: 16 | A[i][start] = 1 - A[i][start] 17 | 18 | return A -------------------------------------------------------------------------------- /leetcode/84.largest-rectangle-in-histogram.py: -------------------------------------------------------------------------------- 1 | # Tag: Array, Stack, Monotonic Stack 2 | # Time: O(N) 3 | # Space: O(N) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram. 8 | #   9 | # Example 1: 10 | # 11 | # 12 | # Input: heights = [2,1,5,6,2,3] 13 | # Output: 10 14 | # Explanation: The above is a histogram where width of each bar is 1. 15 | # The largest rectangle is shown in the red area, which has an area = 10 units. 16 | # 17 | # Example 2: 18 | # 19 | # 20 | # Input: heights = [2,4] 21 | # Output: 4 22 | # 23 | #   24 | # Constraints: 25 | # 26 | # 1 <= heights.length <= 105 27 | # 0 <= heights[i] <= 104 28 | # 29 | # 30 | 31 | class Solution: 32 | def largestRectangleArea(self, heights: List[int]) -> int: 33 | 34 | heights = [0] + heights + [0] 35 | stack = [0] 36 | n = len(heights) 37 | 38 | res = 0 39 | for i in range(1, n): 40 | while heights[i] < heights[stack[-1]]: 41 | h = heights[stack[-1]] 42 | stack.pop() 43 | width = i - stack[-1] - 1 44 | res = max(res, width * h) 45 | 46 | stack.append(i) 47 | 48 | return res 49 | -------------------------------------------------------------------------------- /leetcode/859.buddy-strings.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool buddyStrings(string A, string B) { 4 | 5 | if (A.size() != B.size()){ 6 | return false; 7 | } 8 | 9 | if (A.size() < 2){ 10 | return false; 11 | } 12 | 13 | if (A == B){ 14 | unordered_set set = unordered_set(A.begin(), A.end()); 15 | return set.size() < A.size(); 16 | } 17 | 18 | vector indexes; 19 | for (int i = 0; i < A.size(); ++i){ 20 | if (A[i] != B[i]){ 21 | indexes.push_back(i); 22 | } 23 | } 24 | 25 | return (indexes.size() == 2 && A[indexes[0]] == B[indexes[1]] && A[indexes[1]] == B[indexes[0]]); 26 | } 27 | }; -------------------------------------------------------------------------------- /leetcode/86.partition-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* partition(ListNode* head, int x) { 12 | 13 | ListNode newList(0); 14 | ListNode *new_cur = &newList; 15 | 16 | ListNode oldList(0); 17 | oldList.next = head; 18 | ListNode *cur = &oldList; 19 | 20 | while(cur && cur->next) 21 | { 22 | if (cur->next->val < x) 23 | { 24 | ListNode *tmp = cur->next; 25 | cur->next = tmp->next; 26 | 27 | // append to new list 28 | tmp->next = NULL; 29 | new_cur->next = tmp; 30 | new_cur = new_cur->next; 31 | } 32 | else 33 | { 34 | cur = cur->next; 35 | } 36 | } 37 | 38 | new_cur->next = oldList.next; 39 | 40 | return newList.next; 41 | } 42 | }; -------------------------------------------------------------------------------- /leetcode/86.partition-list.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | class ListNode(object): 3 | def __init__(self, x): 4 | self.val = x 5 | self.next = None 6 | 7 | class Solution(object): 8 | def partition(self, head, x): 9 | """ 10 | :type head: ListNode 11 | :type x: int 12 | :rtype: ListNode 13 | """ 14 | 15 | if head is None: 16 | return None 17 | 18 | left_head = ListNode(0) 19 | left_head.next = head 20 | 21 | right_head = ListNode(0) 22 | 23 | left = left_head 24 | right = right_head 25 | 26 | while head: 27 | 28 | if head.val < x: 29 | left.next = head 30 | left = left.next 31 | else: 32 | right.next = head 33 | right = right.next 34 | 35 | head = head.next 36 | 37 | right.next = None 38 | left.next = right_head.next 39 | 40 | return left_head.next 41 | -------------------------------------------------------------------------------- /leetcode/870.advantage-shuffle.py: -------------------------------------------------------------------------------- 1 | # Tag: Array, Two Pointers, Greedy, Sorting 2 | # Time: O(NlogN) 3 | # Space: O(N) 4 | # Ref: - 5 | # Note: - 6 | 7 | # You are given two integer arrays nums1 and nums2 both of the same length. The advantage of nums1 with respect to nums2 is the number of indices i for which nums1[i] > nums2[i]. 8 | # Return any permutation of nums1 that maximizes its advantage with respect to nums2. 9 | #   10 | # Example 1: 11 | # Input: nums1 = [2,7,11,15], nums2 = [1,10,4,11] 12 | # Output: [2,11,7,15] 13 | # Example 2: 14 | # Input: nums1 = [12,24,8,32], nums2 = [13,25,32,11] 15 | # Output: [24,32,8,12] 16 | # 17 | #   18 | # Constraints: 19 | # 20 | # 1 <= nums1.length <= 105 21 | # nums2.length == nums1.length 22 | # 0 <= nums1[i], nums2[i] <= 109 23 | # 24 | # 25 | 26 | from collections import deque 27 | class Solution: 28 | def advantageCount(self, nums1: List[int], nums2: List[int]) -> List[int]: 29 | n = len(nums1) 30 | target = sorted([(nums2[i], i) for i in range(n)], reverse=True) 31 | q = deque(sorted(nums1)) 32 | 33 | res = list(nums2) 34 | for i in range(n): 35 | val, j = target[i] 36 | if q[-1] > val: 37 | res[j] = q.pop() 38 | else: 39 | res[j] = q.popleft() 40 | 41 | return res 42 | 43 | -------------------------------------------------------------------------------- /leetcode/876.middle-of-the-linked-list.py: -------------------------------------------------------------------------------- 1 | # Tag: Linked List, Two Pointers 2 | # Time: O(N) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given the head of a singly linked list, return the middle node of the linked list. 8 | # If there are two middle nodes, return the second middle node. 9 | #   10 | # Example 1: 11 | # 12 | # 13 | # Input: head = [1,2,3,4,5] 14 | # Output: [3,4,5] 15 | # Explanation: The middle node of the list is node 3. 16 | # 17 | # Example 2: 18 | # 19 | # 20 | # Input: head = [1,2,3,4,5,6] 21 | # Output: [4,5,6] 22 | # Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one. 23 | # 24 | #   25 | # Constraints: 26 | # 27 | # The number of nodes in the list is in the range [1, 100]. 28 | # 1 <= Node.val <= 100 29 | # 30 | # 31 | 32 | # Definition for singly-linked list. 33 | # class ListNode: 34 | # def __init__(self, val=0, next=None): 35 | # self.val = val 36 | # self.next = next 37 | class Solution: 38 | def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: 39 | fast = head 40 | slow = head 41 | while fast and fast.next: 42 | fast = fast.next.next 43 | slow = slow.next 44 | 45 | return slow -------------------------------------------------------------------------------- /leetcode/90.subsets-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private: 3 | void helper(vector& nums, int start, vector &ans, vector>& res) 4 | { 5 | res.push_back(ans); 6 | 7 | for (auto i = start; i < nums.size(); ++i) 8 | { 9 | if (i != start && nums[i] == nums[i - 1]) 10 | { 11 | continue; 12 | } 13 | 14 | ans.push_back(nums[i]); 15 | helper(nums, i + 1, ans, res); 16 | ans.pop_back(); 17 | } 18 | } 19 | public: 20 | vector> subsetsWithDup(vector& nums) { 21 | sort(nums.begin(), nums.end()); 22 | vector> res; 23 | vector ans; 24 | 25 | helper(nums, 0, ans, res); 26 | return res; 27 | } 28 | }; -------------------------------------------------------------------------------- /leetcode/905.sort-array-by-parity.cpp: -------------------------------------------------------------------------------- 1 | // Tag: Array, Two Pointers, Sorting 2 | // Time: O(N) 3 | // Space: O(1) 4 | // Ref: - 5 | // Note: - 6 | 7 | // Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers. 8 | // Return any array that satisfies this condition. 9 | //   10 | // Example 1: 11 | // 12 | // Input: nums = [3,1,2,4] 13 | // Output: [2,4,3,1] 14 | // Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. 15 | // 16 | // Example 2: 17 | // 18 | // Input: nums = [0] 19 | // Output: [0] 20 | // 21 | //   22 | // Constraints: 23 | // 24 | // 1 <= nums.length <= 5000 25 | // 0 <= nums[i] <= 5000 26 | // 27 | // 28 | 29 | class Solution { 30 | public: 31 | vector sortArrayByParity(vector& nums) { 32 | int n = nums.size(); 33 | int l = 0; 34 | for (int i = 0; i < n; i++) { 35 | if (nums[i] % 2 == 0) { 36 | swap(nums[l], nums[i]); 37 | l += 1; 38 | } 39 | } 40 | return nums; 41 | } 42 | }; -------------------------------------------------------------------------------- /leetcode/905.sort-array-by-parity.py: -------------------------------------------------------------------------------- 1 | # Tag: Array, Two Pointers, Sorting 2 | # Time: O(N) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers. 8 | # Return any array that satisfies this condition. 9 | #   10 | # Example 1: 11 | # 12 | # Input: nums = [3,1,2,4] 13 | # Output: [2,4,3,1] 14 | # Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. 15 | # 16 | # Example 2: 17 | # 18 | # Input: nums = [0] 19 | # Output: [0] 20 | # 21 | #   22 | # Constraints: 23 | # 24 | # 1 <= nums.length <= 5000 25 | # 0 <= nums[i] <= 5000 26 | # 27 | # 28 | 29 | class Solution: 30 | def sortArrayByParity(self, nums: List[int]) -> List[int]: 31 | n = len(nums) 32 | l = 0 33 | for i in range(n): 34 | if nums[i] % 2 == 0: 35 | nums[i], nums[l] = nums[l], nums[i] 36 | l += 1 37 | 38 | return nums -------------------------------------------------------------------------------- /leetcode/92.reverse-linked-list-ii.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* reverseBetween(ListNode* head, int m, int n) { 12 | 13 | if (m >= n) 14 | { 15 | return head; 16 | } 17 | 18 | ListNode newHead(0); 19 | newHead.next = head; 20 | ListNode *cur = &newHead; 21 | 22 | for (auto i = 0; i < m - 1; ++i) 23 | { 24 | cur = cur->next; 25 | } 26 | 27 | head = cur; 28 | cur = cur->next; 29 | 30 | for (auto i = 0; i < n - m; ++i) 31 | { 32 | ListNode *tmp = cur->next; 33 | cur->next = cur->next->next; 34 | 35 | tmp->next = head->next; 36 | head->next = tmp; 37 | } 38 | 39 | return newHead.next; 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /leetcode/92.reverse-linked-list-ii.py: -------------------------------------------------------------------------------- 1 | # Definition for singly-linked list. 2 | # class ListNode(object): 3 | # def __init__(self, x): 4 | # self.val = x 5 | # self.next = None 6 | 7 | class Solution(object): 8 | def reverseBetween(self, head, m, n): 9 | """ 10 | :type head: ListNode 11 | :type m: int 12 | :type n: int 13 | :rtype: ListNode 14 | """ 15 | 16 | new_head = ListNode(0) 17 | new_head.next = head 18 | 19 | # find node.next = target 20 | cur = new_head 21 | for _ in range(m - 1): 22 | cur = cur.next 23 | 24 | head = cur 25 | cur = cur.next 26 | 27 | # n1, n2... nk, move n2, n3... nk before n1 28 | # times = n - 1 29 | # loop time = (n - m + 1) - 1 30 | for _ in range(n - m): 31 | 32 | node = cur.next 33 | cur.next = cur.next.next 34 | 35 | node.next = head.next 36 | head.next = node 37 | 38 | 39 | return new_head.next 40 | -------------------------------------------------------------------------------- /leetcode/928.minimize-malware-spread-ii.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/leetcode/928.minimize-malware-spread-ii.py -------------------------------------------------------------------------------- /leetcode/929.unique-email-addresses.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def numUniqueEmails(self, emails): 3 | """ 4 | :type emails: List[str] 5 | :rtype: int 6 | """ 7 | ans = set() 8 | for e in emails: 9 | ans.add(self.convert(e)) 10 | 11 | return len(ans) 12 | 13 | 14 | def convert(self, email): 15 | local, at, domain = email.partition('@') 16 | 17 | if '+' in local: 18 | local = local[:local.index('+')] 19 | 20 | return local.replace('.', '') + at + domain -------------------------------------------------------------------------------- /lintcode/126.max-tree.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/lintcode/126.max-tree.vip -------------------------------------------------------------------------------- /lintcode/138.subarray-sum.py: -------------------------------------------------------------------------------- 1 | # Tag: Hash Table, Prefix Sum Array, Array 2 | # Time: O(N) 3 | # Space: O(N) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given an integer array, find a subarray where the sum of numbers is **zero**. 8 | # Your code should return the index of the first number and the index of the last number. 9 | # 10 | # **Example 1:** 11 | # 12 | # ``` 13 | # Input: [-3, 1, 2, -3, 4] 14 | # Output: [0, 2] or [1, 3]. 15 | # Explanation: return anyone that the sum is 0. 16 | # ``` 17 | # 18 | # **Example 2:** 19 | # 20 | # ``` 21 | # Input: [-3, 1, -4, 2, -3, 4] 22 | # Output: [1,5] 23 | # ``` 24 | # 25 | # There is at least one subarray that it's sum equals to zero. 26 | 27 | from typing import ( 28 | List, 29 | ) 30 | 31 | class Solution: 32 | """ 33 | @param nums: A list of integers 34 | @return: A list of integers includes the index of the first number and the index of the last number 35 | """ 36 | def subarray_sum(self, nums: List[int]) -> List[int]: 37 | # write your code here 38 | n = len(nums) 39 | pre = 0 40 | table = {pre: 0} 41 | for i in range(1, n + 1): 42 | pre += nums[i - 1] 43 | if pre in table: 44 | return [table[pre], i - 1] 45 | else: 46 | table[pre] = i 47 | -------------------------------------------------------------------------------- /lintcode/139.subarray-sum-closest.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/lintcode/139.subarray-sum-closest.vip -------------------------------------------------------------------------------- /lintcode/1396.set-union.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/lintcode/1396.set-union.vip -------------------------------------------------------------------------------- /lintcode/144.interleaving-positive-and-negative-numbers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | /* 4 | * @param A: An integer array. 5 | * @return: nothing 6 | */ 7 | void rerange(vector &A) { 8 | // write your code here 9 | 10 | int k = 0; 11 | for (auto i = 0; i < A.size(); ++i) 12 | { 13 | if (A[i] < 0) 14 | { 15 | int tmp = A[k]; 16 | A[k] = A[i]; 17 | A[i] = tmp; 18 | k++; 19 | } 20 | } 21 | 22 | int negCount = k; 23 | int posCount = A.size() - k; 24 | 25 | bool isPos = posCount > negCount; 26 | 27 | for (auto i = 0; i < A.size(); ++i) 28 | { 29 | if ((isPos && A[i] < 0) || (!isPos && A[i] > 0)) 30 | { 31 | int tmp = A[k]; 32 | A[k] = A[i]; 33 | A[i] = tmp; 34 | k++; 35 | } 36 | 37 | isPos = !isPos; 38 | } 39 | } 40 | }; -------------------------------------------------------------------------------- /lintcode/144.interleaving-positive-and-negative-numbers.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param: A: An integer array. 4 | @return: nothing 5 | """ 6 | def rerange(self, A): 7 | # write your code here 8 | 9 | k = 0 10 | for i in range(len(A)): 11 | if A[i] < 0: 12 | A[i], A[k] = A[k], A[i] 13 | k += 1 14 | 15 | neg_count = k 16 | pos_count = len(A) - k 17 | 18 | isPos = pos_count > neg_count 19 | 20 | for i in range(len(A)): 21 | if (isPos and A[i] < 0) or (not isPos and A[i] > 0): 22 | A[i], A[k] = A[k], A[i] 23 | k += 1 24 | 25 | isPos = not isPos -------------------------------------------------------------------------------- /lintcode/202.segment-tree-query.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/lintcode/202.segment-tree-query.vip -------------------------------------------------------------------------------- /lintcode/31.partition-array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param nums: The integer array you should partition 4 | @param k: An integer 5 | @return: The index after partition 6 | """ 7 | def partitionArray(self, nums, k): 8 | # write your code here 9 | target = 0 10 | for i in range(len(nums)): 11 | if nums[i] < k: 12 | nums[i], nums[target] = nums[target], nums[i] 13 | target += 1 14 | 15 | return target -------------------------------------------------------------------------------- /lintcode/382.triangle-count.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | /** 4 | * @param S: A list of integers 5 | * @return: An integer 6 | */ 7 | int triangleCount(vector &S) { 8 | // write your code here 9 | int res = 0; 10 | sort(S.begin(), S.end()); 11 | 12 | for (auto i = (int)(S.size()) - 1; i >=0; --i) 13 | { 14 | res += count(S, i); 15 | } 16 | 17 | return res; 18 | } 19 | 20 | int count(vector &nums, int longestIndex) 21 | { 22 | int res = 0; 23 | int start = 0; 24 | int end = longestIndex - 1; 25 | 26 | while (start < end) 27 | { 28 | if (nums[start] + nums[end] > nums[longestIndex]) 29 | { 30 | res += end - start; 31 | end --; 32 | } 33 | else 34 | { 35 | start ++; 36 | } 37 | } 38 | 39 | return res; 40 | } 41 | }; -------------------------------------------------------------------------------- /lintcode/382.triangle-count.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | """ 3 | @param S: A list of integers 4 | @return: An integer 5 | """ 6 | def triangleCount(self, S): 7 | # write your code here 8 | S.sort() 9 | 10 | res = 0 11 | for i in range(len(S) - 1, -1, -1): 12 | res += self.counting(S, i) 13 | 14 | return res 15 | 16 | def counting(self, nums, longestIndex): 17 | start = 0 18 | end = longestIndex - 1 19 | count = 0 20 | 21 | while (start < end): 22 | 23 | while (start < end and nums[start] + nums[end] > nums[longestIndex]): 24 | count += end - start 25 | end -= 1 26 | else: 27 | start += 1 28 | 29 | return count -------------------------------------------------------------------------------- /lintcode/386.longest-substring-with-at-most-k-distinct-characters.py: -------------------------------------------------------------------------------- 1 | # Tag: Same Direction Two Pointers, Two Pointers 2 | # Time: O(N) 3 | # Space: O(K) 4 | # Ref: Leetcode-340 5 | # Note: - 6 | 7 | # Given a string *S*, find the length of the longest substring *T* that contains at most k distinct characters. 8 | # 9 | # **Example 1:** 10 | # 11 | # ``` 12 | # Input: S = "eceba" and k = 3 13 | # Output: 4 14 | # Explanation: T = "eceb" 15 | # ``` 16 | # 17 | # **Example 2:** 18 | # 19 | # ``` 20 | # Input: S = "WORLD" and k = 4 21 | # Output: 4 22 | # Explanation: T = "WORL" or "ORLD" 23 | # ``` 24 | # 25 | # 26 | 27 | from collections import defaultdict 28 | class Solution: 29 | """ 30 | @param s: A string 31 | @param k: An integer 32 | @return: An integer 33 | """ 34 | def length_of_longest_substring_k_distinct(self, s: str, k: int) -> int: 35 | # write your code here 36 | n = len(s) 37 | res = 0 38 | i = 0 39 | counter = defaultdict(int) 40 | for j in range(n): 41 | counter[s[j]] += 1 42 | while len(counter) > k: 43 | counter[s[i]] -= 1 44 | if counter[s[i]] == 0: 45 | del counter[s[i]] 46 | i += 1 47 | 48 | res = max(res, j - i + 1) 49 | return res 50 | -------------------------------------------------------------------------------- /lintcode/396.coins-in-a-line-iii.cpp: -------------------------------------------------------------------------------- 1 | // f[i][j] = max(a[i] - f[i + 1][j], a[j] - f[i][j - 1]) 2 | class Solution { 3 | public: 4 | /** 5 | * @param values: a vector of integers 6 | * @return: a boolean which equals to true if the first player will win 7 | */ 8 | bool firstWillWin(vector &values) { 9 | // write your code here 10 | 11 | if (values.size() == 0) 12 | { 13 | return true; 14 | } 15 | 16 | int m = values.size(); 17 | vector> table(m, vector(m, 0)); 18 | 19 | //len = 1 20 | for(auto i = 0; i < m; ++i) 21 | { 22 | table[i][i] = values[i]; 23 | } 24 | 25 | for(auto len = 2; len <= m; ++len) 26 | { 27 | for(auto i = 0; i <= m - len; ++i) 28 | { 29 | int j = i + len - 1; 30 | table[i][j] = max(values[i] - table[i + 1][j], values[j] - table[i][j - 1]); 31 | } 32 | } 33 | 34 | return table[0][m - 1]; 35 | } 36 | }; -------------------------------------------------------------------------------- /lintcode/396.coins-in-a-line-iii.py: -------------------------------------------------------------------------------- 1 | # f[i][j] = max(a[i] - f[i + 1][j], a[j] - f[i][j - 1]) 2 | class Solution: 3 | """ 4 | @param values: a vector of integers 5 | @return: a boolean which equals to true if the first player will win 6 | """ 7 | def firstWillWin(self, values): 8 | # write your code here 9 | if values is None or len(values) == 0: 10 | return 0 11 | 12 | m = len(values) 13 | table = [[0 for _ in range(m)] for _ in range(m)] 14 | 15 | # length = 1 16 | for i in range(m): 17 | table[i][i] = values[i] 18 | 19 | for length in range(2, m + 1): 20 | for i in range(0, m - length + 1): 21 | j = i + length - 1 22 | table[i][j] = max(values[i] - table[i + 1][j], values[j] - table[i][j - 1]) 23 | 24 | return table[0][m - 1] >= 0 -------------------------------------------------------------------------------- /lintcode/396.coins-in-a-line-iii.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/lintcode/396.coins-in-a-line-iii.vip -------------------------------------------------------------------------------- /lintcode/403.continuous-subarray-sum-ii.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/lintcode/403.continuous-subarray-sum-ii.vip -------------------------------------------------------------------------------- /lintcode/404.subarray-sum-ii.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/lintcode/404.subarray-sum-ii.vip -------------------------------------------------------------------------------- /lintcode/405.submatrix-sum.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/lintcode/405.submatrix-sum.vip -------------------------------------------------------------------------------- /lintcode/447.search-in-a-big-sorted-array.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/lintcode/447.search-in-a-big-sorted-array.vip -------------------------------------------------------------------------------- /lintcode/458.last-position-of-target.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/lintcode/458.last-position-of-target.vip -------------------------------------------------------------------------------- /lintcode/461.kth-smallest-numbers-in-unsorted-array.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/lintcode/461.kth-smallest-numbers-in-unsorted-array.vip -------------------------------------------------------------------------------- /lintcode/462.total-occurrence-of-target.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/lintcode/462.total-occurrence-of-target.vip -------------------------------------------------------------------------------- /lintcode/465.kth-smallest-sum-in-two-sorted-arrays.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/lintcode/465.kth-smallest-sum-in-two-sorted-arrays.vip -------------------------------------------------------------------------------- /lintcode/543.kth-largest-in-n-arrays.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/lintcode/543.kth-largest-in-n-arrays.vip -------------------------------------------------------------------------------- /lintcode/585.maximum-number-in-mountain-sequence.cpp: -------------------------------------------------------------------------------- 1 | // Tag: Binary Search 2 | // Time: O(logN) 3 | // Space: O(1) 4 | // Ref: - 5 | // Note: - 6 | 7 | // Given a mountain sequence of `n` integers which increase firstly and then decrease, find the mountain top(Maximum). 8 | // 9 | // --- 10 | // 11 | // 12 | // Example 1: 13 | // ``` 14 | // Input: nums = [1, 2, 4, 8, 6, 3] 15 | // Output: 8 16 | // ``` 17 | // Example 2: 18 | // ``` 19 | // Input: nums = [10, 9, 8, 7], 20 | // Output: 10 21 | // ``` 22 | // 23 | // Arrays are strictly incremented, strictly decreasing 24 | 25 | class Solution { 26 | public: 27 | /** 28 | * @param nums: a mountain sequence which increase firstly and then decrease 29 | * @return: then mountain top 30 | */ 31 | int mountainSequence(vector &nums) { 32 | // write your code here 33 | int n = nums.size(); 34 | int left = 0; 35 | int right = n - 1; 36 | while (left < right) { 37 | int mid = left + (right - left) / 2; 38 | if (nums[mid] < nums[mid + 1]) { 39 | left = mid + 1; 40 | } else { 41 | right = mid; 42 | } 43 | } 44 | 45 | return nums[left]; 46 | } 47 | }; -------------------------------------------------------------------------------- /lintcode/585.maximum-number-in-mountain-sequence.py: -------------------------------------------------------------------------------- 1 | # Tag: Binary Search 2 | # Time: O(logN) 3 | # Space: O(1) 4 | # Ref: - 5 | # Note: - 6 | 7 | # Given a mountain sequence of `n` integers which increase firstly and then decrease, find the mountain top(Maximum). 8 | # 9 | # --- 10 | # 11 | # 12 | # Example 1: 13 | # ``` 14 | # Input: nums = [1, 2, 4, 8, 6, 3] 15 | # Output: 8 16 | # ``` 17 | # Example 2: 18 | # ``` 19 | # Input: nums = [10, 9, 8, 7], 20 | # Output: 10 21 | # ``` 22 | # 23 | # Arrays are strictly incremented, strictly decreasing 24 | 25 | from typing import ( 26 | List, 27 | ) 28 | 29 | class Solution: 30 | """ 31 | @param nums: a mountain sequence which increase firstly and then decrease 32 | @return: then mountain top 33 | """ 34 | def mountain_sequence(self, nums: List[int]) -> int: 35 | # write your code here 36 | n = len(nums) 37 | left = 0 38 | right = n - 1 39 | while left < right: 40 | mid = left + (right - left) // 2 41 | if (nums[mid] < nums[mid + 1]): 42 | left = mid + 1 43 | else: 44 | right = mid 45 | 46 | return nums[left] -------------------------------------------------------------------------------- /lintcode/586.sqrtx-ii.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/lintcode/586.sqrtx-ii.vip -------------------------------------------------------------------------------- /lintcode/589.connecting-graph.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/lintcode/589.connecting-graph.vip -------------------------------------------------------------------------------- /lintcode/590.connecting-graph-ii.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/lintcode/590.connecting-graph-ii.vip -------------------------------------------------------------------------------- /lintcode/601.flatten-2d-vector.py: -------------------------------------------------------------------------------- 1 | # Tag: Iterator 2 | # Time: O(*1) 3 | # Space: O(N) 4 | # Ref: Leetcode-251 5 | # Note: - 6 | 7 | # Design an iterator to realize the function of flattening two-dimensional vector. 8 | # 9 | # Example 1: 10 | # ``` 11 | # Input:[[1,2],[3],[4,5,6]] 12 | # Output:[1,2,3,4,5,6] 13 | # ``` 14 | # Example 2: 15 | # ``` 16 | # Input:[[7,9],[5]] 17 | # Output:[7,9,5] 18 | # ``` 19 | # 20 | # 21 | 22 | class Vector2D(object): 23 | 24 | # @param vec2d {List[List[int]]} 25 | def __init__(self, vec2d): 26 | # Initialize your data structure here 27 | self.stack = vec2d[::-1] 28 | self.res = [] 29 | 30 | # @return {int} a next element 31 | def next(self): 32 | # Write your code here 33 | return self.res.pop() 34 | 35 | # @return {boolean} true if it has next element 36 | # or false 37 | def hasNext(self): 38 | # Write your code here 39 | while len(self.stack) > 0 and len(self.res) == 0: 40 | cur = self.stack.pop() 41 | self.res.extend(reversed(cur)) 42 | return len(self.res) > 0 43 | 44 | # Your Vector2D object will be instantiated and called as such: 45 | # i, v = Vector2D(vec2d), [] 46 | # while i.hasNext(): v.append(i.next()) -------------------------------------------------------------------------------- /lintcode/618.search-graph-nodes.py: -------------------------------------------------------------------------------- 1 | """ 2 | Definition for a undirected graph node 3 | class UndirectedGraphNode: 4 | def __init__(self, x): 5 | self.label = x 6 | self.neighbors = [] 7 | """ 8 | 9 | 10 | class Solution: 11 | """ 12 | @param: graph: a list of Undirected graph node 13 | @param: values: a hash mapping, 14 | @param: node: an Undirected graph node 15 | @param: target: An integer 16 | @return: a node 17 | """ 18 | def searchNode(self, graph, values, node, target): 19 | # write your code here 20 | if node is None or len(graph) == 0 or len(values) == 0: 21 | return None 22 | 23 | queue = [node] 24 | visited = set([node]) 25 | 26 | while (len(queue) > 0): 27 | 28 | size = len(queue) 29 | 30 | for i in range(size): 31 | 32 | tmp = queue.pop(0) 33 | 34 | if values[tmp] == target: 35 | return tmp 36 | 37 | for neighbor in tmp.neighbors: 38 | if neighbor not in visited: 39 | visited.add(neighbor) 40 | queue.append(neighbor) 41 | 42 | return None -------------------------------------------------------------------------------- /lintcode/623.k-edit-distance.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/lintcode/623.k-edit-distance.vip -------------------------------------------------------------------------------- /lintcode/628.maximum-subtree.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/lintcode/628.maximum-subtree.vip -------------------------------------------------------------------------------- /lintcode/631.maximal-square-ii.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/lintcode/631.maximal-square-ii.vip -------------------------------------------------------------------------------- /lintcode/644.strobogrammatic-number.py: -------------------------------------------------------------------------------- 1 | # Tag: Hash Table, Simulation 2 | # Time: O(N) 3 | # Space: O(1) 4 | # Ref: Leetcode-246 5 | # Note: - 6 | 7 | # A mirror number is a number that looks the same when rotated 180 degrees (looked at upside down).For example, the numbers "69", "88", and "818" are all mirror numbers. 8 | # 9 | # Write a function to determine if a number is mirror. 10 | # The number is represented as a string. 11 | # 12 | # **Example 1:** 13 | # ``` 14 | # Input : "69" 15 | # Output : true 16 | # ``` 17 | # 18 | # **Example 2:** 19 | # ``` 20 | # Input : "68" 21 | # Output : false 22 | # ``` 23 | # 24 | # 25 | 26 | class Solution: 27 | """ 28 | @param num: a string 29 | @return: true if a number is strobogrammatic or false 30 | """ 31 | def is_strobogrammatic(self, num: str) -> bool: 32 | # write your code here 33 | mirrors = { 34 | '6': '9', 35 | '1': '1', 36 | '8': '8', 37 | '9': '6', 38 | '0': '0' 39 | } 40 | 41 | left = 0 42 | right = len(num) - 1 43 | while left <= right: 44 | if num[left] not in mirrors or mirrors[num[left]] != num[right]: 45 | return False 46 | left += 1 47 | right -= 1 48 | 49 | return True -------------------------------------------------------------------------------- /lintcode/805.maximum-association-set.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/lintcode/805.maximum-association-set.vip -------------------------------------------------------------------------------- /lintcode/821.time-intersection.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/lintcode/821.time-intersection.vip -------------------------------------------------------------------------------- /lintcode/91.minimum-adjustment-cost.py: -------------------------------------------------------------------------------- 1 | # f[i][j] = min(f[i - 1][k] + |j - A[i - 1]|) where 1 <= K <= 100, | K - j | <= target 2 | 3 | class Solution: 4 | """ 5 | @param: A: An integer array 6 | @param: target: An integer 7 | @return: An integer 8 | """ 9 | def MinAdjustmentCost(self, A, target): 10 | # write your code here 11 | 12 | size = len(A) 13 | table = [[float('inf') for _ in range(100 + 1)] for _ in range(size + 1)] 14 | 15 | for i in range(1, 101): 16 | table[1][i] = abs(A[0] - i) 17 | 18 | for i in range(2, size + 1): 19 | for j in range(1, 100 + 1): 20 | value = float('inf') 21 | 22 | for k in range(j - target, j + target + 1): 23 | if k < 1 or k > 100 or table[i - 1][k] == float('inf'): 24 | continue 25 | 26 | value = min(value, table[i - 1][k] + abs(j - A[i - 1])) 27 | 28 | table[i][j] = value 29 | 30 | return min(table[size]) -------------------------------------------------------------------------------- /lintcode/91.minimum-adjustment-cost.vip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/lintcode/91.minimum-adjustment-cost.vip -------------------------------------------------------------------------------- /lintcode/928.longest-substring-with-at-most-two-distinct-characters.py: -------------------------------------------------------------------------------- 1 | # Tag: Same Direction Two Pointers, Two Pointers, Hash Table, String 2 | # Time: O(N) 3 | # Space: O(1) 4 | # Ref: Leetcode-159 5 | # Note: - 6 | 7 | # Given a string, find the length of the longest substring T that contains at most `2` distinct characters. 8 | # 9 | # --- 10 | # 11 | # 12 | # ### Example 1 13 | # ``` 14 | # Input: “eceba” 15 | # Output: 3 16 | # Explanation: 17 | # T is "ece" which its length is 3. 18 | # ``` 19 | # 20 | # ### Example 2 21 | # ``` 22 | # Input: “aaa” 23 | # Output: 3 24 | # ``` 25 | # 26 | # 27 | 28 | from collections import defaultdict 29 | class Solution: 30 | """ 31 | @param s: a string 32 | @return: the length of the longest substring T that contains at most 2 distinct characters 33 | """ 34 | def length_of_longest_substring_two_distinct(self, s: str) -> int: 35 | # Write your code here 36 | n = len(s) 37 | res = 0 38 | i = 0 39 | counter = defaultdict(int) 40 | for j in range(n): 41 | counter[s[j]] += 1 42 | while len(counter) > 2: 43 | counter[s[i]] -= 1 44 | if counter[s[i]] == 0: 45 | del counter[s[i]] 46 | i += 1 47 | 48 | res = max(res, j - i + 1) 49 | return res -------------------------------------------------------------------------------- /list/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "__bit_reference": "cpp", 4 | "__hash_table": "cpp", 5 | "__split_buffer": "cpp", 6 | "array": "cpp", 7 | "deque": "cpp", 8 | "initializer_list": "cpp", 9 | "string": "cpp", 10 | "string_view": "cpp", 11 | "unordered_map": "cpp", 12 | "vector": "cpp", 13 | "queue": "cpp", 14 | "stack": "cpp" 15 | } 16 | } -------------------------------------------------------------------------------- /logger.py: -------------------------------------------------------------------------------- 1 | class Logger: 2 | HEADER = '\033[95m' 3 | OKBLUE = '\033[94m' 4 | OKCYAN = '\033[96m' 5 | OKGREEN = '\033[92m' 6 | WARNING = '\033[93m' 7 | FAIL = '\033[91m' 8 | BOLD = '\033[1m' 9 | UNDERLINE = '\033[4m' 10 | 11 | @staticmethod 12 | def log(content, color='', end='\n'): 13 | ENDC = '\033[0m' 14 | print(f"{color}{content}{ENDC}", end=end) 15 | 16 | @staticmethod 17 | def test_all(): 18 | Logger.log("HEADER", Logger.HEADER) 19 | Logger.log("OKBLUE", Logger.OKBLUE) 20 | 21 | Logger.log("OKCYAN", Logger.OKCYAN) 22 | Logger.log("OKGREEN", Logger.OKGREEN) 23 | Logger.log("WARNING", Logger.WARNING) 24 | Logger.log("FAIL", Logger.FAIL) 25 | Logger.log("BOLD", Logger.BOLD) 26 | Logger.log("UNDERLINE", Logger.UNDERLINE) 27 | 28 | if __name__ == '__main__': 29 | Logger.test_all() -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | beautifulsoup4==4.12.2 2 | certifi==2024.7.4 3 | charset-normalizer==3.3.0 4 | idna==3.7 5 | requests==2.32.0 6 | soupsieve==2.5 7 | urllib3==2.2.2 8 | -------------------------------------------------------------------------------- /test.mov: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/geemaple/leetcode/6a94dc41c5a5c60acae619343dd959dc98f780b5/test.mov -------------------------------------------------------------------------------- /test/cpp.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /test/cpp.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /test/python.py: -------------------------------------------------------------------------------- 1 | 2 | from typing import List 3 | from datetime import datetime 4 | from collections import defaultdict 5 | import heapq 6 | from collections import deque 7 | import math 8 | 9 | import heapq 10 | 11 | from typing import ( 12 | List, 13 | ) 14 | 15 | 16 | from typing import ( 17 | List, 18 | ) 19 | import heapq 20 | 21 | import bisect 22 | class Solution: 23 | def maxTotalFruits(self, fruits: List[List[int]], startPos: int, k: int) -> int: 24 | n = len(fruits) 25 | l = bisect.bisect_left(fruits, startPos - k, key=lambda x: x[0]) 26 | pick = 0 27 | res = 0 28 | r = l 29 | while (r < n and fruits[r][0] <= startPos + k): 30 | pick += fruits[r][1] 31 | while min(startPos - 2 * fruits[l][0] + fruits[r][0], 2 * fruits[r][0] - fruits[l][0] - startPos) > k: 32 | pick -= fruits[l][1] 33 | l += 1 34 | 35 | res = max(res, pick) 36 | r += 1 37 | 38 | return res 39 | 40 | s = Solution() 41 | ts = datetime.now() 42 | 43 | res = s.maxTotalFruits([[2,8],[6,3],[8,6]], 5, 4) 44 | 45 | print(datetime.now() - ts) 46 | print(res) 47 | --------------------------------------------------------------------------------