├── .github ├── FUNDING.yml ├── issue_template.md ├── pull_request_template.md └── workflows │ └── deploy.yml ├── .gitignore ├── .prettierrc ├── CONTRIBUTING.md ├── README.md ├── babel.config.js ├── blog ├── 2019-05-28-first-blog-post.md ├── 2019-05-29-long-blog-post.md ├── 2021-08-01-mdx-blog-post.mdx ├── 2021-08-26-welcome │ ├── docusaurus-plushie-banner.jpeg │ └── index.md └── authors.yml ├── config.json ├── converter ├── README.md ├── background.js ├── content.js ├── manifest.json ├── popup.css ├── popup.html └── popup.js ├── docs └── index.md ├── docusaurus.config.js ├── package.json ├── pnpm-lock.yaml ├── renovate.json ├── roadmap ├── arrays.md ├── backtracking.md ├── binary-search.md ├── data-structure-i.md ├── dynamic-programming.md ├── graph-theory.md ├── heap.md ├── index.md ├── leetcode-summer-intensive.md ├── programming-skills-i.md ├── sliding-windows.md ├── stack.md ├── tree.md ├── trie.md └── two-pointers.md ├── sidebars.js ├── solutions ├── 0000-0099 │ ├── 0001-two-sum.md │ ├── 0002-add-two-numbers-medium.md │ ├── 0003-longest-substring-without-repeating-characters-medium.md │ ├── 0004-median-of-two-sorted-arrays-hard.md │ ├── 0005-longest-palindromic-substring-medium.md │ ├── 0006-zigzag-conversion-medium.md │ ├── 0007-reverse-integer-medium.md │ ├── 0009-palindrome-number-easy.md │ ├── 0010-regular-expression-matching-hard.md │ ├── 0011-container-with-most-water-medium.md │ ├── 0012-integer-to-roman-medium.md │ ├── 0013-roman-to-integer-easy.md │ ├── 0014-longest-common-prefix-easy.md │ ├── 0017-letter-combinations-of-a-phone-number-medium.md │ ├── 0019-remove-nth-node-from-end-of-list-medium.md │ ├── 0020-valid-parentheses-easy.md │ ├── 0021-merge-two-sorted-lists-easy.md │ ├── 0022-generate-parentheses-medium.md │ ├── 0023-merge-k-sorted-lists-hard.md │ ├── 0024-swap-nodes-in-pairs-medium.md │ ├── 0025-reverse-nodes-in-k-group-hard.md │ ├── 0026-Remove-Duplicates-from-Sorted-Array-easy.md │ ├── 0027-remove-element-easy.md │ ├── 0028-find-the-index-of-the-first-occurrence-in-a-string-easy.md │ ├── 0033-search-in-rotated-sorted-array-medium.md │ ├── 0034-find-first-and-last-position-of-element-in-sorted-array-medium.md │ ├── 0035-search-insert-position-easy.md │ ├── 0036-valid-sudoku-easy.md │ ├── 0037-sudoku-solver-hard.md │ ├── 0039-combination-sum-medium.md │ ├── 0040-combination-sum-ii-medium.md │ ├── 0042-trapping-rain-water-hard.md │ ├── 0045-jump-game-ii-medium.md │ ├── 0046-permutations-medium.md │ ├── 0048-rotate-image-medium.md │ ├── 0049-group-anagrams-medium.md │ ├── 0050-pow-x-n-medium.md │ ├── 0051-n-queens-hard.md │ ├── 0053-maximum-subarray-medium.md │ ├── 0054-spiral-matrix-medium.md │ ├── 0055-jump-game-medium.md │ ├── 0056-merge-intervals-medium.md │ ├── 0057-insert-interval-medium.md │ ├── 0058-length-of-last-word-easy.md │ ├── 0061-rotate-list-medium.md │ ├── 0062-unique-paths-medium.md │ ├── 0063-unique-paths-ii-medium.md │ ├── 0066-plus-one-easy.md │ ├── 0067-add-binary-easy.md │ ├── 0069-sqrt-x-easy.md │ ├── 0070-climbing-stairs-easy.md │ ├── 0072-edit-distance-hard.md │ ├── 0073-set-matrix-zeroes-medium.md │ ├── 0074-search-a-2d-matrix-medium.md │ ├── 0075-sort-colors-medium.md │ ├── 0076-minimum-window-substring-hard.md │ ├── 0077-combinations-medium.md │ ├── 0078-subsets-medium.md │ ├── 0079-word-search-medium.md │ ├── 0084-largest-rectangle-in-histogram-hard.md │ ├── 0088-merge-sorted-array-easy.md │ ├── 0090-subsets-ii-medium.md │ ├── 0091-decode-ways-medium.md │ ├── 0093-restore-ip-addresses-medium.md │ ├── 0094-binary-tree-inorder-traversal-easy.md │ ├── 0097-interleaving-string-medium.md │ ├── 0098-validate-binary-search-tree-medium.md │ └── _category_.json ├── 0100-0199 │ ├── 0100-same-tree-easy.md │ ├── 0101-symmetric-tree-easy.md │ ├── 0102-binary-tree-level-order-traversal-medium.md │ ├── 0103-binary-tree-zigzag-level-order-traversal-medium.md │ ├── 0104-maximum-depth-of-binary-tree-easy.md │ ├── 0105-construct-binary-tree-from-preorder-and-inorder-traversal-medium.md │ ├── 0110-balanced-binary-tree-easy.md │ ├── 0112-path-sum-easy.md │ ├── 0113-path-sum-ii-medium.md │ ├── 0115-distinct-subsequences-hard.md │ ├── 0118-pascals-triangle-easy.md │ ├── 0121-best-time-to-buy-and-sell-stock-easy.md │ ├── 0124-binary-tree-maximum-path-sum-hard.md │ ├── 0125-valid-palindrome.md │ ├── 0127-word-ladder-hard.md │ ├── 0129-sum-root-to-leaf-numbers-medium.md │ ├── 0130-surrounded-regions-medium.md │ ├── 0131-palindrome-partitioning-medium.md │ ├── 0133-clone-graph-medium.md │ ├── 0134-gas-station-medium.md │ ├── 0136-single-number-easy.md │ ├── 0138-copy-list-with-random-pointer-medium.md │ ├── 0139-word-break-medium.md │ ├── 0141-linked-list-cycle.md │ ├── 0143-reorder-list-medium.md │ ├── 0144-binary-tree-preorder-traversal-easy.md │ ├── 0145-binary-tree-postorder-traversal-easy.md │ ├── 0146-lru-cache-medium.md │ ├── 0148-sort-list-medium.md │ ├── 0150-evaluate-reverse-olish-notation-medium.md │ ├── 0152-maximum-product-subarray-medium.md │ ├── 0154-find-minimum-in-rotated-sorted-array-ii-hard.md │ ├── 0155-min-stack-medium.md │ ├── 0162-find-peak-element-medium.md │ ├── 0165-compare-version-numbers-medium.md │ ├── 0169-majority-element-easy.md │ ├── 0188-best-time-to-buy-and-sell-stock-iv-hard.md │ ├── 0191-number-of-1-bits-easy.md │ ├── 0198-house-robber-medium.md │ ├── 0199-binary-tree-right-side-view-medium.md │ └── _category_.json ├── 0200-0299 │ ├── 0200-number-of-islands-medium.md │ ├── 0202-happy-number-easy.md │ ├── 0204-count-primes.md │ ├── 0205-isomorphic-strings-easy.md │ ├── 0206-reverse-linked-list-easy.md │ ├── 0207-course-schedule-medium.md │ ├── 0208-implement-trie-medium.md │ ├── 0210-course-schedule-ii-medium.md │ ├── 0211-design-add-and-search-words-data-structure-medium.md │ ├── 0212-word-search-ii-hard.md │ ├── 0213-house-robber-ii-medium.md │ ├── 0214-shortest-palindrome-hard.md │ ├── 0215-kth-largest-element-in-an-array-medium.md │ ├── 0217-contains-duplicate-easy.md │ ├── 0219-contains-duplicate-ii-easy.md │ ├── 0225-implement-stack-using-queues-easy.md │ ├── 0226-invert-binary-tree-easy.md │ ├── 0228-summary-ranges-easy.md │ ├── 0230-kth-smallest-element-in-a-bst-medium.md │ ├── 0231-power-of-two-easy.md │ ├── 0234-palindrome-linked-list-easy.md │ ├── 0235-lowest-common-ancestor-of-a-binary-search-tree-medium.md │ ├── 0237-delete-node-in-a-linked-list-medium.md │ ├── 0239-sliding-maximum-window-hard.md │ ├── 0242-valid-anagram-easy.md │ ├── 0246-strobogrammatic-number-easy.md │ ├── 0258-add-digits-easy.md │ ├── 0261-graph-valid-tree-medium.md │ ├── 0263-ugly-number-easy.md │ ├── 0268-missing-number-easy.md │ ├── 0278-first-bad-version-easy.md │ ├── 0283-move-zeroes-easy.md │ ├── 0286-walls-and-gates-medium.md │ ├── 0287-find-the-duplicate-number-medium.md │ ├── 0290-word-pattern-easy.md │ ├── 0295-find-median-from-data-stream-hard.md │ ├── 0297-serialize-and-deserialize-binary-tree-hard.md │ ├── 0298-binary-tree-longest-consecutive-sequence-medium.md │ ├── 0299-bulls-and-cows-medium.md │ └── _category_.json ├── 0300-0399 │ ├── 0300-longest-increasing-subsequence-medium.md │ ├── 0307-range-sum-query-mutable-medium.md │ ├── 0309-best-time-to-buy-and-sell-stock-with-cooldown-medium.md │ ├── 0312-burst-balloons-hard.md │ ├── 0322-coin-change-medium.md │ ├── 0323-number-of-connected-components-in-an-undirected-graph-medium.md │ ├── 0327-count-of-range-sum-hard.md │ ├── 0329-longest-increasing-path-in-a-matrix-hard.md │ ├── 0332-reconstruct-itinerary-hard.md │ ├── 0334-increasing-triplet-subsequence-medium.md │ ├── 0338-counting-bits-easy.md │ ├── 0342-power-of-four-easy.md │ ├── 0344-reverse-string-easy.md │ ├── 0345-reverse-vowels-of-a-string-easy.md │ ├── 0346-moving-average-from-data-stream-easy.md │ ├── 0347-top-k-frequent-elements-medium.md │ ├── 0349-intersection-of-two-arrays-easy.md │ ├── 0350-intersection-of-two-arrays-ii-easy.md │ ├── 0355-design-twitter-medium.md │ ├── 0365-water-and-jug-problem-medium.md │ ├── 0367-valid-perfect-square-easy.md │ ├── 0374-guess-number-higher-or-lower-easy.md │ ├── 0377-combination-sum-iv-medium.md │ ├── 0383-ransom-note-easy.md │ ├── 0387-first-unique-character-in-a-string-easy.md │ ├── 0389-find-the-difference-easy.md │ ├── 0392-is-subsequence-easy.md │ ├── 0393-utf-8-validation-medium.md │ └── _category_.json ├── 0400-0499 │ ├── 0402-remove-k-digits-medium.md │ ├── 0403-Frog-Jump.md │ ├── 0404-sum-of-left-leaves-easy.md │ ├── 0413-arithmetic-slices-medium.md │ ├── 0416-partition-equal-subset-sum-medium.md │ ├── 0417-pacific-atlantic-water-flow-medium.md │ ├── 0421-maximum-xor-of-two-numbers-in-an-array.md │ ├── 0424-longest-repeating-character-replacement-medium.md │ ├── 0429-n-ary-tree-level-order-traversal-medium.md │ ├── 0433-minimum-genetic-mutation-medium.md │ ├── 0435-non-overlapping-intervals-medium.md │ ├── 0437-path-sum-iii-medium.md │ ├── 0438-find-all-anagrams-in-a-string-medium.md │ ├── 0441-arranging-coins-easy.md │ ├── 0443-string-compression-medium.md │ ├── 0445-Add-Two-Numbers-II.md │ ├── 0451-sort-characters-by-frequency-medium.md │ ├── 0452-minimum-number-of-arrows-to-burst-balloons-medium.md │ ├── 0454-4sum-ii-medium.md │ ├── 0464-can-i-win-medium.md │ ├── 0465-optimal-account-balancing-hard.md │ ├── 0472-concatenated-words-hard.md │ ├── 0473-matchsticks-to-square-medium.md │ ├── 0491-non-decreasing-subsequences-medium.md │ ├── 0493-reverse-pairs-hard.md │ ├── 0494-target-sum-medium.md │ ├── 0496-next-greater-element-i-easy.md │ └── _category_.json ├── 0500-0599 │ ├── 0501-find-mode-in-binary-search-tree-easy.md │ ├── 0508-most-frequent-subtree-sum-medium.md │ ├── 0518-coin-change-2-medium.md │ ├── 0520-detect-capital-easy.md │ ├── 0523-continuous-subarray-sum-medium.md │ ├── 0525-contiguous-array-medium.md │ ├── 0532-k-diff-pairs-in-an-array-medium.md │ ├── 0540-single-element-in-a-sorted-array-medium.md │ ├── 0542-01-matrix-medium.md │ ├── 0543-diameter-of-binary-tree-easy.md │ ├── 0557-reverse-words-in-a-string-iii-easy.md │ ├── 0559-maximum-depth-of-n-ary-tree-easy.md │ ├── 0560-subarray-sum-equals-k-medium.md │ ├── 0567-permutation-in-string-medium.md │ ├── 0572-subtree-of-another-tree-easy.md │ ├── 0581-shortest-unsorted-continuous-subarray-medium.md │ ├── 0589-n-ary-tree-preorder-traversal-easy.md │ └── _category_.json ├── 0600-0699 │ ├── 0605-can-place-flowers-easy.md │ ├── 0606-construct-string-from-binary-tree-easy.md │ ├── 0609-find-duplicate-file-in-system-medium.md │ ├── 0621-task-scheduler-medium.md │ ├── 0622-design-circular-queue-medium.md │ ├── 0623-add-one-row-to-tree-medium.md │ ├── 0633-sum-of-square-numbers-medium.md │ ├── 0637-average-of-levels-in-binary-tree-medium.md │ ├── 0645-set-mismatch-easy.md │ ├── 0647-palindromic-substrings-medium.md │ ├── 0650-two-keys-keyboard-medium.md │ ├── 0653-two-sum-IV-input-is-a-BST-easy.md │ ├── 0659-split-array-into-consecutive-subsequences-medium.md │ ├── 0662-maximum-width-of-binary-tree-medium.md │ ├── 0678-valid-parenthesis-string-medium.md │ ├── 0680-valid-palindrome-ii-easy.md │ ├── 0682-baseball-game-easy.md │ ├── 0684-redundant-connection-medium.md │ ├── 0692-top-k-frequent-words-medium.md │ ├── 0695-max-area-of-island-medium.md │ ├── 0698-partition-to-k-equal-sum-subsets-medium.md │ └── _category_.json ├── 0700-0799 │ ├── 0703-kth-largest-element-in-a-stream-easy.md │ ├── 0704-binary-search-easy.md │ ├── 0706-design-hashmap-medium.md │ ├── 0713-subarray-product-less-than-k-medium.md │ ├── 0718-maximum-length-of-repeated-subarray-medium.md │ ├── 0724-find-pivot-index-easy.md │ ├── 0732-my-calendar-iii-hard.md │ ├── 0733-flood-fill-easy.md │ ├── 0739-daily-temperatures-medium.md │ ├── 0740-delete-and-earn-medium.md │ ├── 0743-network-delay-time-medium.md │ ├── 0744-find-smallest-letter-greater-than-target-easy.md │ ├── 0746-min-cost-climbing-stairs-easy.md │ ├── 0763-partition-labels-medium.md │ ├── 0778-swim-in-rising-water-hard.md │ ├── 0785-is-graph-bipartite-medium.md │ ├── 0787-cheapest-flights-within-k-stops-medium.md │ ├── 0799-champagne-tower-medium.md │ └── _category_.json ├── 0800-0899 │ ├── 0813-largest-sum-of-averages-medium.md │ ├── 0814-binary-tree-pruning-medium.md │ ├── 0829-consecutive-numbers-sum-hard.md │ ├── 0838-push-dominoes-medium.md │ ├── 0841-keys-and-rooms-medium.md │ ├── 0844-backspace-string-compare-easy.md │ ├── 0846-hand-of-straights-medium.md │ ├── 0847-shortest-path-visiting-all-nodes-hard.md │ ├── 0852-peak-index-in-a-mountain-array-easy.md │ ├── 0853-car-fleet-medium.md │ ├── 0867-transpose-matrix-easy.md │ ├── 0869-reordered-power-of-2-medium.md │ ├── 0871-minimum-number-of-refueling-stops-hard.md │ ├── 0875-koko-eating-bananas-medium.md │ ├── 0876-middle-of-the-linked-list-easy.md │ ├── 0877-stone-game-medium.md │ ├── 0881-boats-to-save-people-medium.md │ ├── 0896-monotonic-array-easy.md │ ├── 0899-orderly-queue-hard.md │ └── _category_.json ├── 0900-0999 │ ├── 0901-online-stock-span-medium.md │ ├── 0904-fruit-into-baskets-medium.md │ ├── 0907-sum-of-subarray-minimums-medium.md │ ├── 0909-snakes-and-ladders-medium.md │ ├── 0912-sort-an-array-medium.md │ ├── 0918-maximum-sum-circular-subarray-medium.md │ ├── 0923-3sum-with-multiplicity-medium.md │ ├── 0926-flip-string-to-monotone-increasing-medium.md │ ├── 0935-knight-dialer-medium.md │ ├── 0936-stamping-the-sequence-hard.md │ ├── 0941-valid-mountain-array-easy.md │ ├── 0944-delete-columns-to-make-sorted-easy.md │ ├── 0946-validate-stack-sequences-medium.md │ ├── 0947-most-stones-removed-with-same-row-or-column-medium.md │ ├── 0948-bag-of-tokens-medium.md │ ├── 0952-largest-component-size-by-common-factor-hard.md │ ├── 0967-numbers-with-same-consecutive-differences-medium.md │ ├── 0973-k-closest-points-to-origin-medium.md │ ├── 0974-subarray-sums-divisible-by-k-medium.md │ ├── 0976-largest-perimeter-triangle-easy.md │ ├── 0981-time-based-key-value-store-medium.md │ ├── 0985-sum-of-even-numbers-after-queries.medium.md │ ├── 0987-vertical-order-traversal-of-a-binary-tree-hard.md │ ├── 0990-satisfiability-of-equality-equations-medium.md │ ├── 0991-broken-calculator-medium.md │ ├── 0992-subarrays-with-k-different-integers-hard.md │ ├── 0994-rotting-oranges-medium.md │ └── _category_.json ├── 1000-1099 │ ├── 0997-find-the-town-judge-easy.md │ ├── 1000-minimum-cost-to-merge-stones-hard.md │ ├── 1004-max-consecutive-ones-iii-medium.md │ ├── 1011-capacity-to-ship-packages-within-d-days-medium.md │ ├── 1019-next-greater-node-in-linked-list.md │ ├── 1029-two-city-scheduling-medium.md │ ├── 1043-partition-array-for-maximum-sum-medium.md │ ├── 1046-last-stone-weight-easy.md │ ├── 1047-remove-all-adjacent-duplicates-in-string-easy.md │ ├── 1061-lexicographically-smallest-equivalent-string-medium.md │ ├── 1066-campus-bikes-ii-medium.md │ ├── 1071-greatest-common-divisor-of-strings-easy.md │ └── _category_.json ├── 1100-1199 │ ├── 1123-lowest-common-ancestor-of-deepest-leaves-medium.md │ ├── 1125-smallest-sufficient-team-hard.md │ ├── 1135-connecting-cities-with-minimum-cost-medium.md │ ├── 1137-n-th-tribonacci-number-easy.md │ ├── 1140-stone-game-ii-medium.md │ ├── 1143-longest-common-subsequence-medium.md │ ├── 1147-longest-chunked-palindrome-decomposition-hard.md │ ├── 1154-make-the-string-great-easy.md │ ├── 1155-number-of-dice-rolls-with-target-sum-medium.md │ ├── 1162-as-far-from-land-as-possible-medium.md │ ├── 1168-optimize-water-distribution-in-a-village-hard.md │ └── _category_.json ├── 1200-1299 │ ├── 1201-ugly-number-iii-medium.md │ ├── 1202-smallest-string-with-swaps-medium.md │ ├── 1219-path-with-maximum-gold-medium.md │ ├── 1232-check-if-it-is-a-straight-line-easy.md │ ├── 1235-maximum-profit-in-job-scheduling-hard.md │ ├── 1239-maximum-length-of-a-concatenated-string-with-unique-characters-medium.md │ ├── 1259-handshakes-that-dont-cross-hard.md │ ├── 1269-number-of-ways-to-stay-in-the-same-place-after-some-steps-hard.md │ ├── 1281-subtract-the-product-and-sum-of-digits-of-an-integer-easy.md │ ├── 1293-shortest-path-in-a-grid-with-obstacles-elimination-hard.md │ ├── 1299-replace-elements-with-greatest-element-on-right-side-easy.md │ └── _category_.json ├── 1300-1399 │ ├── 1305-all-elements-in-two-binary-search-trees-medium.md │ ├── 1326-minimum-number-of-taps-to-open-to-water-a-garden-hard.md │ ├── 1328-break-a-palindrome-medium.md │ ├── 1329-sort-the-matrix-diagonally-medium.md │ ├── 1331-rank-transform-of-an-array-easy.md │ ├── 1334-find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance-medium.md │ ├── 1335-minimum-difficulty-of-a-job-schedule-hard.md │ ├── 1337-the-k-weakest-rows-in-a-matrix-easy.md │ ├── 1346-check-if-n-and-its-double-exist-easy.md │ ├── 1347-minimum-number-of-steps-to-make-two-strings-anagram-medium.md │ ├── 1349-maximum-students-taking-exam-hard.md │ ├── 1356-sort-integers-by-the-number-of-1-bits-easy.md │ ├── 1359-count-all-valid-pickup-and-delivery-options-hard.md │ ├── 1365-how-many-numbers-are-smaller-than-the-current-number-easy.md │ ├── 1371-find-the-longest-substring-containing-vowels-in-even-counts-medium.md │ ├── 1372-longest-zigzag-path-in-a-binary-tree-medium.md │ ├── 1383-maximum-performance-of-a-team-hard.md │ └── _category_.json ├── 1400-1499 │ ├── 1431-kids-with-the-greatest-number-of-candies-easy.md │ ├── 1434-number-of-ways-to-wear-different-hats-to-each-other-hard.md │ ├── 1443-minimum-time-to-collect-all-apples-in-a-tree.md │ ├── 1448-count-good-nodes-in-binary-tree-medium.md │ ├── 1457-pseudo-palindromic-paths-in-a-binary-tree-medium.md │ ├── 1460-make-two-arrays-equal-by-reversing-subarrays-easy.md │ ├── 1464-maximum-product-of-two-elements-in-an-array-easy.md │ ├── 1470-shuffle-the-array-easy.md │ ├── 1475-final-prices-with-a-special-discount-in-a-shop-easy.md │ ├── 1480-running-sum-of-1d-array-easy.md │ ├── 1482-minimum-number-of-days-to-make-m-bouquets-medium.md │ ├── 1491-average-salary-excluding-the-minimum-and-maximum-salary-easy.md │ ├── 1494-parallel-courses-ii-hard.md │ ├── 1496-path-crossing-easy.md │ └── _category_.json ├── 1500-1599 │ ├── 1502-can-make-arithmetic-progression-from-sequence-easy.md │ ├── 1510-stone-game-iv-hard.md │ ├── 1514-path-with-maximum-probability.md │ ├── 1519-number-of-nodes-in-the-sub-tree-with-the-same-label-medium.md │ ├── 1523-count-odd-numbers-in-an-interval-range-easy.md │ ├── 1531-string-compression-ii-hard.md │ ├── 1539-kth-missing-positive-number-easy.md │ ├── 1544-make-the-string-great-easy.md │ ├── 1547-minimum-cost-to-cut-a-stick-hard.md │ ├── 1550-three-consecutive-odds-easy.md │ ├── 1572-matrix-diagonal-sum-easy.md │ ├── 1575-count-all-possible-routes-hard.md │ ├── 1578-minimum-time-to-make-rope-colorful-medium.md │ ├── 1584-min-cost-to-connect-all-points-medium.md │ ├── 1588-sum-of-all-odd-length-subarrays-easy.md │ ├── 1590-make_sum_divisible_by_p-medium.md │ └── _category_.json ├── 1600-1699 │ ├── 1624-largest-substring-between-two-equal-characters-easy.md │ ├── 1626-best-team-with-no-conflicts-medium.md │ ├── 1630-arithmetic-subarrays-medium.md │ ├── 1631-path-with-minimum-effort-medium.md │ ├── 1633-smallest-string-with-a-given-numeric-value-medium.md │ ├── 1639-number-of-ways-to-form-a-target-string-given-a-dictionary-hard.md │ ├── 1655-distribute-repeating-integers-hard.md │ ├── 1657-define-if-two-strings-are-close-medium.md │ ├── 1662-check-if-two-string-arrays-are-equivalent-easy.md │ ├── 1664-ways-to-make-a-fair-array-medium.md │ ├── 1672-richest-customer-wealth-easy.md │ ├── 1675-minimize-deviation-in-array-hard.md │ ├── 1679-max-number-of-k-sum-pairs-medium.md │ ├── 1680-concatenation-of-consecutive-binary-numbers-medium.md │ ├── 1685-sum-of-absolute-differences-in-a-sorted-array-medium.md │ ├── 1692-count-ways-to-distribute-candies-hard.md │ └── _category_.json ├── 1700-1799 │ ├── 1704-determine-if-string-halves-are-alike-easy.md │ ├── 1706-where-will-the-ball-fall-medium.md │ ├── 1727-largest-submatrix-with-rearrangements-medium.md │ ├── 1748-sum-of-unique-elements-easy.md │ ├── 1751-maximum-number-of-events-that-can-be-attended-ii-hard.md │ ├── 1758-minimum-changes-to-make-alternating-binary-string-easy.md │ ├── 1762-buildings-with-an-ocean-view-medium.md │ ├── 1768-merge-strings-alternately-easy.md │ ├── 1770-maximum-score-from-performing-multiplication-operations-medium.md │ ├── 1779-find-nearest-point-that-has-the-same-x-or-y-coordinate-easy.md │ ├── 1790-check-if-one-string-swap-can-make-strings-equal-easy.md │ ├── 1791-find-center-of-star-graph-easy.md │ ├── 1793-maximum-score-of-a-good-subarray-hard.md │ └── _category_.json ├── 1800-1899 │ ├── 1800-maximum-ascending-subarray-sum-easy.md │ ├── 1822-sign-of-the-product-of-an-array-easy.md │ ├── 1823-find-the-winner-of-the-circular-game-medium.md │ ├── 1833-maximum-ice-cream-bars-medium.md │ ├── 1851-minimum-interval-to-include-each-query-hard.md │ ├── 1852-distinct-numbers-in-each-subarray-medium.md │ ├── 1854-maximum-population-year-easy.md │ ├── 1855-maximum-distance-between-a-pair-of-values-medium.md │ ├── 1859-sorting-the-sentence-easy.md │ ├── 1863-sum-of-all-subset-xor-totals-easy.md │ ├── 1866-number-of-ways-to-rearrange-sticks-with-k-sticks-visible-hard.md │ ├── 1899-merge-triplets-to-form-target-triplet-medium.md │ └── _category_.json ├── 1900-1999 │ ├── 1903-largest-odd-number-in-string-easy.md │ ├── 1913-maximum-product-difference-between-two-pairs-easy.md │ ├── 1916-count-ways-to-build-rooms-in-an-ant-colony.md │ ├── 1922-count-good-numbers-medium.md │ ├── 1926-nearest-exit-from-entrance-in-maze-medium.md │ ├── 1929-concatenation-of-array-easy.md │ ├── 1980-find-unique-binary-string-medium.md │ ├── 1992-find-all-groups-of-farmland-medium.md │ ├── 1996-the-number-of-weak-characters-in-the-game-medium.md │ └── _category_.json ├── 2000-2099 │ ├── 2007-find-original-array-from-doubled-array-medium.md │ ├── 2009-minimum-number-of-operations-to-make-array-continuous-hard.md │ ├── 2013-detect-squares-medium.md │ ├── 2017-grid-game-medium.md │ ├── 2032-two-out-of-three-easy.md │ ├── 2050-parallel-courses-iii-hard.md │ ├── 2075-decode-the-slanted-ciphertext-medium.md │ └── _category_.json ├── 2100-2199 │ ├── 2104-solving-questions-with-brainpower-medium.md │ ├── 2108-find-first-palindromic-string-in-the-array-easy.md │ ├── 2109-adding-spaces-to-a-string-medium.md │ ├── 2110-number-of-smooth-descent-periods-of-a-stock-medium.md │ ├── 2111-minimum-operations-to-make-the-array-k-increasing-hard.md │ ├── 2119-a-number-after-a-double-reversal-easy.md │ ├── 2120-execution-of-all-suffix-instructions-staying-in-a-grid-medium.md │ ├── 2121-intervals-between-identical-elements-medium.md │ ├── 2122-recover-the-original-array-hard.md │ ├── 2127-maximum-employees-to-be-invited-to-a-meeting-hard.md │ ├── 2131-longest-palindrome-by-concatenating-two-letter-words-medium.md │ ├── 2144-minimum-cost-of-buying-candies-with-discount-easy.md │ ├── 2145-count-the-hidden-sequences-medium.md │ ├── 2146-k-highest-ranked-items-within-a-price-range-medium.md │ ├── 2147-number-of-ways-to-divide-a-long-corridor-hard.md │ ├── 2148-count-elements-with-strictly-smaller-and-greater-elements-easy.md │ ├── 2149-rearrange-array-elements-by-sign-medium.md │ ├── 2150-find-all-lonely-numbers-in-the-array-medium.md │ ├── 2151-maximum-good-people-based-on-statements-hard.md │ ├── 2154-keep-multiplying-found-values-by-two-easy.md │ ├── 2155-all-divisions-with-the-highest-score-of-a-binary-array-medium.md │ ├── 2156-find-substring-with-given-hash-value-medium.md │ ├── 2160-minimum-sum-of-four-digit-number-after-splitting-digits-easy.md │ ├── 2161-partition-array-according-to-given-pivot-medium.md │ ├── 2162-minimum-cost-to-set-cooking-time-medium.md │ ├── 2163-minimum-difference-in-sums-after-removal-of-elements-hard.md │ ├── 2164-sort-even-and-odd-indices-independently-easy.md │ ├── 2165-smallest-value-of-the-rearranged-number-medium.md │ ├── 2166-design-bitset-medium.md │ ├── 2167-minimum-time-to-remove-all-cars-containing-illegal-goods-hard.md │ ├── 2169-count-operations-to-obtain-zero-easy.md │ ├── 2170-minimum-operations-to-make-the-array-alternating-medium.md │ ├── 2171-removing-minimum-number-of-magic-beans-medium.md │ ├── 2172-maximum-and-sum-of-array-hard.md │ ├── 2176-count-equal-and-divisible-pairs-in-an-array-easy.md │ ├── 2177-find-three-consecutive-integers-that-sum-to-a-given-number-medium.md │ ├── 2178-maximum-split-of-positive-even-integers-medium.md │ ├── 2179-count-good-triplets-in-an-array-hard.md │ ├── 2180-count-integers-with-even-digit-sum-easy.md │ ├── 2181-merge-nodes-in-between-zeros-medium.md │ ├── 2182-construct-string-with-repeat-limit-medium.md │ ├── 2183-count-array-pairs-divisible-by-k-hard.md │ ├── 2185-counting-words-with-a-given-prefix-easy.md │ ├── 2186-minimum-number-of-steps-to-make-two-strings-anagram-ii-medium.md │ ├── 2187-minimum-time-to-complete-trips-medium.md │ ├── 2188-minimum-time-to-finish-the-race-hard.md │ ├── 2190-most-frequent-number-following-key-in-an-array-easy.md │ ├── 2191-sort-the-jumbled-numbers-medium.md │ ├── 2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph-medium.md │ ├── 2193-minimum-number-of-moves-to-make-palindrome-hard.md │ ├── 2194-cells-in-a-range-on-an-excel-sheet-easy.md │ ├── 2195-append-k-integers-with-minimal-sum-medium.md │ ├── 2196-create-binary-tree-from-descriptions-medium.md │ ├── 2197-replace-non-coprime-numbers-in-array-hard.md │ ├── 2200-find-all-k-distant-indices-in-an-array-easy.md │ ├── 2201-count-artifacts-that-can-be-extracted-medium.md │ ├── 2202-maximize-the-topmost-element-after-k-moves-medium.md │ ├── 2203-minimum-weighted-subgraph-with-the-required-paths-hard.md │ ├── 2206-divide-array-into-equal-pairs-easy.md │ ├── 2207-maximize-number-of-subsequences-in-a-string-medium.md │ └── _category_.json ├── 2200-2299 │ ├── 2208-minimum-operations-to-halve-array-sum-easy.md │ ├── 2209-minimum-white-tiles-after-covering-with-carpets-hard.md │ ├── 2214-minimum-health-to-beat-game-medium.md │ ├── 2215-find-the-difference-of-two-arrays-easy.md │ ├── 2216-minimum-deletions-to-make-array-beautiful-medium.md │ ├── 2217-find-palindrome-with-fixed-length-medium.md │ ├── 2218-maximum-value-of-k-coins-from-piles-hard.md │ ├── 2223-sum-of-scores-of-built-strings-hard.md │ ├── 2224-minimum-number-of-operations-to-convert-time-easy.md │ ├── 2225-find-players-with-zero-or-one-losses-medium.md │ ├── 2226-maximum-candies-allocated-to-k-children-medium.md │ ├── 2227-encrypt-and-decrypt-strings-hard.md │ ├── 2229-check-if-an-array-is-consecutive-easy.md │ ├── 2231-largest-number-after-digit-swaps-by-parity-easy.md │ ├── 2232-minimize-result-by-adding-parentheses-to-expression-medium.md │ ├── 2233-maximum-product-after-k-increments-medium.md │ ├── 2235-add-two-integers-easy.md │ ├── 2237-count-positions-on-street-with-required-brightness-medium.md │ ├── 2239-find-closest-number-to-zero-easy.md │ ├── 2240-number-of-ways-to-buy-pens-and-pencils-medium.md │ ├── 2241-design-an-atm-machine-medium.md │ ├── 2242-maximum-score-of-a-node-sequence-hard.md │ ├── 2243-calculate-digit-sum-of-a-string-easy.md │ ├── 2244-minimum-rounds-to-complete-all-tasks-medium.md │ ├── 2246-longest-path-with-different-adjacent-characters-hard.md │ ├── 2248-intersection-of-multiple-arrays-easy.md │ ├── 2249-count-lattice-points-inside-a-circle-medium.md │ ├── 2250-count-number-of-rectangles-containing-each-point-medium.md │ ├── 2251-number-of-flowers-in-full-bloom-hard.md │ ├── 2255-count-prefixes-of-a-given-string-easy.md │ ├── 2256-minimum-average-difference-medium.md │ ├── 2259-remove-digit-from-number-to-maximize-result-easy.md │ ├── 2260-minimum-consecutive-cards-to-pick-up-medium.md │ ├── 2261-k-divisible-elements-subarrays-medium.md │ ├── 2262-total-appeal-of-a-string-hard.md │ ├── 2264-largest-3-same-digit-number-in-string-easy.md │ ├── 2265-count-nodes-equal-to-average-of-subtree-medium.md │ ├── 2266-count-number-of-texts-medium.md │ ├── 2267-check-if-there-is-a-valid-parentheses-string-path-hard.md │ ├── 2273-find-resultant-array-after-removing-anagrams-easy.md │ ├── 2274-maximum-consecutive-floors-without-special-floors-medium.md │ ├── 2275-largest-combination-with-bitwise-and-greater-than-zero-medium.md │ ├── 2276-count-integers-in-intervals-hard.md │ ├── 2278-percentage-of-letter-in-string.md │ ├── 2279-maximum-bags-with-full-capacity-of-rock-medium.md │ ├── 2280-minimum-lines-to-represent-a-line-chart-medium.md │ └── _category_.json ├── 2300-2399 │ ├── 2300-successful-pairs-of-spells-and-potions-medium.md │ ├── 2302-count-subarrays-with-score-less-than-k.md │ ├── 2331-evaluate-boolean-binary-tree-easy.md │ ├── 2332-the-latest-time-to-catch-a-bus-medium.md │ ├── 2333-minimum-sum-of-squared-difference-medium.md │ ├── 2334-subarray-with-elements-greater-than-varying-threshold-hard.md │ ├── 2335-minimum-amount-of-time-to-fill-cups-easy.md │ ├── 2336-smallest-number-in-infinite-set-medium.md │ ├── 2337-move-pieces-to-obtain-a-string-medium.md │ ├── 2338-count-the-number-of-ideal-arrays-hard.md │ ├── 2351-first-letter-to-appear-twice-easy.md │ ├── 2352-equal-row-and-column-pairs-medium.md │ ├── 2353-design-a-food-rating-system-medium.md │ ├── 2354-number-of-excellent-pairs-hard.md │ ├── 2357-make-array-zero-by-subtracting-equal-amounts-easy.md │ ├── 2358-maximum-number-of-groups-entering-a-competition-medium.md │ ├── 2359-find-closest-node-to-given-two-nodes-medium.md │ ├── 2360-longest-cycle-in-a-graph-hard.md │ ├── 2373-largest-local-values-in-a-matrix-easy.md │ ├── 2376-count-special-integers-hard.md │ ├── 2379-minimum-recolors-to-get-k-consecutive-black-blocks-easy.md │ ├── 2380-time-needed-to-rearrange-a-binary-string-medium.md │ ├── 2381-shifting-letters-ii-medium.md │ ├── 2383-minimum-hours-of-training-to-win-a-competition-easy.md │ ├── 2384-largest-palindromic-number-medium.md │ ├── 2392-build-a-matrix-with-conditions-hard.md │ └── _category_.json ├── 2400-2499 │ ├── 2400-number-of-ways-to-reach-a-position-after-exactly-k-steps-medium.md │ ├── 2401-longest-nice-subarray-medium.md │ ├── 2404-most-frequent-even-element-easy.md │ ├── 2405-optimal-partition-of-string-medium.md │ ├── 2406-divide-intervals-into-minimum-number-of-groups-medium.md │ ├── 2413-smallest-even-multiple-easy.md │ ├── 2418-sort-the-people-easy.md │ ├── 2419-longest-subarray-with-maximum-bitwise-and-medium.md │ ├── 2420-find-all-good-indices-medium.md │ ├── 2421-number-of-good-paths-hard.md │ ├── 2425-bitwise-xor-of-all-pairs-medium.md │ ├── 2432-the-employee-that-worked-on-the-longest-task-easy.md │ ├── 2433-find-the-original-array-of-prefix-xor-medium.md │ ├── 2439-minimize-maximum-of-array-medium.md │ ├── 2441-largest-positive-integer-that-exists-with-its-negative-easy.md │ ├── 2445-number-of-nodes-with-value-one-medium.md │ ├── 2455-average-value-of-even-numbers-that-are-divisible-by-three-easy.md │ ├── 2461-maximum-sum-of-distinct-subarrays-with-length-k-medium.md │ ├── 2469-convert-the-temperature-easy.md │ ├── 2477-minimum-fuel-cost-to-report-to-the-capital-medium.md │ ├── 2482-difference-between-ones-and-zeros-in-row-and-column-medium.md │ ├── 2485-find-the-pivot-integer-easy.md │ ├── 2486-append-characters-to-string-to-make-subsequence-medium.md │ ├── 2487-remove-nodes-from-linked-list-medium.md │ └── _category_.json ├── 2500-2599 │ ├── 2501-longest-square-streak-in-an-array-medium.md │ ├── 2520-count-the-digits-that-divide-a-number-easy.md │ ├── 2521-distinct-prime-factors-of-product-of-array-medium.md │ ├── 2523-closest-prime-numbers-in-range-medium.md │ ├── 2529-maximum-count-of-positive-integer-and-negative-integer-easy.md │ ├── 2530-maximal-score-after-applying-k-operations-medium.md │ ├── 2531-make-number-of-distinct-characters-equal-medium.md │ ├── 2535-difference-between-element-sum-and-digit-sum-of-an-array-easy.md │ ├── 2571-minimum-operations-to-reduce-an-integer-to-0-easy.md │ └── _category_.json ├── 2600-2699 │ ├── 2610-convert-an-array-into-a-2d-array-with-conditions-medium.md │ ├── 2614-prime-in-diagonal-easy.md │ ├── 2615-sum-of-distances-medium.md │ ├── 2616-minimize-the-maximum-difference-of-pairs-medium.md │ ├── 2639-find-the-width-of-columns-of-a-grid-easy.md │ ├── 2644-find-the-maximum-divisibility-score-easy.md │ ├── 2678-number-of-senior-citizens-easy.md │ ├── 2679-sum-in-a-matrix-medium.md │ ├── 2680-maximum-or-medium.md │ ├── 2681-power-of-heroes-hard.md │ └── _category_.json ├── 2700-2799 │ ├── 2709-greatest-common-divisor-traversal-hard.md │ ├── 2750-ways-to-split-array-into-good-subarrays-medium.md │ ├── 2761-prime-pairs-with-target-sum-medium.md │ └── _category_.json ├── 2800-2899 │ ├── 2810-faulty-keyboard-easy.md │ ├── 2811-check-if-it-is-possible-to-split-array-medium.md │ ├── 2815-max-pair-sum-in-an-array-easy.md │ ├── 2839-check-if-strings-can-be-made-equal-with-operations-i-easy.md │ ├── 2840-check-if-strings-can-be-made-equal-with-operations-ii-medium.md │ ├── 2841-maximum-sum-of-almost-unique-subarray-medium.md │ ├── 2843-count-symmetric-integers-easy.md │ ├── 2859-sum-of-values-at-indices-with-k-set-bits-easy.md │ ├── 2864-maximum-odd-binary-number-easy.md │ ├── 2873-maximum-value-of-an-ordered-triplet-i-easy.md │ ├── 2873-maximum-value-of-an-ordered-triplet-ii-medium.md │ └── _category_.json ├── 2900-2999 │ ├── 2095-find-indices-with-index-and-value-difference-ii-medium.md │ ├── 2903-find-indices-with-index-and-value-difference-i-easy.md │ ├── 2913-subarrays-distinct-element-sum-of-squares-i-easy.md │ ├── 2914-minimum-number-of-changes-to-make-binary-string-beautiful-medium.md │ └── _category_.json ├── 3000-3099 │ ├── 3005-count-elements-with-maximum-frequency-easy.md │ ├── 3033-modify-the-matrix-easy.md │ ├── 3034-number-of-subarrays-that-match-a-pattern-i-medium.md │ ├── 3035-maximum-palindromes-after-operations-medium.md │ ├── 3064-guess-the-number-using-bitwise-questions-i-medium.md │ └── _category_.json ├── 3100-3199 │ ├── 3142-check-if-grid-satisfies-conditions-easy.md │ └── _category_.json ├── 3200-3299 │ ├── 3289-the-two-sneaky-numbers-of-digitville-easy.md │ └── _category_.json └── 3300-3399 │ ├── 3300-minimum-element-after-replacement-with-digit-sum-easy.md │ ├── 3375-minimum-operations-to-make-array-values-equal-to-k-easy.md │ └── _category_.json ├── src ├── components │ ├── HomepageFeatures │ │ ├── index.js │ │ └── styles.module.css │ ├── SolutionAuthor │ │ └── index.js │ ├── Table │ │ └── index.js │ ├── Tags │ │ └── index.js │ └── TutorialCredits │ │ └── index.js ├── css │ └── custom.css ├── pages │ ├── index.js │ └── index.module.css └── theme │ └── MDXComponents.js ├── static ├── .nojekyll ├── CNAME ├── ads.txt ├── img │ ├── banner.png │ ├── favicon.ico │ ├── logo.svg │ ├── undraw_community_re_cyrm.svg │ ├── undraw_learning_sketching_nd4f.svg │ └── undraw_onboarding_re_6osc.svg └── robots.txt ├── templates ├── binary-search.md ├── bit-manipulation.md ├── euler.md ├── fenwick-tree.md ├── graph-theory.md ├── index.md ├── linked-list.md ├── manachers-algorithm.md ├── ordered-set.md ├── prefix-sum.md ├── segment-tree.md ├── sparse-table.md └── two-pointers.md └── tutorials ├── basic-topics ├── _category_.json ├── arrays.md ├── backtracking.md ├── binary-search.md ├── brute-force.md ├── divide-and-conquer.md ├── doubly-linked-list.md ├── greedy.md ├── hash-map.md ├── heap.md ├── kadane.md ├── linear-search.md ├── linked-list.md ├── mod.md ├── prefix-sum.md ├── queue-and-stack.md ├── sliding-window.md ├── sorting │ ├── _category_.json │ ├── bubble-sort.md │ ├── bucket-sort.md │ ├── counting-sort.md │ ├── cyclic-sort.md │ ├── heap-sort.md │ ├── insertion-sort.md │ ├── introduction.md │ ├── merge-sort.md │ ├── quick-sort.md │ ├── radix-sort.md │ ├── selection-sort.md │ ├── shell-sort.md │ └── tim-sort.md ├── time-complexity.md ├── trie.md └── two-pointers.md ├── dynamic-programming.md ├── graph-theory ├── _category_.json ├── bellman-ford-algorithm.md ├── binary-search-tree.md ├── binary-tree.md ├── breadth-first-search.md ├── depth-first-search.md ├── dijkstra.md ├── disjoint-set-union.md ├── floyd-warshall-algorithm.md ├── introduction.md ├── kahns-algorithm.md ├── kruskals-algorithm.md ├── lca.md ├── minimum-spanning-tree.md ├── prims-algorithm.md ├── tarjans-algorithm.md └── topological-sorting.md ├── math ├── _category_.json ├── bit-manipulation.md ├── combinatorics.md ├── matrix-exponentiation.md ├── number-theory │ ├── _category_.json │ ├── binary-exponentiation.md │ └── sieve-of-eratosthenes.md └── prime-factors.md └── strings ├── _category_.json ├── knuth–morris–pratt-algorithm.md ├── levenshtein-distance.md ├── manachers-algorithm.md ├── palindrome.md ├── rabin-karp-algorithm.md └── z-algorithm.md /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: wingkwong 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry 13 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 14 | -------------------------------------------------------------------------------- /.github/issue_template.md: -------------------------------------------------------------------------------- 1 | ## Tutorial 2 | 3 | If you want to request a topic on LeetCode The Hard Way 4 | 5 | - State the topic 6 | 7 | If you want to take the assignment as well 8 | 9 | - Suggest the markdown location 10 | - Suggest a few LC problems on this topic 11 | 12 | ## Solution 13 | 14 | You **DON'T** need to create an issue and ask for assignment. Just create a pull request. Issues created for solutions will be closed directly. 15 | -------------------------------------------------------------------------------- /.github/workflows/deploy.yml: -------------------------------------------------------------------------------- 1 | name: Deploy to GitHub Pages 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | # Review gh actions docs if you want to further define triggers, paths, etc 8 | # https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#on 9 | 10 | jobs: 11 | deploy: 12 | name: Deploy to GitHub Pages 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/checkout@v4 16 | - uses: pnpm/action-setup@v4 17 | - uses: actions/setup-node@v4 18 | with: 19 | node-version: 22.16.0 20 | registry-url: https://registry.npmjs.org 21 | 22 | - name: Install dependencies 23 | run: pnpm install --frozen-lockfile 24 | - name: Build website 25 | run: pnpm run build 26 | 27 | # Popular action to deploy to GitHub Pages: 28 | # Docs: https://github.com/peaceiris/actions-gh-pages#%EF%B8%8F-docusaurus 29 | - name: Deploy to GitHub Pages 30 | uses: peaceiris/actions-gh-pages@v4 31 | with: 32 | github_token: ${{ secrets.GITHUB_TOKEN }} 33 | # Build output to publish to the `gh-pages` branch: 34 | publish_dir: ./build 35 | # The following lines assign commit authorship to the official 36 | # GH-Actions bot for deploys to `gh-pages` branch: 37 | # https://github.com/actions/checkout/issues/13#issuecomment-724415212 38 | user_name: wingkwong 39 | user_email: wingkwong.code@gmail.com 40 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Dependencies 2 | /node_modules 3 | 4 | # Production 5 | /build 6 | 7 | # Generated files 8 | .docusaurus 9 | .cache-loader 10 | 11 | # Misc 12 | .DS_Store 13 | .env.local 14 | .env.development.local 15 | .env.test.local 16 | .env.production.local 17 | 18 | npm-debug.log* 19 | yarn-debug.log* 20 | yarn-error.log* 21 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "bracketSameLine": false, 3 | "printWidth": 80, 4 | "proseWrap": "never", 5 | "singleQuote": true, 6 | "trailingComma": "all" 7 | } 8 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: [require.resolve('@docusaurus/core/lib/babel/preset')], 3 | }; 4 | -------------------------------------------------------------------------------- /blog/2019-05-28-first-blog-post.md: -------------------------------------------------------------------------------- 1 | --- 2 | slug: first-blog-post 3 | title: First Blog Post 4 | authors: 5 | name: Gao Wei 6 | title: Docusaurus Core Team 7 | url: https://github.com/wgao19 8 | image_url: https://github.com/wgao19.png 9 | tags: [hola, docusaurus] 10 | --- 11 | 12 | Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque elementum dignissim ultricies. Fusce rhoncus ipsum tempor eros aliquam consequat. Lorem ipsum dolor sit amet 13 | -------------------------------------------------------------------------------- /blog/2021-08-01-mdx-blog-post.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | slug: mdx-blog-post 3 | title: MDX Blog Post 4 | authors: [slorber] 5 | tags: [docusaurus] 6 | --- 7 | 8 | Blog posts support [Docusaurus Markdown features](https://docusaurus.io/docs/markdown-features), such as [MDX](https://mdxjs.com/). 9 | 10 | :::tip 11 | 12 | Use the power of React to create interactive blog posts. 13 | 14 | ```js 15 | 16 | ``` 17 | 18 | 19 | 20 | ::: 21 | -------------------------------------------------------------------------------- /blog/2021-08-26-welcome/docusaurus-plushie-banner.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wingkwong/leetcode-the-hard-way/56d707a6d4868aa8bfad3f048cb114485d3f6982/blog/2021-08-26-welcome/docusaurus-plushie-banner.jpeg -------------------------------------------------------------------------------- /blog/2021-08-26-welcome/index.md: -------------------------------------------------------------------------------- 1 | --- 2 | slug: welcome 3 | title: Welcome 4 | authors: [slorber, yangshun] 5 | tags: [facebook, hello, docusaurus] 6 | --- 7 | 8 | [Docusaurus blogging features](https://docusaurus.io/docs/blog) are powered by the [blog plugin](https://docusaurus.io/docs/api/plugins/@docusaurus/plugin-content-blog). 9 | 10 | Simply add Markdown files (or folders) to the `blog` directory. 11 | 12 | Regular blog authors can be added to `authors.yml`. 13 | 14 | The blog post date can be extracted from filenames, such as: 15 | 16 | - `2019-05-30-welcome.md` 17 | - `2019-05-30-welcome/index.md` 18 | 19 | A blog post folder can be convenient to co-locate blog post images: 20 | 21 | ![Docusaurus Plushie](./docusaurus-plushie-banner.jpeg) 22 | 23 | The blog supports tags as well! 24 | 25 | **And if you don't want a blog**: just delete this directory, and use `blog: false` in your Docusaurus config. 26 | -------------------------------------------------------------------------------- /blog/authors.yml: -------------------------------------------------------------------------------- 1 | endi: 2 | name: Endilie Yacop Sucipto 3 | title: Maintainer of Docusaurus 4 | url: https://github.com/endiliey 5 | image_url: https://github.com/endiliey.png 6 | 7 | yangshun: 8 | name: Yangshun Tay 9 | title: Front End Engineer @ Facebook 10 | url: https://github.com/yangshun 11 | image_url: https://github.com/yangshun.png 12 | 13 | slorber: 14 | name: Sébastien Lorber 15 | title: Docusaurus maintainer 16 | url: https://sebastienlorber.com 17 | image_url: https://github.com/slorber.png 18 | -------------------------------------------------------------------------------- /config.json: -------------------------------------------------------------------------------- 1 | { 2 | "index_name": "leetcode-the-hard-way", 3 | "start_urls": ["https://leetcodethehardway.com/"], 4 | "selectors": { 5 | "lvl0": "", 6 | "lvl1": "h1", 7 | "lvl2": "h2", 8 | "lvl3": "h3", 9 | "text": "article div,article p,article theme-code-block" 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /converter/README.md: -------------------------------------------------------------------------------- 1 | # LeetCode The Hard Way - Converter 2 | 3 | Chrome Extension to convert LeetCode problems into LTHW format. Originally work is done by [crx-leetmark](https://github.com/crimx/crx-leetmark). 4 | -------------------------------------------------------------------------------- /converter/background.js: -------------------------------------------------------------------------------- 1 | chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => { 2 | switch (msg.type) { 3 | case 'page_action_show': 4 | if (sender.tab && sender.tab.id) chrome.pageAction.show(sender.tab.id); 5 | sendResponse(); 6 | return; 7 | } 8 | }); 9 | -------------------------------------------------------------------------------- /converter/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "LeetCode The Hard Way - Converter", 3 | "short_name": "LTHWConverter", 4 | "description": "Converts a Leetcode problem page into Github Flavored Markdown", 5 | "manifest_version": 2, 6 | "minimum_chrome_version": "55", 7 | "version": "0.1.0", 8 | "content_scripts": [ 9 | { 10 | "js": ["content.js"], 11 | "matches": [ 12 | "https://*.leetcode.com/problems/*", 13 | "https://*.leetcode-cn.com/problems/*" 14 | ] 15 | } 16 | ], 17 | "background": { 18 | "scripts": ["background.js"], 19 | "persistent": false 20 | }, 21 | "page_action": { 22 | "default_title": "Click to generate Markdown from a Leetcode problem page", 23 | "default_popup": "popup.html" 24 | }, 25 | "permissions": ["https://*.leetcode.com/*", "https://*.leetcode-cn.com/*"] 26 | } 27 | -------------------------------------------------------------------------------- /converter/popup.css: -------------------------------------------------------------------------------- 1 | body { 2 | display: flex; 3 | flex-direction: column; 4 | overflow: hidden; 5 | width: 600px; 6 | height: 600px; 7 | box-sizing: border-box; 8 | margin: 0; 9 | padding: 8px; 10 | } 11 | 12 | .btn-tab { 13 | position: relative; 14 | top: 1px; 15 | border: 1px solid #aaa; 16 | border-top-left-radius: 5px; 17 | border-top-right-radius: 5px; 18 | background: #fff; 19 | cursor: pointer; 20 | outline: none; 21 | transition: all 0.4s; 22 | } 23 | 24 | .btn-tab:active, 25 | .btn-tab:focus { 26 | border-top-color: #5b9dd9; 27 | box-shadow: 0px -1px 0px 0px #5b9dd9; 28 | } 29 | 30 | .btn-tab.active { 31 | border-bottom-color: #fff !important; 32 | } 33 | 34 | .txt { 35 | flex: 1; 36 | resize: none; 37 | padding: 5px; 38 | } 39 | -------------------------------------------------------------------------------- /converter/popup.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | LeetCode The Hard Way - Converter 5 | 6 | 7 | 8 |
9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wingkwong/leetcode-the-hard-way/56d707a6d4868aa8bfad3f048cb114485d3f6982/docs/index.md -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "leetcode-the-hard-way", 3 | "version": "0.0.0", 4 | "private": true, 5 | "scripts": { 6 | "docusaurus": "docusaurus", 7 | "start": "docusaurus start", 8 | "build": "docusaurus build", 9 | "swizzle": "docusaurus swizzle", 10 | "deploy": "docusaurus deploy", 11 | "clear": "docusaurus clear", 12 | "serve": "docusaurus serve", 13 | "write-translations": "docusaurus write-translations", 14 | "write-heading-ids": "docusaurus write-heading-ids", 15 | "crawl": "docker run -it --env-file=.env.local -e \"CONFIG=$(cat ./config.json | jq -r tostring)\" algolia/docsearch-scraper", 16 | "prettier": "prettier --write ." 17 | }, 18 | "dependencies": { 19 | "@docusaurus/core": "3.7.0", 20 | "@docusaurus/plugin-content-docs": "3.7.0", 21 | "@docusaurus/plugin-google-analytics": "3.7.0", 22 | "@docusaurus/plugin-google-gtag": "3.7.0", 23 | "@docusaurus/preset-classic": "3.7.0", 24 | "@mdx-js/react": "^3.0.0", 25 | "clsx": "^2.1.1", 26 | "hast-util-is-element": "^3.0.0", 27 | "prism-react-renderer": "^2.4.1", 28 | "react": "18.3.1", 29 | "react-dom": "18.3.1", 30 | "rehype-katex": "7.0.1", 31 | "remark-math": "6.0.0" 32 | }, 33 | "devDependencies": { 34 | "@docusaurus/module-type-aliases": "3.7.0", 35 | "prettier": "3.5.3" 36 | }, 37 | "browserslist": { 38 | "production": [ 39 | ">0.5%", 40 | "not dead", 41 | "not op_mini all" 42 | ], 43 | "development": [ 44 | "last 1 chrome version", 45 | "last 1 firefox version", 46 | "last 1 safari version" 47 | ] 48 | }, 49 | "packageManager": "pnpm@10.11.0" 50 | } 51 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": ["config:base"] 4 | } 5 | -------------------------------------------------------------------------------- /roadmap/arrays.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Arrays' 3 | description: '' 4 | hide_table_of_contents: true 5 | sidebar_position: 22 6 | draft: true 7 | keywords: 8 | - leetcode 9 | - study plan 10 | - roadmap 11 | - arrays 12 | --- 13 | 14 | Coming Soon 15 | -------------------------------------------------------------------------------- /roadmap/backtracking.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Backtracking' 3 | description: 'A backtracking algorithm is used to construct a solution recursively by starting with an empty solution and adding solution one by one.' 4 | hide_table_of_contents: true 5 | sidebar_position: 40 6 | keywords: 7 | - leetcode 8 | - study plan 9 | - roadmap 10 | - backtracking 11 | --- 12 | 13 | export const problems = [ { "problemName": "0077. Combinations", "difficulty": "Medium", "leetCodeLink": "https://leetcode.com/problems/combinations", "solutionLink": "../../solutions/0000-0099/combinations-medium" }, { "problemName": "0046. Permutations", "difficulty": "Medium", "leetCodeLink": "https://leetcode.com/problems/permutations", "solutionLink": "../../solutions/0000-0099/permutations-medium" }, { "problemName": "0017. Letter Combinations of a Phone Number", "difficulty": "Medium", "leetCodeLink": "https://leetcode.com/problems/letter-combinations-of-a-phone-number", "solutionLink": "../../solutions/0000-0099/letter-combinations-of-a-phone-number-medium" }, ] 14 | 15 | 21 | -------------------------------------------------------------------------------- /roadmap/binary-search.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Binary Search' 3 | description: '' 4 | hide_table_of_contents: true 5 | sidebar_position: 70 6 | draft: true 7 | keywords: 8 | - leetcode 9 | - study plan 10 | - roadmap 11 | - binary search 12 | --- 13 | 14 | Coming Soon 15 | -------------------------------------------------------------------------------- /roadmap/graph-theory.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Graph Theory' 3 | description: '' 4 | hide_table_of_contents: true 5 | sidebar_position: 70 6 | draft: true 7 | keywords: 8 | - leetcode 9 | - study plan 10 | - roadmap 11 | - graph theory 12 | --- 13 | 14 | Coming Soon 15 | -------------------------------------------------------------------------------- /roadmap/index.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Introduction' 3 | description: 'Collections of LeetCode Problems in different categories' 4 | hide_table_of_contents: true 5 | sidebar_position: 0 6 | keywords: 7 | - leetcode 8 | - road map 9 | - study plan 10 | --- 11 | 12 | Here is the section for group of problems sorted in differnt categories to help you get started in a specific topic or way with your coding journey and not get overwhelmed from the sheer number of problems available in Leetcode. You can find different topics in left side bar or you can also navigate with the list given below. 13 | -------------------------------------------------------------------------------- /roadmap/sliding-windows.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Sliding Windows' 3 | description: '' 4 | hide_table_of_contents: true 5 | sidebar_position: 30 6 | draft: true 7 | keywords: 8 | - leetcode 9 | - study plan 10 | - roadmap 11 | - sliding windows 12 | --- 13 | 14 | Coming Soon 15 | -------------------------------------------------------------------------------- /roadmap/stack.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Stack' 3 | description: '' 4 | hide_table_of_contents: true 5 | sidebar_position: 40 6 | draft: true 7 | keywords: 8 | - leetcode 9 | - study plan 10 | - roadmap 11 | - stack 12 | --- 13 | 14 | Coming Soon 15 | -------------------------------------------------------------------------------- /roadmap/tree.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Tree' 3 | description: '' 4 | hide_table_of_contents: true 5 | sidebar_position: 40 6 | draft: true 7 | keywords: 8 | - leetcode 9 | - study plan 10 | - roadmap 11 | - tree 12 | --- 13 | 14 | Coming Soon 15 | -------------------------------------------------------------------------------- /roadmap/trie.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Trie' 3 | description: '' 4 | hide_table_of_contents: true 5 | sidebar_position: 80 6 | draft: true 7 | keywords: 8 | - leetcode 9 | - study plan 10 | - roadmap 11 | - trie 12 | --- 13 | 14 | Coming Soon 15 | -------------------------------------------------------------------------------- /roadmap/two-pointers.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Two Pointers' 3 | description: '' 4 | hide_table_of_contents: true 5 | sidebar_position: 25 6 | draft: true 7 | keywords: 8 | - leetcode 9 | - study plan 10 | - roadmap 11 | - two pointers 12 | --- 13 | 14 | Coming Soon 15 | -------------------------------------------------------------------------------- /sidebars.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Creating a sidebar enables you to: 3 | - create an ordered group of docs 4 | - render a sidebar for each doc of that group 5 | - provide next/previous navigation 6 | 7 | The sidebars can be generated from the filesystem, or explicitly defined here. 8 | 9 | Create as many sidebars as you want. 10 | */ 11 | 12 | // @ts-check 13 | 14 | /** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ 15 | const sidebars = { 16 | // By default, Docusaurus generates a sidebar from the docs folder structure 17 | tutorialSidebar: [{ type: 'autogenerated', dirName: '.' }], 18 | 19 | // But you can create a sidebar manually 20 | /* 21 | tutorialSidebar: [ 22 | { 23 | type: 'category', 24 | label: 'Tutorial', 25 | items: ['hello'], 26 | }, 27 | ], 28 | */ 29 | }; 30 | 31 | module.exports = sidebars; 32 | -------------------------------------------------------------------------------- /solutions/0000-0099/0067-add-binary-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @DoubleSpicy | https://leetcode.com/problems/add-binary/' 3 | --- 4 | 5 | # 0067 - Add Binary (easy) 6 | 7 | ## Problem Link 8 | 9 | https://leetcode.com/problems/add-binary/ 10 | 11 | ## Problem Statement 12 | 13 | Given two binary strings `a` and `b`, return their sum as a binary string. 14 | 15 | **Example 1:** 16 | 17 | ``` 18 | Input: a = "11", b = "1" 19 | Output: "100" 20 | ``` 21 | 22 | **Example 2:** 23 | 24 | ``` 25 | Input: a = "1010", b = "1011" 26 | Output: "10101" 27 | ``` 28 | 29 | **Example 3:** 30 | 31 | ``` 32 | Input: num = "10", k = 2 33 | Output: "0" 34 | Explanation: Remove all the digits from the number and it is left with nothing which is 0. 35 | ``` 36 | 37 | **Constraints:** 38 | 39 | - $1 <= a.length, b.length <= 10^4$ 40 | - a and b consist only of '0' or '1' characters. 41 | - Each string does not contain leading zeros except for the zero itself. 42 | 43 | ## Approach 1: Adding Digits One By One 44 | 45 | For each digit, start from least significant ones, calculate the sum of digits and the carry. If the value > 1 then carry to the next digit. 46 | 47 | The annoying part of this problem is taking care about index out-of-bound. 48 | 49 | 50 | 51 | ```cpp 52 | class Solution { 53 | public: 54 | string addBinary(string a, string b) { 55 | // preallocate a long string, no copying is needed in iteration. 56 | string ans(max(a.size(), b.size()), '0'); 57 | int i = a.size()-1, j = b.size()-1, k = ans.size()-1, carry = 0; 58 | while(i >= 0 || j >= 0){ 59 | // if all digits are used up for one of the string, give 0 for that part. 60 | int digit = (i >= 0 ? a[i] - '0': 0) + (j >= 0 ? b[j] - '0': 0) + carry; 61 | ans[k] = (digit % 2) + '0'; 62 | carry = digit / 2; 63 | i--; 64 | j--; 65 | k--; 66 | } 67 | if(carry){ 68 | return to_string(carry) + ans; 69 | } 70 | return ans; 71 | } 72 | }; 73 | ``` 74 | -------------------------------------------------------------------------------- /solutions/0000-0099/0077-combinations-medium.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/combinations/' 3 | tags: [Backtracking] 4 | --- 5 | 6 | # 0077 - Combinations (Medium) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/combinations/ 11 | 12 | ## Problem Statement 13 | 14 | Given two integers `n` and `k`, return _all possible combinations of_ `k` _numbers chosen from the range_ `[1, n]`. 15 | 16 | You may return the answer in **any order**. 17 | 18 | **Example 1:** 19 | 20 | ``` 21 | Input: n = 4, k = 2 22 | Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] 23 | Explanation: There are 4 choose 2 = 6 total combinations. 24 | Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination. 25 | ``` 26 | 27 | **Example 2:** 28 | 29 | ``` 30 | Input: n = 1, k = 1 31 | Output: [[1]] 32 | Explanation: There is 1 choose 1 = 1 total combination. 33 | ``` 34 | 35 | **Constraints:** 36 | 37 | - `1 <= n <= 20` 38 | - `1 <= k <= n` 39 | 40 | ## Approach 1: Backtracking 41 | 42 | This question can be solved by standard backtracking. Check out [Backtracking](../../tutorials/basic-topics/backtracking) section for the detailed explanation. 43 | 44 | 45 | 46 | 47 | 48 | ```cpp 49 | class Solution { 50 | public: 51 | vector> combine(int n, int k) { 52 | vector chosen; 53 | vector> ans; 54 | function backtrack = [&](int start) { 55 | if (chosen.size() == k) { 56 | ans.push_back(chosen); 57 | return; 58 | } 59 | for (int i = start; i <= n; i++) { 60 | chosen.push_back(i); 61 | backtrack(i + 1); 62 | chosen.pop_back(); 63 | } 64 | }; 65 | backtrack(1); 66 | return ans; 67 | } 68 | }; 69 | ``` 70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /solutions/0000-0099/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "0000 - 0099", 3 | "position": 2, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/0100-0199/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "0100 - 0199", 3 | "position": 3, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/0200-0299/0204-count-primes.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/count-primes/' 3 | --- 4 | 5 | # 0204 - Count Primes 6 | 7 | ## Problem Link 8 | 9 | https://leetcode.com/problems/count-primes/ 10 | 11 | ## Problem Statement 12 | 13 | Given an integer `n`, return _the number of prime numbers that are strictly less than_ `n`. 14 | 15 | **Example 1:** 16 | 17 | ``` 18 | Input: n = 10 19 | Output: 4 20 | Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7. 21 | ``` 22 | 23 | **Example 2:** 24 | 25 | ``` 26 | Input: n = 0 27 | Output: 0 28 | ``` 29 | 30 | **Example 3:** 31 | 32 | ``` 33 | Input: n = 1 34 | Output: 0 35 | ``` 36 | 37 | **Constraints:** 38 | 39 | - `0 <= n <= 5 * 10^6` 40 | 41 | ## Approach 1: Sieve of Eratosthenes 42 | 43 | See [Sieve of Eratosthenes](../../tutorials/math/number-theory/sieve-of-eratosthenes). 44 | 45 | 46 | 47 | ```cpp 48 | class Solution { 49 | public: 50 | vector seiveOfEratosthenes(const int n) { 51 | vector isPrime(n + 1, true); 52 | isPrime[0] = isPrime[1] = 0; 53 | for (int i = 2; i * i <= n; i++) { 54 | if (isPrime[i]) { 55 | for (int j = i * i; j <= n; j += i) { 56 | isPrime[j] = false; 57 | } 58 | } 59 | } 60 | return isPrime; 61 | } 62 | 63 | int countPrimes(int n) { 64 | if(n < 2) return 0; 65 | vector isPrime = seiveOfEratosthenes(n - 1); 66 | int cnt = 0; 67 | for(int i = 2; i < n; i++) cnt += isPrime[i] == true; 68 | return cnt; 69 | } 70 | }; 71 | ``` 72 | -------------------------------------------------------------------------------- /solutions/0200-0299/0214-shortest-palindrome-hard.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/shortest-palindrome/' 3 | --- 4 | 5 | # 0214 - Shortest Palindrome (Hard) 6 | 7 | ## Problem Link 8 | 9 | https://leetcode.com/problems/shortest-palindrome/ 10 | 11 | ## Problem Statement 12 | 13 | You are given a string `s`. You can convert `s` to a palindrome by adding characters in front of it. 14 | 15 | Return _the shortest palindrome you can find by performing this transformation_. 16 | 17 | **Example 1:** 18 | 19 | ``` 20 | Input: s = "aacecaaa" 21 | Output: "aaacecaaa" 22 | ``` 23 | 24 | **Example 2:** 25 | 26 | ``` 27 | Input: s = "abcd" 28 | Output: "dcbabcd" 29 | ``` 30 | 31 | **Constraints:** 32 | 33 | - `0 <= s.length <= 5 * 10^4` 34 | - `s` consists of lowercase English letters only. 35 | 36 | ## Approach 1: Z Algorithm 37 | 38 | We first concatenate the search pattern and given string with a character that is not in either strings, says $$ $ $$. Hence, we have $$k = s + $ + t$$. Then We built $$Z$$ and iterate $$k$$. If there is a $$i$$ that can satisfy $$Z[i] == n - i$$, then the answer would be $$t'$$+ $$s$$ where $$t'$$ is the first $$n - i$$ characters of $$s$$. 39 | 40 | 41 | 42 | ```cpp 43 | class Solution { 44 | public: 45 | vector z_function(string s) { 46 | int n = (int) s.length(); 47 | vector z(n); 48 | for (int i = 1, l = 0, r = 0; i < n; ++i) { 49 | if (i <= r) 50 | z[i] = min (r - i + 1, z[i - l]); 51 | while (i + z[i] < n && s[z[i]] == s[i + z[i]]) 52 | ++z[i]; 53 | if (i + z[i] - 1 > r) 54 | l = i, r = i + z[i] - 1; 55 | } 56 | return z; 57 | } 58 | 59 | string shortestPalindrome(string s) { 60 | string r(s); 61 | reverse(r.begin(), r.end()); 62 | string k = s + "$" + r; 63 | vector z = z_function(k); 64 | int n = k.size(); 65 | for(int i = 0; i < n; i++) { 66 | if(z[i] == n - i) { 67 | string s2 = s.substr(n - i); 68 | reverse(s2.begin(), s2.end()); 69 | return s2 + s; 70 | } 71 | } 72 | return ""; 73 | } 74 | }; 75 | ``` 76 | -------------------------------------------------------------------------------- /solutions/0200-0299/0263-ugly-number-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @Ishwarendra | https://leetcode.com/problems/ugly-number/' 3 | tags: ['Prime Factor', 'Math'] 4 | --- 5 | 6 | # 0263 - Ugly Number 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/ugly-number/ 11 | 12 | ## Problem Statement 13 | 14 | An **ugly number** is a positive integer whose prime factors are limited to `2`, `3`, and `5`. 15 | 16 | Given an integer `n`, return `true` if `n` is an **_ugly number._** 17 | 18 | **Example 1:** 19 | 20 | ``` 21 | Input: n = 6 22 | Output: true 23 | Explanation: 6 = 2 × 3 24 | ``` 25 | 26 | **Example 2:** 27 | 28 | ``` 29 | Input: n = 1 30 | Output: true 31 | Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. 32 | ``` 33 | 34 | **Example 3:** 35 | 36 | ``` 37 | Input: n = 14 38 | Output: false 39 | Explanation: 14 is not ugly since it includes the prime factor 7. 40 | ``` 41 | 42 | **Constraints:** 43 | 44 | - $-2^{31} \leq n \leq 2^{31} - 1$ 45 | 46 | ## Approach 1: Brute Force 47 | 48 | Remove all power of $2$ from $n$ by dividing it by $2$ until $n$ is no longer divisible by $2$. Repeat the same for $3$ and $5$. If $n$ becomes $1$ then it doesn't have any prime factor other than these three, thus it is an **ugly number**. Otherwise $n$ is not an ugly number. 49 | 50 | 51 | 52 | ```cpp 53 | class Solution { 54 | public: 55 | bool isUgly(int n) { 56 | // Since ugly numbers are positive 57 | if (n <= 0) return false; 58 | 59 | array nums {2, 3, 5}; 60 | 61 | for (int num : nums) { 62 | while (n % num == 0) n /= num; 63 | } 64 | 65 | return n == 1; 66 | } 67 | }; 68 | ``` 69 | 70 | - **Time Complexity:** $O(log(n))$. 71 | - **Space Complexity:** $O(1)$. 72 | -------------------------------------------------------------------------------- /solutions/0200-0299/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "0200 - 0299", 3 | "position": 4, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/0300-0399/0327-count-of-range-sum-hard.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/count-of-range-sum/' 3 | --- 4 | 5 | # 0327 - Count of Range Sum (Hard) 6 | 7 | ## Problem Link 8 | 9 | https://leetcode.com/problems/count-of-range-sum/ 10 | 11 | ## Problem Statement 12 | 13 | Given an integer array `nums` and two integers `lower` and `upper`, return _the number of range sums that lie in_ `[lower, upper]` _inclusive_. 14 | 15 | Range sum `S(i, j)` is defined as the sum of the elements in `nums` between indices `i` and `j` inclusive, where `i <= j`. 16 | 17 | **Example 1:** 18 | 19 | ``` 20 | Input: nums = [-2,5,-1], lower = -2, upper = 2 21 | Output: 3 22 | Explanation: The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2. 23 | ``` 24 | 25 | **Example 2:** 26 | 27 | ``` 28 | Input: nums = [0], lower = 0, upper = 0 29 | Output: 1 30 | ``` 31 | 32 | **Constraints:** 33 | 34 | - `1 <= nums.length <= 10^5` 35 | - `-2^31 <= nums[i] <= 2^31 - 1` 36 | - `-10^5 <= lower <= upper <= 10^5` 37 | - The answer is **guaranteed** to fit in a **32-bit** integer. 38 | 39 | ## Approach 1: Ordered Set 40 | 41 | 42 | 43 | ```cpp 44 | #include 45 | #include 46 | using namespace __gnu_pbds; 47 | 48 | class Solution { 49 | public: 50 | tree, rb_tree_tag, tree_order_statistics_node_update> T; 51 | 52 | // lower <= sum[j] - sum[i] <= upper 53 | // sum[j] - sum[i] >= lower 54 | // sum[j] - sum[i] <= upper 55 | // where i < j 56 | 57 | // given sum[j], find the number of i such that 58 | // 1. i < j 59 | // 2. sum[j] - upper <= sum[i] <= sum[j] - lower 60 | 61 | int countRangeSum(vector& nums, int lower, int upper) { 62 | long long sum = 0, ans = 0; 63 | // normalise as lower <= sum[j] - 0 <= upper 64 | T.insert(0); 65 | for (auto x : nums) { 66 | // prefix sum 67 | sum += x; 68 | // count the range 69 | ans += T.order_of_key(sum - lower + 1) - T.order_of_key(sum - upper); 70 | // update T 71 | T.insert(sum); 72 | } 73 | return ans; 74 | } 75 | }; 76 | ``` 77 | -------------------------------------------------------------------------------- /solutions/0300-0399/0342-power-of-four-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/power-of-four/' 3 | tags: [Math, Bit Manipulation, Recursion] 4 | --- 5 | 6 | # 0342 - Power of Four (Easy) 7 | 8 | ## Problem Statement 9 | 10 | Given an integer `n`, return _true if it is a power of four. Otherwise, return false_. 11 | 12 | An integer `n` is a power of four, if there exists an integer `x` such that `n == 4 ^ x`. 13 | 14 | **Example 1:** 15 | 16 | ``` 17 | Input: n = 16 18 | Output: true 19 | ``` 20 | 21 | **Example 2:** 22 | 23 | ``` 24 | Input: n = 5 25 | Output: false 26 | ``` 27 | 28 | **Example 3:** 29 | 30 | ``` 31 | Input: n = 1 32 | Output: true 33 | ``` 34 | 35 | **Constraints:** 36 | 37 | - `-2^31 <= n <= 2^31 - 1` 38 | 39 | **Follow up:** Could you solve it without loops/recursion? 40 | 41 | ## Approach 1: Binary Search 42 | 43 | 44 | 45 | ```cpp 46 | class Solution { 47 | public: 48 | bool isPowerOfFour(int n) { 49 | // the idea is to use binary search to find x to see if 4 ^ x = n is true or false 50 | int l = 0, r = (int) log(pow(2, 31)) / log(4); 51 | while (l < r) { 52 | // get the middle one 53 | // for even number of elements, take the lower one 54 | int m = l + (r - l) / 2; 55 | // exclude m 56 | if (pow(4, m) < n) l = m + 1; 57 | // include m 58 | else r = m; 59 | } 60 | // check if 4 ^ l is n 61 | // if so, then n is a power of four, otherwise it is not 62 | return pow(4, l) == n; 63 | } 64 | }; 65 | ``` 66 | 67 | ## Approach 2: Bit Manipulation 68 | 69 | 70 | 71 | ```cpp 72 | class Solution { 73 | public: 74 | bool isPowerOfFour(int num) { 75 | // 4: 100 76 | // 16: 10000 77 | // observation: 78 | // count of 1s is 1 and the number of trailing zeros is even 79 | return __builtin_popcount(num) == 1 && // only 1 bit is set 80 | (__builtin_ctz(num) & 1) == 0; // with even trailing zeros 81 | } 82 | }; 83 | ``` 84 | -------------------------------------------------------------------------------- /solutions/0300-0399/0349-intersection-of-two-arrays-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @ganajayant | https://leetcode.com/problems/intersection-of-two-arrays/' 3 | --- 4 | 5 | # 0349 - Intersection of Two Arrays (Easy) 6 | 7 | ## Problem Link 8 | 9 | https://leetcode.com/problems/intersection-of-two-arrays/ 10 | 11 | ## Problem Statement 12 | 13 | Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order. 14 | 15 | **Example 1:** 16 | 17 | ``` 18 | Input: nums1 = [1,2,2,1], nums2 = [2,2] 19 | Output: [2] 20 | ``` 21 | 22 | **Example 2:** 23 | 24 | ``` 25 | Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 26 | Output: [9,4] 27 | ``` 28 | 29 | **Constraints:** 30 | 31 | - `1 <= nums1.length, nums2.length <= 1000` 32 | - `0 <= nums1[i], nums2[i] <= 1000` 33 | 34 | ## Approach 1: HashMap 35 | 36 | 1. Insert all elements from first array into hash table (set). 37 | 38 | 2. for each element i in second array if it is present in our hash table insert into result list & remove that element from our hash table so we again not insert into result. 39 | 40 | 3. return result. 41 | 42 | 43 | 44 | 45 | ```java 46 | class Solution { 47 | public int[] intersection(int[] nums1, int[] nums2) { 48 | HashMap hm = new HashMap<>(); 49 | for (int i : nums1) { 50 | if (hm.containsKey(i)) { 51 | hm.put(i, hm.get(i) + 1); 52 | } else { 53 | hm.put(i, 1); 54 | } 55 | } 56 | LinkedList ll = new LinkedList<>(); 57 | for (int i : nums2) { 58 | if (hm.containsKey(i)) { 59 | if (hm.get(i) >= 1) { 60 | hm.put(i, hm.get(i) - 1); 61 | if (!ll.contains(i)) { 62 | ll.add(i); 63 | } 64 | } 65 | } 66 | } 67 | int ar[] = new int[ll.size()]; 68 | for (int i = 0; i < ar.length; i++) { 69 | ar[i] = ll.get(i); 70 | } 71 | return ar; 72 | } 73 | } 74 | ``` 75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /solutions/0300-0399/0365-water-and-jug-problem-medium.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/water-and-jug-problem' 3 | --- 4 | 5 | # 0365 - Water and Jug Problem (Medium) 6 | 7 | ## Problem Link 8 | 9 | https://leetcode.com/problems/water-and-jug-problem 10 | 11 | ## Problem Statement 12 | 13 | You are given two jugs with capacities `jug1Capacity` and `jug2Capacity` liters. There is an infinite amount of water supply available. Determine whether it is possible to measure exactly `targetCapacity` liters using these two jugs. 14 | 15 | If `targetCapacity` liters of water are measurable, you must have `targetCapacity` liters of water contained **within one or both buckets** by the end. 16 | 17 | Operations allowed: 18 | 19 | - Fill any of the jugs with water. 20 | - Empty any of the jugs. 21 | - Pour water from one jug into another till the other jug is completely full, or the first jug itself is empty. 22 | 23 | **Example 1:** 24 | 25 | ``` 26 | Input: jug1Capacity = 3, jug2Capacity = 5, targetCapacity = 4 27 | Output: true 28 | Explanation: The famous Die Hard example 29 | ``` 30 | 31 | **Example 2:** 32 | 33 | ``` 34 | Input: jug1Capacity = 2, jug2Capacity = 6, targetCapacity = 5 35 | Output: false 36 | ``` 37 | 38 | **Example 3:** 39 | 40 | ``` 41 | Input: jug1Capacity = 1, jug2Capacity = 2, targetCapacity = 3 42 | Output: true 43 | ``` 44 | 45 | **Constraints:** 46 | 47 | - `1 <= jug1Capacity, jug2Capacity, targetCapacity <= 10^6` 48 | 49 | ## Approach 1: Bézout's identity 50 | 51 | It's obvious that it is impossible to measure if the target capacity $$z$$ is greater than the total capacity of jug $$x$$ and jug $$y$$. Otherwise, we can express it as a linear combination of $$x$$ and $$y$$ and check if $$z$$ is a linear combination of $$x$$ and $$y$$. In order to do so, $$z$$ has to be a multiple of the gcd of $$x$$ and $$y$$. 52 | 53 | 54 | 55 | ```cpp 56 | class Solution { 57 | public: 58 | bool canMeasureWater(int x, int y, int z) { 59 | // impossible case 60 | if (x + y < z) return false; 61 | // check if z is a multiple of GCD(x, y) 62 | return z % gcd(x, y) == 0; 63 | } 64 | }; 65 | ``` 66 | -------------------------------------------------------------------------------- /solutions/0300-0399/0383-ransom-note-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/ransom-note/' 3 | tags: [Hash Table, String, Counting] 4 | --- 5 | 6 | # 0383 - Ransom Note (Easy) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/ransom-note/ 11 | 12 | ## Problem Statement 13 | 14 | Given two strings `ransomNote` and `magazine`, return `true`_if_`ransomNote`_can be constructed by using the letters from_`magazine`_and_`false`_otherwise_. 15 | 16 | Each letter in `magazine` can only be used once in `ransomNote`. 17 | 18 | **Example 1:** 19 | 20 | ``` 21 | Input: ransomNote = "a", magazine = "b" 22 | Output: false 23 | ``` 24 | 25 | **Example 2:** 26 | 27 | ``` 28 | Input: ransomNote = "aa", magazine = "ab" 29 | Output: false 30 | ``` 31 | 32 | **Example 3:** 33 | 34 | ``` 35 | Input: ransomNote = "aa", magazine = "aab" 36 | Output: true 37 | ``` 38 | 39 | **Constraints:** 40 | 41 | - `1 <= ransomNote.length, magazine.length <= 10^5` 42 | - `ransomNote` and `magazine` consist of lowercase English letters. 43 | 44 | ## Approach 1: Counting 45 | 46 | 47 | 48 | ```cpp 49 | class Solution { 50 | public: 51 | bool canConstruct(string ransomNote, string magazine) { 52 | // you can also use unordered_map m; here 53 | // since we're just dealing with lowercase English letters, 54 | // we can just use an array of length 26 to store the frequency of them 55 | int m[26] = {0}; 56 | // count each character 57 | for(char c : magazine) m[c - 'a']++; 58 | // check if it can be found in m and substract by 1 59 | for(char c : ransomNote) { 60 | // if it is less than 0, it means it cannot be constructed from magazine 61 | if(--m[c - 'a'] < 0) return false; 62 | } 63 | return true; 64 | } 65 | }; 66 | ``` 67 | -------------------------------------------------------------------------------- /solutions/0300-0399/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "0300 - 0399", 3 | "position": 5, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/0400-0499/0421-maximum-xor-of-two-numbers-in-an-array.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @wkw | https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/ 4 | --- 5 | 6 | # 0421 - Maximum XOR of Two Numbers in an Array 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/ 11 | 12 | ## Problem Statement 13 | 14 | Given an integer array `nums`, return _the maximum result of_ `nums[i] XOR nums[j]`, where `0 <= i <= j < n`. 15 | 16 | **Example 1:** 17 | 18 | ``` 19 | Input: nums = [3,10,5,25,2,8] 20 | Output: 28 21 | Explanation: The maximum result is 5 XOR 25 = 28. 22 | ``` 23 | 24 | **Example 2:** 25 | 26 | ``` 27 | Input: nums = [14,70,53,83,49,91,36,80,92,51,66,70] 28 | Output: 127 29 | ``` 30 | 31 | **Constraints:** 32 | 33 | - `1 <= nums.length <= 2 * 10^5` 34 | - `0 <= nums[i] <= 2^31 - 1` 35 | 36 | ## Approach 1: Bit Masking + Set + Two Sum Idea 37 | 38 | In order to maximise the answer, we can construct the max XOR from the leftmost bit. The best answer is always all bits set. Hence, we can check bit by bit. We need to find two numbers such that its XOR starts with `1000...000`, then find `1100..000,` then `1110...000`, `1111...000` and till `1111...111`. We build each mask to extract the prefix of length `(L - i)` in binary representation of each number by using `num & mask`. Then apply Two Sum idea, if the complement exists in the set, then we can update answer. 39 | 40 | ```cpp 41 | class Solution { 42 | public: 43 | int findMaximumXOR(vector& nums) { 44 | int ans = 0, mask = 0; 45 | for(int i = 31; i >= 0; i--){ 46 | unordered_set s; 47 | mask |= (1 << i); 48 | for (auto x : nums) s.insert(mask & x); 49 | int best = ans | (1 << i); 50 | for(auto pref : s){ 51 | if(s.find(pref ^ best) != s.end()){ 52 | ans = best; 53 | break; 54 | } 55 | } 56 | } 57 | return ans; 58 | } 59 | }; 60 | ``` 61 | -------------------------------------------------------------------------------- /solutions/0400-0499/0465-optimal-account-balancing-hard.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @TBC | https://leetcode.com/problems/optimal-account-balancing/' 3 | --- 4 | 5 | # 0465 - Optimal Account Balancing (Hard) 6 | 7 | ## Problem Link 8 | 9 | https://leetcode.com/problems/optimal-account-balancing/ 10 | 11 | ## Problem Statement 12 | 13 | You are given an array of transactions `transactions` where `transactions[i] = [fromi, toi, amounti]` indicates that the person with `ID = fromi` gave `amounti $` to the person with `ID = toi`. 14 | 15 | Return _the minimum number of transactions required to settle the debt_. 16 | 17 | **Example 1:** 18 | 19 | ``` 20 | Input: transactions = [[0,1,10],[2,0,5]] 21 | Output: 2 22 | Explanation: 23 | Person #0 gave person #1 $10. 24 | Person #2 gave person #0 $5. 25 | Two transactions are needed. One way to settle the debt is person #1 pays person #0 and #2 $5 each. 26 | ``` 27 | 28 | **Example 2:** 29 | 30 | ``` 31 | Input: transactions = [[0,1,10],[1,0,1],[1,2,5],[2,0,5]] 32 | Output: 1 33 | Explanation: 34 | Person #0 gave person #1 $10. 35 | Person #1 gave person #0 $1. 36 | Person #1 gave person #2 $5. 37 | Person #2 gave person #0 $5. 38 | Therefore, person #1 only need to give person #0 $4, and all debt is settled. 39 | ``` 40 | 41 | **Constraints:** 42 | 43 | - `1 <= transactions.length <= 8` 44 | - `transactions[i].length == 3` 45 | - `0 <= fromi, toi < 12` 46 | - `fromi != toi` 47 | - `1 <= amounti <= 100` 48 | 49 | ## Approach 1: TBC 50 | -------------------------------------------------------------------------------- /solutions/0400-0499/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "0400 - 0499", 3 | "position": 6, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/0500-0599/0540-single-element-in-a-sorted-array-medium.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/single-element-in-a-sorted-array/' 3 | tags: [Array, Binary Search] 4 | --- 5 | 6 | # 0540 - Single Element in a Sorted Array (Medium) 7 | 8 | ## Problem Statement 9 | 10 | You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. 11 | 12 | Return _the single element that appears only once_. 13 | 14 | Your solution must run in `O(log n)` time and `O(1)` space. 15 | 16 | **Example 1:** 17 | 18 | ``` 19 | Input: nums = [1,1,2,3,3,4,4,8,8] 20 | Output: 2 21 | ``` 22 | 23 | **Example 2:** 24 | 25 | ``` 26 | Input: nums = [3,3,7,7,10,11,11] 27 | Output: 10 28 | ``` 29 | 30 | **Constraints:** 31 | 32 | - `1 <= nums.length <= 1e5` 33 | - `0 <= nums[i] <= 1e5` 34 | 35 | ## Approach 1: Binary Search 36 | 37 | 38 | 39 | ```cpp 40 | class Solution { 41 | public: 42 | int singleNonDuplicate(vector& nums) { 43 | // init possible boundary 44 | int n = nums.size(), l = 0, r = n - 1; 45 | while (l < r) { 46 | // get the middle one 47 | // for even number of elements, take the lower one 48 | int m = l + (r - l) / 2; 49 | // handle case like [3,3,7,7,10,11,11] 50 | m -= m & 1; 51 | // exclude m 52 | if (nums[m] == nums[m + 1]) l = m + 2; 53 | // include m 54 | else r = m; 55 | } 56 | return nums[l]; 57 | } 58 | }; 59 | ``` 60 | -------------------------------------------------------------------------------- /solutions/0500-0599/0560-subarray-sum-equals-k-medium.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw, @ganajayant | https://leetcode.com/problems/subarray-sum-equals-k/' 3 | --- 4 | 5 | # 0560 - Subarray Sum Equals K (Medium) 6 | 7 | ## Problem Link 8 | 9 | https://leetcode.com/problems/subarray-sum-equals-k/ 10 | 11 | ## Problem Statement 12 | 13 | Given an array of integers `nums` and an integer `k`, return _the total number of continuous subarrays whose sum equals to `k`_. 14 | 15 | **Example 1:** 16 | 17 | ``` 18 | Input: nums = [1,1,1], k = 2 19 | Output: 2 20 | ``` 21 | 22 | **Example 2:** 23 | 24 | ``` 25 | Input: nums = [1,2,3], k = 3 26 | Output: 2 27 | ``` 28 | 29 | **Constraints:** 30 | 31 | - `1 <= nums.length <= 2 * 10^4` 32 | - `-1000 <= nums[i] <= 1000` 33 | - `-10^7 <= k <= 10^7` 34 | 35 | ## Approach 1: Hash Map 36 | 37 | We use hash map to store the cumulative sum $$sum[i]$$ up to index $$i$$. If $$sum[i] - sum[j] = k$$, then it means the sum between indices $$i$$ and $$j$$ is $$k$$. Therefore, we store the cumulative sum, search for $$sum - k$$ in the hash map and add the occurrences if it is found to the answer. 38 | 39 | 40 | 41 | 42 | 43 | ```cpp 44 | class Solution { 45 | public: 46 | int subarraySum(vector& nums, int k) { 47 | unordered_map m; 48 | m[0]++; 49 | int sum = 0, ans = 0; 50 | for (int i = 0; i < nums.size(); i++) { 51 | sum += nums[i]; 52 | ans += m[sum - k]; 53 | m[sum]++; 54 | } 55 | return ans; 56 | } 57 | }; 58 | ``` 59 | 60 | 61 | 62 | 63 | 64 | ```java 65 | class Solution { 66 | public int subarraySum(int[] nums, int k) { 67 | int sum = 0, result = 0; 68 | HashMap preSum = new HashMap<>(); 69 | preSum.put(0, 1); 70 | for (int i = 0; i < nums.length; i++) { 71 | sum += nums[i]; 72 | if (preSum.containsKey(sum - k)) { 73 | result += preSum.get(sum - k); 74 | } 75 | preSum.put(sum, preSum.getOrDefault(sum, 0) + 1); 76 | } 77 | return result; 78 | } 79 | } 80 | ``` 81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /solutions/0500-0599/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "0500 - 0599", 3 | "position": 7, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/0600-0699/0659-split-array-into-consecutive-subsequences-medium.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @TBC | https://leetcode.com/problems/split-array-into-consecutive-subsequences/' 3 | draft: 'true' 4 | tags: [Array, Hash Table, Greedy, Heap (Priority Queue)] 5 | --- 6 | 7 | # 0659 - Split Array into Consecutive Subsequences (Medium) 8 | 9 | ## Problem Statement 10 | 11 | You are given an integer array `nums` that is **sorted in non-decreasing order**. 12 | 13 | Determine if it is possible to split `nums` into **one or more subsequences** such that **both** of the following conditions are true: 14 | 15 | - Each subsequence is a **consecutive increasing sequence** (i.e. each integer is **exactly one** more than the previous integer). 16 | - All subsequences have a length of `3`**or more**. 17 | 18 | Return `true`_if you can split_`nums`_according to the above conditions, or_`false`_otherwise_. 19 | 20 | A **subsequence** of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., `[1,3,5]` is a subsequence of `[1,2,3,4,5]` while `[1,3,2]` is not). 21 | 22 | **Example 1:** 23 | 24 | ``` 25 | Input: nums = [1,2,3,3,4,5] 26 | Output: true 27 | Explanation: nums can be split into the following subsequences: 28 | [1,2,3,3,4,5] --> 1, 2, 3 29 | [1,2,3,3,4,5] --> 3, 4, 5 30 | ``` 31 | 32 | **Example 2:** 33 | 34 | ``` 35 | Input: nums = [1,2,3,3,4,4,5,5] 36 | Output: true 37 | Explanation: nums can be split into the following subsequences: 38 | [1,2,3,3,4,4,5,5] --> 1, 2, 3, 4, 5 39 | [1,2,3,3,4,4,5,5] --> 3, 4, 5 40 | ``` 41 | 42 | **Example 3:** 43 | 44 | ``` 45 | Input: nums = [1,2,3,4,4,5] 46 | Output: false 47 | Explanation: It is impossible to split nums into consecutive increasing subsequences of length 3 or more. 48 | ``` 49 | 50 | **Constraints:** 51 | 52 | - `1 <= nums.length <= 10^4` 53 | - `-1000 <= nums[i] <= 1000` 54 | - `nums` is sorted in **non-decreasing** order. 55 | 56 | ## Approach 1: TBC 57 | 58 | 59 | -------------------------------------------------------------------------------- /solutions/0600-0699/0680-valid-palindrome-ii-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/valid-palindrome-ii/' 3 | --- 4 | 5 | # 0680 - Valid Palindrome II (Easy) 6 | 7 | ## Problem Link 8 | 9 | https://leetcode.com/problems/valid-palindrome-ii 10 | 11 | ## Problem Statement 12 | 13 | Given a string `s`, return `true` _if the_ `s` _can be palindrome after deleting **at most one** character from it_. 14 | 15 | **Example 1:** 16 | 17 | ``` 18 | Input: s = "aba" 19 | Output: true 20 | ``` 21 | 22 | **Example 2:** 23 | 24 | ``` 25 | Input: s = "abca" 26 | Output: true 27 | Explanation: You could delete the character 'c'. 28 | ``` 29 | 30 | **Example 3:** 31 | 32 | ``` 33 | Input: s = "abc" 34 | Output: false 35 | ``` 36 | 37 | **Constraints:** 38 | 39 | - `1 <= s.length <= 10^5` 40 | - `s` consists of lowercase English letters. 41 | 42 | ## Approach 1: Brute Force 43 | 44 | To check if a string is a palindrome, we can use two pointers to compare the character at pointer $$i$$ and that at pointer $$j$$. If they are not same, then it means it is not a palindrome. However, this problem allows us to delete at most one character from it. Therefore, we do the same way. If there is a difference, that means we can potentially delete the one at pointer $$i$$ or the one at pointer $$j$$. We try both case to see if it is possible to form a palindrome. 45 | 46 | 47 | 48 | ```cpp 49 | class Solution { 50 | public: 51 | // check palindrome with target range 52 | bool palindromeWithRange(string s, int i, int j) { 53 | while (i < j) { 54 | if (s[i] != s[j]) return false; 55 | i++, j--; 56 | } 57 | return true; 58 | } 59 | 60 | bool validPalindrome(string s) { 61 | int n = s.size(), i = 0, j = n - 1; 62 | while (i < j) { 63 | // not same -> potentially delete s[i] or s[j] 64 | if (s[i] != s[j]) { 65 | // try both case 66 | return palindromeWithRange(s, i, j - 1) || palindromeWithRange(s, i + 1, j); 67 | } 68 | i++, j--; 69 | } 70 | return true; 71 | } 72 | }; 73 | ``` 74 | -------------------------------------------------------------------------------- /solutions/0600-0699/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "0600 - 0699", 3 | "position": 8, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/0700-0799/0713-subarray-product-less-than-k-medium.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/subarray-product-less-than-k/' 3 | tags: [Array, Sliding Window] 4 | --- 5 | 6 | # 0713 - Subarray Product Less Than K (Medium) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/subarray-product-less-than-k/ 11 | 12 | ## Problem Statement 13 | 14 | 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`. 15 | 16 | **Example 1:** 17 | 18 | ``` 19 | Input: nums = [10,5,2,6], k = 100 20 | Output: 8 21 | Explanation: The 8 subarrays that have product less than 100 are: 22 | [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6] 23 | Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k. 24 | ``` 25 | 26 | **Example 2:** 27 | 28 | ``` 29 | Input: nums = [1,2,3], k = 0 30 | Output: 0 31 | ``` 32 | 33 | **Constraints:** 34 | 35 | - `1 <= nums.length <= 3 * 10^4` 36 | - `1 <= nums[i] <= 1000` 37 | - `0 <= k <= 10^6` 38 | 39 | ## Approach 1: Sliding Window 40 | 41 | 42 | 43 | 44 | 45 | ```cpp 46 | class Solution { 47 | public: 48 | int numSubarrayProductLessThanK(vector& nums, int k) { 49 | // edge case 50 | if (k <= 1) return 0; 51 | int n = nums.size(), p = 1, ans = 0, i = 0; 52 | // standard sliding window 53 | for (int j = 0; j < n; j++){ 54 | // step 1: expand the window 55 | p *= nums[j]; 56 | // step 2: shrink the window if applicable 57 | while (p >= k) p /= nums[i++]; 58 | // step 3: add the window size to answer 59 | ans += j - i + 1; 60 | } 61 | return ans; 62 | } 63 | }; 64 | ``` 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /solutions/0700-0799/0744-find-smallest-letter-greater-than-target-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @wkw | https://leetcode.com/problems/find-smallest-letter-greater-than-target 4 | --- 5 | 6 | # 0744 - Find Smallest Letter Greater Than Target (Easy) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/find-smallest-letter-greater-than-target 11 | 12 | ## Problem Statement 13 | 14 | Given a characters array `letters` that is sorted in **non-decreasing** order and a character `target`, return _the smallest character in the array that is larger than_ `target`. 15 | 16 | **Note** that the letters wrap around. 17 | 18 | - For example, if `target == 'z'` and `letters == ['a', 'b']`, the answer is `'a'`. 19 | 20 | **Example 1:** 21 | 22 | ``` 23 | Input: letters = ["c","f","j"], target = "a" 24 | Output: "c" 25 | ``` 26 | 27 | **Example 2:** 28 | 29 | ``` 30 | Input: letters = ["c","f","j"], target = "c" 31 | Output: "f" 32 | ``` 33 | 34 | **Example 3:** 35 | 36 | ``` 37 | Input: letters = ["c","f","j"], target = "d" 38 | Output: "f" 39 | ``` 40 | 41 | **Constraints:** 42 | 43 | - `2 <= letters.length <= 10^4` 44 | - `letters[i]` is a lowercase English letter. 45 | - `letters` is sorted in **non-decreasing** order. 46 | - `letters` contains at least two different characters. 47 | - `target` is a lowercase English letter. 48 | 49 | ## Approach 1: Binary Search 50 | 51 | :::info Prerequisite 52 | 53 | - [Binary Search](../../tutorials/basic-topics/binary-search) 54 | 55 | ::: 56 | 57 | 58 | 59 | ```cpp 60 | class Solution { 61 | public: 62 | char nextGreatestLetter(vector& letters, char target) { 63 | // init possible range 64 | int l = 0, r = letters.size() - 1; 65 | while (l < r) { 66 | int m = l + (r - l) / 2; 67 | // exclude m 68 | if (target >= letters[m]) l = m + 1; 69 | // include m 70 | else r = m; 71 | } 72 | // handle letter wrap case 73 | return letters[l] > target ? letters[l] : letters[0]; 74 | } 75 | }; 76 | ``` 77 | -------------------------------------------------------------------------------- /solutions/0700-0799/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "0700 - 0799", 3 | "position": 9, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/0800-0899/0852-peak-index-in-a-mountain-array-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @wingkowng | https://leetcode.com/problems/peak-index-in-a-mountain-array/ 4 | --- 5 | 6 | # 0852 - Peak Index in a Mountain Array (Easy) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/peak-index-in-a-mountain-array/ 11 | 12 | ## Problem Statement 13 | 14 | Let's call an array `arr` a **mountain** if the following properties hold: 15 | 16 | - `arr.length >= 3` 17 | - There exists some `i` with `0 < i < arr.length - 1` such that: 18 | - `arr[0] < arr[1] < ... arr[i-1] < arr[i]` 19 | - `arr[i] > arr[i+1] > ... > arr[arr.length - 1]` 20 | 21 | Given an integer array `arr` that is **guaranteed** to be a mountain, return any `i` such that `arr[0] < arr[1] < ... arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`. 22 | 23 | **Example 1:** 24 | 25 | ``` 26 | Input: arr = [0,1,0] 27 | Output: 1 28 | ``` 29 | 30 | **Example 2:** 31 | 32 | ``` 33 | Input: arr = [0,2,1,0] 34 | Output: 1 35 | ``` 36 | 37 | **Example 3:** 38 | 39 | ``` 40 | Input: arr = [0,10,5,2] 41 | Output: 1 42 | ``` 43 | 44 | **Constraints:** 45 | 46 | - `3 <= arr.length <= 10^4` 47 | - `0 <= arr[i] <= 10^6` 48 | - `arr` is **guaranteed** to be a mountain array. 49 | 50 | **Follow up:** Finding the `O(n)` is straightforward, could you find an `O(log(n))` solution?\ 51 | 52 | ## Approach 1: Binary Search 53 | 54 | :::info Prerequisite 55 | 56 | - [Binary Search](../../tutorials/basic-topics/binary-search) 57 | 58 | ::: 59 | 60 | 61 | 62 | ```cpp 63 | class Solution { 64 | public: 65 | int peakIndexInMountainArray(vector& arr) { 66 | // arr[i] < arr[i + 1] 67 | // [T, T, T, .., T, F, F, F, .., F] 68 | int l = 0, r = arr.size() - 1; 69 | while (l < r) { 70 | int m = l + (r - l) / 2; 71 | if (arr[m] < arr[m + 1]) l = m + 1; 72 | else r = m; 73 | } 74 | return l; 75 | } 76 | }; 77 | ``` 78 | -------------------------------------------------------------------------------- /solutions/0800-0899/0869-reordered-power-of-2-medium.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/reordered-power-of-2/' 3 | tags: [Math, Sorting, Counting, Enumeration] 4 | --- 5 | 6 | # 0869 - Reordered Power of 2 (Medium) 7 | 8 | ## Problem Statement 9 | 10 | You are given an integer `n`. We reorder the digits in any order (including the original order) such that the leading digit is not zero. 11 | 12 | Return `true` _if and only if we can do this so that the resulting number is a power of two_. 13 | 14 | **Example 1:** 15 | 16 | ``` 17 | Input: n = 1 18 | Output: true 19 | ``` 20 | 21 | **Example 2:** 22 | 23 | ``` 24 | Input: n = 10 25 | Output: false 26 | ``` 27 | 28 | **Constraints:** 29 | 30 | - `1 <= n <= 10^9` 31 | 32 | ## Approach 1: Sorting 33 | 34 | 35 | 36 | ```cpp 37 | class Solution { 38 | public: 39 | string sortStr(int n) { 40 | // since the input is an integer, 41 | // we convert it to a string first 42 | string t = to_string(n); 43 | // use STL to sort 44 | sort(t.begin(), t.end()); 45 | // return the string 46 | return t; 47 | } 48 | 49 | // the idea is to sort `n` and compare all sorted power of two 50 | // if they are matched, then it means they can be reordered to each other 51 | bool reorderedPowerOf2(int n) { 52 | // since the sorted string of n is always same 53 | // so we convert it here instead of doing it in the loop 54 | string s = sortStr(n); 55 | for (int i = 0; i < 30; i++) { 56 | // power of 2 = 1 << i 57 | // we sort each power of 2 string 58 | string t = sortStr(1 << i); 59 | // and compare with `s` 60 | // if they are matched, then return true 61 | if (s == t) return true; 62 | } 63 | // otherwise it is not possible to reorder to a power of 2 64 | return false; 65 | } 66 | }; 67 | ``` 68 | -------------------------------------------------------------------------------- /solutions/0800-0899/0876-middle-of-the-linked-list-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/middle-of-the-linked-list/description/' 3 | tags: [Linked List, Two Pointers] 4 | --- 5 | 6 | # 0876 - Middle of the Linked List (Easy) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/middle-of-the-linked-list/description/ 11 | 12 | ## Problem Statement 13 | 14 | Given the `head` of a singly linked list, return _the middle node of the linked list_. 15 | 16 | If there are two middle nodes, return **the second middle** node. 17 | 18 | **Example 1:** 19 | 20 | ``` 21 | Input: head = [1,2,3,4,5] 22 | Output: [3,4,5] 23 | Explanation: The middle node of the list is node 3. 24 | ``` 25 | 26 | **Example 2:** 27 | 28 | ``` 29 | Input: head = [1,2,3,4,5,6] 30 | Output: [4,5,6] 31 | Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one. 32 | ``` 33 | 34 | **Constraints:** 35 | 36 | - The number of nodes in the list is in the range `[1, 100]`. 37 | - `1 <= Node.val <= 100` 38 | 39 | ## Approach 1: Fast and Slow Pointer 40 | 41 | Classic Fast and Slow Pointer question 42 | 43 | - Time Complexity: $O(N)$ where $N$ is the number of nodes 44 | - Space Complexity: $O(1)$ 45 | 46 | 47 | 48 | 49 | 50 | ```cpp 51 | /** 52 | * Definition for singly-linked list. 53 | * struct ListNode { 54 | * int val; 55 | * ListNode *next; 56 | * ListNode() : val(0), next(nullptr) {} 57 | * ListNode(int x) : val(x), next(nullptr) {} 58 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 59 | * }; 60 | */ 61 | class Solution { 62 | public: 63 | ListNode* middleNode(ListNode* head) { 64 | // fast & slow pointer 65 | // slow moves 1 step 66 | // fast moves 2 steps 67 | // 1 -> 2 -> 3 -> 4 -> 5 68 | // slow : 1 -> 2 -> 3 69 | // fast : 1 -> 3 -> 5 70 | // when fast reaches the end, slow will be the middle 71 | ListNode* slow = head; 72 | ListNode* fast = head; 73 | while (fast != NULL && fast->next != NULL) { 74 | slow = slow->next; 75 | fast = fast->next->next; 76 | } 77 | return slow; 78 | } 79 | }; 80 | ``` 81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /solutions/0800-0899/0896-monotonic-array-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/monotonic-array/' 3 | tags: [Array] 4 | --- 5 | 6 | # 0896 - Monotonic Array (Easy) 7 | 8 | ## Problem Statement 9 | 10 | An array is **monotonic** if it is either monotone increasing or monotone decreasing. 11 | 12 | An array `nums` is monotone increasing if for all `i <= j`, `nums[i] <= nums[j]`. An array `nums` is monotone decreasing if for all `i <= j`, `nums[i] >= nums[j]`. 13 | 14 | Given an integer array `nums`, return `true`_if the given array is monotonic, or_`false`_otherwise_. 15 | 16 | **Example 1:** 17 | 18 | ``` 19 | Input: nums = [1,2,2,3] 20 | Output: true 21 | ``` 22 | 23 | **Example 2:** 24 | 25 | ``` 26 | Input: nums = [6,5,4,4] 27 | Output: true 28 | ``` 29 | 30 | **Example 3:** 31 | 32 | ``` 33 | Input: nums = [1,3,2] 34 | Output: false 35 | ``` 36 | 37 | **Constraints:** 38 | 39 | - `1 <= nums.length <= 10^5` 40 | - `-10^5 <= nums[i] <= 10^5` 41 | 42 | ## Approach 1: Two Loops 43 | 44 | 45 | 46 | ```cpp 47 | class Solution { 48 | public: 49 | bool isMonotonic(vector& nums) { 50 | int n = nums.size(), ok = 1; 51 | // check for monotone increasing 52 | for (int i = 1 ; i < n; i++) ok &= nums[i - 1] <= nums[i]; 53 | // if it is monotone increasing, return true 54 | if (ok) return true; 55 | // reset ok 56 | ok = 1; 57 | // check for monotone decreasing 58 | for (int i = n - 2; i >= 0; i--) ok &= nums[i] >= nums[i + 1]; 59 | // return the answer 60 | return ok; 61 | } 62 | }; 63 | ``` 64 | 65 | ## Approach 2: One Pass 66 | 67 | 68 | 69 | ```cpp 70 | class Solution { 71 | public: 72 | bool isMonotonic(vector& nums) { 73 | int n = nums.size(), inc = 1, dec = 1; 74 | for (int i = 1 ; i < n; i++) { 75 | // check for monotone increasing 76 | inc &= nums[i - 1] <= nums[i]; 77 | // check for monotone decreasing 78 | dec &= nums[i - 1] >= nums[i]; 79 | } 80 | // the given is monotonic if either one is true 81 | return inc || dec; 82 | } 83 | }; 84 | ``` 85 | -------------------------------------------------------------------------------- /solutions/0800-0899/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "0800 - 0899", 3 | "position": 10, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/0900-0999/0946-validate-stack-sequences-medium.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/validate-stack-sequences/' 3 | --- 4 | 5 | # 0946 - Validate Stack Sequences (Medium) 6 | 7 | ## Problem Link 8 | 9 | https://leetcode.com/problems/validate-stack-sequences/ 10 | 11 | ## Problem Statement 12 | 13 | Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._ 14 | 15 | **Example 1:** 16 | 17 | ``` 18 | Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1] 19 | Output: true 20 | Explanation: We might do the following sequence: 21 | push(1), push(2), push(3), push(4), 22 | pop() -> 4, 23 | push(5), 24 | pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 25 | ``` 26 | 27 | **Example 2:** 28 | 29 | ``` 30 | Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2] 31 | Output: false 32 | Explanation: 1 cannot be popped before 2. 33 | ``` 34 | 35 | **Constraints:** 36 | 37 | - `1 <= pushed.length <= 1000` 38 | - `0 <= pushed[i] <= 1000` 39 | - All the elements of `pushed` are **unique**. 40 | - `popped.length == pushed.length` 41 | - `popped` is a permutation of `pushed`. 42 | 43 | ## Approach 1: Simulation 44 | 45 | We use stack to simulate. For each item in $$pushed$$, we push it to the stack. If the top element of the stack matches the target element in $$popped$$, we pop that and increase the pointer in $$popped$$. At the end, return true if the stack is empty, return false if not. 46 | 47 | 48 | 49 | ```cpp 50 | class Solution { 51 | public: 52 | bool validateStackSequences(vector& pushed, vector& popped) { 53 | stack s; 54 | for (auto i = 0, j = 0; i < pushed.size(); i++) { 55 | // push each item 56 | s.push(pushed[i]); 57 | // greedily pop from the stack 58 | // increase the pointer in popped 59 | while (!s.empty() && s.top() == popped[j]) s.pop(), j++; 60 | } 61 | // if there is no element in the stack, return true 62 | // else false 63 | return s.empty(); 64 | } 65 | }; 66 | ``` 67 | -------------------------------------------------------------------------------- /solutions/0900-0999/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "0900 - 0999", 3 | "position": 11, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/1000-1099/1004-max-consecutive-ones-iii-medium.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw| https://leetcode.com/problems/max-consecutive-ones-iii/' 3 | --- 4 | 5 | # 1004 - Max Consecutive Ones III (Medium) 6 | 7 | ## Problem Link 8 | 9 | https://leetcode.com/problems/max-consecutive-ones-iii/ 10 | 11 | ## Problem Statement 12 | 13 | Given a binary array `nums` and an integer `k`, return _the maximum number of consecutive_ `1`_'s in the array if you can flip at most_ `k` `0`'s. 14 | 15 | **Example 1:** 16 | 17 | ``` 18 | Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2 19 | Output: 6 20 | Explanation: [1,1,1,0,0,1,1,1,1,1,1] 21 | Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. 22 | ``` 23 | 24 | **Example 2:** 25 | 26 | ``` 27 | Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3 28 | Output: 10 29 | Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1] 30 | Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. 31 | ``` 32 | 33 | **Constraints:** 34 | 35 | - `1 <= nums.length <= 10^5` 36 | - `nums[i]` is either `0` or `1`. 37 | - `0 <= k <= nums.length` 38 | 39 | ## Approach 1: Sliding Window 40 | 41 | We are looking for the longest subarray with $$k$$ zeros. We can use standard sliding windows to solve it. 42 | 43 | 44 | 45 | ```cpp 46 | class Solution { 47 | public: 48 | int longestOnes(vector& nums, int k) { 49 | // pointer i = window starting point 50 | // pointer j = window ending point 51 | int n = nums.size(), ans = 0, i = 0, j = 0; 52 | while (j < n) { 53 | // if it is 0, then decrease k by 1 54 | if (nums[j] == 0) k -= 1; 55 | // k < 0 means the window includes k zeros 56 | if (k < 0) { 57 | // if the starting point of the window is 0, 58 | // then add 1 to k to reduce the window size by 1 59 | if (nums[i] == 0) k++; 60 | // move pointer i 61 | i++; 62 | } 63 | // move pointer j 64 | j++; 65 | } 66 | return j - i; 67 | } 68 | };c 69 | ``` 70 | -------------------------------------------------------------------------------- /solutions/1000-1099/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "1000 - 1099", 3 | "position": 12, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/1100-1199/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "1100 - 1199", 3 | "position": 14, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/1200-1299/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "1200 - 1299", 3 | "position": 15, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/1300-1399/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "1300 - 1399", 3 | "position": 16, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/1400-1499/1460-make-two-arrays-equal-by-reversing-subarrays-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/make-two-arrays-equal-by-reversing-subarrays/' 3 | tags: [Array, Hash Table, Sorting] 4 | --- 5 | 6 | # 1460 - Make Two Arrays Equal by Reversing Subarrays (Easy) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/make-two-arrays-equal-by-reversing-subarrays/ 11 | 12 | ## Problem Statement 13 | 14 | You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps. 15 | 16 | Return `true` _if you can make_`arr`_equal to_`target`_or_`false`_otherwise_. 17 | 18 | **Example 1:** 19 | 20 | ``` 21 | Input: target = [1,2,3,4], arr = [2,4,1,3] 22 | Output: true 23 | Explanation: You can follow the next steps to convert arr to target: 24 | 1- Reverse subarray [2,4,1], arr becomes [1,4,2,3] 25 | 2- Reverse subarray [4,2], arr becomes [1,2,4,3] 26 | 3- Reverse subarray [4,3], arr becomes [1,2,3,4] 27 | There are multiple ways to convert arr to target, this is not the only way to do so. 28 | ``` 29 | 30 | **Example 2:** 31 | 32 | ``` 33 | Input: target = [7], arr = [7] 34 | Output: true 35 | Explanation: arr is equal to target without any reverses. 36 | ``` 37 | 38 | **Example 3:** 39 | 40 | ``` 41 | Input: target = [3,7,9], arr = [3,7,11] 42 | Output: false 43 | Explanation: arr does not have value 9 and it can never be converted to target. 44 | ``` 45 | 46 | **Constraints:** 47 | 48 | - `target.length == arr.length` 49 | - `1 <= target.length <= 1000` 50 | - `1 <= target[i] <= 1000` 51 | - `1 <= arr[i] <= 1000` 52 | 53 | ## Approach 1: Sorting 54 | 55 | - Time Complexity: $O(n log n)$ 56 | - Space Complexity: $O(log n)$ 57 | 58 | 59 | 60 | 61 | 62 | ```cpp 63 | class Solution: 64 | def canBeEqual(self, target: List[int], arr: List[int]) -> bool: 65 | return sorted(target) == sorted(arr) 66 | ``` 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /solutions/1400-1499/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "1400 - 1499", 3 | "position": 17, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/1500-1599/1510-stone-game-iv-hard.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/stone-game-iv/' 3 | --- 4 | 5 | # 1510 - Stone Game IV (Hard) 6 | 7 | ## Problem Link 8 | 9 | https://leetcode.com/problems/stone-game-iv/ 10 | 11 | ## Problem Statement 12 | 13 | Alice and Bob take turns playing a game, with Alice starting first. 14 | 15 | Initially, there are `n` stones in a pile. On each player's turn, that player makes a _move_ consisting of removing **any** non-zero **square number** of stones in the pile. 16 | 17 | Also, if a player cannot make a move, he/she loses the game. 18 | 19 | Given a positive integer `n`, return `true` if and only if Alice wins the game otherwise return `false`, assuming both players play optimally. 20 | 21 | **Example 1:** 22 | 23 | ``` 24 | Input: n = 1 25 | Output: true 26 | Explanation: Alice can remove 1 stone winning the game because Bob doesn't have any moves. 27 | ``` 28 | 29 | **Example 2:** 30 | 31 | ``` 32 | Input: n = 2 33 | Output: false 34 | Explanation: Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0). 35 | ``` 36 | 37 | **Example 3:** 38 | 39 | ``` 40 | Input: n = 4 41 | Output: true 42 | Explanation: n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0). 43 | ``` 44 | 45 | **Constraints:** 46 | 47 | - `1 <= n <= 10^5` 48 | 49 | ## Approach 1: Dynamic Programming 50 | 51 | Let `dp[i]` be the result of the game with `i` stones. If it is true, it means Alice must win. If it is false, it means Bob must win. If there is any `j` that `dp[i - j * j]` make the other lose the game, then `dp[i]` would be true. For example, Alice can take `j * j` to make Bob into a losing state and end the game. 52 | 53 | 54 | 55 | ```cpp 56 | class Solution { 57 | public: 58 | bool winnerSquareGame(int n) { 59 | int dp[n + 1]; 60 | memset(dp, 0, sizeof(dp)); 61 | for(int i = 1; i <= n; i++){ 62 | for(int j = 1; j * j <= i; j++){ 63 | dp[i] |= !dp[i - j * j]; 64 | } 65 | } 66 | return dp[n]; 67 | } 68 | }; 69 | ``` 70 | -------------------------------------------------------------------------------- /solutions/1500-1599/1523-count-odd-numbers-in-an-interval-range-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @wkw | https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/ 4 | --- 5 | 6 | # 1523 - Count Odd Numbers in an Interval Range (Easy) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/ 11 | 12 | ## Problem Statement 13 | 14 | Given two non-negative integers `low` and `high`. Return the _count of odd numbers between_ `low` _and_ `high` _(inclusive)_. 15 | 16 | **Example 1:** 17 | 18 | ``` 19 | Input: low = 3, high = 7 20 | Output: 3 21 | Explanation: The odd numbers between 3 and 7 are [3,5,7]. 22 | ``` 23 | 24 | **Example 2:** 25 | 26 | ``` 27 | Input: low = 8, high = 10 28 | Output: 1 29 | Explanation: The odd numbers between 8 and 10 are [9]. 30 | ``` 31 | 32 | **Constraints:** 33 | 34 | - `0 <= low <= high <= 10^9` 35 | 36 | ## Approach 1: Brute Force 37 | 38 | Iterate from $$low$$ to $$high$$ and check if $$i$$ is odd. 39 | 40 | 41 | 42 | ```go 43 | func countOdds(low int, high int) int { 44 | ans := 0 45 | for i := low; i <= high; i += 1 { 46 | ans += i & 1 47 | } 48 | return ans 49 | } 50 | ``` 51 | 52 | 53 | 54 | ```rust 55 | impl Solution { 56 | pub fn count_odds(low: i32, high: i32) -> i32 { 57 | let mut ans = 0; 58 | for i in low .. high + 1 { 59 | ans += i & 1; 60 | } 61 | return ans; 62 | } 63 | } 64 | ``` 65 | 66 | ## Approach 2: Math 67 | 68 | Numbers of odd numbers in $$[low, high]$$ is same as $$[1, high] - [1 , low - 1]$$. Therefore, we just find out those two numbers to get the answer. There are $$(high + 1) / 2$$ odd numbers in $$[1, high]$$ and $$low/2$$ odd numbers in $$[1, low - 1]$$. 69 | 70 | 71 | 72 | ```go 73 | func countOdds(low int, high int) int { 74 | return (high + 1) / 2 - (low / 2); 75 | } 76 | ``` 77 | 78 | 79 | 80 | ```rust 81 | impl Solution { 82 | pub fn count_odds(low: i32, high: i32) -> i32 { 83 | return (high + 1) / 2 - (low / 2); 84 | } 85 | } 86 | ``` 87 | -------------------------------------------------------------------------------- /solutions/1500-1599/1539-kth-missing-positive-number-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @wkw | https://leetcode.com/problems/kth-missing-positive-number/ 4 | --- 5 | 6 | # 1539 - Kth Missing Positive Number (Easy) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/kth-missing-positive-number/ 11 | 12 | ## Problem Statement 13 | 14 | Given an array `arr` of positive integers sorted in a **strictly increasing order**, and an integer `k`. 15 | 16 | _Find the_ `kth` _positive integer that is missing from this array._ 17 | 18 | **Example 1:** 19 | 20 | ``` 21 | Input: arr = [2,3,4,7,11], k = 5 22 | Output: 9 23 | Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9. 24 | ``` 25 | 26 | **Example 2:** 27 | 28 | ``` 29 | Input: arr = [1,2,3,4], k = 2 30 | Output: 6 31 | Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6. 32 | ``` 33 | 34 | **Constraints:** 35 | 36 | - `1 <= arr.length <= 1000` 37 | - `1 <= arr[i] <= 1000` 38 | - `1 <= k <= 1000` 39 | - `arr[i] < arr[j]` for `1 <= i < j <= arr.length` 40 | 41 | ## Approach 1: Brute Force 42 | 43 | Iterate each number to find out the $$k$$-th missing number. 44 | 45 | 46 | 47 | ```cpp 48 | class Solution { 49 | public: 50 | int findKthPositive(vector& arr, int k) { 51 | int target = 1; 52 | while (k > 0) { 53 | // target is missing. decrease k by 1 54 | if (find(arr.begin(), arr.end(), target) == arr.end()) k -= 1; 55 | // find the ans 56 | if (k == 0) break; 57 | // check next number 58 | target += 1; 59 | } 60 | return target; 61 | } 62 | }; 63 | ``` 64 | -------------------------------------------------------------------------------- /solutions/1500-1599/1550-three-consecutive-odds-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/three-consecutive-odds/' 3 | tags: [Array] 4 | --- 5 | 6 | # 1550 - Three Consecutive Odds (Easy) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/three-consecutive-odds/ 11 | 12 | ## Problem Statement 13 | 14 | Given an integer array `arr`, return `true` if there are three consecutive odd numbers in the array. Otherwise, return `false`. 15 | 16 | **Example 1:** 17 | 18 | ``` 19 | Input: arr = [2,6,4,1] 20 | Output: false 21 | Explanation: There are no three consecutive odds. 22 | ``` 23 | 24 | **Example 2:** 25 | 26 | ``` 27 | Input: arr = [1,2,34,3,4,5,7,23,12] 28 | Output: true 29 | Explanation: [5,7,23] are three consecutive odds. 30 | ``` 31 | 32 | **Constraints:** 33 | 34 | - `1 <= arr.length <= 1000` 35 | - `1 <= arr[i] <= 1000` 36 | 37 | ## Approach 1: TBC 38 | 39 | 40 | 41 | 42 | 43 | ```py 44 | class Solution: 45 | def threeConsecutiveOdds(self, arr: List[int]) -> bool: 46 | for i in range(1, len(arr) - 1): 47 | if arr[i - 1] & 1 and arr[i] & 1 and arr[i + 1] & 1: 48 | return True 49 | return False 50 | ``` 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /solutions/1500-1599/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "1500 - 1599", 3 | "position": 18, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/1600-1699/1655-distribute-repeating-integers-hard.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @TBC | https://leetcode.com/problems/distribute-repeating-integers/' 3 | draft: 'true' 4 | --- 5 | 6 | # 1655 - Distribute Repeating Integers (Hard) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/distribute-repeating-integers/ 11 | 12 | ## Problem Statement 13 | 14 | You are given an array of `n` integers, `nums`, where there are at most `50` unique values in the array. You are also given an array of `m` customer order quantities, `quantity`, where `quantity[i]` is the amount of integers the `ith` customer ordered. Determine if it is possible to distribute `nums` such that: 15 | 16 | - The `ith` customer gets **exactly** `quantity[i]` integers, 17 | - The integers the `ith` customer gets are **all equal**, and 18 | - Every customer is satisfied. 19 | 20 | Return `true` _if it is possible to distribute_ `nums` _according to the above conditions_. 21 | 22 | **Example 1:** 23 | 24 | ``` 25 | Input: nums = [1,2,3,4], quantity = [2] 26 | Output: false 27 | Explanation: The 0th customer cannot be given two different integers. 28 | ``` 29 | 30 | **Example 2:** 31 | 32 | ``` 33 | Input: nums = [1,2,3,3], quantity = [2] 34 | Output: true 35 | Explanation: The 0th customer is given [3,3]. The integers [1,2] are not used. 36 | ``` 37 | 38 | **Example 3:** 39 | 40 | ``` 41 | Input: nums = [1,1,2,2], quantity = [2,2] 42 | Output: true 43 | Explanation: The 0th customer is given [1,1], and the 1st customer is given [2,2]. 44 | ``` 45 | 46 | **Constraints:** 47 | 48 | - `n == nums.length` 49 | - `1 <= n <= 10^5` 50 | - `1 <= nums[i] <= 1000` 51 | - `m == quantity.length` 52 | - `1 <= m <= 10` 53 | - `1 <= quantity[i] <= 10^5` 54 | - There are at most `50` unique values in `nums`. 55 | 56 | ## Approach 1: TBC 57 | -------------------------------------------------------------------------------- /solutions/1600-1699/1675-minimize-deviation-in-array-hard.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @TBC | https://leetcode.com/problems/minimize-deviation-in-array/' 3 | draft: 'true' 4 | --- 5 | 6 | # 1675 - Minimize Deviation in Array (Hard) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/minimize-deviation-in-array 11 | 12 | ## Problem Statement 13 | 14 | You are given an array `nums` of `n` positive integers. 15 | 16 | You can perform two types of operations on any element of the array any number of times: 17 | 18 | - If the element is **even**, **divide** it by `2`. 19 | - For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array will be `[1,2,3,2].` 20 | - If the element is **odd**, **multiply** it by `2`. 21 | - For example, if the array is `[1,2,3,4]`, then you can do this operation on the first element, and the array will be `[2,2,3,4].` 22 | 23 | The **deviation** of the array is the **maximum difference** between any two elements in the array. 24 | 25 | Return _the **minimum deviation** the array can have after performing some number of operations._ 26 | 27 | **Example 1:** 28 | 29 | ``` 30 | Input: nums = [1,2,3,4] 31 | Output: 1 32 | Explanation: You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1. 33 | ``` 34 | 35 | **Example 2:** 36 | 37 | ``` 38 | Input: nums = [4,1,5,20,3] 39 | Output: 3 40 | Explanation: You can transform the array after two operations to [4,2,5,5,3], then the deviation will be 5 - 2 = 3. 41 | ``` 42 | 43 | **Example 3:** 44 | 45 | ``` 46 | Input: nums = [2,10,8] 47 | Output: 3 48 | ``` 49 | 50 | **Constraints:** 51 | 52 | - `n == nums.length` 53 | - `2 <= n <= 10^5` 54 | - `1 <= nums[i] <= 10^9` 55 | 56 | ## Approach 1: TBC 57 | -------------------------------------------------------------------------------- /solutions/1600-1699/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "1600 - 1699", 3 | "position": 19, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/1700-1799/1727-largest-submatrix-with-rearrangements-medium.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @jit | https://leetcode.com/problems/largest-submatrix-with-rearrangements/' 3 | tags: [Array, Greedy, Sorting, Matrix] 4 | --- 5 | 6 | # 1727 - Largest Submatrix With Rearrangements (Medium) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/largest-submatrix-with-rearrangements/ 11 | 12 | ## Problem Statement 13 | 14 | You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order. 15 | 16 | Return _the area of the largest submatrix within_`matrix`_where **every** element of the submatrix is_`1`_after reordering the columns optimally._ 17 | 18 | **Example 1:** 19 | 20 | ``` 21 | Input: matrix = [[0,0,1],[1,1,1],[1,0,1]] 22 | Output: 4 23 | Explanation: You can rearrange the columns as shown above. 24 | The largest submatrix of 1s, in bold, has an area of 4. 25 | ``` 26 | 27 | **Example 2:** 28 | 29 | ``` 30 | Input: matrix = [[1,0,1,0,1]] 31 | Output: 3 32 | Explanation: You can rearrange the columns as shown above. 33 | The largest submatrix of 1s, in bold, has an area of 3. 34 | ``` 35 | 36 | **Example 3:** 37 | 38 | ``` 39 | Input: matrix = [[1,1,0],[1,0,1]] 40 | Output: 2 41 | Explanation: Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2. 42 | ``` 43 | 44 | **Constraints:** 45 | 46 | - `m == matrix.length` 47 | - `n == matrix[i].length` 48 | - `1 <= m * n <= 1e5` 49 | - `matrix[i][j]` is either `0` or `1`. 50 | 51 | ## Approach 1: Sorting 52 | 53 | 54 | 55 | 56 | 57 | ```elixir 58 | @spec largest_submatrix(matrix :: [[integer]]) :: integer 59 | # Enumerate the height of columns, then sort: 60 | def largest_submatrix(matrix) do 61 | std_heights = matrix 62 | |> Enum.zip_with(&Enum.scan(&1, fn elt, h -> elt * (h + 1) end)) 63 | |> Enum.zip_with(&Enum.sort(&1, :desc)) 64 | 65 | for row <- std_heights, 66 | {h, w} <- Enum.with_index(row, 1), reduce: 0 do 67 | area -> max(area, h * w) 68 | end 69 | end 70 | ``` 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /solutions/1700-1799/1748-sum-of-unique-elements-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @wkw | https://leetcode.com/problems/sum-of-unique-elements/ 4 | 5 | 6 | tags: ['Hash Map'] 7 | --- 8 | 9 | # 1748 - Sum of Unique Elements (Easy) 10 | 11 | ## Problem Link 12 | 13 | https://leetcode.com/problems/sum-of-unique-elements/ 14 | 15 | ## Problem Statement 16 | 17 | You are given an integer array `nums`. The unique elements of an array are the elements that appear **exactly once** in the array. 18 | 19 | Return _the **sum** of all the unique elements of_ `nums`. 20 | 21 | **Example 1:** 22 | 23 | ``` 24 | Input: nums = [1,2,3,2] 25 | Output: 4 26 | Explanation: The unique elements are [1,3], and the sum is 4. 27 | ``` 28 | 29 | **Example 2:** 30 | 31 | ``` 32 | Input: nums = [1,1,1,1,1] 33 | Output: 0 34 | Explanation: There are no unique elements, and the sum is 0. 35 | ``` 36 | 37 | **Example 3:** 38 | 39 | ``` 40 | Input: nums = [1,2,3,4,5] 41 | Output: 15 42 | Explanation: The unique elements are [1,2,3,4,5], and the sum is 15. 43 | ``` 44 | 45 | **Constraints:** 46 | 47 | - `1 <= nums.length <= 100` 48 | - `1 <= nums[i] <= 100` 49 | 50 | ## Approach 1: Hash Map 51 | 52 | 53 | 54 | ```cpp 55 | class Solution { 56 | public: 57 | int sumOfUnique(vector& nums) { 58 | unordered_map m; 59 | int ans = 0; 60 | // use hash map to count the frequency of each number 61 | for(int x : nums) m[x]++; 62 | // unique number would have frequency of 1 63 | for(auto x : m) { 64 | if(x.second == 1) { 65 | ans += x.first; 66 | } 67 | } 68 | return ans; 69 | } 70 | }; 71 | ``` 72 | -------------------------------------------------------------------------------- /solutions/1700-1799/1758-minimum-changes-to-make-alternating-binary-string-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @jit, @wkw | https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/' 3 | tags: [String] 4 | --- 5 | 6 | # 1758 - Minimum Changes To Make Alternating Binary String (Easy) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/ 11 | 12 | ## Problem Statement 13 | 14 | You are given a string `s` consisting only of the characters `'0'` and `'1'`. In one operation, you can change any `'0'` to `'1'` or vice versa. 15 | 16 | The string is called alternating if no two adjacent characters are equal. For example, the string `"010"` is alternating, while the string `"0100"` is not. 17 | 18 | Return _the **minimum** number of operations needed to make_ `s` _alternating_. 19 | 20 | **Example 1:** 21 | 22 | ``` 23 | Input: s = "0100" 24 | Output: 1 25 | Explanation: If you change the last character to '1', s will be "0101", which is alternating. 26 | ``` 27 | 28 | **Example 2:** 29 | 30 | ``` 31 | Input: s = "10" 32 | Output: 0 33 | Explanation: s is already alternating. 34 | ``` 35 | 36 | **Example 3:** 37 | 38 | ``` 39 | Input: s = "1111" 40 | Output: 2 41 | Explanation: You need two operations to reach "0101" or "1010". 42 | ``` 43 | 44 | **Constraints:** 45 | 46 | - $1 <= s.length <= 10^4$ 47 | - `s[i]` is either `'0'` or `'1'`. 48 | 49 | ## Approach 1: Counting 50 | 51 | 52 | 53 | 54 | 55 | ```scala 56 | object Solution { 57 | // Count swaps required for an alternating string starting with 0. 58 | // The alternating string starting with 1 is just the complement. 59 | def minOperations(s: String): Int = { 60 | val zSwaps = s.indices.count(i => s(i).asDigit == i % 2) 61 | zSwaps min (s.length - zSwaps) 62 | } 63 | } 64 | ``` 65 | 66 | 67 | 68 | 69 | 70 | 71 | ```cpp 72 | class Solution { 73 | public: 74 | int minOperations(string s) { 75 | int cnt = 0, n = s.size(); 76 | for (int i = 0; i < n; i++) cnt += s[i] - '0' == i % 2; 77 | return min(cnt, n - cnt); 78 | } 79 | }; 80 | ``` 81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /solutions/1700-1799/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "1700 - 1799", 3 | "position": 20, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/1800-1899/1852-distinct-numbers-in-each-subarray-medium.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @TBC | https://leetcode.com/problems/distinct-numbers-in-each-subarray/ 4 | 5 | 6 | draft: 'true' 7 | --- 8 | 9 | # 1852 - Distinct Numbers in Each Subarray (Medium) 10 | 11 | ## Problem Link 12 | 13 | https://leetcode.com/problems/distinct-numbers-in-each-subarray/ 14 | 15 | ## Problem Statement 16 | 17 | Given an integer array `nums` and an integer `k`, you are asked to construct the array `ans` of size `n-k+1` where `ans[i]` is the number of **distinct** numbers in the subarray `nums[i:i+k-1] = [nums[i], nums[i+1], ..., nums[i+k-1]]`. 18 | 19 | Return _the array_ `ans`. 20 | 21 | **Example 1:** 22 | 23 | ``` 24 | Input: nums = [1,2,3,2,2,1,3], k = 3 25 | Output: [3,2,2,2,3] 26 | Explanation: The number of distinct elements in each subarray goes as follows: 27 | - nums[0:2] = [1,2,3] so ans[0] = 3 28 | - nums[1:3] = [2,3,2] so ans[1] = 2 29 | - nums[2:4] = [3,2,2] so ans[2] = 2 30 | - nums[3:5] = [2,2,1] so ans[3] = 2 31 | - nums[4:6] = [2,1,3] so ans[4] = 3 32 | ``` 33 | 34 | **Example 2:** 35 | 36 | ``` 37 | Input: nums = [1,1,1,1,2,3,4], k = 4 38 | Output: [1,2,3,4] 39 | Explanation: The number of distinct elements in each subarray goes as follows: 40 | - nums[0:3] = [1,1,1,1] so ans[0] = 1 41 | - nums[1:4] = [1,1,1,2] so ans[1] = 2 42 | - nums[2:5] = [1,1,2,3] so ans[2] = 3 43 | - nums[3:6] = [1,2,3,4] so ans[3] = 4 44 | ``` 45 | 46 | **Constraints:** 47 | 48 | - `1 <= k <= nums.length <= 10^5` 49 | - `1 <= nums[i] <= 10^5` 50 | 51 | ## Approach 1: TBC 52 | -------------------------------------------------------------------------------- /solutions/1800-1899/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "1800 - 1899", 3 | "position": 21, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/1900-1999/1903-largest-odd-number-in-string-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw, @jit | https://leetcode.com/problems/largest-odd-number-in-string/' 3 | tags: [Math, String, Greedy] 4 | --- 5 | 6 | # 1903 - Largest Odd Number in String (Easy) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/largest-odd-number-in-string/ 11 | 12 | ## Problem Statement 13 | 14 | You are given a string `num`, representing a large integer. Return _the **largest-valued odd** integer (as a string) that is a **non-empty substring** of_`num`_, or an empty string_`""`_if no odd integer exists_. 15 | 16 | A **substring** is a contiguous sequence of characters within a string. 17 | 18 | **Example 1:** 19 | 20 | ``` 21 | Input: num = "52" 22 | Output: "5" 23 | Explanation: The only non-empty substrings are "5", "2", and "52". "5" is the only odd number. 24 | ``` 25 | 26 | **Example 2:** 27 | 28 | ``` 29 | Input: num = "4206" 30 | Output: "" 31 | Explanation: There are no odd numbers in "4206". 32 | ``` 33 | 34 | **Example 3:** 35 | 36 | ``` 37 | Input: num = "35427" 38 | Output: "35427" 39 | Explanation: "35427" is already an odd number. 40 | ``` 41 | 42 | **Constraints:** 43 | 44 | - $1 <= num.length <= 10 ^ 5$ 45 | - `num` only consists of digits and does not contain any leading zeros. 46 | 47 | ## Approach 1: Retain from last odd number 48 | 49 | A number is odd as long as the last digit is odd. Therefore, we can search the last odd digit in the string and build the substring. 50 | 51 | 52 | 53 | 54 | 55 | ```py 56 | class Solution: 57 | def largestOddNumber(self, num: str) -> str: 58 | last = -1 59 | for i in range(len(num)): 60 | if int(num[i]) & 1: 61 | last = i 62 | return num[:last + 1] 63 | ``` 64 | 65 | 66 | 67 | 68 | 69 | 70 | ```erlang 71 | -spec largest_odd_number(Num :: unicode:unicode_binary()) -> unicode:unicode_binary(). 72 | %% Retain from last odd number: 73 | largest_odd_number(Num) -> 74 | {Leading, _} = string:take(Num, "13579", true, trailing), 75 | Leading. 76 | ``` 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /solutions/1900-1999/1929-concatenation-of-array-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @heiheihang | https://leetcode.com/problems/concatenation-of-array/' 3 | --- 4 | 5 | # 1929 - Concatenation of Array (Easy) 6 | 7 | ## Problem Link 8 | 9 | https://leetcode.com/problems/concatenation-of-array/ 10 | 11 | ## Problem Statement 12 | 13 | Given an integer array `nums` of length `n`, you want to create an array `ans` of length `2n` where `ans[i] == nums[i]` and `ans[i + n] == nums[i]` for `0 <= i < n` (**0-indexed**). 14 | 15 | Specifically, `ans` is the **concatenation** of two `nums` arrays. 16 | 17 | Return _the array_ `ans`. 18 | 19 | **Example 1:** 20 | 21 | ``` 22 | Input: nums = [1,2,1] 23 | Output: [1,2,1,1,2,1] 24 | Explanation: The array ans is formed as follows: 25 | - ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]] 26 | - ans = [1,2,1,1,2,1] 27 | ``` 28 | 29 | **Example 2:** 30 | 31 | ``` 32 | Input: nums = [1,3,2,1] 33 | Output: [1,3,2,1,1,3,2,1] 34 | Explanation: The array ans is formed as follows: 35 | - ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]] 36 | - ans = [1,3,2,1,1,3,2,1] 37 | ``` 38 | 39 | **Constraints:** 40 | 41 | - `n == nums.length` 42 | - `1 <= n <= 1000` 43 | - `1 <= nums[i] <= 1000` 44 | 45 | ## Approach 1: Iteration 46 | 47 | We need to look at `nums` two times to create the desired result. The simplest approach is to perform two for-loops in `nums` and copy the numbers to `result` . 48 | 49 | 50 | 51 | ```python 52 | def getConcatenation(self, nums: List[int]) -> List[int]: 53 | 54 | #initialize result 55 | result = [] 56 | 57 | #first iteration of nums 58 | for i in range(len(nums)): 59 | result.append(nums[i]) 60 | 61 | #second iteration of nums 62 | for i in range(len(nums)): 63 | result.append(nums[i]) 64 | 65 | #return result 66 | return result 67 | ``` 68 | -------------------------------------------------------------------------------- /solutions/1900-1999/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "1900 - 1999", 3 | "position": 21, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/2000-2099/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "2000 - 2099", 3 | "position": 22, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/2100-2199/2119-a-number-after-a-double-reversal-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @wkw | https://leetcode.com/problems/a-number-after-a-double-reversal/ 4 | --- 5 | 6 | # 2119 - A Number After a Double Reversal (Easy) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/a-number-after-a-double-reversal/ 11 | 12 | ## Problem Statement 13 | 14 | **Reversing** an integer means to reverse all its digits. 15 | 16 | - For example, reversing `2021` gives `1202`. Reversing `12300` gives `321` as the **leading zeros are not retained**. 17 | 18 | Given an integer `num`, **reverse** `num` to get `reversed1`, **then reverse** `reversed1` to get `reversed2`. Return `true` _if_ `reversed2` _equals_ `num`. Otherwise return `false`. 19 | 20 | **Example 1:** 21 | 22 | ``` 23 | Input: num = 526 24 | Output: true 25 | Explanation: Reverse num to get 625, then reverse 625 to get 526, which equals num. 26 | ``` 27 | 28 | **Example 2:** 29 | 30 | ``` 31 | Input: num = 1800 32 | Output: false 33 | Explanation: Reverse num to get 81, then reverse 81 to get 18, which does not equal num. 34 | ``` 35 | 36 | **Example 3:** 37 | 38 | ``` 39 | Input: num = 0 40 | Output: true 41 | Explanation: Reverse num to get 0, then reverse 0 to get 0, which equals num. 42 | ``` 43 | 44 | **Constraints:** 45 | 46 | - `0 <= num <= 10^6` 47 | 48 | ## Approach 1: Just do what it says 49 | 50 | 51 | 52 | ```cpp 53 | class Solution { 54 | public: 55 | bool isSameAfterReversals(int num) { 56 | if (num == 0) return 1; 57 | string s = to_string(num); 58 | int n = s.size(), j = 0; 59 | while (s[n - 1 - j] == '0') j++; 60 | string t = s.substr(0, n - j); 61 | return s == t; 62 | } 63 | }; 64 | ``` 65 | 66 | ## Approach 2: Check Trailing Zero 67 | 68 | However, a better way to solve this is to check if there is any trailing zero. No matter how many zeros at the end, after removing them all, it won't be same if you reverse it. The only exceptional case is $$num=0$$. 69 | 70 | 71 | 72 | ```cpp 73 | class Solution { 74 | public: 75 | bool isSameAfterReversals(int num) { 76 | return num == 0 || num % 10; 77 | } 78 | }; 79 | ``` 80 | 81 | Time Complexity : $O(1)$ 82 | 83 | Space Complexity: $O(1)$ 84 | -------------------------------------------------------------------------------- /solutions/2100-2199/2148-count-elements-with-strictly-smaller-and-greater-elements-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @wkw | https://leetcode.com/problems/count-elements-with-strictly-smaller-and-greater-elements/ 4 | --- 5 | 6 | # 2148 - Count Elements With Strictly Smaller and Greater Elements (Easy) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/count-elements-with-strictly-smaller-and-greater-elements/ 11 | 12 | ## Problem Statement 13 | 14 | Given an integer array `nums`, return _the number of elements that have **both** a strictly smaller and a strictly greater element appear in_ `nums`. 15 | 16 | **Example 1:** 17 | 18 | ``` 19 | Input: nums = [11,7,2,15] 20 | Output: 2 21 | Explanation: The element 7 has the element 2 strictly smaller than it and the element 11 strictly greater than it. 22 | Element 11 has element 7 strictly smaller than it and element 15 strictly greater than it. 23 | In total there are 2 elements having both a strictly smaller and a strictly greater element appear in nums. 24 | ``` 25 | 26 | **Example 2:** 27 | 28 | ``` 29 | Input: nums = [-3,3,3,90] 30 | Output: 2 31 | Explanation: The element 3 has the element -3 strictly smaller than it and the element 90 strictly greater than it. 32 | Since there are two elements with the value 3, in total there are 2 elements having both a strictly smaller and a strictly greater element appear in nums. 33 | ``` 34 | 35 | **Constraints:** 36 | 37 | - `1 <= nums.length <= 100` 38 | - `-10^5 <= nums[i] <= 10^5` 39 | 40 | ## Approach 1: Sorting 41 | 42 | The order doesn't matter. We can sort the array and only focus on all elements except the first one and the last one because those two elements won't have strictly smaller and greater elements at the same time. From `nums[1..n - 2]`, we can check if the element is greater than the smallest one and smaller than the greatest one. 43 | 44 | 45 | 46 | ```cpp 47 | class Solution { 48 | public: 49 | int countElements(vector& nums) { 50 | sort(nums.begin(), nums.end()); 51 | int ans = 0; 52 | for (int i = 1; i < nums.size() - 1; i++) { 53 | ans += nums[i] > nums.front() && nums[i] < nums.back(); 54 | } 55 | return ans; 56 | } 57 | }; 58 | ``` 59 | -------------------------------------------------------------------------------- /solutions/2100-2199/2154-keep-multiplying-found-values-by-two-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @wkw | https://leetcode.com/problems/keep-multiplying-found-values-by-two/ 4 | --- 5 | 6 | # 2154 - Keep Multiplying Found Values by Two (Easy) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/keep-multiplying-found-values-by-two/ 11 | 12 | ## Problem Statement 13 | 14 | You are given an array of integers `nums`. You are also given an integer `original` which is the first number that needs to be searched for in `nums`. 15 | 16 | You then do the following steps: 17 | 18 | 1. If `original` is found in `nums`, **multiply** it by two (i.e., set `original = 2 * original`). 19 | 2. Otherwise, **stop** the process. 20 | 3. **Repeat** this process with the new number as long as you keep finding the number. 21 | 22 | Return _the **final** value of_ `original`. 23 | 24 | **Example 1:** 25 | 26 | ``` 27 | Input: nums = [5,3,6,1,12], original = 3 28 | Output: 24 29 | Explanation: 30 | - 3 is found in nums. 3 is multiplied by 2 to obtain 6. 31 | - 6 is found in nums. 6 is multiplied by 2 to obtain 12. 32 | - 12 is found in nums. 12 is multiplied by 2 to obtain 24. 33 | - 24 is not found in nums. Thus, 24 is returned. 34 | ``` 35 | 36 | **Example 2:** 37 | 38 | ``` 39 | Input: nums = [2,7,9], original = 4 40 | Output: 4 41 | Explanation: 42 | - 4 is not found in nums. Thus, 4 is returned. 43 | ``` 44 | 45 | **Constraints:** 46 | 47 | - `1 <= nums.length <= 1000` 48 | - `1 <= nums[i], original <= 1000` 49 | 50 | ## Approach 1: Simulation with Set 51 | 52 | 53 | 54 | ```cpp 55 | class Solution { 56 | public: 57 | int findFinalValue(vector& nums, int original) { 58 | set s(nums.begin(), nums.end()); 59 | while (s.count(original)) original *= 2; 60 | return original; 61 | } 62 | }; 63 | ``` 64 | -------------------------------------------------------------------------------- /solutions/2100-2199/2160-minimum-sum-of-four-digit-number-after-splitting-digits-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @wkw | https://leetcode.com/problems/minimum-sum-of-four-digit-number-after-splitting-digits/ 4 | --- 5 | 6 | # 2160 - Minimum Sum of Four Digit Number After Splitting Digits (Easy) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/minimum-sum-of-four-digit-number-after-splitting-digits/ 11 | 12 | ## Problem Statement 13 | 14 | You are given a **positive** integer `num` consisting of exactly four digits. Split `num` into two new integers `new1` and `new2` by using the **digits** found in `num`. **Leading zeros** are allowed in `new1` and `new2`, and **all** the digits found in `num` must be used. 15 | 16 | For example, given `num = 2932`, you have the following digits: two `2`'s, one `9` and one `3`. Some of the possible pairs `[new1, new2]` are `[22, 93]`, `[23, 92]`, `[223, 9]` and `[2, 329]`. 17 | 18 | Return _the **minimum** possible sum of_ `new1` _and_ `new2`. 19 | 20 | **Example 1:** 21 | 22 | ``` 23 | Input: num = 2932 24 | Output: 52 25 | Explanation: Some possible pairs [new1, new2] are [29, 23], [223, 9], etc. 26 | The minimum sum can be obtained by the pair [29, 23]: 29 + 23 = 52. 27 | ``` 28 | 29 | **Example 2:** 30 | 31 | ``` 32 | Input: num = 4009 33 | Output: 13 34 | Explanation: Some possible pairs [new1, new2] are [0, 49], [490, 0], etc. 35 | The minimum sum can be obtained by the pair [4, 9]: 4 + 9 = 13. 36 | ``` 37 | 38 | **Constraints:** 39 | 40 | - `1000 <= num <= 9999` 41 | 42 | ## Approach 1: Sorting & Greedy 43 | 44 | We can sort those 4 digits in an increasing order. Let's say $$abcd$$ where $$a <= b <= c <= d$$. We put those two smallest digits to be decimal's place, and those two largest ones in one's place. The answer is simply $$ac + bd$$. 45 | 46 | 47 | 48 | ```cpp 49 | class Solution { 50 | public: 51 | int minimumSum(int num) { 52 | string s = to_string(num); 53 | vector d; 54 | while (num > 0) { 55 | d.push_back(num % 10); 56 | num /= 10; 57 | } 58 | sort(d.begin(), d.end()); 59 | return d[0] * 10 + d[3] + d[1] * 10 + d[2]; 60 | } 61 | }; 62 | ``` 63 | -------------------------------------------------------------------------------- /solutions/2100-2199/2176-count-equal-and-divisible-pairs-in-an-array-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @wkw | https://leetcode.com/problems/count-equal-and-divisible-pairs-in-an-array/ 4 | --- 5 | 6 | # 2176 - Count Equal and Divisible Pairs in an Array (Easy) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/count-equal-and-divisible-pairs-in-an-array/ 11 | 12 | ## Problem Statement 13 | 14 | Given a **0-indexed** integer array `nums` of length `n` and an integer `k`, return _the **number of pairs**_ `(i, j)` _where_ `0 <= i < j < n`, _such that_ `nums[i] == nums[j]` _and_ `(i * j)` _is divisible by_ `k`. 15 | 16 | **Example 1:** 17 | 18 | ``` 19 | Input: nums = [3,1,2,2,2,1,3], k = 2 20 | Output: 4 21 | Explanation: 22 | There are 4 pairs that meet all the requirements: 23 | - nums[0] == nums[6], and 0 * 6 == 0, which is divisible by 2. 24 | - nums[2] == nums[3], and 2 * 3 == 6, which is divisible by 2. 25 | - nums[2] == nums[4], and 2 * 4 == 8, which is divisible by 2. 26 | - nums[3] == nums[4], and 3 * 4 == 12, which is divisible by 2. 27 | ``` 28 | 29 | **Example 2:** 30 | 31 | ``` 32 | Input: nums = [1,2,3,4], k = 1 33 | Output: 0 34 | Explanation: Since no value in nums is repeated, there are no pairs (i,j) that meet all the requirements. 35 | ``` 36 | 37 | **Constraints:** 38 | 39 | - `1 <= nums.length <= 100` 40 | - `1 <= nums[i], k <= 100` 41 | 42 | ## Approach 1: Brute Force 43 | 44 | Just do what it says. 45 | 46 | 47 | 48 | ```cpp 49 | class Solution { 50 | public: 51 | int countPairs(vector& nums, int k) { 52 | int n = nums.size(), ans = 0; 53 | for (int i = 0; i < n; i++) { 54 | for (int j = i + 1; j < n; j++) { 55 | ans += nums[i] == nums[j] && (i * j) % k == 0; 56 | } 57 | } 58 | return ans; 59 | } 60 | }; 61 | ``` 62 | -------------------------------------------------------------------------------- /solutions/2100-2199/2177-find-three-consecutive-integers-that-sum-to-a-given-number-medium.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @wkw | https://leetcode.com/problems/find-three-consecutive-integers-that-sum-to-a-given-number/ 4 | --- 5 | 6 | # 2177 - Find Three Consecutive Integers That Sum to a Given Number (Medium) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/find-three-consecutive-integers-that-sum-to-a-given-number/ 11 | 12 | ## Problem Statement 13 | 14 | Given an integer `num`, return _three consecutive integers (as a sorted array) that **sum** to_ `num`. If `num` cannot be expressed as the sum of three consecutive integers, return _an **empty** array._ 15 | 16 | **Example 1:** 17 | 18 | ``` 19 | Input: num = 33 20 | Output: [10,11,12] 21 | Explanation: 33 can be expressed as 10 + 11 + 12 = 33. 22 | 10, 11, 12 are 3 consecutive integers, so we return [10, 11, 12]. 23 | ``` 24 | 25 | **Example 2:** 26 | 27 | ``` 28 | Input: num = 4 29 | Output: [] 30 | Explanation: There is no way to express 4 as the sum of 3 consecutive integers. 31 | ``` 32 | 33 | **Constraints:** 34 | 35 | - `0 <= num <= 10^15` 36 | 37 | ## Approach 1: Math 38 | 39 | We can express it as $$n + (n + 1) + (n + 2) = num$$ and find what $$n$$ is. 40 | 41 | $$ 42 | n + (n + 1) + (n + 2) = num 43 | $$ 44 | 45 | $$ 46 | 3 * n + 3 = num 47 | $$ 48 | 49 | $$ 50 | n = (num - 3) / 3 51 | $$ 52 | 53 | If $$(num - 3)$$ is not divisible by $$3$$, then return empty array. Otherwise, calculate $$n$$ and return $$n$$, $$n + 1$$, and $$n + 2$$. 54 | 55 | ```cpp 56 | class Solution { 57 | public: 58 | vector sumOfThree(long long num) { 59 | num -= 3; 60 | if (num % 3 == 0) { 61 | long long n = num / 3; 62 | return {n, n + 1, n + 2}; 63 | } 64 | return {}; 65 | } 66 | }; 67 | ``` 68 | 69 | Alternatively, we can find the middle number and get the first and the third one. 70 | 71 | ```cpp 72 | class Solution { 73 | public: 74 | vector sumOfThree(long long num) { 75 | if (num % 3 == 0) { 76 | long long x = num / 3; 77 | return {x - 1, x, x + 1}; 78 | } 79 | return {}; 80 | } 81 | }; 82 | ``` 83 | -------------------------------------------------------------------------------- /solutions/2100-2199/2180-count-integers-with-even-digit-sum-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @wkw | https://leetcode.com/problems/count-integers-with-even-digit-sum/ 4 | --- 5 | 6 | # 2180 - Count Integers With Even Digit Sum (Easy) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/count-integers-with-even-digit-sum/ 11 | 12 | ## Problem Statement 13 | 14 | Given a positive integer `num`, return _the number of positive integers **less than or equal to**_ `num` _whose digit sums are **even**_. 15 | 16 | The **digit sum** of a positive integer is the sum of all its digits. 17 | 18 | **Example 1:** 19 | 20 | ``` 21 | Input: num = 4 22 | Output: 2 23 | Explanation: 24 | The only integers less than or equal to 4 whose digit sums are even are 2 and 4. 25 | ``` 26 | 27 | **Example 2:** 28 | 29 | ``` 30 | Input: num = 30 31 | Output: 14 32 | Explanation: 33 | The 14 integers less than or equal to 30 whose digit sums are even are 34 | 2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, and 28. 35 | ``` 36 | 37 | **Constraints:** 38 | 39 | - `1 <= num <= 1000` 40 | 41 | ## Approach 1: Brute Force 42 | 43 | We try all numbers in $$[1, num]$$ to see its digit sum is even or not. 44 | 45 | 46 | 47 | ```cpp 48 | class Solution { 49 | public: 50 | int ds(int x) { 51 | int res = 0; 52 | while (x) { 53 | // get the last digit 54 | res += x % 10; 55 | // erase the last digit 56 | x /= 10; 57 | } 58 | return res; 59 | } 60 | int countEven(int num) { 61 | int ans = 0; 62 | // try all possible numbers and calculate its digit sum 63 | // add 1 to ans if it is even 64 | for (int i = 1; i <= num; i++) ans += ds(i) % 2 == 0; 65 | return ans; 66 | } 67 | }; 68 | ``` 69 | -------------------------------------------------------------------------------- /solutions/2100-2199/2181-merge-nodes-in-between-zeros-medium.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @TBC | https://leetcode.com/problems/merge-nodes-in-between-zeros/' 3 | draft: 'true' 4 | --- 5 | 6 | # 2181 - Merge Nodes in Between Zeros (Medium) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/merge-nodes-in-between-zeros/ 11 | 12 | ## Problem Statement 13 | 14 | You are given the `head` of a linked list, which contains a series of integers **separated** by `0`'s. The **beginning** and **end** of the linked list will have `Node.val == 0`. 15 | 16 | For **every** two consecutive `0`'s, **merge** all the nodes lying in between them into a single node whose value is the **sum** of all the merged nodes. The modified list should not contain any `0`'s. 17 | 18 | Return _the_ `head` _of the modified linked list_. 19 | 20 | **Example 1:** 21 | 22 | ![](https://assets.leetcode.com/uploads/2022/02/02/ex1-1.png) 23 | 24 | ``` 25 | Input: head = [0,3,1,0,4,5,2,0] 26 | Output: [4,11] 27 | Explanation: 28 | The above figure represents the given linked list. The modified list contains 29 | - The sum of the nodes marked in green: 3 + 1 = 4. 30 | - The sum of the nodes marked in red: 4 + 5 + 2 = 11. 31 | ``` 32 | 33 | **Example 2:** 34 | 35 | ![](https://assets.leetcode.com/uploads/2022/02/02/ex2-1.png) 36 | 37 | ``` 38 | Input: head = [0,1,0,3,0,2,2,0] 39 | Output: [1,3,4] 40 | Explanation: 41 | The above figure represents the given linked list. The modified list contains 42 | - The sum of the nodes marked in green: 1 = 1. 43 | - The sum of the nodes marked in red: 3 = 3. 44 | - The sum of the nodes marked in yellow: 2 + 2 = 4. 45 | ``` 46 | 47 | **Constraints:** 48 | 49 | - The number of nodes in the list is in the range `[3, 2 * 10^5]`. 50 | - `0 <= Node.val <= 1000` 51 | - There are **no** two consecutive nodes with `Node.val == 0`. 52 | - The **beginning** and **end** of the linked list have `Node.val == 0`. 53 | 54 | ## Approach 1: TBC 55 | -------------------------------------------------------------------------------- /solutions/2100-2199/2183-count-array-pairs-divisible-by-k-hard.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @TBC | https://leetcode.com/problems/count-array-pairs-divisible-by-k/' 3 | --- 4 | 5 | # 2183 - Count Array Pairs Divisible by K (Hard) 6 | 7 | ## Problem Link 8 | 9 | https://leetcode.com/problems/count-array-pairs-divisible-by-k/ 10 | 11 | ## Problem Statement 12 | 13 | Given a **0-indexed** integer array `nums` of length `n` and an integer `k`, return _the **number of pairs**_ `(i, j)` _such that:_ 14 | 15 | - `0 <= i < j <= n - 1` _and_ 16 | - `nums[i] * nums[j]` _is divisible by_ `k`. 17 | 18 | **Example 1:** 19 | 20 | ``` 21 | Input: nums = [1,2,3,4,5], k = 2 22 | Output: 7 23 | Explanation: 24 | The 7 pairs of indices whose corresponding products are divisible by 2 are 25 | (0, 1), (0, 3), (1, 2), (1, 3), (1, 4), (2, 3), and (3, 4). 26 | Their products are 2, 4, 6, 8, 10, 12, and 20 respectively. 27 | Other pairs such as (0, 2) and (2, 4) have products 3 and 15 respectively, which are not divisible by 2. 28 | ``` 29 | 30 | **Example 2:** 31 | 32 | ``` 33 | Input: nums = [1,2,3,4], k = 5 34 | Output: 0 35 | Explanation: There does not exist any pair of indices whose corresponding product is divisible by 5. 36 | ``` 37 | 38 | **Constraints:** 39 | 40 | - `1 <= nums.length <= 10^5` 41 | - `1 <= nums[i], k <= 10^5` 42 | 43 | ## Approach 1: TBC 44 | -------------------------------------------------------------------------------- /solutions/2100-2199/2206-divide-array-into-equal-pairs-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @wkw | https://leetcode.com/problems/divide-array-into-equal-pairs/ 4 | --- 5 | 6 | # 2206 - Divide Array Into Equal Pairs (Easy) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/divide-array-into-equal-pairs/ 11 | 12 | ## Problem Statement 13 | 14 | You are given an integer array `nums` consisting of `2 * n` integers. 15 | 16 | You need to divide `nums` into `n` pairs such that: 17 | 18 | - Each element belongs to **exactly one** pair. 19 | - The elements present in a pair are **equal**. 20 | 21 | Return `true` _if nums can be divided into_ `n` _pairs, otherwise return_ `false`. 22 | 23 | ## Approach 1: Brute Force 24 | 25 | Count the frequency for each number. If there is a number with odd frequency, then the answer is false. Otherwise, it must be true. 26 | 27 | 28 | 29 | ```cpp 30 | class Solution { 31 | public: 32 | bool divideArray(vector& nums) { 33 | int n = nums.size(), cnt = 0; 34 | unordered_map m; 35 | // count the frequency for each number 36 | for (auto x : nums) m[x]++; 37 | for (auto x : m) { 38 | // check if it is odd 39 | if (x.second & 1) { 40 | return false; 41 | } 42 | } 43 | return true; 44 | } 45 | }; 46 | ``` 47 | -------------------------------------------------------------------------------- /solutions/2100-2199/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "2100 - 2199", 3 | "position": 23, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/2200-2299/2215-find-the-difference-of-two-arrays-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @TBC | https://leetcode.com/problems/find-the-difference-of-two-arrays/ 4 | 5 | 6 | draft: true 7 | --- 8 | 9 | # 2215 - Find the Difference of Two Arrays (Easy) 10 | 11 | ## Problem Link 12 | 13 | https://leetcode.com/problems/find-the-difference-of-two-arrays/ 14 | 15 | ## Problem Statement 16 | 17 | Given two **0-indexed** integer arrays `nums1` and `nums2`, return _a list_ `answer` _of size_ `2` _where:_ 18 | 19 | - `answer[0]` _is a list of all **distinct** integers in_ `nums1` _which are **not** present in_ `nums2`_._ 20 | - `answer[1]` _is a list of all **distinct** integers in_ `nums2` _which are **not** present in_ `nums1`. 21 | 22 | **Note** that the integers in the lists may be returned in **any** order. 23 | 24 | **Example 1:** 25 | 26 | ``` 27 | Input: nums1 = [1,2,3], nums2 = [2,4,6] 28 | Output: [[1,3],[4,6]] 29 | Explanation: 30 | For nums1, nums1[1] = 2 is present at index 0 of nums2, whereas nums1[0] = 1 and nums1[2] = 3 are not present in nums2. Therefore, answer[0] = [1,3]. 31 | For nums2, nums2[0] = 2 is present at index 1 of nums1, whereas nums2[1] = 4 and nums2[2] = 6 are not present in nums2. Therefore, answer[1] = [4,6]. 32 | ``` 33 | 34 | **Example 2:** 35 | 36 | ``` 37 | Input: nums1 = [1,2,3,3], nums2 = [1,1,2,2] 38 | Output: [[3],[]] 39 | Explanation: 40 | For nums1, nums1[2] and nums1[3] are not present in nums2. Since nums1[2] == nums1[3], their value is only included once and answer[0] = [3]. 41 | Every integer in nums2 is present in nums1. Therefore, answer[1] = []. 42 | ``` 43 | 44 | **Constraints:** 45 | 46 | - `1 <= nums1.length, nums2.length <= 1000` 47 | - `-1000 <= nums1[i], nums2[i] <= 1000` 48 | 49 | ## Approach 1: TBC 50 | -------------------------------------------------------------------------------- /solutions/2200-2299/2216-minimum-deletions-to-make-array-beautiful-medium.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @TBC | https://leetcode.com/problems/minimum-deletions-to-make-array-beautiful/ 4 | 5 | 6 | draft: true 7 | --- 8 | 9 | # 2216 - Minimum Deletions to Make Array Beautiful (Medium) 10 | 11 | ## Problem Link 12 | 13 | https://leetcode.com/problems/minimum-deletions-to-make-array-beautiful/ 14 | 15 | ## Problem Statement 16 | 17 | You are given a **0-indexed** integer array `nums`. The array `nums` is **beautiful** if: 18 | 19 | - `nums.length` is even. 20 | - `nums[i] != nums[i + 1]` for all `i % 2 == 0`. 21 | 22 | Note that an empty array is considered beautiful. 23 | 24 | You can delete any number of elements from `nums`. When you delete an element, all the elements to the right of the deleted element will be **shifted one unit to the left** to fill the gap created and all the elements to the left of the deleted element will remain **unchanged**. 25 | 26 | Return _the **minimum** number of elements to delete from_ `nums` _to make it beautiful._ 27 | 28 | **Example 1:** 29 | 30 | ``` 31 | Input: nums = [1,1,2,3,5] 32 | Output: 1 33 | Explanation: You can delete either nums[0] or nums[1] to make nums = [1,2,3,5] which is beautiful. It can be proven you need at least 1 deletion to make nums beautiful. 34 | ``` 35 | 36 | **Example 2:** 37 | 38 | ``` 39 | Input: nums = [1,1,2,2,3,3] 40 | Output: 2 41 | Explanation: You can delete nums[0] and nums[5] to make nums = [1,2,2,3] which is beautiful. It can be proven you need at least 2 deletions to make nums beautiful. 42 | ``` 43 | 44 | **Constraints:** 45 | 46 | - `1 <= nums.length <= 10^5` 47 | - `0 <= nums[i] <= 10^5` 48 | 49 | ## Approach 1: TBC 50 | -------------------------------------------------------------------------------- /solutions/2200-2299/2217-find-palindrome-with-fixed-length-medium.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @TBC | https://leetcode.com/problems/find-palindrome-with-fixed-length/ 4 | 5 | 6 | draft: true 7 | --- 8 | 9 | # 2217 - Find Palindrome With Fixed Length (Medium) 10 | 11 | ## Problem Link 12 | 13 | https://leetcode.com/problems/find-palindrome-with-fixed-length/ 14 | 15 | ## Problem Statement 16 | 17 | Given an integer array `queries` and a **positive** integer `intLength`, return _an array_ `answer` _where_ `answer[i]` _is either the_ `queries[i]th` _smallest **positive palindrome** of length_ `intLength` _or_ `-1` _if no such palindrome exists_. 18 | 19 | A **palindrome** is a number that reads the same backwards and forwards. Palindromes cannot have leading zeros. 20 | 21 | **Example 1:** 22 | 23 | ``` 24 | Input: queries = [1,2,3,4,5,90], intLength = 3 25 | Output: [101,111,121,131,141,999] 26 | Explanation: 27 | The first few palindromes of length 3 are: 28 | 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 201, ... 29 | The 90th palindrome of length 3 is 999. 30 | ``` 31 | 32 | **Example 2:** 33 | 34 | ``` 35 | Input: queries = [2,4,6], intLength = 4 36 | Output: [1111,1331,1551] 37 | Explanation: 38 | The first six palindromes of length 4 are: 39 | 1001, 1111, 1221, 1331, 1441, and 1551. 40 | ``` 41 | 42 | **Constraints:** 43 | 44 | - `1 <= queries.length <= 5 * 10^4` 45 | - `1 <= queries[i] <= 10^9` 46 | - `1 <= intLength <= 15` 47 | 48 | ## Approach 1: TBC 49 | -------------------------------------------------------------------------------- /solutions/2200-2299/2235-add-two-integers-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/add-two-integers/' 3 | --- 4 | 5 | # 2235 - Add Two Integers (Easy) 6 | 7 | ## Problem Link 8 | 9 | https://leetcode.com/problems/add-two-integers/ 10 | 11 | ## Problem Statement 12 | 13 | Given two integers `num1` and `num2`, return _the **sum** of the two integers_. 14 | 15 | **Example 1:** 16 | 17 | ``` 18 | Input: num1 = 12, num2 = 5 19 | Output: 17 20 | Explanation: num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned. 21 | ``` 22 | 23 | **Example 2:** 24 | 25 | ``` 26 | Input: num1 = -10, num2 = 4 27 | Output: -6 28 | Explanation: num1 + num2 = -6, so -6 is returned. 29 | ``` 30 | 31 | **Constraints:** 32 | 33 | - `-100 <= num1, num2 <= 100` 34 | 35 | ## Approach 1: A + B 36 | 37 | 38 | 39 | ```cpp 40 | class Solution { 41 | public: 42 | int sum(int num1, int num2) { 43 | return num1 + num2; 44 | } 45 | }; 46 | ``` 47 | 48 | ## Approach 2: Half Adder 49 | 50 | 51 | 52 | ```cpp 53 | class Solution { 54 | public: 55 | int sum(int num1, int num2) { 56 | return num2 == 0 ? num1 : sum(num1 ^ num2, (unsigned) (num1 & num2) << 1); 57 | } 58 | }; 59 | ``` 60 | 61 | ## Approach 3: Log & Exp 62 | 63 | 64 | 65 | ```cpp 66 | class Solution { 67 | public: 68 | int sum(int num1, int num2) { 69 | return log(exp(num1) * exp(num2))); 70 | } 71 | }; 72 | ``` 73 | -------------------------------------------------------------------------------- /solutions/2200-2299/2239-find-closest-number-to-zero-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @wkw | https://leetcode.com/problems/find-closest-number-to-zero/ 4 | --- 5 | 6 | # 2239 - Find Closest Number to Zero (Easy) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/find-closest-number-to-zero/ 11 | 12 | ## Problem Statement 13 | 14 | Given an integer array `nums` of size `n`, return _the number with the value **closest** to_ `0` _in_ `nums`. If there are multiple answers, return _the number with the **largest** value_. 15 | 16 | **Example 1:** 17 | 18 | ``` 19 | Input: nums = [-4,-2,1,4,8] 20 | Output: 1 21 | Explanation: 22 | The distance from -4 to 0 is |-4| = 4. 23 | The distance from -2 to 0 is |-2| = 2. 24 | The distance from 1 to 0 is |1| = 1. 25 | The distance from 4 to 0 is |4| = 4. 26 | The distance from 8 to 0 is |8| = 8. 27 | Thus, the closest number to 0 in the array is 1. 28 | ``` 29 | 30 | **Example 2:** 31 | 32 | ``` 33 | Input: nums = [2,-1,1] 34 | Output: 1 35 | Explanation: 1 and -1 are both the closest numbers to 0, so 1 being larger is returned. 36 | ``` 37 | 38 | **Constraints:** 39 | 40 | - `1 <= n <= 1000` 41 | - `-105 <= nums[i] <= 10^5` 42 | 43 | ## Approach 1: 44 | 45 | If we sort the input and check if the absolute value is minimal, the answer would be found in the last round. However, it is not necessary to sort it here. We just need to check if the number is greater that answer or not. 46 | 47 | 48 | 49 | ```cpp 50 | class Solution { 51 | public: 52 | int findClosestNumber(vector& nums) { 53 | int ans = INT_MAX, mi = INT_MAX; 54 | for (auto x : nums) { 55 | int d = abs(x); 56 | if (d < mi || (d == mi && x > ans)) { 57 | mi = d; 58 | ans = x; 59 | } 60 | } 61 | return ans; 62 | } 63 | }; 64 | ``` 65 | -------------------------------------------------------------------------------- /solutions/2200-2299/2248-intersection-of-multiple-arrays-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @wkw | https://leetcode.com/problems/intersection-of-multiple-arrays/ 4 | --- 5 | 6 | # 2248 - Intersection of Multiple Arrays (Easy) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/intersection-of-multiple-arrays/ 11 | 12 | ## Problem Statement 13 | 14 | Given a 2D integer array `nums` where `nums[i]` is a non-empty array of **distinct** positive integers, return _the list of integers that are present in **each array** of_ `nums` _sorted in **ascending order**_. 15 | 16 | **Example 1:** 17 | 18 | ``` 19 | Input: nums = [[3,1,2,4,5],[1,2,3,4],[3,4,5,6]] 20 | Output: [3,4] 21 | Explanation: 22 | The only integers present in each of nums[0] = [3,1,2,4,5], nums[1] = [1,2,3,4], and nums[2] = [3,4,5,6] are 3 and 4, so we return [3,4]. 23 | ``` 24 | 25 | **Example 2:** 26 | 27 | ``` 28 | Input: nums = [[1,2,3],[4,5,6]] 29 | Output: [] 30 | Explanation: 31 | There does not exist any integer present both in nums[0] and nums[1], so we return an empty list []. 32 | ``` 33 | 34 | **Constraints:** 35 | 36 | - `1 <= nums.length <= 1000` 37 | - `1 <= sum(nums[i].length) <= 1000` 38 | - `1 <= nums[i][j] <= 1000` 39 | - All the values of `nums[i]` are **unique**. 40 | 41 | ## Approach 1: Brute Force 42 | 43 | Observation: Each element of the final output would have a frequency of $$nums.length$$. 44 | 45 | We use hash map to store the frequency for each integer. Iterate the map and look for the those with $$occurrence ==nums.length$$. 46 | 47 | 48 | 49 | ```cpp 50 | class Solution { 51 | public: 52 | vector intersection(vector>& nums) { 53 | int n = nums.size(); 54 | unordered_map m; 55 | vector ans; 56 | // count each integer 57 | for (auto x : nums) for (auto y : x) m[y]++; 58 | // if the count is equal to n, then take this integer 59 | for (auto x : m) if (x.second == n) ans.push_back(x.first); 60 | // sort in ascending order 61 | sort(ans.begin(), ans.end()); 62 | return ans; 63 | } 64 | }; 65 | ``` 66 | -------------------------------------------------------------------------------- /solutions/2200-2299/2255-count-prefixes-of-a-given-string-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @wkw | https://leetcode.com/problems/count-prefixes-of-a-given-string/ 4 | --- 5 | 6 | # 2255 - Count Prefixes of a Given String (Easy) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/count-prefixes-of-a-given-string/ 11 | 12 | ## Problem Statement 13 | 14 | You are given a string array `words` and a string `s`, where `words[i]` and `s` comprise only of **lowercase English letters**. 15 | 16 | Return _the **number of strings** in_ `words` _that are a **prefix** of_ `s`. 17 | 18 | A **prefix** of a string is a substring that occurs at the beginning of the string. A **substring** is a contiguous sequence of characters within a string. 19 | 20 | **Example 1:** 21 | 22 | ``` 23 | Input: words = ["a","b","c","ab","bc","abc"], s = "abc" 24 | Output: 3 25 | Explanation: 26 | The strings in words which are a prefix of s = "abc" are: 27 | "a", "ab", and "abc". 28 | Thus the number of strings in words which are a prefix of s is 3. 29 | ``` 30 | 31 | **Example 2:** 32 | 33 | ``` 34 | Input: words = ["a","a"], s = "aa" 35 | Output: 2 36 | Explanation: 37 | Both of the strings are a prefix of s. 38 | Note that the same string can occur multiple times in words, and it should be counted each time. 39 | ``` 40 | 41 | **Constraints:** 42 | 43 | - `1 <= words.length <= 1000` 44 | - `1 <= words[i].length, s.length <= 10` 45 | - `words[i]` and `s` consist of lowercase English letters **only**. 46 | 47 | ## Approach 1: STL 48 | 49 | 50 | 51 | ```cpp 52 | class Solution { 53 | public: 54 | int countPrefixes(vector& words, string s) { 55 | int ans = 0; 56 | // if it returns index 0, then it means t is the prefix of s 57 | for (auto& t : words) ans += s.find(t) == 0; 58 | return ans; 59 | } 60 | }; 61 | ``` 62 | -------------------------------------------------------------------------------- /solutions/2200-2299/2278-percentage-of-letter-in-string.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @wkw | https://leetcode.com/problems/percentage-of-letter-in-string 4 | --- 5 | 6 | # 2278 - Percentage of Letter in String (Easy) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/percentage-of-letter-in-string 11 | 12 | ## Problem Statement 13 | 14 | Given a string s and a character letter, return the percentage of characters in s that equal letter rounded down to the nearest whole percent. 15 | 16 | **Example 1:** 17 | 18 | ``` 19 | Input: s = "foobar", letter = "o" 20 | Output: 33 21 | Explanation: 22 | The percentage of characters in s that equal the letter 'o' is 2 / 6 * 100% = 33% when rounded down, so we return 33. 23 | ``` 24 | 25 | **Example 2:** 26 | 27 | ``` 28 | Input: s = "jjjj", letter = "k" 29 | Output: 0 30 | Explanation: 31 | The percentage of characters in s that equal the letter 'k' is 0%, so we return 0. 32 | ``` 33 | 34 | **Constraints:** 35 | 36 | - $1 <= s.length <= 100$ 37 | - s consists of lowercase English letters. 38 | - letter is a lowercase English letter. 39 | 40 | ## Approach 1: Counting 41 | 42 | 43 | 44 | ```cpp 45 | class Solution { 46 | public: 47 | int percentageLetter(string s, char letter) { 48 | int cnt = 0, n = s.size(); 49 | // counting 50 | for (char& c : s) cnt += (c == letter); 51 | // return the percentage of characters in s 52 | // that equal letter rounded down to the nearest whole percent 53 | return ((double) cnt / n) * 100; 54 | } 55 | }; 56 | ``` 57 | -------------------------------------------------------------------------------- /solutions/2200-2299/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "2200 - 2299", 3 | "position": 24, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/2300-2399/2333-minimum-sum-of-squared-difference-medium.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @TBC | https://leetcode.com/problems/minimum-sum-of-squared-difference/ 4 | 5 | 6 | draft: true 7 | --- 8 | 9 | # 2333 - Minimum Sum of Squared Difference (Medium) 10 | 11 | ## Problem Link 12 | 13 | https://leetcode.com/problems/minimum-sum-of-squared-difference/ 14 | 15 | ## Problem Statement 16 | 17 | You are given two positive **0-indexed** integer arrays `nums1` and `nums2`, both of length `n`. 18 | 19 | The **sum of squared difference** of arrays `nums1` and `nums2` is defined as the **sum** of `(nums1[i] - nums2[i])2` for each `0 <= i < n`. 20 | 21 | You are also given two positive integers `k1` and `k2`. You can modify any of the elements of `nums1` by `+1` or `-1` at most `k1` times. Similarly, you can modify any of the elements of `nums2` by `+1` or `-1` at most `k2` times. 22 | 23 | Return _the minimum **sum of squared difference** after modifying array_ `nums1` _at most_ `k1` _times and modifying array_ `nums2` _at most_ `k2` _times_. 24 | 25 | **Note**: You are allowed to modify the array elements to become **negative** integers. 26 | 27 | **Example 1:** 28 | 29 | ``` 30 | Input: nums1 = [1,2,3,4], nums2 = [2,10,20,19], k1 = 0, k2 = 0 31 | Output: 579 32 | Explanation: The elements in nums1 and nums2 cannot be modified because k1 = 0 and k2 = 0. 33 | The sum of square difference will be: (1 - 2)2 + (2 - 10)2 + (3 - 20)2 + (4 - 19)2 = 579. 34 | ``` 35 | 36 | **Example 2:** 37 | 38 | ``` 39 | Input: nums1 = [1,4,10,12], nums2 = [5,8,6,9], k1 = 1, k2 = 1 40 | Output: 43 41 | Explanation: One way to obtain the minimum sum of square difference is: 42 | - Increase nums1[0] once. 43 | - Increase nums2[2] once. 44 | The minimum of the sum of square difference will be: 45 | (2 - 5)2 + (4 - 8)2 + (10 - 7)2 + (12 - 9)2 = 43. 46 | Note that, there are other ways to obtain the minimum of the sum of square difference, but there is no way to obtain a sum smaller than 43. 47 | ``` 48 | 49 | **Constraints:** 50 | 51 | - `n == nums1.length == nums2.length` 52 | - `1 <= n <= 10^5` 53 | - `0 <= nums1[i], nums2[i] <= 10^5` 54 | - `0 <= k1, k2 <= 10^9` 55 | 56 | ## Approach: TBC 57 | 58 | 59 | 60 | ``` 61 | // TODO 62 | ``` 63 | -------------------------------------------------------------------------------- /solutions/2300-2399/2334-subarray-with-elements-greater-than-varying-threshold-hard.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @TBC | https://leetcode.com/problems/subarray-with-elements-greater-than-varying-threshold 4 | 5 | 6 | draft: true 7 | --- 8 | 9 | # 2334 - Subarray With Elements Greater Than Varying Threshold (Hard) 10 | 11 | ## Problem Link 12 | 13 | https://leetcode.com/problems/subarray-with-elements-greater-than-varying-threshold 14 | 15 | ## Problem Statement 16 | 17 | You are given an integer array `nums` and an integer `threshold`. 18 | 19 | Find any subarray of `nums` of length `k` such that **every** element in the subarray is **greater** than `threshold / k`. 20 | 21 | Return _the **size** of **any** such subarray_. If there is no such subarray, return `-1`. 22 | 23 | A **subarray** is a contiguous non-empty sequence of elements within an array. 24 | 25 | **Example 1:** 26 | 27 | ``` 28 | Input: nums = [1,3,4,3,1], threshold = 6 29 | Output: 3 30 | Explanation: The subarray [3,4,3] has a size of 3, and every element is greater than 6 / 3 = 2. 31 | Note that this is the only valid subarray. 32 | ``` 33 | 34 | **Example 2:** 35 | 36 | ``` 37 | Input: nums = [6,5,6,5,8], threshold = 7 38 | Output: 1 39 | Explanation: The subarray [8] has a size of 1, and 8 > 7 / 1 = 7. So 1 is returned. 40 | Note that the subarray [6,5] has a size of 2, and every element is greater than 7 / 2 = 3.5. 41 | Similarly, the subarrays [6,5,6], [6,5,6,5], [6,5,6,5,8] also satisfy the given conditions. 42 | Therefore, 2, 3, 4, or 5 may also be returned. 43 | ``` 44 | 45 | **Constraints:** 46 | 47 | - `1 <= nums.length <= 10^5` 48 | - `1 <= nums[i], threshold <= 10^9` 49 | 50 | ## Approach: TBC 51 | 52 | 53 | 54 | ``` 55 | // TODO 56 | ``` 57 | -------------------------------------------------------------------------------- /solutions/2300-2399/2335-minimum-amount-of-time-to-fill-cups-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @TBC | https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups 4 | 5 | 6 | draft: true 7 | --- 8 | 9 | # 2335 - Minimum Amount of Time to Fill Cups (Easy) 10 | 11 | ## Problem Link 12 | 13 | https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups 14 | 15 | ## Problem Statement 16 | 17 | You have a water dispenser that can dispense cold, warm, and hot water. Every second, you can either fill up `2` cups with **different** types of water, or `1` cup of any type of water. 18 | 19 | You are given a **0-indexed** integer array `amount` of length `3` where `amount[0]`, `amount[1]`, and `amount[2]` denote the number of cold, warm, and hot water cups you need to fill respectively. Return _the **minimum** number of seconds needed to fill up all the cups_. 20 | 21 | **Example 1:** 22 | 23 | ``` 24 | Input: amount = [1,4,2] 25 | Output: 4 26 | Explanation: One way to fill up the cups is: 27 | Second 1: Fill up a cold cup and a warm cup. 28 | Second 2: Fill up a warm cup and a hot cup. 29 | Second 3: Fill up a warm cup and a hot cup. 30 | Second 4: Fill up a warm cup. 31 | It can be proven that 4 is the minimum number of seconds needed. 32 | ``` 33 | 34 | **Example 2:** 35 | 36 | ``` 37 | Input: amount = [5,4,4] 38 | Output: 7 39 | Explanation: One way to fill up the cups is: 40 | Second 1: Fill up a cold cup, and a hot cup. 41 | Second 2: Fill up a cold cup, and a warm cup. 42 | Second 3: Fill up a cold cup, and a warm cup. 43 | Second 4: Fill up a warm cup, and a hot cup. 44 | Second 5: Fill up a cold cup, and a hot cup. 45 | Second 6: Fill up a cold cup, and a warm cup. 46 | Second 7: Fill up a hot cup. 47 | ``` 48 | 49 | **Example 3:** 50 | 51 | ``` 52 | Input: amount = [5,0,0] 53 | Output: 5 54 | Explanation: Every second, we fill up a cold cup. 55 | ``` 56 | 57 | **Constraints:** 58 | 59 | - `amount.length == 3` 60 | - `0 <= amount[i] <= 100` 61 | 62 | ## Approach: TBC 63 | 64 | 65 | 66 | ``` 67 | // TODO 68 | ``` 69 | -------------------------------------------------------------------------------- /solutions/2300-2399/2336-smallest-number-in-infinite-set-medium.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @TBC | https://leetcode.com/problems/smallest-number-in-infinite-set 4 | 5 | 6 | draft: true 7 | --- 8 | 9 | # 2336 - Smallest Number in Infinite Set (Medium) 10 | 11 | ## Problem Link 12 | 13 | https://leetcode.com/problems/smallest-number-in-infinite-set 14 | 15 | ## Problem Statement 16 | 17 | You have a set which contains all positive integers `[1, 2, 3, 4, 5, ...]`. 18 | 19 | Implement the `SmallestInfiniteSet` class: 20 | 21 | - `SmallestInfiniteSet()` Initializes the **SmallestInfiniteSet** object to contain **all** positive integers. 22 | - `int popSmallest()` **Removes** and returns the smallest integer contained in the infinite set. 23 | - `void addBack(int num)` **Adds** a positive integer `num` back into the infinite set, if it is **not** already in the infinite set. 24 | 25 | **Example 1:** 26 | 27 | ``` 28 | Input 29 | ["SmallestInfiniteSet", "addBack", "popSmallest", "popSmallest", "popSmallest", "addBack", "popSmallest", "popSmallest", "popSmallest"] 30 | [[], [2], [], [], [], [1], [], [], []] 31 | Output 32 | [null, null, 1, 2, 3, null, 1, 4, 5] 33 | 34 | Explanation 35 | SmallestInfiniteSet smallestInfiniteSet = new SmallestInfiniteSet(); 36 | smallestInfiniteSet.addBack(2); // 2 is already in the set, so no change is made. 37 | smallestInfiniteSet.popSmallest(); // return 1, since 1 is the smallest number, and remove it from the set. 38 | smallestInfiniteSet.popSmallest(); // return 2, and remove it from the set. 39 | smallestInfiniteSet.popSmallest(); // return 3, and remove it from the set. 40 | smallestInfiniteSet.addBack(1); // 1 is added back to the set. 41 | smallestInfiniteSet.popSmallest(); // return 1, since 1 was added back to the set and 42 | // is the smallest number, and remove it from the set. 43 | smallestInfiniteSet.popSmallest(); // return 4, and remove it from the set. 44 | smallestInfiniteSet.popSmallest(); // return 5, and remove it from the set. 45 | ``` 46 | 47 | **Constraints:** 48 | 49 | - `1 <= num <= 1000` 50 | - At most `1000` calls will be made **in total** to `popSmallest` and `addBack`. 51 | 52 | ## Approach: TBC 53 | 54 | 55 | 56 | ``` 57 | // TODO 58 | ``` 59 | -------------------------------------------------------------------------------- /solutions/2300-2399/2338-count-the-number-of-ideal-arrays-hard.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @TBC | https://leetcode.com/problems/count-the-number-of-ideal-arrays 4 | 5 | 6 | draft: true 7 | --- 8 | 9 | # 2338 - Count the Number of Ideal Arrays (Hard) 10 | 11 | ## Problem Link 12 | 13 | https://leetcode.com/problems/count-the-number-of-ideal-arrays 14 | 15 | ## Problem Statement 16 | 17 | You are given two integers `n` and `maxValue`, which are used to describe an **ideal** array. 18 | 19 | A **0-indexed** integer array `arr` of length `n` is considered **ideal** if the following conditions hold: 20 | 21 | - Every `arr[i]` is a value from `1` to `maxValue`, for `0 <= i < n`. 22 | - Every `arr[i]` is divisible by `arr[i - 1]`, for `0 < i < n`. 23 | 24 | Return _the number of **distinct** ideal arrays of length_ `n`. Since the answer may be very large, return it modulo `10^9 + 7`. 25 | 26 | **Example 1:** 27 | 28 | ``` 29 | Input: n = 2, maxValue = 5 30 | Output: 10 31 | Explanation: The following are the possible ideal arrays: 32 | - Arrays starting with the value 1 (5 arrays): [1,1], [1,2], [1,3], [1,4], [1,5] 33 | - Arrays starting with the value 2 (2 arrays): [2,2], [2,4] 34 | - Arrays starting with the value 3 (1 array): [3,3] 35 | - Arrays starting with the value 4 (1 array): [4,4] 36 | - Arrays starting with the value 5 (1 array): [5,5] 37 | There are a total of 5 + 2 + 1 + 1 + 1 = 10 distinct ideal arrays. 38 | ``` 39 | 40 | **Example 2:** 41 | 42 | ``` 43 | Input: n = 5, maxValue = 3 44 | Output: 11 45 | Explanation: The following are the possible ideal arrays: 46 | - Arrays starting with the value 1 (9 arrays): 47 | - With no other distinct values (1 array): [1,1,1,1,1] 48 | - With 2nd distinct value 2 (4 arrays): [1,1,1,1,2], [1,1,1,2,2], [1,1,2,2,2], [1,2,2,2,2] 49 | - With 2nd distinct value 3 (4 arrays): [1,1,1,1,3], [1,1,1,3,3], [1,1,3,3,3], [1,3,3,3,3] 50 | - Arrays starting with the value 2 (1 array): [2,2,2,2,2] 51 | - Arrays starting with the value 3 (1 array): [3,3,3,3,3] 52 | There are a total of 9 + 1 + 1 = 11 distinct ideal arrays. 53 | ``` 54 | 55 | **Constraints:** 56 | 57 | - `2 <= n <= 10^4` 58 | - `1 <= maxValue <= 10^4` 59 | 60 | ## Approach: TBC 61 | 62 | 63 | 64 | ``` 65 | // TODO 66 | ``` 67 | -------------------------------------------------------------------------------- /solutions/2300-2399/2351-first-letter-to-appear-twice-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @wkw | https://leetcode.com/problems/first-letter-to-appear-twice 4 | 5 | 6 | tags: ['Hash Map'] 7 | --- 8 | 9 | # 2351 - First Letter to Appear Twice (Easy) 10 | 11 | ## Problem Link 12 | 13 | https://leetcode.com/problems/first-letter-to-appear-twice 14 | 15 | ## Problem Statement 16 | 17 | Given a string `s` consisting of lowercase English letters, return _the first letter to appear **twice**_. 18 | 19 | **Note**: 20 | 21 | - A letter `a` appears twice before another letter `b` if the **second** occurrence of `a` is before the **second** occurrence of `b`. 22 | - `s` will contain at least one letter that appears twice. 23 | 24 | **Example 1:** 25 | 26 | ``` 27 | Input: s = "abccbaacz" 28 | Output: "c" 29 | Explanation: 30 | The letter 'a' appears on the indexes 0, 5 and 6. 31 | The letter 'b' appears on the indexes 1 and 4. 32 | The letter 'c' appears on the indexes 2, 3 and 7. 33 | The letter 'z' appears on the index 8. 34 | The letter 'c' is the first letter to appear twice, because out of all the letters the index of its second occurrence is the smallest. 35 | ``` 36 | 37 | **Example 2:** 38 | 39 | ``` 40 | Input: s = "abcdd" 41 | Output: "d" 42 | Explanation: 43 | The only letter that appears twice is 'd' so we return 'd'. 44 | ``` 45 | 46 | **Constraints:** 47 | 48 | - `2 <= s.length <= 100` 49 | - `s` consists of lowercase English letters. 50 | - `s` has at least one repeated letter. 51 | 52 | ## Approach 1: Hash Map 53 | 54 | 55 | 56 | ```cpp 57 | class Solution { 58 | public: 59 | char repeatedCharacter(string s) { 60 | // store the frequency of each character 61 | // alternatively, we can use int cnt[26]; 62 | unordered_map m; 63 | // for each character, check the frequency 64 | // if it appears twice, return that character 65 | for (auto& c: s) if (++m[c] == 2) return c; 66 | // return the last one 67 | return s.back(); 68 | } 69 | }; 70 | ``` 71 | -------------------------------------------------------------------------------- /solutions/2300-2399/2357-make-array-zero-by-subtracting-equal-amounts-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @wkw | https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts 4 | --- 5 | 6 | # 2357 - Make Array Zero by Subtracting Equal Amounts (Easy) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts 11 | 12 | ## Problem Statement 13 | 14 | You are given a non-negative integer array `nums`. In one operation, you must: 15 | 16 | - Choose a positive integer `x` such that `x` is less than or equal to the **smallest non-zero** element in `nums`. 17 | - Subtract `x` from every **positive** element in `nums`. 18 | 19 | Return _the **minimum** number of operations to make every element in_ `nums` _equal to_ `0`. 20 | 21 | **Example 1:** 22 | 23 | ``` 24 | Input: nums = [1,5,0,3,5] 25 | Output: 3 26 | Explanation: 27 | In the first operation, choose x = 1. Now, nums = [0,4,0,2,4]. 28 | In the second operation, choose x = 2. Now, nums = [0,2,0,0,2]. 29 | In the third operation, choose x = 2. Now, nums = [0,0,0,0,0]. 30 | ``` 31 | 32 | **Example 2:** 33 | 34 | ``` 35 | Input: nums = [0] 36 | Output: 0 37 | Explanation: Each element in nums is already 0 so no operations are needed. 38 | ``` 39 | 40 | **Constraints:** 41 | 42 | - `1 <= nums.length <= 100` 43 | - `0 <= nums[i] <= 100` 44 | 45 | ## Approach: Counting 46 | 47 | Observations: 48 | 49 | - We can remove all numbers `x` in one go 50 | - We need $n$ moves to remove $n$ distinct numbers 51 | - Hence, the problem is to find out the number of different positive numbers 52 | 53 | 54 | 55 | ```go 56 | func minimumOperations(nums []int) int { 57 | s := make(map[int]bool) 58 | for _, v := range nums { 59 | if v > 0 { 60 | s[v] = true 61 | } 62 | } 63 | return len(s) 64 | } 65 | ``` 66 | -------------------------------------------------------------------------------- /solutions/2300-2399/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "2300 - 2399", 3 | "position": 25, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/2400-2499/2404-most-frequent-even-element-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/most-frequent-even-element/' 3 | --- 4 | 5 | # 2404 - Most Frequent Even Element (Easy) 6 | 7 | ## Problem Statement 8 | 9 | Given an integer array `nums`, return _the most frequent even element_. 10 | 11 | If there is a tie, return the **smallest** one. If there is no such element, return `-1`. 12 | 13 | **Example 1:** 14 | 15 | ``` 16 | Input: nums = [0,1,2,2,4,4,1] 17 | Output: 2 18 | Explanation: 19 | The even elements are 0, 2, and 4. Of these, 2 and 4 appear the most. 20 | We return the smallest one, which is 2. 21 | ``` 22 | 23 | **Example 2:** 24 | 25 | ``` 26 | Input: nums = [4,4,4,9,2,4] 27 | Output: 4 28 | Explanation: 4 is the even element appears the most. 29 | ``` 30 | 31 | **Example 3:** 32 | 33 | ``` 34 | Input: nums = [29,47,21,41,13,37,25,7] 35 | Output: -1 36 | Explanation: There is no even element. 37 | ``` 38 | 39 | **Constraints:** 40 | 41 | - `1 <= nums.length <= 2000` 42 | - `0 <= nums[i] <= 10^5` 43 | 44 | ## Approach 1: Hash Map 45 | 46 | 47 | 48 | ```cpp 49 | class Solution { 50 | public: 51 | int mostFrequentEven(vector& nums) { 52 | // init ans to -1 here in case there is no such element 53 | int ans = -1, mx = 0; 54 | // use hash map to store the frequency of each element 55 | map m; 56 | for (auto &x : nums) m[x]++; 57 | // iterate each element in the hash map 58 | for (auto &x : m) { 59 | // x.first is the element 60 | // x.second is the frequency of that element 61 | // if the element is even -> x.first % 2 == 0 62 | // and if the count is greater than the current maximum -> x.second > mx 63 | if (x.first % 2 == 0 && x.second > mx) { 64 | // then we can update the maximum 65 | mx = x.second; 66 | // and this element can be the answer 67 | ans = x.first; 68 | } 69 | } 70 | return ans; 71 | } 72 | }; 73 | ``` 74 | -------------------------------------------------------------------------------- /solutions/2400-2499/2405-optimal-partition-of-string-medium.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/optimal-partition-of-string/' 3 | --- 4 | 5 | # 2405 - Optimal Partition of String (Medium) 6 | 7 | ## Problem Statement 8 | 9 | Given a string `s`, partition the string into one or more **substrings** such that the characters in each substring are **unique**. That is, no letter appears in a single substring more than **once**. 10 | 11 | Return _the **minimum** number of substrings in such a partition._ 12 | 13 | Note that each character should belong to exactly one substring in a partition. 14 | 15 | **Example 1:** 16 | 17 | ``` 18 | Input: s = "abacaba" 19 | Output: 4 20 | Explanation: 21 | Two possible partitions are ("a","ba","cab","a") and ("ab","a","ca","ba"). 22 | It can be shown that 4 is the minimum number of substrings needed. 23 | ``` 24 | 25 | **Example 2:** 26 | 27 | ``` 28 | Input: s = "ssssss" 29 | Output: 6 30 | Explanation: 31 | The only valid partition is ("s","s","s","s","s","s"). 32 | ``` 33 | 34 | **Constraints:** 35 | 36 | - `1 <= s.length <= 1e5` 37 | - `s` consists of only English lowercase letters. 38 | 39 | ## Approach 1: Greedy 40 | 41 | 42 | 43 | ```cpp 44 | class Solution { 45 | public: 46 | // the idea is to keep each partition as long as possible 47 | // so that we could have the minimum number of substrings 48 | int partitionString(string s) { 49 | // the minimum number of substring is at least 1 50 | // e.g. "a" 51 | int ans = 1; 52 | // cnt is used to count the frequency of each character 53 | vector cnt(26); 54 | // for each character 55 | for (auto& c : s) { 56 | // we check if it exists before 57 | // if so, then we should create a new partition 58 | // because no letter appears in a single substring more than once 59 | if (cnt[c - 'a']) { 60 | // reset the counter 61 | cnt = vector(26); 62 | // create a new partition 63 | ans++; 64 | } 65 | // increase the frequency of the current character by 1 66 | cnt[c - 'a']++; 67 | } 68 | return ans; 69 | } 70 | }; 71 | ``` 72 | -------------------------------------------------------------------------------- /solutions/2400-2499/2433-find-the-original-array-of-prefix-xor-medium.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: >- 3 | Author: @vigneshshiv | https://leetcode.com/problems/find-the-original-array-of-prefix-xor/ 4 | --- 5 | 6 | # 2433 - Find the Original array of prefix XOR (Medium) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/find-the-original-array-of-prefix-xor/ 11 | 12 | ## Problem Statement 13 | 14 | You are given an **integer** array `pref` of size `n`. Find and return _the array `arr` of size `n` that satisfies_: 15 | 16 | - `pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i]`. Note that `^` denotes the **bitwise-xor** operation. 17 | 18 | It can be proven that the answer is **unique**. 19 | 20 | **Example 1:** 21 | 22 | ``` 23 | Input: pref = [5,2,0,3,1] 24 | Output: [5,7,2,3,2] 25 | Explanation: From the array [5,7,2,3,2] we have the following: 26 | - pref[0] = 5. 27 | - pref[1] = 5 ^ 7 = 2. 28 | - pref[2] = 5 ^ 7 ^ 2 = 0. 29 | - pref[3] = 5 ^ 7 ^ 2 ^ 3 = 3. 30 | - pref[4] = 5 ^ 7 ^ 2 ^ 3 ^ 2 = 1. 31 | ``` 32 | 33 | **Example 2:** 34 | 35 | ``` 36 | Input: pref = [13] 37 | Output: [13] 38 | Explanation: We have pref[0] = arr[0] = 13. 39 | ``` 40 | 41 | **Constraints:** 42 | 43 | - `1 <= pref.length <= 10^5` 44 | - `0 <= pref[i] <= 10^6` 45 | 46 | ## Approach 1: STL 47 | 48 | Time Complexity: $O(n)$, where $n$ - # of elements in the array 49 | 50 | Space Complexity: $O(n)$ 51 | 52 | 53 | 54 | 55 | 56 | ```java 57 | class Solution { 58 | public int[] findArray(int[] pref) { 59 | int[] nums = new int[pref.length]; 60 | nums[0] = pref[0]; 61 | for (int i = 1; i < pref.length; i++) { 62 | nums[i] = pref[i] ^ pref[i - 1]; 63 | } 64 | return nums; 65 | } 66 | } 67 | ``` 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /solutions/2400-2499/2469-convert-the-temperature-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/convert-the-temperature/' 3 | tags: [Math] 4 | --- 5 | 6 | # 2469 - Convert the Temperature (Easy) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/convert-the-temperature/ 11 | 12 | ## Problem Statement 13 | 14 | You are given a non-negative floating point number rounded to two decimal places `celsius`, that denotes the **temperature in Celsius**. 15 | 16 | You should convert Celsius into **Kelvin** and **Fahrenheit** and return it as an array `ans = [kelvin, fahrenheit]`. 17 | 18 | Return *the array ans.*Answers within `10-5` of the actual answer will be accepted. 19 | 20 | **Note that:** 21 | 22 | - `Kelvin = Celsius + 273.15` 23 | - `Fahrenheit = Celsius * 1.80 + 32.00` 24 | 25 | **Example 1:** 26 | 27 | ``` 28 | Input: celsius = 36.50 29 | Output: [309.65000,97.70000] 30 | Explanation: Temperature at 36.50 Celsius converted in Kelvin is 309.65 and converted in Fahrenheit is 97.70. 31 | ``` 32 | 33 | **Example 2:** 34 | 35 | ``` 36 | Input: celsius = 122.11 37 | Output: [395.26000,251.79800] 38 | Explanation: Temperature at 122.11 Celsius converted in Kelvin is 395.26 and converted in Fahrenheit is 251.798. 39 | ``` 40 | 41 | **Constraints:** 42 | 43 | - `0 <= celsius <= 1000` 44 | 45 | ## Approach 1: Just do it 46 | 47 | - Kelvin = Celsius + 273.15 48 | - Fahrenheit = Celsius \* 1.80 + 32.00 49 | 50 | 51 | 52 | 53 | 54 | ```cpp 55 | class Solution { 56 | public: 57 | vector convertTemperature(double celsius) { 58 | return { 59 | celsius + 273.15, 60 | celsius * 1.80 + 32.00 61 | }; 62 | } 63 | }; 64 | ``` 65 | 66 | 67 | 68 | -------------------------------------------------------------------------------- /solutions/2400-2499/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "2400 - 2499", 3 | "position": 26, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/2500-2599/2520-count-the-digits-that-divide-a-number-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/count-the-digits-that-divide-a-number/' 3 | --- 4 | 5 | # 2520 - Count the Digits That Divide a Number (Easy) 6 | 7 | ## Problem Link 8 | 9 | https://leetcode.com/problems/count-the-digits-that-divide-a-number/ 10 | 11 | ## Problem Statement 12 | 13 | Given an integer `num`, return _the number of digits in num that divide_`num`. 14 | 15 | An integer `val` divides `nums` if `nums % val == 0`. 16 | 17 | **Example 1:** 18 | 19 | ``` 20 | Input: num = 7 21 | Output: 1 22 | Explanation: 7 divides itself, hence the answer is 1. 23 | ``` 24 | 25 | **Example 2:** 26 | 27 | ``` 28 | Input: num = 121 29 | Output: 2 30 | Explanation: 121 is divisible by 1, but not 2. Since 1 occurs twice as a digit, we return 2. 31 | ``` 32 | 33 | **Example 3:** 34 | 35 | ``` 36 | Input: num = 1248 37 | Output: 4 38 | Explanation: 1248 is divisible by all of its digits, hence the answer is 4. 39 | ``` 40 | 41 | **Constraints:** 42 | 43 | - `1 <= num <= 10^9` 44 | - `num` does not contain `0` as one of its digits. 45 | 46 | ## Approach 1: Convert to String 47 | 48 | 49 | 50 | 51 | 52 | ```cpp 53 | class Solution { 54 | public: 55 | int countDigits(int num) { 56 | int ans = 0; 57 | // convert num to string 58 | string s = to_string(num); 59 | // for each character 60 | for (auto c : s) { 61 | // convert it to number 62 | int d = c - '0'; 63 | // check if it divisible 64 | ans += num % d == 0; 65 | } 66 | return ans; 67 | } 68 | }; 69 | ``` 70 | 71 | 72 | 73 | 74 | ## Approach 2: Check each digit 75 | 76 | 77 | 78 | 79 | 80 | ```cpp 81 | class Solution { 82 | public: 83 | int countDigits(int num) { 84 | int ans = 0, n = num; 85 | while (n > 0) { 86 | // check each digit using remainder 87 | ans += num % (n % 10) == 0; 88 | // move to the next digit 89 | n /= 10; 90 | } 91 | return ans; 92 | } 93 | }; 94 | ``` 95 | 96 | 97 | 98 | -------------------------------------------------------------------------------- /solutions/2500-2599/2529-maximum-count-of-positive-integer-and-negative-integer-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/maximum-count-of-positive-integer-and-negative-integer/' 3 | --- 4 | 5 | # 2529 - Maximum Count of Positive Integer and Negative Integer (Easy) 6 | 7 | ## Problem Link 8 | 9 | https://leetcode.com/problems/maximum-count-of-positive-integer-and-negative-integer/ 10 | 11 | ## Problem Statement 12 | 13 | Given an array `nums` sorted in **non-decreasing** order, return _the maximum between the number of positive integers and the number of negative integers._ 14 | 15 | - In other words, if the number of positive integers in `nums` is `pos` and the number of negative integers is `neg`, then return the maximum of `pos` and `neg`. 16 | 17 | **Note** that `0` is neither positive nor negative. 18 | 19 | **Example 1:** 20 | 21 | ``` 22 | Input: nums = [-2,-1,-1,1,2,3] 23 | Output: 3 24 | Explanation: There are 3 positive integers and 3 negative integers. The maximum count among them is 3. 25 | ``` 26 | 27 | **Example 2:** 28 | 29 | ``` 30 | Input: nums = [-3,-2,-1,0,0,1,2] 31 | Output: 3 32 | Explanation: There are 2 positive integers and 3 negative integers. The maximum count among them is 3. 33 | ``` 34 | 35 | **Example 3:** 36 | 37 | ``` 38 | Input: nums = [5,20,66,1314] 39 | Output: 4 40 | Explanation: There are 4 positive integers and 0 negative integers. The maximum count among them is 4. 41 | ``` 42 | 43 | **Constraints:** 44 | 45 | - `1 <= nums.length <= 2000` 46 | - `-2000 <= nums[i] <= 2000` 47 | - `nums` is sorted in a **non-decreasing order**. 48 | 49 | ## Approach 1: Counting 50 | 51 | 52 | 53 | 54 | 55 | ```cpp 56 | class Solution { 57 | public: 58 | int maximumCount(vector& nums) { 59 | int pos = 0, neg = 0; 60 | for (auto x : nums) { 61 | // count positive numbers 62 | if (x > 0) pos += 1; 63 | // count negative numbers 64 | if (x < 0) neg += 1; 65 | } 66 | // take the max of pos and neg 67 | return max(pos, neg); 68 | } 69 | }; 70 | ``` 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /solutions/2500-2599/2571-minimum-operations-to-reduce-an-integer-to-0-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/minimum-operations-to-reduce-an-integer-to-0/' 3 | --- 4 | 5 | # 2571 - Minimum Operations to Reduce an Integer to 0 (Easy) 6 | 7 | ## Problem Link 8 | 9 | https://leetcode.com/problems/minimum-operations-to-reduce-an-integer-to-0/ 10 | 11 | ## Problem Statement 12 | 13 | You are given a positive integer `n`, you can do the following operation **any** number of times: 14 | 15 | - Add or subtract a **power** of `2` from `n`. 16 | 17 | Return _the **minimum** number of operations to make_`n`_equal to_`0`. 18 | 19 | A number `x` is power of `2` if `x == 2i` where `i >= 0`_._ 20 | 21 | **Example 1:** 22 | 23 | ``` 24 | Input: n = 39 25 | Output: 3 26 | Explanation: We can do the following operations: 27 | - Add 20 = 1 to n, so now n = 40. 28 | - Subtract 23 = 8 from n, so now n = 32. 29 | - Subtract 25 = 32 from n, so now n = 0. 30 | It can be shown that 3 is the minimum number of operations we need to make n equal to 0. 31 | ``` 32 | 33 | **Example 2:** 34 | 35 | ``` 36 | Input: n = 54 37 | Output: 3 38 | Explanation: We can do the following operations: 39 | - Add 21 = 2 to n, so now n = 56. 40 | - Add 23 = 8 to n, so now n = 64. 41 | - Subtract 26 = 64 from n, so now n = 0. 42 | So the minimum number of operations is 3. 43 | ``` 44 | 45 | **Constraints:** 46 | 47 | - `1 <= n <= 10^5` 48 | 49 | ## Approach 1: DP 50 | 51 | 52 | 53 | 54 | 55 | ```py 56 | class Solution: 57 | def minOperations(self, n: int) -> int: 58 | # precompute power of 2 59 | p = {1 << i for i in range(20)} 60 | def dp(x): 61 | # reach 0 -> 0 operation 62 | if x == 0: return 0 63 | # if x is a power of 2, 64 | # we need 1 operation (i.e. subtract itself) 65 | if x in p: return 1 66 | # otherwise we either add / subtract the lsb to x 67 | # e.g. 0111 -> 1000 -> 0000 68 | # e.g. 1001 -> 1000 -> 0000 69 | return min(dp(x + (x & -x)), dp(x - (x & -x))) + 1 70 | return dp(n) 71 | ``` 72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /solutions/2500-2599/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "2500 - 2599", 3 | "position": 27, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/2600-2699/2678-number-of-senior-citizens-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/number-of-senior-citizens/' 3 | --- 4 | 5 | # 2678 - Number of Senior Citizens (Easy) 6 | 7 | ## Problem Link 8 | 9 | https://leetcode.com/problems/number-of-senior-citizens/ 10 | 11 | ## Problem Statement 12 | 13 | You are given a **0-indexed** array of strings `details`. Each element of `details` provides information about a given passenger compressed into a string of length `15`. The system is such that: 14 | 15 | - The first ten characters consist of the phone number of passengers. 16 | - The next character denotes the gender of the person. 17 | - The following two characters are used to indicate the age of the person. 18 | - The last two characters determine the seat allotted to that person. 19 | 20 | Return _the number of passengers who are **strictly\*\***more than 60 years old\*\*._ 21 | 22 | **Example 1:** 23 | 24 | ``` 25 | Input: details = ["7868190130M7522","5303914400F9211","9273338290F4010"] 26 | Output: 2 27 | Explanation: The passengers at indices 0, 1, and 2 have ages 75, 92, and 40. Thus, there are 2 people who are over 60 years old. 28 | ``` 29 | 30 | **Example 2:** 31 | 32 | ``` 33 | Input: details = ["1313579440F2036","2921522980M5644"] 34 | Output: 0 35 | Explanation: None of the passengers are older than 60. 36 | ``` 37 | 38 | **Constraints:** 39 | 40 | - `1 <= details.length <= 100` 41 | - `details[i].length == 15` 42 | - `details[i] consists of digits from '0' to '9'.` 43 | - `details[i][10] is either 'M' or 'F' or 'O'.` 44 | - The phone numbers and seat numbers of the passengers are distinct. 45 | 46 | ## Approach 1: Extract The Number 47 | 48 | 49 | 50 | 51 | 52 | ```py 53 | class Solution: 54 | def countSeniors(self, details: List[str]) -> int: 55 | res = 0 56 | for detail in details: 57 | # just check if the age is strictly more than 60 years old 58 | if int(detail[11:13]) > 60: 59 | res += 1 60 | return res 61 | 62 | ``` 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /solutions/2600-2699/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "2600 - 2699", 3 | "position": 28, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/2700-2799/2750-ways-to-split-array-into-good-subarrays-medium.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/ways-to-split-array-into-good-subarrays/' 3 | tags: [Array, Math, Dynamic Programming] 4 | --- 5 | 6 | # 2750 - Ways to Split Array Into Good Subarrays (Medium) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/ways-to-split-array-into-good-subarrays/ 11 | 12 | ## Problem Statement 13 | 14 | You are given a binary array `nums`. 15 | 16 | A subarray of an array is **good** if it contains **exactly** **one** element with the value `1`. 17 | 18 | Return _an integer denoting the number of ways to split the array_`nums`_into **good** subarrays_. As the number may be too large, return it **modulo** `1e9 + 7`. 19 | 20 | A subarray is a contiguous **non-empty** sequence of elements within an array. 21 | 22 | **Example 1:** 23 | 24 | ``` 25 | Input: nums = [0,1,0,0,1] 26 | Output: 3 27 | Explanation: There are 3 ways to split nums into good subarrays: 28 | - [0,1] [0,0,1] 29 | - [0,1,0] [0,1] 30 | - [0,1,0,0] [1] 31 | ``` 32 | 33 | **Example 2:** 34 | 35 | ``` 36 | Input: nums = [0,1,0] 37 | Output: 1 38 | Explanation: There is 1 way to split nums into good subarrays: 39 | - [0,1,0] 40 | ``` 41 | 42 | **Constraints:** 43 | 44 | - $1 <= nums.length <= 10^5$ 45 | - $0 <= nums[i] <= 1$ 46 | 47 | ## Approach 1: Counting 48 | 49 | 50 | 51 | 52 | 53 | ```cpp 54 | class Solution { 55 | public: 56 | int numberOfGoodSubarraySplits(vector& nums) { 57 | int M = 1e9 + 7, n = nums.size(); 58 | long long ans = 1; 59 | vector ones; 60 | // we store all the indices `i` where nums[i] is 1 61 | for (int i = 0; i < n; i++) if (nums[i] == 1) ones.push_back(i); 62 | // if there is no ones, then the answer is obviously zero 63 | if (ones.size() == 0) return 0; 64 | // for each gap, calculate the numbers of ways (ones[i] - ones[i - 1]) 65 | // and multiply the answer 66 | // and take the mod 67 | for (int i = 1; i < ones.size(); i++) (ans *= (ones[i] - ones[i - 1])) %= M; 68 | return ans; 69 | } 70 | }; 71 | ``` 72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /solutions/2700-2799/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "2700 - 2799", 3 | "position": 29, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/2800-2899/2839-check-if-strings-can-be-made-equal-with-operations-i-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/check-if-strings-can-be-made-equal-with-operations-i/' 3 | --- 4 | 5 | # 2839 - Check if Strings Can be Made Equal With Operations I (Easy) 6 | 7 | ## Problem Link 8 | 9 | https://leetcode.com/problems/check-if-strings-can-be-made-equal-with-operations-i/ 10 | 11 | ## Problem Statement 12 | 13 | You are given two strings `s1` and `s2`, both of length `4`, consisting of **lowercase** English letters. 14 | 15 | You can apply the following operation on any of the two strings **any** number of times: 16 | 17 | - Choose any two indices `i` and `j` such that `j - i = 2`, then **swap** the two characters at those indices in the string. 18 | 19 | Return `true`_if you can make the strings_`s1`_and_`s2`_equal, and_`false`_otherwise_. 20 | 21 | **Example 1:** 22 | 23 | ``` 24 | Input: s1 = "abcd", s2 = "cdab" 25 | Output: true 26 | Explanation: We can do the following operations on s1: 27 | - Choose the indices i = 0, j = 2. The resulting string is s1 = "cbad". 28 | - Choose the indices i = 1, j = 3. The resulting string is s1 = "cdab" = s2. 29 | ``` 30 | 31 | **Example 2:** 32 | 33 | ``` 34 | Input: s1 = "abcd", s2 = "dacb" 35 | Output: false 36 | Explanation: It is not possible to make the two strings equal. 37 | ``` 38 | 39 | **Constraints:** 40 | 41 | - `s1.length == s2.length == 4` 42 | - `s1` and `s2` consist only of lowercase English letters. 43 | 44 | ## Approach 1: Brute Force 45 | 46 | Since we have 4 characters and given we can only swap `s1[i]` and `s1[j]` where `j - i = 2`, we can brute force the solution by checking two cases. If $s1[0]$ is not same as $s2[0]$, we can only swap $s1[0]$ and $s1[2]$. Similarly, we perform the same logic on $s1[1]$ and compare $s1$ and $s2$ at the end. 47 | 48 | 49 | 50 | 51 | 52 | ```cpp 53 | class Solution { 54 | public: 55 | bool canBeEqual(string s1, string s2) { 56 | if (s1[0] ^ s2[0]) swap(s1[0], s1[2]); 57 | if (s1[1] ^ s2[1]) swap(s1[1], s1[3]); 58 | return s1 == s2; 59 | } 60 | }; 61 | ``` 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /solutions/2800-2899/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "2800 - 2899", 3 | "position": 30, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/2900-2999/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "2900 - 2999", 3 | "position": 31, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/3000-3099/3064-guess-the-number-using-bitwise-questions-i-medium.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/guess-the-number-using-bitwise-questions-i/' 3 | tags: [Bit Manipulation, Interactive] 4 | --- 5 | 6 | # 3064 - Guess the Number Using Bitwise Questions I (Medium) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/guess-the-number-using-bitwise-questions-i/ 11 | 12 | ## Problem Statement 13 | 14 | There is a number `n` that you have to find. 15 | 16 | There is also a pre-defined API `int commonSetBits(int num)`, which returns the number of bits where both `n` and `num` are `1` in that position of their binary representation. In other words, it returns the number of set bits in `n & num`, where `&` is the bitwise `AND` operator. 17 | 18 | Return _the number_ `n`. 19 | 20 | **Example 1:** 21 | 22 | **Input:** n = 31 23 | 24 | **Output:** 31 25 | 26 | **Explanation:** It can be proven that it's possible to find `31` using the provided API. 27 | 28 | **Example 2:** 29 | 30 | **Input:** n = 33 31 | 32 | **Output:** 33 33 | 34 | **Explanation:** It can be proven that it's possible to find `33` using the provided API. 35 | 36 | **Constraints:** 37 | 38 | - $1 <= n <= 2 ^ 30 - 1$ 39 | - $0 <= num <= 2 ^ 30 - 1$ 40 | - If you ask for some `num` out of the given range, the output wouldn't be reliable. 41 | 42 | ## Approach 1: Bit Manipulation 43 | 44 | 45 | 46 | 47 | 48 | ```cpp 49 | /** 50 | * Definition of commonSetBits API. 51 | * int commonSetBits(int num); 52 | */ 53 | 54 | class Solution { 55 | public: 56 | int findNumber() { 57 | int ans = 0; 58 | // ask for 2 ^ i for 0 <= i < 30 59 | for (int i = 0; i < 30; i++) { 60 | // since we only have one bit set in `num`, 61 | // commonSetBits returns either 0 or 1 62 | // e.g. 1010 & 0001 -> 0 63 | // e.g. 1011 & 0001 -> 1 64 | if (commonSetBits(1 << i)) { 65 | // if it is 1, then that means this bit in `n` is set 66 | // then use OR operator to set the bit to `ans` 67 | ans |= (1 << i); 68 | } 69 | } 70 | return ans; 71 | } 72 | }; 73 | ``` 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /solutions/3000-3099/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "3000 - 3099", 3 | "position": 32, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/3100-3199/3142-check-if-grid-satisfies-conditions-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/check-if-grid-satisfies-conditions/' 3 | tags: [Array, Matrix] 4 | --- 5 | 6 | # 3142 - Check if Grid Satisfies Conditions (Easy) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/check-if-grid-satisfies-conditions/ 11 | 12 | ## Problem Statement 13 | 14 | You are given a 2D matrix `grid` of size `m x n`. You need to check if each cell `grid[i][j]` is: 15 | 16 | - Equal to the cell below it, i.e. `grid[i][j] == grid[i + 1][j]` (if it exists). 17 | - Different from the cell to its right, i.e. `grid[i][j] != grid[i][j + 1]` (if it exists). 18 | 19 | Return `true` if **all** the cells satisfy these conditions, otherwise, return `false`. 20 | 21 | **Example 1:** 22 | 23 | **Input:** grid = [[1,0,2],[1,0,2]] 24 | 25 | **Output:** true 26 | 27 | **Explanation:** 28 | 29 | All the cells in the grid satisfy the conditions. 30 | 31 | **Example 2:** 32 | 33 | **Input:** grid = [[1,1,1],[0,0,0]] 34 | 35 | **Output:** false 36 | 37 | **Explanation:** 38 | 39 | All cells in the first row are equal. 40 | 41 | **Example 3:** 42 | 43 | **Input:** grid = [[1],[2],[3]] 44 | 45 | **Output:** false 46 | 47 | **Explanation:** 48 | 49 | Cells in the first column have different values. 50 | 51 | **Constraints:** 52 | 53 | - `1 <= n, m <= 10` 54 | - `0 <= grid[i][j] <= 9` 55 | 56 | ## Approach 1: Brute Force 57 | 58 | Iterate over each cell to check if the conditions can be satisified. 59 | 60 | - Time Complexity: $O(n * m)$ where $n$ is the number of rows and $m$ is the number of columns 61 | - Space Complexity: $O(1)$ 62 | 63 | 64 | 65 | 66 | 67 | ```py 68 | class Solution: 69 | def satisfiesConditions(self, grid: List[List[int]]) -> bool: 70 | n, m = len(grid), len(grid[0]) 71 | for i in range(n): 72 | for j in range(m): 73 | if i < n - 1 and grid[i][j] != grid[i + 1][j]: return False 74 | if j < m - 1 and grid[i][j] == grid[i][j + 1]: return False 75 | return True 76 | ``` 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /solutions/3100-3199/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "3100 - 3199", 3 | "position": 33, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/3200-3299/3289-the-two-sneaky-numbers-of-digitville-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/the-two-sneaky-numbers-of-digitville/' 3 | tags: [Array, Hash Table, Math] 4 | --- 5 | 6 | # 3289 - The Two Sneaky Numbers of Digitville (Easy) 7 | 8 | ## Problem Link 9 | 10 | https://leetcode.com/problems/the-two-sneaky-numbers-of-digitville/ 11 | 12 | ## Problem Statement 13 | 14 | In the town of Digitville, there was a list of numbers called `nums` containing integers from `0` to `n - 1`. Each number was supposed to appear **exactly once** in the list, however, **two** mischievous numbers sneaked in an _additional time_, making the list longer than usual. 15 | 16 | As the town detective, your task is to find these two sneaky numbers. Return an array of size **two** containing the two numbers (in _any order_), so peace can return to Digitville. 17 | 18 | **Example 1:** 19 | 20 | **Input:** nums = [0,1,1,0] 21 | 22 | **Output:** [0,1] 23 | 24 | **Explanation:** 25 | 26 | The numbers 0 and 1 each appear twice in the array. 27 | 28 | **Example 2:** 29 | 30 | **Input:** nums = [0,3,2,1,3,2] 31 | 32 | **Output:** [2,3] 33 | 34 | **Explanation:** 35 | 36 | The numbers 2 and 3 each appear twice in the array. 37 | 38 | **Example 3:** 39 | 40 | **Input:** nums = [7,1,5,4,3,4,6,0,9,5,8,2] 41 | 42 | **Output:** [4,5] 43 | 44 | **Explanation:** 45 | 46 | The numbers 4 and 5 each appear twice in the array. 47 | 48 | **Constraints:** 49 | 50 | - `2 <= n <= 100` 51 | - `nums.length == n + 2` 52 | - `0 <= nums[i] < n` 53 | - The input is generated such that `nums` contains **exactly** two repeated elements. 54 | 55 | ## Approach 1: Counter 56 | 57 | We can simply count the frequency and find which two numbers have appear more than one time. 58 | 59 | 60 | 61 | 62 | 63 | ```py 64 | class Solution: 65 | def getSneakyNumbers(self, nums: List[int]) -> List[int]: 66 | cnt = Counter(nums) 67 | return [x for x, f in cnt.items() if f > 1] 68 | ``` 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /solutions/3200-3299/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "3200 - 3299", 3 | "position": 34, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /solutions/3300-3399/3300-minimum-element-after-replacement-with-digit-sum-easy.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: 'Author: @wkw | https://leetcode.com/problems/minimum-element-after-replacement-with-digit-sum/' 3 | --- 4 | 5 | # 3300 - Minimum Element After Replacement With Digit Sum (Easy) 6 | 7 | ## Problem Link 8 | 9 | https://leetcode.com/problems/minimum-element-after-replacement-with-digit-sum/ 10 | 11 | ## Problem Statement 12 | 13 | You are given an integer array `nums`. 14 | 15 | You replace each element in `nums` with the **sum** of its digits. 16 | 17 | Return the **minimum** element in `nums` after all replacements. 18 | 19 | **Example 1:** 20 | 21 | **Input:** nums = [10,12,13,14] 22 | 23 | **Output:** 1 24 | 25 | **Explanation:** 26 | 27 | `nums` becomes `[1, 3, 4, 5]` after all replacements, with minimum element 1. 28 | 29 | **Example 2:** 30 | 31 | **Input:** nums = [1,2,3,4] 32 | 33 | **Output:** 1 34 | 35 | **Explanation:** 36 | 37 | `nums` becomes `[1, 2, 3, 4]` after all replacements, with minimum element 1. 38 | 39 | **Example 3:** 40 | 41 | **Input:** nums = [999,19,199] 42 | 43 | **Output:** 10 44 | 45 | **Explanation:** 46 | 47 | `nums` becomes `[27, 10, 19]` after all replacements, with minimum element 10. 48 | 49 | **Constraints:** 50 | 51 | - `1 <= nums.length <= 100` 52 | - `1 <= nums[i] <= 10^4` 53 | 54 | ## Approach 1: Brute Force 55 | 56 | For each element, we calculate the digit sum and use $res$ to keep track of the minimum one. 57 | 58 | 59 | 60 | 61 | 62 | ```py 63 | class Solution: 64 | def minElement(self, nums: List[int]) -> int: 65 | res = 10 ** 9 66 | for x in nums: 67 | s = 0 68 | while x > 0: 69 | s += x % 10 70 | x //= 10 71 | res = min(res, s) 72 | return res 73 | ``` 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /solutions/3300-3399/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "3300 - 3399", 3 | "position": 35, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Solutions categorised by Problem IDs" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/components/HomepageFeatures/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import clsx from 'clsx'; 3 | import styles from './styles.module.css'; 4 | 5 | const FeatureList = [ 6 | { 7 | title: 'DSA Topics Tutorials', 8 | Svg: require('@site/static/img/undraw_learning_sketching_nd4f.svg').default, 9 | description: ( 10 | <> 11 | Acquire knowledge of Data Structures and Algorithms, covering a range 12 | from fundamental to advanced level, by working through problems on 13 | LeetCode. 14 | 15 | ), 16 | }, 17 | { 18 | title: 'Detailed Explanations', 19 | Svg: require('@site/static/img/undraw_onboarding_re_6osc.svg').default, 20 | description: ( 21 | <> 22 | In contrast to many discussions posts, our approach is to offer in-depth 23 | explanations, both in-line and in the form of articles. 24 | 25 | ), 26 | }, 27 | { 28 | title: 'LeetCode Community', 29 | Svg: require('@site/static/img/undraw_community_re_cyrm.svg').default, 30 | description: ( 31 | <> 32 | Join our Discord group to engage in live conversations about Leetcode 33 | topics with other community members. 34 | 35 | ), 36 | }, 37 | ]; 38 | 39 | function Feature({ Svg, title, description }) { 40 | return ( 41 |
42 |
43 | 44 |
45 |
46 |

{title}

47 |

{description}

48 |
49 |
50 | ); 51 | } 52 | 53 | export default function HomepageFeatures() { 54 | return ( 55 |
56 |
57 |
58 | {FeatureList.map((props, idx) => ( 59 | 60 | ))} 61 |
62 |
63 |
64 | ); 65 | } 66 | -------------------------------------------------------------------------------- /src/components/HomepageFeatures/styles.module.css: -------------------------------------------------------------------------------- 1 | .features { 2 | display: flex; 3 | text-align: center; 4 | align-items: center; 5 | padding: 3rem 0; 6 | width: 100%; 7 | background: var(--ifm-feature-background-color); 8 | } 9 | 10 | .featureSvg { 11 | height: 200px; 12 | width: 200px; 13 | } 14 | -------------------------------------------------------------------------------- /src/components/SolutionAuthor/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | export default function SolutionAuthor({ name }) { 4 | return ( 5 |
6 | Written by {name} 7 |
8 | ); 9 | } 10 | -------------------------------------------------------------------------------- /src/components/Table/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import Tags from '@site/src/components/Tags'; 3 | 4 | export default function Table({ 5 | title, 6 | collectionLink, 7 | isSorted = true, 8 | data, 9 | }) { 10 | const hasTopic = data.some((d) => d.tags); 11 | const sortOrder = { 12 | Easy: 0, 13 | Medium: 1, 14 | Hard: 2, 15 | }; 16 | const renderDifficultyClassName = (difficulty) => { 17 | return difficulty.toLowerCase(); 18 | }; 19 | const renderRow = ( 20 | isSorted 21 | ? data.sort((x, y) => sortOrder[x.difficulty] - sortOrder[y.difficulty]) 22 | : data 23 | ).map((d, idx) => { 24 | return ( 25 |
26 | 31 | 34 | 42 | {hasTopic && ( 43 | 46 | )} 47 | 48 | ); 49 | }); 50 | 51 | return ( 52 | <> 53 |

{title}

54 | {collectionLink && ( 55 |

56 | Start Practicing:{' '} 57 | 58 | {collectionLink} 59 | 60 |

61 | )} 62 |
27 | 28 | {d.problemName} 29 | 30 | 32 | {d.difficulty} 33 | 35 | {d.solutionLink && ( 36 | 37 | View Solutions 38 | 39 | )} 40 | {!d.solutionLink && N/A} 41 | 44 | 45 |
63 | 64 | 65 | 66 | 67 | 68 | {hasTopic && } 69 | 70 | 71 | {renderRow} 72 |
Problem NameDifficultySolution LinkTopic
73 | 74 | ); 75 | } 76 | -------------------------------------------------------------------------------- /src/components/Tags/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | export default function Tags({ names }) { 4 | if (!names) return null; 5 | const tags = names.split(','); 6 | return ( 7 |
8 | {tags.map((tag, idx) => { 9 | return ( 10 | 11 | {tag} 12 | 13 | ); 14 | })} 15 |
16 | ); 17 | } 18 | -------------------------------------------------------------------------------- /src/components/TutorialCredits/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | export default function TutorialCredits({ authors, contributors }) { 4 | const authorNames = authors ? authors.split(',') : authors; 5 | const contributorNames = contributors 6 | ? contributors.split(',') 7 | : contributors; 8 | return ( 9 |
10 |
11 |
12 | {authorNames.length > 1 ? 'Authors: ' : 'Author: '} 13 |
14 |
15 | {authorNames.map((author) => { 16 | return ( 17 | {author} 18 | ); 19 | })} 20 |
21 |
22 | {contributorNames && ( 23 |
24 |
25 | {contributorNames.length > 1 ? 'Contributors: ' : 'Contributor: '} 26 |
27 |
28 | {contributorNames.map((contributor) => { 29 | return ( 30 | 31 | {contributor} 32 | 33 | ); 34 | })} 35 |
36 |
37 | )} 38 |
39 | ); 40 | } 41 | -------------------------------------------------------------------------------- /src/pages/index.module.css: -------------------------------------------------------------------------------- 1 | /** 2 | * CSS files with the .module.css suffix will be treated as CSS modules 3 | * and scoped locally. 4 | */ 5 | 6 | .heroBanner { 7 | padding: 4rem 0; 8 | text-align: center; 9 | position: relative; 10 | overflow: hidden; 11 | display: block; 12 | /* background-image: url('/static/img/banner.png'); */ 13 | /* background-size: cover; */ 14 | } 15 | 16 | .heroBanner img { 17 | margin: 0px 20px; 18 | } 19 | 20 | .buttons { 21 | --ifm-button-size-multiplier: 1.6; 22 | display: inline-flex; 23 | flex-wrap: wrap; 24 | align-items: center; 25 | } 26 | 27 | .buttons a, 28 | .buttons a:hover { 29 | color: #fff !important; 30 | background: #032341; 31 | width: 100%; 32 | padding: 10px; 33 | border: none; 34 | } 35 | 36 | .buttons a:last-of-type { 37 | margin-top: 20px; 38 | } 39 | 40 | .gitHubButton { 41 | overflow: hidden; 42 | } 43 | 44 | .highlightedColor { 45 | color: #f7f8f8; 46 | } 47 | 48 | .about { 49 | align-items: center; 50 | padding: 4rem 2rem; 51 | text-align: left; 52 | background: var(--ifm-about-background-color); 53 | } 54 | 55 | .advertise { 56 | align-items: center; 57 | padding: 4rem 2rem; 58 | text-align: left; 59 | background: var(--ifm-advertise-background-color); 60 | } 61 | 62 | @media only screen and (max-width: 768px) { 63 | .gitHubButtonWrapper { 64 | display: none; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/theme/MDXComponents.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | // Import the original mapper 3 | import MDXComponents from '@theme-original/MDXComponents'; 4 | import Tabs from '@theme/Tabs'; 5 | import TabItem from '@theme/TabItem'; 6 | import SolutionAuthor from '@site/src/components/SolutionAuthor'; 7 | import TutorialCredits from '@site/src/components/TutorialCredits'; 8 | import Table from '@site/src/components/Table'; 9 | 10 | export default { 11 | // Re-use the default mapping 12 | ...MDXComponents, 13 | // custom 14 | SolutionAuthor, 15 | Tabs, 16 | TabItem, 17 | TutorialCredits, 18 | Table, 19 | }; 20 | -------------------------------------------------------------------------------- /static/.nojekyll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wingkwong/leetcode-the-hard-way/56d707a6d4868aa8bfad3f048cb114485d3f6982/static/.nojekyll -------------------------------------------------------------------------------- /static/CNAME: -------------------------------------------------------------------------------- 1 | leetcodethehardway.com -------------------------------------------------------------------------------- /static/ads.txt: -------------------------------------------------------------------------------- 1 | google.com, pub-4531209581366540, DIRECT, f08c47fec0942fa0 -------------------------------------------------------------------------------- /static/img/banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wingkwong/leetcode-the-hard-way/56d707a6d4868aa8bfad3f048cb114485d3f6982/static/img/banner.png -------------------------------------------------------------------------------- /static/img/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wingkwong/leetcode-the-hard-way/56d707a6d4868aa8bfad3f048cb114485d3f6982/static/img/favicon.ico -------------------------------------------------------------------------------- /static/robots.txt: -------------------------------------------------------------------------------- 1 | User-agent: * 2 | Disallow: -------------------------------------------------------------------------------- /templates/euler.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Euler Path' 3 | description: '' 4 | hide_table_of_contents: false 5 | keywords: 6 | - leetcode 7 | - template 8 | - euler path 9 | --- 10 | 11 | 12 | 13 | 14 | ```cpp 15 | // Hierholzer's Algorithm 16 | void euler(unordered_map>& g, string src, vector& ans) { 17 | while(!g[src].empty()) { 18 | string nxt = g[src].front(); 19 | g[src].pop(); 20 | euler(g, nxt, ans); 21 | } 22 | ans.push_back(src); 23 | } 24 | 25 | // Example: 332. Reconstruct Itinerary 26 | // https://leetcode.com/problems/reconstruct-itinerary/ 27 | vector findItinerary(vector>& tickets) { 28 | vector ans; 29 | sort(tickets.begin(), tickets.end(), [&](const vector& x, const vector& y) { 30 | return x[1] < y[1]; 31 | }); 32 | unordered_map> g; 33 | for(auto x : tickets) { 34 | g[x[0]].push(x[1]); 35 | } 36 | string src = "JFK"; 37 | euler(g, src, ans); 38 | reverse(ans.begin(), ans.end()); 39 | return ans; 40 | } 41 | ``` 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /templates/fenwick-tree.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Fenwick Tree' 3 | description: '' 4 | hide_table_of_contents: false 5 | keywords: 6 | - leetcode 7 | - template 8 | - fenwick tree 9 | --- 10 | 11 | 12 | 13 | 14 | ```cpp 15 | template 16 | struct BIT { //1-indexed 17 | int n; vector t; 18 | BIT() {} 19 | BIT(int _n) { 20 | n = _n; t.assign(n + 1, 0); 21 | } 22 | T query(int i) { 23 | T ans = 0; 24 | for (; i >= 1; i -= (i & -i)) ans += t[i]; 25 | return ans; 26 | } 27 | void upd(int i, T val) { 28 | if (i <= 0) return; 29 | for (; i <= n; i += (i & -i)) t[i] += val; 30 | } 31 | void upd(int l, int r, T val) { 32 | upd(l, val); 33 | upd(r + 1, -val); 34 | } 35 | T query(int l, int r) { 36 | return query(r) - query(l - 1); 37 | } 38 | }; 39 | 40 | 41 | // BIT bit = BIT(n); 42 | ``` 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /templates/index.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Introduction' 3 | description: 'General templates for tackling LeetCode problems' 4 | hide_table_of_contents: true 5 | sidebar_position: 1 6 | keywords: 7 | - leetcode 8 | - templates 9 | --- 10 | 11 | Here you can find the general templates for tackling LeetCode problems. These templates are pre-written code or snippets. The goal of using these templates is to save time by providing a starting point for the solution, rather than having to start from scratch. Before using the templates, you should have deep understanding on the logic. 12 | -------------------------------------------------------------------------------- /templates/linked-list.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Linked List' 3 | description: '' 4 | hide_table_of_contents: false 5 | keywords: 6 | - leetcode 7 | - template 8 | - linked list 9 | --- 10 | 11 | ### Floyd's fast and slow pointer 12 | 13 | 14 | 15 | 16 | ```cpp 17 | ListNode* slow = head; 18 | ListNode* fast = head; 19 | while (fast != nullptr && fast->next != nullptr) { 20 | // do something here 21 | slow = slow->next; 22 | fast = fast->next->next; 23 | } 24 | ``` 25 | 26 | 27 | 28 | 29 | ```java 30 | ListNode slow = head, fast = head; 31 | while (fast != null && fast.next != null) { 32 | // do something here 33 | slow = slow.next; 34 | fast = fast.next.next; 35 | } 36 | ``` 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /templates/ordered-set.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Ordered Set and GNU C++ PBDS' 3 | description: 'a policy based data structure in g++ that keeps the unique elements in sorted order' 4 | hide_table_of_contents: false 5 | keywords: 6 | - leetcode 7 | - template 8 | - ordered set 9 | - gnu c++ pbds 10 | --- 11 | 12 | 13 | 14 | 15 | ```cpp 16 | #include 17 | #include 18 | using namespace __gnu_pbds; 19 | 20 | tree, rb_tree_tag, tree_order_statistics_node_update> x; 21 | tree, rb_tree_tag, tree_order_statistics_node_update> y; 22 | tree, rb_tree_tag, tree_order_statistics_node_update> p; 23 | tree, rb_tree_tag, tree_order_statistics_node_update> q; 24 | 25 | 26 | void solve() { 27 | int k = 5; 28 | x.insert(k); 29 | // Number of items strictly smaller than k 30 | x.order_of_key(k); 31 | // K-th element in a set (counting from zero) 32 | x.find_by_order(k); 33 | } 34 | ``` 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /templates/prefix-sum.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Prefix Sum' 3 | description: '' 4 | hide_table_of_contents: false 5 | keywords: 6 | - leetcode 7 | - template 8 | - prefix sum 9 | --- 10 | 11 | ### Prefix Sum - Starting with first element 12 | 13 | 14 | 15 | 16 | ```cpp 17 | vector pref(n); 18 | pref[0] = a[0]; 19 | for (int i = 1; i < n; i++) { 20 | pref[i] = pref[i - 1] + a[i]; 21 | } 22 | ``` 23 | 24 | 25 | 26 | 27 | ### Prefix Sum - Starting with 0 28 | 29 | 30 | 31 | 32 | ```cpp 33 | vector pref(n + 1); 34 | for (int i = 0; i < n; i++) { 35 | pref[i + 1] = pref[i] + a[i]; 36 | } 37 | ``` 38 | 39 | 40 | 41 | 42 | ### Suffix Sum - Starting with last element 43 | 44 | 45 | 46 | 47 | ```cpp 48 | vector suff(n); 49 | suff[n - 1] = a[n - 1]; 50 | for (int i = n - 2; i >= 0; i--) { 51 | suff[i] = suff[i + 1] + a[i]; 52 | } 53 | ``` 54 | 55 | 56 | 57 | 58 | ### Suffix Sum - Starting with 0 59 | 60 | 61 | 62 | 63 | ```cpp 64 | vector suff(n + 1); 65 | for (int i = n - 1; i >= 0; i--) { 66 | suff[i - 1] = suff[i] + a[i]; 67 | } 68 | ``` 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /templates/sparse-table.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Sparse Table' 3 | description: 'Range Queries finding min, max, gcd, lcm, and etc. The array cannot be changed between two queries.' 4 | hide_table_of_contents: false 5 | keywords: 6 | - leetcode 7 | - template 8 | - sparse table 9 | --- 10 | 11 | 12 | 13 | 14 | ```cpp 15 | template 16 | struct sparse_table { 17 | using T = typename remove_reference())>::type; 18 | vector> t; bin_op f; 19 | 20 | sparse_table(it first, it last, bin_op op) : t(1), f(op) { 21 | int n = distance(first, last); 22 | t.assign(32 - __builtin_clz(n), vector(n)); 23 | t[0].assign(first, last); 24 | for (int i = 1; i < t.size(); i++) 25 | for (int j = 0; j < n - (1 << i) + 1; j++) 26 | t[i][j] = f(t[i - 1][j], t[i - 1][j + (1 << (i - 1))]); 27 | } 28 | 29 | // returns f(a[l .. r]) in O(1) time 30 | T query(int l, int r) { 31 | int h = floor(log2(r - l + 1)); 32 | return f(t[h][l], t[h][r - (1 << h) + 1]); 33 | } 34 | }; 35 | ``` 36 | 37 | 38 | 39 | 40 | Usage: Range Queries finding min, max, gcd, lcm, and etc. The array cannot be changed between two queries. 41 | 42 | 43 | 44 | 45 | ```cpp 46 | void main() { 47 | sparse_table g(a.begin(), a.end(), [](int x, int y){ 48 | return gcd(x, y); 49 | }); 50 | cout << g.query(j, i) << "\n"; 51 | } 52 | ``` 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /templates/two-pointers.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Two Pointers' 3 | description: '' 4 | hide_table_of_contents: false 5 | keywords: 6 | - leetcode 7 | - template 8 | - two pointers 9 | --- 10 | 11 | 12 | 13 | 14 | ```cpp 15 | int f(vector& v) { 16 | int ans = 0; 17 | int l = 0, r = (int) v.size() - 1; 18 | while (l < r) { 19 | // do some logic here 20 | if (/* condition */) { 21 | l += 1; 22 | } else { 23 | r -= 1; 24 | } 25 | } 26 | return ans; 27 | } 28 | ``` 29 | 30 | 31 | 32 | 33 | ```java 34 | int f(int[] v) { 35 | int ans = 0; 36 | int l = 0, r = v.length - 1; 37 | while (l < r) { 38 | // do some logic here 39 | if (/* condition */) { 40 | l += 1; 41 | } else { 42 | r -= 1; 43 | } 44 | } 45 | return ans; 46 | } 47 | ``` 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /tutorials/basic-topics/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "Basic Topics", 3 | "position": 2, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "This section provides tutorials on fundamental Data Structures and Algorithm topics, catering to those who are new to the subject." 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /tutorials/basic-topics/divide-and-conquer.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Divide and Conquer' 3 | description: '' 4 | # hide_table_of_contents: true 5 | draft: true 6 | keywords: 7 | - leetcode 8 | - tutorial 9 | - divide and conquer 10 | - algorithm 11 | --- 12 | 13 | 14 | 15 | ## Overview 16 | 17 | ... 18 | -------------------------------------------------------------------------------- /tutorials/basic-topics/doubly-linked-list.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Doubly Linked List' 3 | description: '' 4 | hide_table_of_contents: true 5 | draft: true 6 | keywords: 7 | - leetcode 8 | - tutorial 9 | - doubly linked List 10 | --- 11 | -------------------------------------------------------------------------------- /tutorials/basic-topics/sorting/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "Sorting", 3 | "link": { 4 | "type": "generated-index", 5 | "description": "Sorting refers to rearranging elements in a specific order." 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /tutorials/basic-topics/sorting/bucket-sort.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Bucket Sort' 3 | description: '' 4 | hide_table_of_contents: true 5 | draft: true 6 | keywords: 7 | - leetcode 8 | - tutorial 9 | - sorting 10 | - algorithm 11 | - bucket sort 12 | --- 13 | 14 | 15 | -------------------------------------------------------------------------------- /tutorials/basic-topics/sorting/counting-sort.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Counting Sort' 3 | description: '' 4 | hide_table_of_contents: true 5 | draft: true 6 | keywords: 7 | - leetcode 8 | - tutorial 9 | - sorting 10 | - algorithm 11 | - counting sort 12 | --- 13 | 14 | 15 | -------------------------------------------------------------------------------- /tutorials/basic-topics/sorting/heap-sort.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Heap Sort' 3 | description: '' 4 | hide_table_of_contents: true 5 | draft: true 6 | keywords: 7 | - leetcode 8 | - tutorial 9 | - sorting 10 | - algorithm 11 | - heap sort 12 | --- 13 | 14 | 15 | -------------------------------------------------------------------------------- /tutorials/basic-topics/sorting/introduction.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Introduction' 3 | description: 'Introduction and overview of sorting' 4 | hide_table_of_contents: true 5 | sidebar_position: 1 6 | keywords: 7 | - leetcode 8 | - tutorial 9 | - sorting 10 | - algorithm 11 | --- 12 | 13 | 14 | 15 | ## Overview 16 | 17 | Sorting refers to rearranging elements in a specific order. The most common order is either ascending or descending. There are a lot of algorithms to sort the array with different time complexity. 18 | 19 | In C++, if define a static array of N elements of type int such as $$a[4]$$ you can sort like as below where $$N$$ is the number of elements to be sorted. 20 | 21 | ```cpp 22 | sort(a, a + N); 23 | ``` 24 | 25 | If you want to sort for a specific range $$[x, y)$$, then use 26 | 27 | ```cpp 28 | sort(a + x, a + y); 29 | ``` 30 | 31 | For dynamic array, we do in such way 32 | 33 | ```cpp 34 | sort(a.begin(), a.end()); 35 | ``` 36 | 37 | If you want to sort for a specific range $$[x, y)$$, then use 38 | 39 | ```cpp 40 | sort(a.begin() + x, a.begin() + y); 41 | ``` 42 | 43 | To sort in an decreasing order, 44 | 45 | ```cpp 46 | sort(a.begin(), a.end(), greater()); 47 | ``` 48 | 49 | By default, `sort()` sorts the elements in the range $$[x, y)$$ into ascending order. If the container includes pairs, tuples or array\, it first sorts the first element, then the second element if there is a tie and so on. For example, the following comparator is same as `sort(a.begin(), a.end());`. 50 | 51 | ```cpp 52 | sort(a.begin(), a.end(), [&](const array& x, const array& y) { 53 | return ( 54 | (x[0] < y[0]) || 55 | (x[0] == y[0] && x[1] < y[1]) || 56 | (x[0] == y[0] && x[1] == y[1] || x[2] < y[2]) 57 | ); 58 | }); 59 | ``` 60 | 61 | export const suggestedProblems = [ { "problemName": "0921 - Sort an Array", "difficulty": "Medium", "leetCodeLink": "https://leetcode.com/problems/sort-an-array/", "solutionLink": "../../solutions/0900-0999/sort-an-array-medium" }, ] 62 | 63 | 64 | -------------------------------------------------------------------------------- /tutorials/basic-topics/sorting/quick-sort.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Quick Sort' 3 | description: '' 4 | hide_table_of_contents: true 5 | draft: true 6 | keywords: 7 | - leetcode 8 | - tutorial 9 | - sorting 10 | - algorithm 11 | - quick sort 12 | --- 13 | 14 | 15 | -------------------------------------------------------------------------------- /tutorials/basic-topics/sorting/radix-sort.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Radix Sort' 3 | description: '' 4 | hide_table_of_contents: true 5 | draft: true 6 | keywords: 7 | - leetcode 8 | - tutorial 9 | - sorting 10 | - algorithm 11 | - radix sort 12 | --- 13 | 14 | 15 | -------------------------------------------------------------------------------- /tutorials/graph-theory/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "Graph Theory", 3 | "position": 3, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Welcome to our Graph Theory tutorial page! Graph theory is a branch of mathematics that deals with the study of graphs and their properties. In computer science, graph theory is used to model and analyze problems related to networks, such as social networks, transportation networks, and communication networks. In below tutorials, we will cover the basic concepts of graph theory. We will start with an introduction to the basic definitions and terminologies used in graph theory and then move on to more advanced topics such as graph traversals, shortest paths, and network flow." 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /tutorials/graph-theory/bellman-ford-algorithm.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Bellman Ford Algorithm' 3 | description: 'Bellman Ford Algorithm computes shortest paths from a single source vertex to all of the other vertices in a weighted digraph' 4 | keywords: 5 | - leetcode 6 | - tutorial 7 | - bellman ford 8 | - algorithm 9 | --- 10 | 11 | 12 | 13 | ## Overview 14 | 15 | Bellman Ford Algorithm computes shortest paths from a single source vertex to all of the other vertices in a weighted digraph. Similar to Dijkstra's algorithm, it proceeds by relaxation. However, Dijkstra's algorithm uses a priority queue to greedily select the closest vertex that has not been processed, which all of its outgoing edges will be processed. On the other hand, Bellman Ford Algorithm relaxes all the edges and does the relaxation only $|V| - 1$ times where $|V|$ is the number of vertices in the graph. This is because given a graph with no negative weight cycles with $V$ vertices, the shortest path between any two vertices has at most $|V| - 1$ edges. 16 | 17 | ## Implementation 18 | 19 | 20 | 21 | 22 | 23 | ```cpp 24 | template 25 | void bellman_ford(T_a3 &g, T_vector &dist, int src, int mx_edges) { 26 | dist[src] = 0; 27 | for (int i = 0; i <= mx_edges; i++) { 28 | T_vector ndist = dist; 29 | for (auto x : g) { 30 | auto [from, to, cost] = x; 31 | ndist[to] = min(ndist[to], dist[from] + cost); 32 | } 33 | dist = ndist; 34 | } 35 | } 36 | ``` 37 | 38 | 39 | 40 | 41 | 42 | 43 | ```py 44 | def bellman_ford(g, dist, src, mx_edges): 45 | dist[src] = 0 46 | for i in range(mx_edges + 1): 47 | ndist = dist[:] 48 | for x in g: 49 | _from, to, cost = x 50 | ndist[to] = min(ndist[to], dist[_from] + cost) 51 | dist = ndist 52 | return dist 53 | ``` 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /tutorials/graph-theory/floyd-warshall-algorithm.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Floyd–Warshall Algorithm' 3 | description: '' 4 | hide_table_of_contents: true 5 | draft: true 6 | keywords: 7 | - leetcode 8 | - tutorial 9 | - floyd-warshall algorithm 10 | - algorithm 11 | --- 12 | -------------------------------------------------------------------------------- /tutorials/graph-theory/introduction.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Introduction' 3 | description: 'Graphs can solve a plethora of interesting problems!' 4 | hide_table_of_contents: true 5 | sidebar_position: 1 6 | keywords: 7 | - leetcode 8 | - tutorial 9 | - graphs 10 | --- 11 | 12 | 13 | 14 | ## Overview 15 | 16 | A graph is made up of a collection of points or objects called vertices and connections between some of those vertices called edges. The edges can be either one-way (can only be traversed in one direction), two-way, have a numerical value associated with traversing them, or without any value. We can use graphs to solve a plethora of interesting problems! 17 | 18 | Here is a undirected graph with 4 vertices (or nodes) and 5 edges. 19 | 20 | ![image](https://assets.leetcode.com/uploads/2020/10/21/bi2.jpg) 21 | 22 | ## Example 23 | 24 | In real life, we may use graphs. Let's say we have six people: 25 | 26 | - Alice 27 | - Bob 28 | - Cathy 29 | - Danny 30 | - Ethan 31 | - Fiona 32 | 33 | and we are also given a list of friends. 34 | 35 | ``` 36 | [["Alice", Bob"], ["Cathy", "Danny"], ["Alice", "Cathy"], ["Ethan", "Fiona"]] 37 | ``` 38 | 39 | Here, we know that: 40 | 41 | - Alice and Bob are friends 42 | - Cathy and Danny are friends 43 | - Alice and Cathy are friends 44 | - Ethan and Fiona are friends 45 | 46 | We say that Alice, Bob, Cathy, and Danny are in **Friend Group 1** (they are friends or have common friends). Ethan and Fiona are in **Friend Group 2** (they are friends or have common friends). 47 | 48 | In this task, we can easily tell the **number of friend groups** (there are 2 friend groups), as well as the **size of the largest friend group** (the largest group - Friend Group 1 - has 4 members). 49 | 50 | This seems easy at first glance! We just need to "group them up". However, this is more complicated than you think. There are three potential solutions to this problem : 51 | 52 | - Breadth-First Search (BFS) 53 | - Depth-First Search (DFS) 54 | - Union Find 55 | 56 | We will learn different strategies for similar problems, and hopefully you know which one to use after learning the key concepts in graph theory. 57 | -------------------------------------------------------------------------------- /tutorials/graph-theory/minimum-spanning-tree.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Minimum Spanning Tree' 3 | description: 'A minimum spanning tree is a subset of the edges of a connected undirected graph with the minimum possible total edge weight and it does not contain any cycles.' 4 | hide_table_of_contents: true 5 | keywords: 6 | - leetcode 7 | - tutorial 8 | - minimum spanning tree 9 | - mst 10 | - algorithm 11 | --- 12 | 13 | 14 | 15 | ## Overview 16 | 17 | A Minimum Spanning Tree (MST) is a subset of the edges of a connected, undirected graph that connects all the vertices together, without any cycles and with the minimum possible total edge weight. There are different algorithms that can be used to find the MST of a graph, such as Kruskal's algorithm, Prim's algorithm and Boruvka's algorithm. 18 | 19 | ### Kruskal's Algorithm 20 | 21 | [See Here](../graph-theory/kruskals-algorithm) 22 | 23 | ### Prim's Algorithm 24 | 25 | Not Available Yet 26 | 27 | ### Boruvka's Algorithm 28 | 29 | Not Available Yet 30 | -------------------------------------------------------------------------------- /tutorials/graph-theory/prims-algorithm.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Prim's Algorithm" 3 | description: 'Coming Soon!' 4 | draft: true 5 | keywords: 6 | - leetcode 7 | - tutorial 8 | - prim 9 | - algorithm 10 | --- 11 | 12 | Coming Soon 13 | -------------------------------------------------------------------------------- /tutorials/math/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "Math", 3 | "position": 4, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Welcome to our Math tutorial section! Math plays a crucial role in problem-solving, especially when it comes to tackling algorithmic challenges on LeetCode. In below tutorials, we will explore various mathematical concepts and techniques that are commonly used to solve problems on LeetCode. The topics covered include basic mathematical operations, number theory, combinatorics, probability and statistics, and linear algebra. We will show you how these concepts can be applied to different types of LeetCode problems, and provide examples and solutions to help you understand the material better." 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /tutorials/math/number-theory/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "Number Theory", 3 | "position": 2, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "Welcome to our Number Theory tutorial page for LeetCode problems! Number theory is a branch of mathematics that deals with the properties and relationships of integers, which is very important in computer science. This tutorial will cover a range of topics in number theory that are commonly used to solve problems on LeetCode. We will be focusing on important algorithms and techniques such as modular arithmetic, prime numbers, gcd and more." 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /tutorials/math/number-theory/sieve-of-eratosthenes.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Sieve of Eratosthenes' 3 | description: 'Sieve of Eratosthenes is a way of finding all prime numbers up to N (inclusive).' 4 | hide_table_of_contents: true 5 | keywords: 6 | - leetcode 7 | - tutorial 8 | - sieve of eratosthenes 9 | - algorithm 10 | --- 11 | 12 | 13 | 14 | ## Overview 15 | 16 | The Sieve of Eratosthenes is an algorithm used to find all prime numbers up to a given limit. It works by iteratively marking as composite (i.e., not prime) the multiples of each prime, starting with 2. The algorithm starts by creating a list of all integers from 2 to the limit. It then marks the first number, 2, as prime and removes all multiples of 2 from the list. The next unmarked number in the list is 3, which is also prime, so it marks it and removes all multiples of 3 from the list. This process continues until all numbers in the list have been marked as prime or composite. The remaining unmarked numbers are the prime numbers up to the given limit. 17 | 18 | ## Implementation 19 | 20 | 21 | 22 | 23 | 24 | ```cpp 25 | vector sieveOfEratosthenes(const int n) { 26 | vector isPrime(n + 1, true); 27 | isPrime[0] = isPrime[1] = false; 28 | for (int i = 2; i * i <= n; i++) { 29 | if (isPrime[i]) { 30 | for (int j = i * i; j <= n; j += i) { 31 | isPrime[j] = false; 32 | } 33 | } 34 | } 35 | return isPrime; 36 | } 37 | ``` 38 | 39 | 40 | 41 | 42 | 43 | export const suggestedProblems = [ { "problemName": "0204 - Count Primes", "difficulty": "Medium", "leetCodeLink": "https://leetcode.com/problems/count-primes/", "solutionLink": "../../../solutions/0200-0299/count-primes" }, ] 44 | 45 |
46 | -------------------------------------------------------------------------------- /tutorials/strings/_category_.json: -------------------------------------------------------------------------------- 1 | { 2 | "label": "Strings", 3 | "position": 5, 4 | "link": { 5 | "type": "generated-index", 6 | "description": "This section covers Strings topics." 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /tutorials/strings/knuth–morris–pratt-algorithm.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Knuth–Morris–Pratt Algorithm' 3 | description: 'KMP is a algorithm to search the occurrences of a word within a string' 4 | draft: true 5 | keywords: 6 | - leetcode 7 | - tutorial 8 | - kmp 9 | - knuth morris pratt 10 | - algorithm 11 | --- 12 | 13 | 14 | 15 | ## Overview 16 | 17 | If we look at the problem [0028 - Implement strStr()](https://leetcode.com/problems/implement-strstr/), we want to return the index of the first occurrence of `needle` in `haystack`. A brute force solution would take $O(n * m)$ where $n$ is the length of the `needle` and $m$ is the length of `haystack` as we try to start at each character in `haystack` and check the character one by one to see if they match `needle`. 18 | 19 | KMP could give $O(n + m)$ in the worst case. The idea of KMP is to cut out some repeated words by doing some preprocessing. Let's take `AAABAAAB` as a haystack and `AAAA` as a needle and we start at index 0. We can see that the first three character match but the forth character is `B` which doesn't match that in the needle. If we start at index 1, we would face the same problem as `AABA` doesn't match with `AAAA`. However, if the prefix of the haystack matches that in the needle, we can start our pointer at the position where the mismatch is, in this case `B` at index 3. 20 | 21 | @wkw: WIP ... 22 | -------------------------------------------------------------------------------- /tutorials/strings/levenshtein-distance.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Levenshtein Distance' 3 | description: '' 4 | hide_table_of_contents: true 5 | draft: true 6 | keywords: 7 | - leetcode 8 | - tutorial 9 | - levenshtein distance 10 | --- 11 | -------------------------------------------------------------------------------- /tutorials/strings/rabin-karp-algorithm.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Rabin Karp Algorithm' 3 | description: '' 4 | hide_table_of_contents: true 5 | draft: true 6 | keywords: 7 | - leetcode 8 | - tutorial 9 | - rabin-karp algorithm 10 | --- 11 | --------------------------------------------------------------------------------