From 03a892cac07974b08032346a636d50ecfbaab10f Mon Sep 17 00:00:00 2001 From: Manideep Date: Thu, 3 Jul 2025 17:15:44 +0100 Subject: [PATCH 1/3] fix; update workflows and dependencies --- .github/workflows/build-readme.yml | 72 ++++++++++----------- .github/workflows/format.yml | 13 ++-- .gitignore | 4 +- kotlin/1143-longest-common-subsequence.kt | 77 +---------------------- package-lock.json | 27 ++++++++ package.json | 8 +++ 6 files changed, 83 insertions(+), 118 deletions(-) create mode 100644 package-lock.json create mode 100644 package.json diff --git a/.github/workflows/build-readme.yml b/.github/workflows/build-readme.yml index fcd5b875e..60ac82c25 100644 --- a/.github/workflows/build-readme.yml +++ b/.github/workflows/build-readme.yml @@ -1,40 +1,42 @@ name: Build readme file on: - #push: - workflow_dispatch: - schedule: - - cron: '0 * * * *' + workflow_dispatch: + schedule: + - cron: '0 * * * *' # Every hour jobs: - Build: - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v3 - with: - ref: ${{ github.head_ref }} - fetch-depth: 1 - - - name: Use Node.js (dependency) - uses: actions/setup-node@v3 - with: - node-version: 16 - - - name: Completion Table - run: node updateCompletionTable.js; - - - name: Check for modified files - id: git-check - run: echo modified=$(if git diff-index --quiet HEAD --; then echo "false"; else echo "true"; fi) >> $GITHUB_OUTPUT - - - name: Push - if: steps.git-check.outputs.modified == 'true' - run: | - git config --global user.email "71089234+Ahmad-A0@users.noreply.github.com" - git config --global user.name "Bot-A0" - git add . - git commit -am "📜 Update README table (🛠️ from Github Actions)" || true - git push || git pull --rebase && git push - - + Build: + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: [20.x] + + steps: + - name: Checkout Repository + uses: actions/checkout@v4 + with: + ref: ${{ github.head_ref }} + fetch-depth: 1 + + - name: Use Node.js (dependency) + uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node-version }} + + - name: Completion Table + run: node updateCompletionTable.js; + + - name: Check for modified files + id: git-check + run: echo modified=$(if git diff-index --quiet HEAD --; then echo "false"; else echo "true"; fi) >> $GITHUB_OUTPUT + + - name: Push + if: steps.git-check.outputs.modified == 'true' + run: | + git config --global user.email "71089234+Ahmad-A0@users.noreply.github.com" + git config --global user.name "Bot-A0" + git add . + git commit -am "📜 Update README table (🛠️ from Github Actions)" || true + git push || git pull --rebase && git push \ No newline at end of file diff --git a/.github/workflows/format.yml b/.github/workflows/format.yml index f2847ab45..bed5f899b 100644 --- a/.github/workflows/format.yml +++ b/.github/workflows/format.yml @@ -10,9 +10,9 @@ name: Format Files # typescript - prettier on: - # pull_request_target: - # types: [opened, synchronize] workflow_dispatch: + pull_request_target: + types: [opened, synchronize, reopened] jobs: Format: @@ -20,16 +20,17 @@ jobs: strategy: matrix: - node-version: [16.x] + node-version: [20.x] steps: - - uses: actions/checkout@v3 + - name: Checkout Repository + uses: actions/checkout@v4 with: ref: ${{ github.head_ref }} fetch-depth: 1 - name: Use Node.js (dependency) - uses: actions/setup-node@v1 + uses: actions/setup-node@v4 with: node-version: ${{ matrix.node-version }} @@ -62,4 +63,4 @@ jobs: git config --global user.name "Bot-A0" git add . git commit -m "🎨 Format files (🛠️ from Github Actions)" || true - git push || true + git push || true \ No newline at end of file diff --git a/.gitignore b/.gitignore index 146f8c207..f4b05d997 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ .DS_Store .metals -.vscode \ No newline at end of file +.vscode +.idea +node_modules \ No newline at end of file diff --git a/kotlin/1143-longest-common-subsequence.kt b/kotlin/1143-longest-common-subsequence.kt index 55dc1f154..ea744645e 100644 --- a/kotlin/1143-longest-common-subsequence.kt +++ b/kotlin/1143-longest-common-subsequence.kt @@ -20,79 +20,4 @@ class Solution { } return dp[M][N] } -} - -/* - * Different solutions - */ - - // Recursion + Memoization, Time Complexity of O(n * m) and space complexity of O(n * m) -class Solution { - fun longestCommonSubsequence(t1: String, t2: String): Int { - val n = t1.length - val m = t2.length - val dp = Array (n) { IntArray (m) { -1 } } - - fun dfs(i: Int, j: Int): Int { - if (i == n || j == m) return 0 - if (dp[i][j] != -1) return dp[i][j] - - if (t1[i] == t2[j]) - dp[i][j] = 1 + dfs(i + 1, j + 1) - else - dp[i][j] = maxOf(dfs(i + 1, j), dfs(i, j + 1)) - - return dp[i][j] - } - - return dfs(0, 0) - } -} - -// Top down DP, Time Complexity of O(n * m) and space complexity of O(n * m) -class Solution { - fun longestCommonSubsequence(t1: String, t2: String): Int { - val n = t1.length - val m = t2.length - val dp = Array (n + 1) { IntArray (m + 1) } - - for (i in n - 1 downTo 0) { - for (j in m - 1 downTo 0) { - if (t1[i] == t2[j]) - dp[i][j] = 1 + dp[i + 1][j + 1] - else - dp[i][j] = maxOf(dp[i + 1][j], dp[i][j + 1]) - } - } - - return dp[0][0] - } -} - -// Optimized DP (Works both for both Top-down and Bottom-up, but here we use bottom-up approach) -// Time Complexity of O(n * m) and space complexity of O(maxOf(n, m)) -class Solution { - fun longestCommonSubsequence(t1: String, t2: String): Int { - val m = t1.length - val n = t2.length - if (m < n) return longestCommonSubsequence(t2, t1) - - var dp = IntArray (n + 1) - - for (i in m downTo 0) { - var newDp = IntArray (n + 1) - for (j in n downTo 0) { - if (i == m || j == n) { - newDp[j] = 0 - } else if (t1[i] == t2[j]) { - newDp[j] = 1 + dp[j + 1] - } else { - newDp[j] = maxOf(dp[j], newDp[j + 1]) - } - } - dp = newDp - } - - return dp[0] - } -} +} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 000000000..77b33b37e --- /dev/null +++ b/package-lock.json @@ -0,0 +1,27 @@ +{ + "name": "leetcode", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "dependencies": { + "prettier": "^3.6.2" + } + }, + "node_modules/prettier": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.6.2.tgz", + "integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==", + "license": "MIT", + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 000000000..7348d0ad4 --- /dev/null +++ b/package.json @@ -0,0 +1,8 @@ +{ + "scripts": { + "format": "prettier --write \"**/**/*.{js,ts,json,md,c,cpp,cs}\"" + }, + "dependencies": { + "prettier": "^3.6.2" + } +} From 44f489eea0b88e7ee1dd952f24af45901cb72b69 Mon Sep 17 00:00:00 2001 From: Manideep Date: Thu, 3 Jul 2025 17:22:02 +0100 Subject: [PATCH 2/3] feat: formatted all js,ts,md,json files using prettier --- .github/pull_request_template.md | 14 +- .problemSiteData.json | 13556 ++++++++-------- CONTRIBUTING.md | 23 +- README.md | 986 +- README_template.md | 8 +- articles/132-pattern.md | 54 +- articles/4sum.md | 49 +- articles/accounts-merge.md | 36 +- articles/add-binary.md | 53 +- articles/add-to-array-form-of-integer.md | 13 +- articles/add-two-numbers.md | 74 +- articles/all-possible-full-binary-trees.md | 20 +- articles/anagram-groups.md | 18 +- .../analyze-user-website-visit-pattern.md | 18 +- ...haracters-to-string-to-make-subsequence.md | 21 +- articles/arithmetic-slices-ii-subsequence.md | 23 +- articles/arranging-coins.md | 37 +- ...ments-not-equal-to-average-of-neighbors.md | 29 +- articles/as-far-from-land-as-possible.md | 94 +- articles/assign-cookies.md | 29 +- articles/asteroid-collision.md | 8 +- articles/average-waiting-time.md | 14 +- articles/backspace-string-compare.md | 43 +- articles/bag-of-tokens.md | 9 +- articles/balanced-binary-tree.md | 59 +- articles/baseball-game.md | 20 +- articles/basic-calculator-ii.md | 22 +- articles/best-team-with-no-conflicts.md | 25 +- .../best-time-to-buy-and-sell-stock-ii.md | 50 +- articles/binary-search-tree-iterator.md | 34 +- articles/binary-search.md | 72 +- articles/binary-subarrays-with-sum.md | 32 +- articles/binary-tree-diameter.md | 128 +- ...ree-from-preorder-and-inorder-traversal.md | 103 +- articles/binary-tree-inorder-traversal.md | 30 +- articles/binary-tree-maximum-path-sum.md | 38 +- articles/binary-tree-postorder-traversal.md | 38 +- articles/binary-tree-preorder-traversal.md | 31 +- articles/binary-tree-right-side-view.md | 46 +- .../binary-tree-vertical-order-traversal.md | 32 +- ...inary-tree-zigzag-level-order-traversal.md | 26 +- articles/bitwise-and-of-numbers-range.md | 20 +- articles/boats-to-save-people.md | 35 +- articles/brick-wall.md | 14 +- articles/build-a-matrix-with-conditions.md | 40 +- articles/buildings-with-an-ocean-view.md | 21 +- articles/burst-balloons.md | 17 +- articles/buy-and-sell-crypto-with-cooldown.md | 70 +- articles/buy-and-sell-crypto.md | 15 +- articles/buy-two-chocolates.md | 17 +- articles/calculate-money-in-leetcode-bank.md | 22 +- articles/can-place-flowers.md | 36 +- articles/candy.md | 22 +- ...capacity-to-ship-packages-within-d-days.md | 14 +- articles/car-fleet.md | 49 +- articles/car-pooling.md | 73 +- articles/champagne-tower.md | 84 +- articles/cheapest-flight-path.md | 57 +- .../check-completeness-of-a-binary-tree.md | 33 +- ...ing-contains-all-binary-codes-of-size-k.md | 73 +- .../check-if-array-is-sorted-and-rotated.md | 15 +- articles/check-if-move-is-legal.md | 48 +- ...here-is-a-valid-partition-for-the-array.md | 94 +- ...eck-if-two-string-arrays-are-equivalent.md | 24 +- articles/cherry-pickup-ii.md | 94 +- articles/circular-sentence.md | 10 +- articles/climbing-stairs.md | 135 +- articles/clone-graph.md | 50 +- articles/coin-change-ii.md | 81 +- articles/coin-change.md | 69 +- articles/combination-sum-iv.md | 59 +- articles/combination-target-sum-ii.md | 59 +- articles/combination-target-sum.md | 40 +- articles/combinations-of-a-phone-number.md | 86 +- articles/combinations.md | 48 +- articles/concatenated-words.md | 36 +- articles/concatenation-of-array.md | 8 +- articles/constrained-subsequence-sum.md | 44 +- ...ee-from-inorder-and-postorder-traversal.md | 24 +- articles/construct-quad-tree.md | 132 +- articles/construct-string-from-binary-tree.md | 42 +- articles/contains-duplicate-ii.md | 32 +- articles/contiguous-array.md | 31 +- articles/continuous-subarray-sum.md | 12 +- ...n-array-into-a-2d-array-with-conditions.md | 30 +- articles/convert-bst-to-greater-tree.md | 20 +- ...vert-sorted-array-to-binary-search-tree.md | 28 +- .../copy-linked-list-with-random-pointer.md | 102 +- ...t-all-valid-pickup-and-delivery-options.md | 81 +- articles/count-connected-components.md | 40 +- articles/count-good-nodes-in-binary-tree.md | 28 +- articles/count-number-of-bad-pairs.md | 14 +- articles/count-number-of-islands.md | 173 +- .../count-odd-numbers-in-an-interval-range.md | 12 +- articles/count-of-matches-in-tournament.md | 8 +- articles/count-paths.md | 94 +- articles/count-squares.md | 76 +- articles/count-sub-islands.md | 83 +- ...re-max-element-appears-at-least-k-times.md | 82 +- articles/count-subsequences.md | 76 +- .../count-the-number-of-consistent-strings.md | 18 +- ...s-that-can-form-two-arrays-of-equal-xor.md | 22 +- articles/count-vowel-strings-in-ranges.md | 30 +- articles/count-vowels-permutation.md | 79 +- articles/count-ways-to-build-good-strings.md | 20 +- articles/counting-bits.md | 46 +- articles/course-schedule-ii.md | 50 +- articles/course-schedule-iv.md | 85 +- articles/course-schedule.md | 22 +- articles/daily-temperatures.md | 48 +- articles/data-stream-as-disjoint-intervals.md | 42 +- articles/decode-string.md | 60 +- articles/decode-ways.md | 104 +- articles/delete-and-earn.md | 69 +- articles/delete-leaves-with-a-given-value.md | 15 +- articles/delete-node-in-a-bst.md | 83 +- articles/depth-of-binary-tree.md | 54 +- articles/design-a-food-rating-system.md | 57 +- articles/design-browser-history.md | 68 +- articles/design-circular-queue.md | 76 +- articles/design-hashmap.md | 40 +- articles/design-hashset.md | 54 +- articles/design-linked-list.md | 608 +- articles/design-parking-system.md | 16 +- articles/design-twitter-feed.md | 112 +- articles/design-underground-system.md | 75 +- articles/design-word-search-data-structure.md | 38 +- articles/destination-city.md | 18 +- articles/detonate-the-maximum-bombs.md | 12 +- .../distribute-candies-among-children-ii.md | 28 +- articles/distribute-coins-in-binary-tree.md | 16 +- ...e-array-into-arrays-with-max-difference.md | 12 +- articles/divide-array-into-equal-pairs.md | 12 +- articles/dota2-senate.md | 45 +- articles/duplicate-integer.md | 18 +- articles/eating-bananas.md | 34 +- articles/edit-distance.md | 125 +- .../eliminate-maximum-number-of-monsters.md | 12 +- articles/encode-and-decode-tinyurl.md | 18 +- articles/evaluate-boolean-binary-tree.md | 16 +- articles/evaluate-division.md | 56 +- articles/evaluate-reverse-polish-notation.md | 167 +- articles/even-odd-tree.md | 60 +- articles/excel-sheet-column-title.md | 21 +- articles/extra-characters-in-a-string.md | 53 +- articles/find-all-anagrams-in-a-string.md | 48 +- articles/find-all-duplicates-in-an-array.md | 30 +- ...ind-all-numbers-disappeared-in-an-array.md | 66 +- articles/find-all-people-with-secret.md | 35 +- articles/find-bottom-left-tree-value.md | 31 +- .../find-closest-node-to-given-two-nodes.md | 30 +- articles/find-common-characters.md | 10 +- ...critical-edges-in-minimum-spanning-tree.md | 56 +- articles/find-duplicate-integer.md | 40 +- articles/find-duplicate-subtrees.md | 53 +- articles/find-eventual-safe-states.md | 28 +- ...ast-position-of-element-in-sorted-array.md | 35 +- ...d-first-palindromic-string-in-the-array.md | 17 +- articles/find-in-mountain-array.md | 38 +- articles/find-k-closest-elements.md | 48 +- .../find-largest-value-in-each-tree-row.md | 12 +- articles/find-median-in-a-data-stream.md | 30 +- .../find-minimum-in-rotated-sorted-array.md | 19 +- articles/find-missing-and-repeated-values.md | 29 +- articles/find-missing-observations.md | 30 +- articles/find-peak-element.md | 22 +- articles/find-pivot-index.md | 25 +- ...find-polygon-with-the-largest-perimeter.md | 18 +- .../find-target-in-rotated-sorted-array.md | 28 +- articles/find-the-difference-of-two-arrays.md | 28 +- articles/find-the-difference.md | 27 +- ...dex-of-the-first-occurrence-in-a-string.md | 100 +- ...nd-the-kth-largest-integer-in-the-array.md | 55 +- ...-valid-obstacle-course-at-each-position.md | 18 +- .../find-the-maximum-sum-of-node-values.md | 44 +- articles/find-the-safest-path-in-a-grid.md | 133 +- articles/find-the-town-judge.md | 52 +- articles/find-unique-binary-string.md | 49 +- ...-words-that-can-be-formed-by-characters.md | 36 +- articles/first-bad-version.md | 25 +- articles/first-missing-positive.md | 50 +- .../first-unique-character-in-a-string.md | 32 +- articles/flatten-nested-list-iterator.md | 26 +- articles/flip-equivalent-binary-trees.md | 94 +- .../flip-string-to-monotone-increasing.md | 39 +- articles/foreign-dictionary.md | 139 +- articles/freedom-trail.md | 138 +- .../frequency-of-the-most-frequent-element.md | 34 +- articles/fruit-into-baskets.md | 49 +- articles/furthest-building-you-can-reach.md | 29 +- articles/gas-station.md | 25 +- articles/generate-parentheses.md | 72 +- .../get-equal-substrings-within-budget.md | 16 +- .../greatest-common-divisor-of-strings.md | 43 +- articles/greatest-common-divisor-traversal.md | 38 +- articles/grid-game.md | 27 +- articles/guess-number-higher-or-lower.md | 42 +- articles/hand-of-straights.md | 79 +- articles/height-checker.md | 10 +- articles/house-robber-ii.md | 155 +- articles/house-robber-iii.md | 26 +- articles/house-robber.md | 43 +- articles/image-smoother.md | 72 +- articles/implement-prefix-tree.md | 20 +- articles/implement-queue-using-stacks.md | 26 +- articles/implement-stack-using-queues.md | 38 +- articles/insert-delete-getrandom-o1.md | 20 +- ...greatest-common-divisors-in-linked-list.md | 13 +- articles/insert-into-a-binary-search-tree.md | 10 +- articles/insert-new-interval.md | 45 +- articles/insertion-sort-list.md | 19 +- articles/integer-break.md | 60 +- articles/integer-to-roman.md | 86 +- articles/interleaving-string.md | 139 +- articles/intersection-of-two-arrays.md | 37 +- articles/intersection-of-two-linked-lists.md | 69 +- articles/invert-a-binary-tree.md | 20 +- articles/ipo.md | 70 +- articles/is-anagram.md | 42 +- articles/is-graph-bipartite.md | 23 +- articles/is-palindrome.md | 50 +- articles/is-subsequence.md | 79 +- articles/island-perimeter.md | 104 +- articles/islands-and-treasure.md | 152 +- articles/isomorphic-strings.md | 25 +- articles/jump-game-ii.md | 34 +- articles/jump-game-vii.md | 32 +- articles/jump-game.md | 66 +- articles/k-closest-points-to-origin.md | 63 +- articles/k-inverse-pairs-array.md | 22 +- .../k-th-smallest-in-lexicographical-order.md | 16 +- articles/k-th-symbol-in-grammar.md | 49 +- articles/knight-dialer.md | 102 +- articles/kth-distinct-string-in-an-array.md | 18 +- articles/kth-largest-element-in-an-array.md | 176 +- articles/kth-largest-integer-in-a-stream.md | 24 +- articles/kth-smallest-integer-in-bst.md | 123 +- .../largest-3-same-digit-number-in-string.md | 60 +- ...largest-color-value-in-a-directed-graph.md | 29 +- articles/largest-divisible-subset.md | 26 +- articles/largest-local-values-in-a-matrix.md | 59 +- articles/largest-number.md | 26 +- articles/largest-odd-number-in-string.md | 28 +- articles/largest-rectangle-in-histogram.md | 150 +- .../largest-submatrix-with-rearrangements.md | 33 +- ...-substring-between-two-equal-characters.md | 26 +- articles/last-stone-weight-ii.md | 54 +- articles/last-stone-weight.md | 110 +- articles/leaf-similar-trees.md | 31 +- ...ber-of-unique-integers-after-k-removals.md | 12 +- articles/lemonade-change.md | 14 +- articles/length-of-last-word.md | 24 +- ...ngest-subarray-with-at-most-k-frequency.md | 20 +- .../level-order-traversal-of-binary-tree.md | 66 +- articles/lfu-cache.md | 69 +- articles/linked-list-cycle-detection.md | 14 +- articles/linked-list-cycle-ii.md | 13 +- articles/longest-common-prefix.md | 30 +- articles/longest-common-subsequence.md | 72 +- articles/longest-consecutive-sequence.md | 53 +- ...solute-diff-less-than-or-equal-to-limit.md | 48 +- articles/longest-happy-string.md | 42 +- articles/longest-ideal-subsequence.md | 25 +- articles/longest-increasing-path-in-matrix.md | 200 +- articles/longest-increasing-subsequence-ii.md | 34 +- articles/longest-increasing-subsequence.md | 145 +- articles/longest-palindrome.md | 18 +- articles/longest-palindromic-subsequence.md | 39 +- articles/longest-palindromic-substring.md | 97 +- ...st-repeating-substring-with-replacement.md | 42 +- ...reasing-or-strictly-decreasing-subarray.md | 31 +- articles/longest-string-chain.md | 19 +- .../longest-substring-without-duplicates.md | 27 +- articles/longest-turbulent-subarray.md | 91 +- ...t-common-ancestor-in-binary-search-tree.md | 12 +- ...st-common-ancestor-of-a-binary-tree-iii.md | 40 +- articles/lru-cache.md | 66 +- articles/majority-element-ii.md | 59 +- articles/majority-element.md | 45 +- articles/make-sum-divisible-by-p.md | 8 +- articles/make-the-string-great.md | 54 +- articles/matchsticks-to-square.md | 66 +- articles/matrix-diagonal-sum.md | 21 +- articles/max-area-of-island.md | 181 +- articles/max-points-on-a-line.md | 24 +- articles/max-water-container.md | 18 +- articles/maximal-square.md | 66 +- articles/maximize-score-after-n-operations.md | 32 +- .../maximum-alternating-subsequence-sum.md | 32 +- articles/maximum-ascending-subarray-sum.md | 11 +- ...lement-after-decreasing-and-rearranging.md | 8 +- articles/maximum-frequency-stack.md | 46 +- ...catenated-string-with-unique-characters.md | 33 +- articles/maximum-length-of-pair-chain.md | 27 +- ...aximum-nesting-depth-of-the-parentheses.md | 17 +- articles/maximum-number-of-balloons.md | 28 +- .../maximum-number-of-removable-characters.md | 40 +- ...f-vowels-in-a-substring-of-given-length.md | 65 +- articles/maximum-odd-binary-number.md | 35 +- articles/maximum-performance-of-a-team.md | 20 +- ...aximum-points-you-can-obtain-from-cards.md | 21 +- ...um-product-difference-between-two-pairs.md | 31 +- ...-length-of-two-palindromic-subsequences.md | 95 +- articles/maximum-product-subarray.md | 42 +- articles/maximum-profit-in-job-scheduling.md | 42 +- .../maximum-score-after-splitting-a-string.md | 29 +- articles/maximum-score-of-a-good-subarray.md | 57 +- .../maximum-score-words-formed-by-letters.md | 24 +- articles/maximum-subarray-min-product.md | 118 +- articles/maximum-subarray.md | 168 +- articles/maximum-subsequence-score.md | 31 +- articles/maximum-sum-circular-subarray.md | 29 +- articles/maximum-twin-sum-of-a-linked-list.md | 30 +- .../maximum-value-of-k-coins-from-piles.md | 36 +- articles/maximum-width-of-binary-tree.md | 31 +- articles/median-of-two-sorted-arrays.md | 80 +- articles/meeting-rooms-iii.md | 46 +- articles/meeting-schedule-ii.md | 117 +- articles/meeting-schedule.md | 12 +- articles/merge-in-between-linked-lists.md | 103 +- articles/merge-intervals.md | 30 +- articles/merge-k-sorted-linked-lists.md | 171 +- articles/merge-sorted-array.md | 33 +- articles/merge-strings-alternately.md | 32 +- articles/merge-triplets-to-form-target.md | 20 +- articles/merge-two-binary-trees.md | 47 +- articles/merge-two-sorted-linked-lists.md | 16 +- articles/middle-of-the-linked-list.md | 17 +- articles/min-cost-climbing-stairs.md | 84 +- articles/min-cost-to-connect-points.md | 74 +- articles/minimize-deviation-in-array.md | 21 +- articles/minimize-maximum-of-array.md | 11 +- ...inimize-the-maximum-difference-of-pairs.md | 66 +- articles/minimum-array-end.md | 12 +- ...anges-to-make-alternating-binary-string.md | 19 +- articles/minimum-cost-for-tickets.md | 76 +- articles/minimum-cost-to-cut-a-stick.md | 36 +- articles/minimum-cost-to-hire-k-workers.md | 11 +- ...ns-to-make-character-frequencies-unique.md | 14 +- ...-between-highest-and-lowest-of-k-scores.md | 8 +- .../minimum-difficulty-of-a-job-schedule.md | 52 +- .../minimum-distance-between-bst-nodes.md | 47 +- articles/minimum-falling-path-sum-ii.md | 61 +- articles/minimum-falling-path-sum.md | 35 +- ...imum-fuel-cost-to-report-to-the-capital.md | 8 +- articles/minimum-height-trees.md | 36 +- articles/minimum-index-of-a-valid-split.md | 25 +- articles/minimum-interval-including-query.md | 219 +- ...h-of-string-after-deleting-similar-ends.md | 7 +- ...imum-number-of-arrows-to-burst-balloons.md | 14 +- ...minimum-number-of-days-to-eat-n-oranges.md | 14 +- ...s-to-make-the-binary-string-alternating.md | 54 +- ...-of-operations-to-make-array-continuous.md | 31 +- ...umber-of-operations-to-make-array-empty.md | 34 +- ...perations-to-move-all-balls-to-each-box.md | 23 +- ...er-of-swaps-to-make-the-string-balanced.md | 17 +- ...m-number-of-vertices-to-reach-all-nodes.md | 22 +- ...ne-bit-operations-to-make-integers-zero.md | 27 +- .../minimum-operations-to-reduce-x-to-zero.md | 60 +- articles/minimum-path-sum.md | 31 +- articles/minimum-penalty-for-a-shop.md | 44 +- ...inimum-remove-to-make-valid-parentheses.md | 45 +- ...imum-score-of-a-path-between-two-cities.md | 23 +- articles/minimum-size-subarray-sum.md | 47 +- articles/minimum-stack.md | 86 +- ...um-time-to-collect-all-apples-in-a-tree.md | 18 +- .../minimum-time-to-make-rope-colorful.md | 25 +- articles/minimum-window-with-characters.md | 33 +- articles/missing-number.md | 26 +- articles/monotonic-array.md | 17 +- articles/move-zeroes.md | 21 +- articles/multiply-strings.md | 134 +- articles/my-calendar-i.md | 47 +- articles/n-queens-ii.md | 75 +- articles/n-queens.md | 117 +- articles/n-th-tribonacci-number.md | 35 +- articles/naming-a-company.md | 29 +- articles/network-delay-time.md | 119 +- articles/new-21-game.md | 40 +- articles/next-greater-element-i.md | 22 +- articles/next-permutation.md | 24 +- articles/non-cyclical-number.md | 21 +- articles/non-decreasing-array.md | 4 +- articles/non-overlapping-intervals.md | 106 +- articles/number-of-closed-islands.md | 72 +- .../number-of-dice-rolls-with-target-sum.md | 30 +- articles/number-of-enclaves.md | 109 +- articles/number-of-flowers-in-full-bloom.md | 49 +- articles/number-of-good-pairs.md | 14 +- articles/number-of-good-paths.md | 40 +- articles/number-of-laser-beams-in-a-bank.md | 6 +- ...umber-of-longest-increasing-subsequence.md | 52 +- articles/number-of-music-playlists.md | 31 +- articles/number-of-one-bits.md | 18 +- ...-of-pairs-of-interchangeable-rectangles.md | 44 +- articles/number-of-senior-citizens.md | 8 +- .../number-of-students-unable-to-eat-lunch.md | 16 +- ...rage-greater-than-or-equal-to-threshold.md | 37 +- articles/number-of-sub-arrays-with-odd-sum.md | 30 +- ...umber-of-submatrices-that-sum-to-target.md | 37 +- ...es-that-satisfy-the-given-sum-condition.md | 63 +- .../number-of-visible-people-in-a-queue.md | 27 +- ...umber-of-ways-to-divide-a-long-corridor.md | 36 +- ...form-a-target-string-given-a-dictionary.md | 35 +- ...-rearrange-sticks-with-k-sticks-visible.md | 18 +- articles/number-of-ways-to-split-array.md | 15 +- ...stay-in-the-same-place-after-some-steps.md | 26 +- articles/number-of-zero-filled-subarrays.md | 27 +- articles/ones-and-zeroes.md | 59 +- articles/online-stock-span.md | 15 +- articles/open-the-lock.md | 64 +- articles/operations-on-tree.md | 78 +- articles/optimal-partition-of-string.md | 20 +- articles/out-of-boundary-paths.md | 53 +- articles/pacific-atlantic-water-flow.md | 229 +- articles/paint-house.md | 23 +- articles/painting-the-walls.md | 37 +- articles/palindrome-linked-list.md | 33 +- articles/palindrome-number.md | 29 +- articles/palindrome-partitioning.md | 130 +- articles/palindromic-substrings.md | 106 +- articles/parallel-courses-iii.md | 19 +- articles/partition-array-for-maximum-sum.md | 29 +- articles/partition-equal-subset-sum.md | 168 +- articles/partition-labels.md | 13 +- articles/partition-list.md | 21 +- articles/partition-to-k-equal-sum-subsets.md | 27 +- articles/pascals-triangle-ii.md | 30 +- articles/pascals-triangle.md | 26 +- articles/path-crossing.md | 24 +- articles/path-sum.md | 40 +- articles/path-with-maximum-gold.md | 72 +- articles/path-with-maximum-probability.md | 30 +- articles/path-with-minimum-effort.md | 118 +- articles/perfect-squares.md | 88 +- articles/permutation-string.md | 44 +- articles/permutations-ii.md | 72 +- articles/permutations.md | 58 +- articles/plus-one.md | 14 +- ...lating-next-right-pointers-in-each-node.md | 35 +- articles/pow-x-n.md | 18 +- articles/power-of-four.md | 38 +- articles/power-of-two.md | 32 +- articles/prefix-and-suffix-search.md | 52 +- articles/process-tasks-using-servers.md | 85 +- articles/products-of-array-discluding-self.md | 80 +- articles/profitable-schemes.md | 42 +- ...eudo-palindromic-paths-in-a-binary-tree.md | 38 +- articles/push-dominoes.md | 103 +- articles/put-marbles-in-bags.md | 22 +- articles/queue-reconstruction-by-height.md | 146 +- articles/range-sum-of-bst.md | 33 +- articles/range-sum-query-2d-immutable.md | 64 +- articles/range-sum-query-immutable.md | 34 +- articles/range-sum-query-mutable.md | 206 +- articles/rearrange-array-elements-by-sign.md | 36 +- articles/reconstruct-flight-path.md | 174 +- ...te-characters-to-make-all-strings-equal.md | 18 +- articles/redundant-connection.md | 65 +- articles/regular-expression-matching.md | 154 +- articles/relative-sort-array.md | 38 +- ...ve-all-adjacent-duplicates-in-string-ii.md | 28 +- ...es-if-both-neighbors-are-the-same-color.md | 23 +- articles/remove-covered-intervals.md | 36 +- .../remove-duplicates-from-sorted-array-ii.md | 32 +- .../remove-duplicates-from-sorted-array.md | 16 +- .../remove-duplicates-from-sorted-list.md | 18 +- articles/remove-element.md | 15 +- articles/remove-k-digits.md | 18 +- articles/remove-linked-list-elements.md | 35 +- ...f-edges-to-keep-graph-fully-traversable.md | 22 +- .../remove-node-from-end-of-linked-list.md | 40 +- articles/remove-nodes-from-linked-list.md | 32 +- articles/removing-stars-from-a-string.md | 22 +- articles/reorder-linked-list.md | 37 +- ...to-make-all-paths-lead-to-the-city-zero.md | 24 +- articles/reorganize-string.md | 57 +- articles/repeated-dna-sequences.md | 43 +- ...nts-with-greatest-element-on-right-side.md | 10 +- articles/restore-ip-addresses.md | 48 +- articles/reveal-cards-in-increasing-order.md | 23 +- articles/reverse-a-linked-list.md | 18 +- articles/reverse-bits.md | 48 +- articles/reverse-integer.md | 42 +- articles/reverse-linked-list-ii.md | 25 +- articles/reverse-nodes-in-k-group.md | 30 +- articles/reverse-string.md | 31 +- articles/reverse-words-in-a-string-iii.md | 38 +- articles/robot-bounded-in-circle.md | 12 +- articles/roman-to-integer.md | 13 +- articles/rotate-array.md | 32 +- articles/rotate-list.md | 18 +- articles/rotate-matrix.md | 51 +- articles/rotating-the-box.md | 32 +- articles/rotting-fruit.md | 142 +- articles/russian-doll-envelopes.md | 89 +- articles/same-binary-tree.md | 80 +- articles/score-after-flipping-matrix.md | 16 +- articles/score-of-a-string.md | 4 +- articles/search-2d-matrix.md | 33 +- articles/search-for-word-ii.md | 175 +- articles/search-for-word.md | 163 +- articles/search-in-a-binary-search-tree.md | 14 +- articles/search-in-rotated-sorted-array-ii.md | 17 +- articles/search-insert-position.md | 35 +- articles/search-suggestions-system.md | 58 +- articles/seat-reservation-manager.md | 44 +- articles/sequential-digits.md | 60 +- .../serialize-and-deserialize-binary-tree.md | 40 +- articles/set-mismatch.md | 54 +- articles/set-zeroes-in-matrix.md | 24 +- articles/shift-2d-grid.md | 44 +- articles/shifting-letters-ii.md | 30 +- articles/shortest-bridge.md | 105 +- articles/shortest-common-supersequence.md | 61 +- articles/shortest-path-in-binary-matrix.md | 93 +- .../shortest-path-with-alternating-colors.md | 43 +- articles/shuffle-the-array.md | 18 +- articles/sign-of-the-product-of-an-array.md | 8 +- articles/simplify-path.md | 30 +- articles/single-element-in-a-sorted-array.md | 51 +- articles/single-number-iii.md | 54 +- articles/single-number.md | 24 +- articles/single-threaded-cpu.md | 83 +- articles/sliding-window-maximum.md | 106 +- articles/sliding-window-median.md | 59 +- .../smallest-string-starting-from-leaf.md | 24 +- articles/snakes-and-ladders.md | 68 +- articles/solving-questions-with-brainpower.md | 35 +- articles/sort-an-array.md | 209 +- .../sort-array-by-increasing-frequency.md | 4 +- articles/sort-array-by-parity.md | 43 +- articles/sort-characters-by-frequency.md | 16 +- articles/sort-colors.md | 35 +- ...items-by-groups-respecting-dependencies.md | 10 +- articles/sort-list.md | 24 +- articles/sort-the-jumbled-numbers.md | 12 +- articles/sort-the-people.md | 16 +- articles/special-array-i.md | 8 +- ...with-x-elements-greater-than-or-equal-x.md | 42 +- articles/spiral-matrix-ii.md | 42 +- articles/spiral-matrix.md | 76 +- articles/split-array-largest-sum.md | 56 +- articles/split-linked-list-in-parts.md | 23 +- ...ring-into-descending-consecutive-values.md | 16 +- articles/sqrtx.md | 23 +- articles/squares-of-a-sorted-array.md | 27 +- articles/stickers-to-spell-word.md | 74 +- articles/stone-game-ii.md | 43 +- articles/stone-game-iii.md | 35 +- articles/stone-game.md | 29 +- articles/string-compression-ii.md | 34 +- articles/string-encode-and-decode.md | 41 +- articles/string-matching-in-an-array.md | 94 +- articles/student-attendance-record-ii.md | 71 +- articles/subarray-product-less-than-k.md | 28 +- articles/subarray-sum-equals-k.md | 13 +- articles/subarray-sums-divisible-by-k.md | 20 +- .../subarrays-with-k-different-integers.md | 60 +- articles/subsets-ii.md | 50 +- articles/subsets.md | 42 +- articles/subtree-of-a-binary-tree.md | 85 +- .../successful-pairs-of-spells-and-potions.md | 86 +- ...-absolute-differences-in-a-sorted-array.md | 61 +- articles/sum-of-all-subset-xor-totals.md | 30 +- articles/sum-of-subarray-minimums.md | 67 +- articles/sum-of-two-integers.md | 34 +- articles/sum-root-to-leaf-numbers.md | 36 +- articles/surrounded-regions.md | 153 +- articles/swap-nodes-in-pairs.md | 19 +- articles/swapping-nodes-in-a-linked-list.md | 47 +- articles/swim-in-rising-water.md | 267 +- articles/symmetric-tree.md | 24 +- articles/target-sum.md | 115 +- articles/task-scheduling.md | 80 +- articles/text-justification.md | 28 +- articles/the-number-of-beautiful-subsets.md | 36 +- articles/three-integer-sum.md | 28 +- articles/time-based-key-value-store.md | 66 +- articles/time-needed-to-buy-tickets.md | 18 +- .../time-needed-to-inform-all-employees.md | 34 +- articles/top-k-elements-in-list.md | 47 +- articles/transpose-matrix.md | 36 +- articles/trapping-rain-water.md | 47 +- articles/triangle.md | 73 +- articles/trim-a-binary-search-tree.md | 24 +- articles/two-city-scheduling.md | 54 +- articles/two-integer-sum-ii.md | 22 +- articles/two-integer-sum.md | 50 +- articles/ugly-number.md | 8 +- articles/uncommon-words-from-two-sentences.md | 18 +- articles/uncrossed-lines.md | 45 +- articles/unique-binary-search-trees-ii.md | 40 +- articles/unique-binary-search-trees.md | 20 +- articles/unique-email-addresses.md | 39 +- ...nique-length-3-palindromic-subsequences.md | 83 +- articles/unique-paths-ii.md | 42 +- articles/valid-binary-search-tree.md | 102 +- articles/valid-palindrome-ii.md | 50 +- articles/valid-parenthesis-string.md | 129 +- articles/valid-perfect-square.md | 38 +- articles/valid-sudoku.md | 95 +- articles/valid-tree.md | 82 +- articles/valid-word-abbreviation.md | 15 +- articles/validate-binary-tree-nodes.md | 24 +- articles/validate-parentheses.md | 29 +- articles/validate-stack-sequences.md | 17 +- articles/verifying-an-alien-dictionary.md | 51 +- ...between-two-points-containing-no-points.md | 13 +- articles/wiggle-sort.md | 32 +- articles/word-break-ii.md | 68 +- articles/word-break.md | 98 +- articles/word-ladder.md | 180 +- articles/word-pattern.md | 92 +- articles/word-subsets.md | 20 +- articles/zigzag-conversion.md | 25 +- hints/add-two-numbers.md | 2 +- hints/anagram-groups.md | 2 +- hints/balanced-binary-tree.md | 2 +- hints/binary-search.md | 2 +- hints/binary-tree-diameter.md | 2 +- ...ree-from-preorder-and-inorder-traversal.md | 2 +- hints/binary-tree-maximum-path-sum.md | 2 +- hints/binary-tree-right-side-view.md | 2 +- hints/burst-balloons.md | 2 +- hints/buy-and-sell-crypto-with-cooldown.md | 2 +- hints/buy-and-sell-crypto.md | 2 +- hints/car-fleet.md | 2 +- hints/cheapest-flight-path.md | 2 +- hints/climbing-stairs.md | 2 +- hints/clone-graph.md | 2 +- hints/coin-change-ii.md | 2 +- hints/coin-change.md | 2 +- hints/combination-target-sum-ii.md | 2 +- hints/combination-target-sum.md | 2 +- hints/combinations-of-a-phone-number.md | 2 +- hints/copy-linked-list-with-random-pointer.md | 2 +- hints/count-connected-components.md | 2 +- hints/count-good-nodes-in-binary-tree.md | 2 +- hints/count-number-of-islands.md | 2 +- hints/count-paths.md | 2 +- hints/count-squares.md | 2 +- hints/count-subsequences.md | 2 +- hints/counting-bits.md | 2 +- hints/course-schedule-ii.md | 2 +- hints/course-schedule.md | 2 +- hints/daily-temperatures.md | 2 +- hints/decode-ways.md | 2 +- hints/depth-of-binary-tree.md | 2 +- hints/design-twitter-feed.md | 2 +- hints/design-word-search-data-structure.md | 2 +- hints/eating-bananas.md | 2 +- hints/edit-distance.md | 2 +- hints/evaluate-reverse-polish-notation.md | 2 +- hints/find-duplicate-integer.md | 2 +- hints/find-median-in-a-data-stream.md | 2 +- hints/find-minimum-in-rotated-sorted-array.md | 2 +- hints/find-target-in-rotated-sorted-array.md | 2 +- hints/foreign-dictionary.md | 2 +- hints/gas-station.md | 2 +- hints/generate-parentheses.md | 2 +- hints/hand-of-straights.md | 2 +- hints/house-robber-ii.md | 2 +- hints/house-robber.md | 2 +- hints/implement-prefix-tree.md | 2 +- hints/insert-new-interval.md | 2 +- hints/interleaving-string.md | 2 +- hints/invert-a-binary-tree.md | 2 +- hints/is-anagram.md | 2 +- hints/is-palindrome.md | 2 +- hints/islands-and-treasure.md | 2 +- hints/jump-game-ii.md | 2 +- hints/jump-game.md | 2 +- hints/k-closest-points-to-origin.md | 2 +- hints/kth-largest-element-in-an-array.md | 2 +- hints/kth-largest-integer-in-a-stream.md | 2 +- hints/kth-smallest-integer-in-bst.md | 2 +- hints/largest-rectangle-in-histogram.md | 2 +- hints/last-stone-weight.md | 2 +- hints/level-order-traversal-of-binary-tree.md | 2 +- hints/linked-list-cycle-detection.md | 2 +- hints/longest-common-subsequence.md | 2 +- hints/longest-consecutive-sequence.md | 2 +- hints/longest-increasing-path-in-matrix.md | 2 +- hints/longest-increasing-subsequence.md | 2 +- hints/longest-palindromic-substring.md | 2 +- ...st-repeating-substring-with-replacement.md | 2 +- hints/longest-substring-without-duplicates.md | 2 +- ...t-common-ancestor-in-binary-search-tree.md | 2 +- hints/lru-cache.md | 2 +- hints/max-area-of-island.md | 2 +- hints/max-water-container.md | 2 +- hints/maximum-product-subarray.md | 2 +- hints/maximum-subarray.md | 2 +- hints/median-of-two-sorted-arrays.md | 2 +- hints/meeting-schedule-ii.md | 2 +- hints/meeting-schedule.md | 2 +- hints/merge-intervals.md | 2 +- hints/merge-k-sorted-linked-lists.md | 2 +- hints/merge-triplets-to-form-target.md | 2 +- hints/merge-two-sorted-linked-lists.md | 2 +- hints/min-cost-climbing-stairs.md | 2 +- hints/min-cost-to-connect-points.md | 2 +- hints/minimum-interval-including-query.md | 2 +- hints/minimum-stack.md | 2 +- hints/minimum-window-with-characters.md | 2 +- hints/missing-number.md | 2 +- hints/multiply-strings.md | 2 +- hints/n-queens.md | 2 +- hints/network-delay-time.md | 2 +- hints/non-cyclical-number.md | 2 +- hints/non-overlapping-intervals.md | 2 +- hints/number-of-one-bits.md | 2 +- hints/pacific-atlantic-water-flow.md | 2 +- hints/palindrome-partitioning.md | 2 +- hints/palindromic-substrings.md | 2 +- hints/partition-equal-subset-sum.md | 2 +- hints/partition-labels.md | 2 +- hints/permutation-string.md | 2 +- hints/permutations.md | 2 +- hints/plus-one.md | 2 +- hints/pow-x-n.md | 2 +- hints/products-of-array-discluding-self.md | 2 +- hints/reconstruct-flight-path.md | 2 +- hints/redundant-connection.md | 2 +- hints/regular-expression-matching.md | 2 +- hints/remove-node-from-end-of-linked-list.md | 2 +- hints/reverse-a-linked-list.md | 2 +- hints/reverse-bits.md | 2 +- hints/reverse-integer.md | 2 +- hints/reverse-nodes-in-k-group.md | 2 +- hints/rotate-matrix.md | 2 +- hints/rotting-fruit.md | 2 +- hints/same-binary-tree.md | 2 +- hints/search-2d-matrix.md | 2 +- hints/search-for-word-ii.md | 2 +- hints/search-for-word.md | 2 +- .../serialize-and-deserialize-binary-tree.md | 2 +- hints/set-zeroes-in-matrix.md | 2 +- hints/single-number.md | 2 +- hints/sliding-window-maximum.md | 2 +- hints/spiral-matrix.md | 2 +- hints/string-encode-and-decode.md | 2 +- hints/subsets-ii.md | 2 +- hints/subsets.md | 2 +- hints/subtree-of-a-binary-tree.md | 2 +- hints/sum-of-two-integers.md | 2 +- hints/surrounded-regions.md | 2 +- hints/swim-in-rising-water.md | 2 +- hints/target-sum.md | 2 +- hints/task-scheduling.md | 2 +- hints/time-based-key-value-store.md | 2 +- hints/top-k-elements-in-list.md | 2 +- hints/trapping-rain-water.md | 2 +- hints/two-integer-sum-ii.md | 2 +- hints/two-integer-sum.md | 2 +- hints/valid-binary-search-tree.md | 2 +- hints/valid-parenthesis-string.md | 2 +- hints/valid-sudoku.md | 2 +- hints/valid-tree.md | 2 +- hints/validate-parentheses.md | 2 +- hints/word-break.md | 2 +- hints/word-ladder.md | 2 +- javascript/0001-two-sum.js | 55 +- javascript/0002-add-two-numbers.js | 40 +- .../0004-median-of-two-sorted-arrays.js | 2 +- .../0005-longest-palindromic-substring.js | 43 +- javascript/0007-reverse-integer.js | 18 +- javascript/0009-palindrome-number.js | 4 +- .../0010-regular-expression-matching.js | 112 +- javascript/0012-integer-to-roman.js | 63 +- javascript/0013-roman-to-integer.js | 38 +- javascript/0014-longest-common-prefix.js | 15 +- javascript/0015-3sum.js | 7 +- ...7-letter-combinations-of-a-phone-number.js | 82 +- javascript/0018-4sum.js | 2 +- .../0019-remove-nth-node-from-end-of-list.js | 36 +- javascript/0020-valid-parentheses.js | 34 +- javascript/0021-merge-two-sorted-lists.js | 23 +- javascript/0022-generate-parentheses.js | 213 +- javascript/0023-merge-k-sorted-lists.js | 17 +- javascript/0025-reverse-nodes-in-k-group.js | 16 +- ...026-remove-duplicates-from-sorted-array.js | 14 +- javascript/0027-remove-element.js | 39 +- ...dex-of-the-first-occurrence-in-a-string.js | 13 +- ...ast-position-of-element-in-sorted-array.js | 44 +- javascript/0036-valid-sudoku.js | 99 +- javascript/0039-combination-sum.js | 20 +- javascript/0040-combination-sum-ii.js | 28 +- javascript/0041-first-missing-positive.js | 60 +- javascript/0042-trapping-rain-water.js | 28 +- javascript/0043-multiply-strings.js | 103 +- javascript/0045-jump-game-ii.js | 21 +- javascript/0046-permutations.js | 135 +- javascript/0048-rotate-image.js | 54 +- javascript/0049-group-anagrams.js | 54 +- javascript/0050-powx-n.js | 97 +- javascript/0051-n-queens.js | 39 +- javascript/0053-maximum-subarray.js | 54 +- javascript/0054-spiral-matrix.js | 298 +- javascript/0055-jump-game.js | 58 +- javascript/0056-merge-intervals.js | 2 +- javascript/0058-length-of-last-word.js | 19 +- javascript/0059-spiral-matrix-ii.js | 22 +- javascript/0062-unique-paths.js | 116 +- javascript/0066-plus-one.js | 49 +- javascript/0069-sqrtx.js | 22 +- javascript/0070-climbing-stairs.js | 112 +- javascript/0071-simplify-path.js | 19 +- javascript/0072-edit-distance.js | 245 +- javascript/0073-set-matrix-zeroes.js | 138 +- javascript/0074-search-a-2d-matrix.js | 36 +- javascript/0075-sort-colors.js | 45 +- javascript/0078-subsets.js | 106 +- javascript/0079-word-search.js | 39 +- ...-remove-duplicates-from-sorted-array-ii.js | 64 +- .../0084-largest-rectangle-in-histogram.js | 94 +- javascript/0088-merge-sorted-array.js | 5 +- javascript/0090-subsets-ii.js | 41 +- javascript/0091-decode-ways.js | 44 +- javascript/0093-restore-ip-addresses.js | 2 +- .../0094-binary-tree-inorder-traversal.js | 43 +- .../0095-unique-binary-search-trees-ii.js | 24 +- javascript/0096-unique-binary-search-trees.js | 11 +- javascript/0097-interleaving-string.js | 199 +- .../0098-validate-binary-search-tree.js | 20 +- javascript/0101-symmetric-tree.js | 7 +- .../0102-binary-tree-level-order-traversal.js | 21 +- ...inary-tree-zigzag-level-order-traversal.js | 35 +- .../0104-maximum-depth-of-binary-tree.js | 18 +- ...ree-from-preorder-and-inorder-traversal.js | 129 +- ...ee-from-inorder-and-postorder-traversal.js | 14 +- ...vert-sorted-array-to-binary-search-tree.js | 92 +- javascript/0110-balanced-binary-tree.js | 41 +- javascript/0112-path-sum.js | 14 +- javascript/0115-distinct-subsequences.js | 104 +- ...lating-next-right-pointers-in-each-node.js | 11 +- javascript/0118-pascals-triangle.js | 13 +- ...0122-best-time-to-buy-and-sell-stock-ii.js | 8 +- .../0124-binary-tree-maximum-path-sum.js | 6 +- javascript/0125-valid-palindrome.js | 78 +- javascript/0127-word-ladder.js | 37 +- .../0128-longest-consecutive-sequence.js | 63 +- javascript/0129-sum-root-to-leaf-numbers.js | 27 +- javascript/0130-surrounded-regions.js | 131 +- javascript/0131-palindrome-partitioning.js | 79 +- javascript/0133-clone-graph.js | 50 +- javascript/0134-gas-station.js | 24 +- javascript/0135-candy.js | 19 +- .../0138-copy-list-with-random-pointer.js | 38 +- javascript/0139-word-break.js | 134 +- javascript/0141-linked-list-cycle.js | 18 +- javascript/0143-reorder-list.js | 29 +- .../0144-binary-tree-preorder-traversal.js | 5 +- .../0145-binary-tree-postorder-traversal.js | 5 +- javascript/0146-lru-cache.js | 28 +- .../0150-evaluate-reverse-polish-notation.js | 31 +- javascript/0152-maximum-product-subarray.js | 29 +- javascript/0155-min-stack.js | 51 +- javascript/0162-find-peak-element.js | 12 +- javascript/0169-majority-element.js | 46 +- .../0173-binary-search-tree-iterator.js | 25 +- javascript/0189-rotate-array.js | 68 +- javascript/0190-reverse-bits.js | 6 +- javascript/0191-number-of-1-bits.js | 30 +- javascript/0198-house-robber.js | 30 +- .../0199-binary-tree-right-side-view.js | 25 +- javascript/0200-number-of-islands.js | 164 +- javascript/0202-happy-number.js | 96 +- .../0203-remove-linked-list-elements.js | 63 +- javascript/0206-reverse-linked-list.js | 17 +- javascript/0207-course-schedule.js | 90 +- javascript/0210-course-schedule-ii.js | 127 +- javascript/0213-house-robber-ii.js | 19 +- .../0215-kth-largest-element-in-an-array.js | 17 +- javascript/0217-contains-duplicate.js | 28 +- javascript/0219-contains-duplicate-ii.js | 6 +- .../0225-implement-stack-using-queues.js | 18 +- javascript/0226-invert-binary-tree.js | 15 +- .../0230-kth-smallest-element-in-a-bst.js | 98 +- .../0232-implement-queue-using-stacks.js | 26 +- ...common-ancestor-of-a-binary-search-tree.js | 12 +- .../0238-product-of-array-except-self.js | 8 +- javascript/0242-valid-anagram.js | 32 +- javascript/0252-meeting-rooms.js | 2 +- javascript/0261-graph-valid-tree.js | 84 +- javascript/0263-ugly-number.js | 11 +- javascript/0268-missing-number.js | 2 +- javascript/0269-alien-dictionary.js | 76 +- javascript/0271-encode-and-decode-strings.js | 83 +- javascript/0273-integer-to-english-words.js | 62 +- javascript/0283-move-zeroes.js | 9 +- javascript/0286-walls-and-gates.js | 71 +- javascript/0287-find-the-duplicate-number.js | 534 +- javascript/0290-word-pattern.js | 33 +- .../0295-find-median-from-data-stream.js | 54 +- ...7-serialize-and-deserialize-binary-tree.js | 170 +- .../0300-longest-increasing-subsequence.js | 76 +- javascript/0303-range-sum-query-immutable.js | 6 +- .../0304-range-sum-query-2d-immutable.js | 44 +- ...ime-to-buy-and-sell-stock-with-cooldown.js | 41 +- javascript/0312-burst-balloons.js | 101 +- javascript/0322-coin-change.js | 92 +- ...ected-components-in-an-undirected-graph.js | 57 +- ...329-longest-increasing-path-in-a-matrix.js | 231 +- javascript/0332-reconstruct-itinerary.js | 13 +- javascript/0337-house-robber-iii.js | 12 +- javascript/0338-counting-bits.js | 8 +- javascript/0344-reverse-string.js | 14 +- javascript/0347-top-k-frequent-elements.js | 32 +- .../0352-data-stream-as-disjoint-intervals.js | 42 +- javascript/0355-design-twitter.js | 85 +- javascript/0367-valid-perfect-square.js | 17 +- javascript/0371-sum-of-two-integers.js | 10 +- .../0374-guess-number-higher-or-lower.js | 17 +- javascript/0392-is-subsequence.js | 23 +- javascript/0410-split-array-largest-sum.js | 13 +- javascript/0416-partition-equal-subset-sum.js | 161 +- .../0417-pacific-atlantic-water-flow.js | 258 +- ...longest-repeating-character-replacement.js | 12 +- javascript/0435-non-overlapping-intervals.js | 2 +- javascript/0441-arranging-coins.js | 45 +- ...ind-all-numbers-disappeared-in-an-array.js | 29 +- javascript/0450-delete-node-in-a-bst.js | 4 +- javascript/0460-lfu-cache.js | 177 +- javascript/0463-island-perimeter.js | 30 +- javascript/0494-target-sum.js | 201 +- javascript/0496-next-greater-element-i.js | 24 +- javascript/0502-ipo.js | 67 +- .../0513-find-bottom-left-tree-value.js | 15 +- ...515-find-largest-value-in-each-tree-row.js | 7 +- javascript/0518-coin-change-ii.js | 139 +- javascript/0523-continuous-subarray-sum.js | 22 +- javascript/0535-encode-and-decode-tinyurl.js | 18 +- .../0538-convert-bst-to-greater-tree.js | 11 +- javascript/0543-diameter-of-binary-tree.js | 6 +- javascript/0554-brick-wall.js | 41 +- javascript/0572-subtree-of-another-tree.js | 114 +- javascript/0605-can-place-flowers.js | 20 +- .../0606-construct-string-from-binary-tree.js | 16 +- javascript/0617-merge-two-binary-trees.js | 22 +- javascript/0621-task-scheduler.js | 228 +- javascript/0647-palindromic-substrings.js | 94 +- javascript/0652-find-duplicate-subtrees.js | 27 +- javascript/0669-trim-a-binary-search-tree.js | 65 +- javascript/0678-valid-parenthesis-string.js | 100 +- javascript/0682-baseball-game.js | 10 +- javascript/0684-redundant-connection.js | 56 +- javascript/0695-max-area-of-island.js | 102 +- .../0701-insert-into-a-binary-search-tree.js | 4 +- .../0703-kth-largest-element-in-a-stream.js | 19 +- javascript/0705-design-hashset.js | 8 +- javascript/0739-daily-temperatures.js | 63 +- javascript/0743-network-delay-time.js | 76 +- javascript/0746-min-cost-climbing-stairs.js | 29 +- javascript/0752-open-the-lock.js | 33 +- javascript/0763-partition-labels.js | 32 +- javascript/0767-reorganize-string.js | 19 +- javascript/0778-swim-in-rising-water.js | 38 +- ...0783-minimum-distance-between-bst-nodes.js | 8 +- .../0787-cheapest-flights-within-k-stops.js | 30 +- javascript/0837-new-21-game.js | 42 +- javascript/0846-hand-of-straights.js | 43 +- javascript/0853-car-fleet.js | 152 +- .../0861-score-after-flipping-matrix.js | 12 +- javascript/0872-leaf-similar-trees.js | 5 +- .../0894-all-possible-full-binary-trees.js | 16 +- javascript/0901-online-stock-span.js | 34 +- javascript/0909-snakes-and-ladders.js | 24 +- javascript/0912-sort-an-array.js | 33 +- javascript/0929-unique-email-addresses.js | 48 +- javascript/0934-shortest-bridge.js | 115 +- javascript/0937-k-closest-points-to-origin.js | 54 +- javascript/0938-range-sum-of-bst.js | 7 +- .../0951-flip-equivalent-binary-trees.js | 7 +- .../0953-verifying-an-alien-dictionary.js | 31 +- ...958-check-completeness-of-a-binary-tree.js | 18 +- javascript/0978-longest-turbulent-subarray.js | 14 +- ...0988-smallest-string-starting-from-leaf.js | 19 +- javascript/0994-rotting-oranges.js | 99 +- javascript/1046-last-stone-weight.js | 20 +- ...1071-greatest-common-divisor-of-strings.js | 31 +- javascript/1094-car-pooling.js | 7 +- javascript/1143-longest-common-subsequence.js | 167 +- javascript/1189-maximum-number-of-balloons.js | 26 +- javascript/1260-shift-2d-grid.js | 22 +- javascript/1268-search-suggestions-system.js | 97 +- ...nary-number-in-a-linked-list-to-integer.js | 5 +- ...nts-with-greatest-element-on-right-side.js | 40 +- javascript/1323-maximum-69-number.js | 10 +- .../1325-delete-leaves-with-a-given-value.js | 5 +- ...ber-of-steps-to-reduce-a-number-to-zero.js | 14 +- ...rage-greater-than-or-equal-to-threshold.js | 25 +- javascript/1361-validate-binary-tree-nodes.js | 43 +- ...376-time-needed-to-inform-all-employees.js | 11 +- .../1383-maximum-performance-of-a-team.js | 10 +- javascript/1396-design-underground-system.js | 95 +- javascript/1405-longest-happy-string.js | 36 +- ...aximum-points-you-can-obtain-from-cards.js | 11 +- ...um-time-to-collect-all-apples-in-a-tree.js | 13 +- .../1448-count-good-nodes-in-binary-tree.js | 118 +- ...ing-contains-all-binary-codes-of-size-k.js | 14 +- ...ber-of-unique-integers-after-k-removals.js | 12 +- javascript/1486-xor-operation-in-an-array.js | 29 +- javascript/1512-number-of-good-pairs.js | 2 +- .../1514-path-with-maximum-probability.js | 28 +- javascript/1572-matrix-diagonal-sum.js | 8 +- .../1584-min-cost-to-connect-all-points.js | 36 +- .../1588-sum-of-all-odd-length-subarrays.js | 5 +- javascript/1603-design-parking-system.js | 58 +- javascript/1609-even-odd-tree.js | 30 +- ...aximum-nesting-depth-of-the-parentheses.js | 8 +- .../1642-furthest-building-you-can-reach.js | 7 +- ...ns-to-make-character-frequencies-unique.js | 9 +- .../1688-count-of-matches-in-tournament.js | 17 +- ...-number-of-students-unable-to-eat-lunch.js | 14 +- javascript/1834-single-threaded-cpu.js | 22 +- javascript/1845-seat-reservation-manager.js | 15 +- ...lement-after-decreasing-and-rearranging.js | 9 +- ...-minimum-interval-to-include-each-query.js | 40 +- .../1863-sum-of-all-subset-xor-totals.js | 4 +- .../1882-process-tasks-using-servers.js | 14 +- ...-maximum-number-of-removable-characters.js | 114 +- ...9-merge-triplets-to-form-target-triplet.js | 44 +- javascript/1905-count-sub-islands.js | 38 +- ...21-eliminate-maximum-number-of-monsters.js | 3 +- javascript/1929-concatenation-of-array.js | 10 +- ...nique-length-3-palindromic-subsequences.js | 5 +- javascript/1958-check-if-move-is-legal.js | 40 +- ...er-of-swaps-to-make-the-string-balanced.js | 7 +- ...ments-not-equal-to-average-of-neighbors.js | 22 +- ...-between-highest-and-lowest-of-k-scores.js | 7 +- ...nd-the-kth-largest-integer-in-the-array.js | 3 +- javascript/1993-operations-on-tree.js | 46 +- ...-of-pairs-of-interchangeable-rectangles.js | 9 +- ...-length-of-two-palindromic-subsequences.js | 2 +- javascript/2013-detect-squares.js | 51 +- javascript/2017-grid-game.js | 16 +- ...es-if-both-neighbors-are-the-same-color.js | 15 +- .../2125-number-of-laser-beams-in-a-bank.js | 9 +- .../2130-maximum-twin-sum-of-a-linked-list.js | 58 +- ...our-digit-number-after-splitting-digits.js | 6 +- javascript/2235-add-two-integers.js | 2 +- javascript/2306-naming-a-company.js | 8 +- .../2331-evaluate-boolean-binary-tree.js | 14 +- .../2348-number-of-zero-filled-subarrays.js | 2 +- .../2390-removing-stars-from-a-string.js | 12 +- javascript/2427-number-of-common-factors.js | 3 +- javascript/2439-minimize-maximum-of-array.js | 3 +- javascript/2469-convert-the-temperature.js | 6 +- javascript/2485-find-the-pivot-integer.js | 5 +- javascript/2542-maximum-subsequence-score.js | 17 +- javascript/2621-sleep.js | 6 +- javascript/2623-memoize.js | 11 +- .../2626-array-reduce-transformation.js | 3 +- javascript/2627-debounce.js | 2 +- javascript/2628-json-deep-equal.js | 13 +- javascript/2629-function-composition.js | 5 +- javascript/2632-curry.js | 8 +- javascript/2634-filter-elements-from-array.js | 4 +- ...ly-transform-over-each-element-in-array.js | 2 +- .../2651-calculate-delayed-arrival-time.js | 11 +- javascript/2652-sum-multiples.js | 8 +- javascript/2665-counter-ii.js | 16 +- javascript/2666-allow-one-function-call.js | 2 +- .../2667-create-hello-world-function.js | 8 +- javascript/2704-to-be-or-not-to-be.js | 12 +- javascript/2706-buy-two-chocolates.js | 15 +- ...710-remove-trailing-zeros-from-a-string.js | 9 +- ...2769-find-the-maximum-achievable-number.js | 4 +- javascript/2810-faulty-keyboard.js | 5 +- javascript/2864-maximum-odd-binary-number.js | 11 +- package.json | 2 +- typescript/0002-add-two-numbers.ts | 2 +- typescript/0014-longest-common-prefix.ts | 10 +- typescript/0018-4sum.ts | 2 +- typescript/0021-merge-two-sorted-lists.ts | 2 +- typescript/0023-merge-k-sorted-lists.ts | 2 +- typescript/0047-permutations-ii.ts | 2 +- typescript/0056-merge-intervals.ts | 16 +- typescript/0057-insert-interval.ts | 19 +- typescript/0067-add-binary.ts | 14 +- typescript/0072-edit-distance.ts | 13 +- typescript/0073-set-matrix-zeroes.ts | 2 +- typescript/0079-word-search.ts | 77 +- .../0094-binary-tree-inorder-traversal.ts | 48 +- .../0098-validate-binary-search-tree.ts | 2 +- typescript/0127-word-ladder.ts | 2 +- typescript/0130-surrounded-regions.ts | 8 +- typescript/0146-lru-cache.ts | 24 +- .../0203-remove-linked-list-elements.ts | 64 +- ...ign-add-and-search-words-data-structure.ts | 2 +- typescript/0212-word-search-ii.ts | 4 +- typescript/0213-house-robber-ii.ts | 2 +- typescript/0219-contains-duplicate-ii.ts | 22 +- ...common-ancestor-of-a-binary-search-tree.ts | 2 +- typescript/0256-paint-house.ts | 4 +- typescript/0261-graph-valid-tree.ts | 2 +- .../0295-find-median-from-data-stream.ts | 11 +- ...7-serialize-and-deserialize-binary-tree.ts | 7 +- typescript/0303-range-sum-query-immutable.ts | 9 +- typescript/0307-range-sum-query-mutable.ts | 7 +- ...ime-to-buy-and-sell-stock-with-cooldown.ts | 4 +- typescript/0312-burst-balloons.ts | 2 +- typescript/0347-top-k-frequent-elements.ts | 4 +- .../0417-pacific-atlantic-water-flow.ts | 50 +- typescript/0435-non-overlapping-intervals.ts | 16 +- .../0438-find-all-anagrams-in-a-string.ts | 49 +- typescript/0474-ones-and-zeroes.ts | 24 +- typescript/0494-target-sum.ts | 5 +- typescript/0502-ipo.ts | 9 +- typescript/0669-trim-a-binary-search-tree.ts | 69 +- .../0703-kth-largest-element-in-a-stream.ts | 30 +- typescript/0705-design-hashset.ts | 15 +- typescript/0743-network-delay-time.ts | 13 +- typescript/0778-swim-in-rising-water.ts | 12 +- .../0787-cheapest-flights-within-k-stops.ts | 2 +- typescript/0983-minimum-cost-for-tickets.ts | 2 +- typescript/1049-last-stone-weight-ii.ts | 7 +- ...ve-all-adjacent-duplicates-in-string-ii.ts | 2 +- ...nts-with-greatest-element-on-right-side.ts | 12 +- typescript/1462-course-schedule-iv.ts | 8 +- ...critical-edges-in-minimum-spanning-tree.ts | 38 +- .../1514-path-with-maximum-probability.ts | 16 +- .../1584-min-cost-to-connect-all-points.ts | 10 +- ...-frequency-of-the-most-frequent-element.ts | 8 +- typescript/1929-concatenation-of-array.ts | 12 +- ...-length-of-two-palindromic-subsequences.ts | 16 +- .../2215-find-the-difference-of-two-arrays.ts | 4 +- .../2390-removing-stars-from-a-string.ts | 12 +- typescript/2421-number-of-good-paths.ts | 1 - typescript/2469-convert-the-temperature.ts | 4 +- typescript/2620-counter.ts | 9 +- .../2667-create-hello-world-function.ts | 6 +- updateCompletionTable.js | 32 +- updateSiteData.js | 58 +- verifySiteData.js | 38 +- 1137 files changed, 31437 insertions(+), 27715 deletions(-) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 86a64e158..fac8e2e97 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,15 +1,15 @@ -[//]: # "Pull Request Template" -[//]: # "Replace the placeholder values in the template below" +[//]: # 'Pull Request Template' +[//]: # 'Replace the placeholder values in the template below' - **File(s) Modified**: _0001-two-sum.py, 0002-add-two-numbers.py, etc..._ - **Language(s) Used**: _python, javascript, etc..._ - **Submission URL**: _https://leetcode.com/problems/[problem-name]/submissions/xxxxxxxxx/_ -[//]: # "Getting the Submission URL" -[//]: # "Go to the leetcode [`Submissions tab`](https://user-images.githubusercontent.com/71089234/180188604-b1ecaf90-bf27-4fd6-a559-5567aebf8930.png)" -[//]: # "and [click on the `Accepted` status of your submission.](https://user-images.githubusercontent.com/71089234/180189321-1a48c33f-aa65-4b29-8aaa-685f4f5f8c9e.png)]" -[//]: # "Finally copy the URL from the nav bar, it should look like https://leetcode.com/problems/[problem-name]/submissions/xxxxxxxxx/" - +[//]: # 'Getting the Submission URL' +[//]: # 'Go to the leetcode [`Submissions tab`](https://user-images.githubusercontent.com/71089234/180188604-b1ecaf90-bf27-4fd6-a559-5567aebf8930.png)' +[//]: # 'and [click on the `Accepted` status of your submission.](https://user-images.githubusercontent.com/71089234/180189321-1a48c33f-aa65-4b29-8aaa-685f4f5f8c9e.png)]' +[//]: # 'Finally copy the URL from the nav bar, it should look like https://leetcode.com/problems/[problem-name]/submissions/xxxxxxxxx/' ### Important + Please make sure the file name is lowercase and a duplicate file does not already exist before merging. diff --git a/.problemSiteData.json b/.problemSiteData.json index 5699c6b13..402862497 100644 --- a/.problemSiteData.json +++ b/.problemSiteData.json @@ -1,6779 +1,6779 @@ [ - { - "neetcode150":true, - "blind75":true, - "problem":"Contains Duplicate", - "pattern":"Arrays & Hashing", - "link":"contains-duplicate/", - "video":"3OamzN90kPg", - "difficulty":"Easy", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0217-contains-duplicate", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true, - "scala":true, - "dart":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Valid Anagram", - "pattern":"Arrays & Hashing", - "link":"valid-anagram/", - "video":"9UtInBqnCgA", - "difficulty":"Easy", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0242-valid-anagram", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true, - "scala":true, - "dart":true - }, - { - "problem":"Concatenation of Array", - "pattern":"Arrays & Hashing", - "link":"concatenation-of-array/", - "video":"68isPRHgcFQ", - "difficulty":"Easy", - "code":"1929-concatenation-of-array", - "python":true, - "cpp":true, - "java":true, - "javascript":true, - "kotlin":true, - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "swift":true, - "rust":true, - "scala":true, - "dart":true - }, - { - "problem":"Replace Elements With Greatest Element On Right Side", - "pattern":"Arrays & Hashing", - "link":"replace-elements-with-greatest-element-on-right-side/", - "video":"ZHjKhUjcsaU", - "difficulty":"Easy", - "code":"1299-replace-elements-with-greatest-element-on-right-side", - "c":true, - "cpp":true, - "csharp":true, - "java":true, - "python":true, - "javascript":true, - "typescript":true, - "go":true, - "rust":true, - "dart":true, - "kotlin":true, - "swift":true - }, - { - "problem":"Is Subsequence", - "pattern":"Arrays & Hashing", - "link":"is-subsequence/", - "video":"99RVfqklbCE", - "difficulty":"Easy", - "code":"0392-is-subsequence", - "c":true, - "cpp":true, - "csharp":true, - "java":true, - "python":true, - "javascript":true, - "typescript":true, - "go":true, - "rust":true, - "dart":true, - "kotlin":true, - "swift":true - }, - { - "problem":"Length of Last Word", - "pattern":"Arrays & Hashing", - "link":"length-of-last-word/", - "video":"KT9rltZTybQ", - "difficulty":"Easy", - "code":"0058-length-of-last-word", - "c":true, - "cpp":true, - "csharp":true, - "java":true, - "python":true, - "javascript":true, - "typescript":true, - "rust":true, - "go":true, - "swift":true, - "dart":true, - "ruby":true, - "kotlin":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Two Sum", - "pattern":"Arrays & Hashing", - "link":"two-sum/", - "video":"KLlXCFG5TnA", - "difficulty":"Easy", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0001-two-sum", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true, - "scala":true, - "dart":true - }, - { - "problem":"Longest Common Prefix", - "pattern":"Arrays & Hashing", - "link":"longest-common-prefix/", - "video":"0sWShKIJoo4", - "difficulty":"Easy", - "code":"0014-longest-common-prefix", - "cpp":true, - "python":true, - "javascript":true, - "c":true, - "csharp":true, - "java":true, - "typescript":true, - "go":true, - "rust":true, - "dart":true, - "kotlin":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Group Anagrams", - "pattern":"Arrays & Hashing", - "link":"group-anagrams/", - "video":"vzdNOK2oB2E", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0049-group-anagrams", - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true, - "dart":true, - "c":true, - "scala":true - }, - { - "problem":"Pascals Triangle", - "pattern":"Arrays & Hashing", - "link":"pascals-triangle/", - "video":"nPVEaB3AjUM", - "difficulty":"Easy", - "code":"0118-pascals-triangle", - "c":true, - "cpp":true, - "java":true, - "python":true, - "javascript":true, - "typescript":true, - "rust":true, - "csharp":true, - "go":true, - "dart":true, - "kotlin":true - }, - { - "problem":"Remove Element", - "pattern":"Arrays & Hashing", - "link":"remove-element/", - "video":"Pcd1ii9P9ZI", - "difficulty":"Easy", - "code":"0027-remove-element", - "c":true, - "java":true, - "python":true, - "javascript":true, - "typescript":true, - "go":true, - "cpp":true, - "csharp":true, - "swift":true, - "rust":true, - "dart":true, - "kotlin":true - }, - { - "problem":"Unique Email Addresses", - "pattern":"Arrays & Hashing", - "link":"unique-email-addresses/", - "video":"TC_xLIWl7qY", - "difficulty":"Easy", - "code":"0929-unique-email-addresses", - "java":true, - "python":true, - "javascript":true, - "typescript":true, - "swift":true, - "cpp":true, - "csharp":true, - "go":true, - "rust":true, - "c":true, - "kotlin":true - }, - { - "problem":"Isomorphic Strings", - "pattern":"Arrays & Hashing", - "link":"isomorphic-strings/", - "video":"7yF-U1hLEqQ", - "difficulty":"Easy", - "code":"0205-isomorphic-strings", - "c":true, - "java":true, - "python":true, - "javascript":true, - "typescript":true, - "swift":true, - "cpp":true, - "csharp":true, - "go":true, - "rust":true, - "kotlin":true - }, - { - "problem":"Can Place Flowers", - "pattern":"Arrays & Hashing", - "link":"can-place-flowers/", - "video":"ZGxqqjljpUI", - "difficulty":"Easy", - "code":"0605-can-place-flowers", - "c":true, - "cpp":true, - "python":true, - "javascript":true, - "typescript":true, - "csharp":true, - "go":true, - "rust":true, - "java":true, - "kotlin":true, - "swift":true - }, - { - "problem":"Majority Element", - "pattern":"Arrays & Hashing", - "link":"majority-element/", - "video":"7pnhv842keE", - "difficulty":"Easy", - "code":"0169-majority-element", - "c":true, - "cpp":true, - "python":true, - "javascript":true, - "typescript":true, - "swift":true, - "csharp":true, - "java":true, - "go":true, - "kotlin":true, - "rust":true - }, - { - "problem":"Next Greater Element I", - "pattern":"Arrays & Hashing", - "link":"next-greater-element-i/", - "video":"68a1Dc_qVq4", - "difficulty":"Easy", - "code":"0496-next-greater-element-i", - "java":true, - "python":true, - "typescript":true, - "c":true, - "cpp":true, - "csharp":true, - "javascript":true, - "go":true, - "rust":true, - "kotlin":true - }, - { - "problem":"Find Pivot Index", - "pattern":"Arrays & Hashing", - "link":"find-pivot-index/", - "video":"u89i60lYx8U", - "difficulty":"Easy", - "code":"0724-find-pivot-index", - "c":true, - "cpp":true, - "java":true, - "python":true, - "javascript":true, - "typescript":true, - "go":true, - "rust":true, - "csharp":true, - "kotlin":true, - "swift":true - }, - { - "problem":"Range Sum Query - Immutable", - "pattern":"Arrays & Hashing", - "link":"range-sum-query-immutable/", - "video":"2pndAmo_sMA", - "difficulty":"Easy", - "code":"0303-range-sum-query-immutable", - "python":true, - "c":true, - "cpp":true, - "java":true, - "kotlin":true, - "csharp":true, - "javascript":true, - "rust":true - }, - { - "problem":"Find All Numbers Disappeared in An Array", - "pattern":"Arrays & Hashing", - "link":"find-all-numbers-disappeared-in-an-array/", - "video":"8i-f24YFWC4", - "difficulty":"Easy", - "code":"0448-find-all-numbers-disappeared-in-an-array", - "cpp":true, - "java":true, - "python":true, - "javascript":true, - "c":true, - "typescript":true, - "go":true, - "rust":true, - "csharp":true, - "kotlin":true - }, - { - "problem":"Maximum Number of Balloons", - "pattern":"Arrays & Hashing", - "link":"maximum-number-of-balloons/", - "video":"G9xeB2-7PqY", - "difficulty":"Easy", - "code":"1189-maximum-number-of-balloons", - "c":true, - "java":true, - "python":true, - "javascript":true, - "cpp":true, - "typescript":true, - "go":true, - "rust":true, - "csharp":true, - "kotlin":true - }, - { - "problem":"Word Pattern", - "pattern":"Arrays & Hashing", - "link":"word-pattern/", - "video":"W_akoecmCbM", - "difficulty":"Easy", - "code":"0290-word-pattern", - "java":true, - "python":true, - "javascript":true, - "typescript":true, - "c":true, - "cpp":true, - "go":true, - "rust":true, - "csharp":true, - "kotlin":true - }, - { - "problem":"Design HashSet", - "pattern":"Arrays & Hashing", - "link":"design-hashset/", - "video":"VymjPQUXjL8", - "difficulty":"Easy", - "code":"0705-design-hashset", - "kotlin":true, - "c":true, - "cpp":true, - "java":true, - "python":true, - "javascript":true, - "rust":true - }, - { - "problem":"Design HashMap", - "pattern":"Arrays & Hashing", - "link":"design-hashmap/", - "video":"cNWsgbKwwoU", - "difficulty":"Easy", - "code":"0706-design-hashmap", - "python":true, - "c":true, - "cpp":true, - "java":true, - "javascript":true, - "kotlin":true, - "rust":true - }, - { - "problem":"Sort an Array", - "pattern":"Arrays & Hashing", - "link":"sort-an-array/", - "video":"MsYZSinhuFo", - "difficulty":"Medium", - "code":"0912-sort-an-array", - "python":true, - "java":true, - "kotlin":true, - "cpp":true, - "csharp":true, - "javascript":true, - "go":true, - "rust":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Top K Frequent Elements", - "pattern":"Arrays & Hashing", - "link":"top-k-frequent-elements/", - "video":"YPTqKIgVk-k", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0347-top-k-frequent-elements", - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true, - "c":true, - "scala":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Product of Array Except Self", - "pattern":"Arrays & Hashing", - "link":"product-of-array-except-self/", - "video":"bNvIQI2wAjk", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0238-product-of-array-except-self", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "problem":"Valid Sudoku", - "pattern":"Arrays & Hashing", - "link":"valid-sudoku/", - "video":"TjFXEUCMqI8", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0036-valid-sudoku", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "kotlin":true, - "rust":true, - "dart":true, - "scala":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Encode and Decode Strings", - "premium":true, - "freeLink":"https://www.lintcode.com/problem/659/", - "pattern":"Arrays & Hashing", - "link":"encode-and-decode-strings/", - "video":"B1k_sxOSgv8", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0271-encode-and-decode-strings", - "csharp":true, - "go":true, - "ruby":true, - "swift":true, - "rust":true, - "typescript":true, - "kotlin":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Longest Consecutive Sequence", - "pattern":"Arrays & Hashing", - "link":"longest-consecutive-sequence/", - "video":"P6RZZMu_maU", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0128-longest-consecutive-sequence", - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true, - "c":true - }, - { - "problem":"Sort Colors", - "pattern":"Arrays & Hashing", - "link":"sort-colors/", - "video":"4xbWSRZHqac", - "difficulty":"Medium", - "code":"0075-sort-colors", - "c":true, - "java":true, - "javascript":true, - "go":true, - "kotlin":true, - "cpp":true, - "python":true, - "typescript":true, - "csharp":true, - "rust":true, - "swift":true - }, - { - "problem":"Encode and Decode TinyURL", - "pattern":"Arrays & Hashing", - "link":"encode-and-decode-tinyurl/", - "video":"VyBOaboQLGc", - "difficulty":"Medium", - "code":"0535-encode-and-decode-tinyurl", - "javascript":true, - "cpp":true, - "python":true, - "typescript":true, - "go":true, - "rust":true, - "swift":true, - "kotlin":true, - "c":true, - "java":true - }, - { - "problem":"Brick Wall", - "pattern":"Arrays & Hashing", - "link":"brick-wall/", - "video":"Kkmv2h48ekw", - "difficulty":"Medium", - "code":"0554-brick-wall", - "javascript":true, - "typescript":true, - "c":true, - "cpp":true, - "java":true, - "python":true, - "rust":true, - "kotlin":true - }, - { - "problem":"Best Time to Buy And Sell Stock II", - "pattern":"Arrays & Hashing", - "link":"best-time-to-buy-and-sell-stock-ii/", - "video":"3SJ3pUkPQMc", - "difficulty":"Medium", - "code":"0122-best-time-to-buy-and-sell-stock-ii", - "c":true, - "javascript":true, - "go":true, - "cpp":true, - "java":true, - "python":true, - "kotlin":true, - "rust":true - }, - { - "problem":"Subarray Sum Equals K", - "pattern":"Arrays & Hashing", - "link":"subarray-sum-equals-k/", - "video":"fFVZt-6sgyo", - "difficulty":"Medium", - "code":"0560-subarray-sum-equals-k", - "java":true, - "cpp":true, - "go":true, - "c":true, - "python":true, - "javascript":true, - "typescript":true, - "kotlin":true, - "rust":true, - "csharp":true - }, - { - "problem":"Unique Length 3 Palindromic Subsequences", - "pattern":"Arrays & Hashing", - "link":"unique-length-3-palindromic-subsequences/", - "video":"3THUt0vAFLU", - "difficulty":"Medium", - "code":"1930-unique-length-3-palindromic-subsequences", - "cpp":true, - "java":true, - "kotlin":true, - "c":true, - "python":true, - "javascript":true, - "typescript":true, - "rust":true - }, - { - "problem":"Minimum Number of Swaps to Make The String Balanced", - "pattern":"Arrays & Hashing", - "link":"minimum-number-of-swaps-to-make-the-string-balanced/", - "video":"3YDBT9ZrfaU", - "difficulty":"Medium", - "code":"1963-minimum-number-of-swaps-to-make-the-string-balanced", - "javascript":true, - "cpp":true, - "c":true, - "python":true, - "kotlin":true, - "java":true, - "rust":true - }, - { - "problem":"Number of Pairs of Interchangeable Rectangles", - "pattern":"Arrays & Hashing", - "link":"number-of-pairs-of-interchangeable-rectangles/", - "video":"lEQ8ZlLOuyQ", - "difficulty":"Medium", - "code":"2001-number-of-pairs-of-interchangeable-rectangles", - "javascript":true, - "cpp":true, - "python":true, - "c":true, - "java":true, - "rust":true, - "kotlin":true - }, - { - "problem":"Maximum Product of The Length of Two Palindromic Subsequences", - "pattern":"Arrays & Hashing", - "link":"maximum-product-of-the-length-of-two-palindromic-subsequences/", - "video":"aoHbYlO8vDg", - "difficulty":"Medium", - "code":"2002-maximum-product-of-the-length-of-two-palindromic-subsequences", - "cpp":true, - "c":true, - "csharp":true, - "java":true, - "python":true, - "javascript":true, - "typescript":true, - "go":true, - "kotlin":true, - "rust":true - }, - { - "problem":"Grid Game", - "pattern":"Arrays & Hashing", - "link":"grid-game/", - "video":"N4wDSOw65hI", - "difficulty":"Medium", - "code":"2017-grid-game", - "python":true, - "cpp":true, - "kotlin":true, - "java":true, - "javascript":true, - "rust":true - }, - { - "problem":"Find All Anagrams in a String", - "pattern":"Arrays & Hashing", - "link":"find-all-anagrams-in-a-string/", - "video":"G8xtZy0fDKg", - "difficulty":"Medium", - "code":"0438-find-all-anagrams-in-a-string", - "cpp":true, - "csharp":true, - "python":true, - "java":true, - "javascript":true, - "go":true, - "kotlin":true, - "c":true - }, - { - "problem":"Find The Index of The First Occurrence in a String", - "pattern":"Arrays & Hashing", - "link":"find-the-index-of-the-first-occurrence-in-a-string/", - "video":"JoF0Z7nVSrA", - "difficulty":"Easy", - "code":"0028-find-the-index-of-the-first-occurrence-in-a-string", - "python":true, - "cpp":true, - "go":true, - "c":true, - "java":true, - "kotlin":true, - "csharp":true, - "javascript":true - }, - { - "problem":"Wiggle Sort", - "pattern":"Arrays & Hashing", - "premium":true, - "freeLink":"https://www.lintcode.com/problem/508/", - "link":"wiggle-sort/", - "video":"vGsyTE4s34w", - "difficulty":"Medium", - "code":"0280-wiggle-sort", - "cpp":true, - "python":true, - "kotlin":true - }, - { - "problem":"Largest Number", - "pattern":"Arrays & Hashing", - "link":"largest-number/", - "video":"WDx6Y4i4xJ8", - "difficulty":"Medium", - "code":"0179-largest-number", - "typescript":true, - "cpp":true, - "java":true, - "kotlin":true, - "c":true, - "csharp":true, - "python":true, - "javascript":true, - "go":true, - "ruby":true, - "swift":true, - "rust":true, - "scala":true - }, - { - "problem":"Continuous Subarray Sum", - "pattern":"Arrays & Hashing", - "link":"continuous-subarray-sum/", - "video":"OKcrLfR-8mE", - "difficulty":"Medium", - "code":"0523-continuous-subarray-sum", - "java":true, - "python":true, - "cpp":true, - "kotlin":true, - "c":true, - "javascript":true, - "rust":true - }, - { - "problem":"Push Dominoes", - "pattern":"Arrays & Hashing", - "link":"push-dominoes/", - "video":"evUFsOb_iLY", - "difficulty":"Medium", - "code":"0838-push-dominoes", - "typescript":true, - "cpp":true, - "python":true, - "kotlin":true, - "java":true - }, - { - "problem":"Repeated DNA Sequences", - "pattern":"Arrays & Hashing", - "link":"repeated-dna-sequences/", - "video":"FzTYfsmtOso", - "difficulty":"Medium", - "code":"0187-repeated-dna-sequences", - "java":true, - "typescript":true, - "cpp":true, - "kotlin":true, - "python":true, - "javascript":true - }, - { - "problem":"Insert Delete Get Random O(1)", - "pattern":"Arrays & Hashing", - "link":"insert-delete-getrandom-o1/", - "video":"j4KwhBziOpg", - "difficulty":"Medium", - "code":"0380-insert-delete-getrandom-o1", - "java":true, - "typescript":true, - "javascript":true, - "go":true, - "cpp":true, - "swift":true, - "kotlin":true, - "python":true - }, - { - "problem":"Check if a String Contains all Binary Codes of Size K", - "pattern":"Arrays & Hashing", - "link":"check-if-a-string-contains-all-binary-codes-of-size-k/", - "video":"qU32rTy_kOM", - "difficulty":"Medium", - "code":"1461-check-if-a-string-contains-all-binary-codes-of-size-k", - "cpp":true, - "kotlin":true, - "python":true, - "javascript":true - }, - { - "problem":"Range Sum Query 2D Immutable", - "pattern":"Arrays & Hashing", - "link":"range-sum-query-2d-immutable/", - "video":"KE8MQuwE2yA", - "difficulty":"Medium", - "code":"0304-range-sum-query-2d-immutable", - "cpp":true, - "python":true, - "kotlin":true, - "javascript":true - }, - { - "problem":"Non Decreasing Array", - "pattern":"Arrays & Hashing", - "link":"non-decreasing-array/", - "video":"RegQckCegDk", - "difficulty":"Medium", - "code":"0665-non-decreasing-array", - "cpp":true, - "java":true, - "javascript":true, - "typescript":true, - "go":true, - "scala":true, - "kotlin":true, - "python":true, - "csharp":true - }, - { - "problem":"First Missing Positive", - "pattern":"Arrays & Hashing", - "link":"first-missing-positive/", - "video":"8g78yfzMlao", - "difficulty":"Hard", - "code":"0041-first-missing-positive", - "python":true, - "typescript":true, - "cpp":true, - "java":true, - "go":true, - "kotlin":true, - "c":true, - "javascript":true - }, - { - "problem":"Sign of An Array", - "pattern":"Arrays & Hashing", - "link":"sign-of-the-product-of-an-array/", - "video":"ILDLM86jNow", - "difficulty":"Easy", - "code":"1822-sign-of-the-product-of-an-array", - "cpp":true, - "java":true, - "python":true, - "javascript":true, - "typescript":true, - "go":true, - "kotlin":true - }, - { - "problem":"Find the Difference of Two Arrays", - "pattern":"Arrays & Hashing", - "link":"find-the-difference-of-two-arrays/", - "video":"a4wqKR-znBE", - "difficulty":"Easy", - "code":"2215-find-the-difference-of-two-arrays", - "kotlin":true, - "cpp":true, - "csharp":true, - "java":true, - "python":true, - "javascript":true, - "typescript":true - }, - { - "problem":"Design Parking System", - "pattern":"Arrays & Hashing", - "link":"design-parking-system/", - "video":"d5zCHesOrSk", - "difficulty":"Easy", - "code":"1603-design-parking-system", - "kotlin":true, - "java":true, - "python":true, - "javascript":true - }, - { - "problem":"Number of Zero-Filled Subarrays", - "pattern":"Arrays & Hashing", - "link":"number-of-zero-filled-subarrays/", - "video":"G-EWVGCcL_w", - "difficulty":"Medium", - "code":"2348-number-of-zero-filled-subarrays", - "kotlin":true, - "cpp":true, - "java":true, - "python":true - }, - { - "problem":"Optimal Partition of String", - "pattern":"Arrays & Hashing", - "link":"optimal-partition-of-string/", - "video":"CKZPdiXiQf0", - "difficulty":"Medium", - "code":"2405-optimal-partition-of-string", - "kotlin":true, - "java":true - }, - { - "problem":"Design Underground System", - "pattern":"Arrays & Hashing", - "link":"design-underground-system/", - "video":"W5QOLqXskZM", - "difficulty":"Medium", - "code":"1396-design-underground-system", - "kotlin":true, - "java":true, - "javascript":true - }, - { - "problem":"Minimum Penalty for a Shop", - "pattern":"Arrays & Hashing", - "link":"minimum-penalty-for-a-shop/", - "video":"0d7ShRoOFVE", - "difficulty":"Medium", - "code":"2483-minimum-penalty-for-a-shop", - "cpp":true, - "java":true, - "kotlin":true - }, - { - "problem":"Text Justification", - "pattern":"Arrays & Hashing", - "link":"text-justification/", - "video":"TzMl4Z7pVh8", - "difficulty":"Hard", - "code":"0068-naming-a-company", - "python":true, - "kotlin":true - }, - { - "problem":"Naming a Company", - "pattern":"Arrays & Hashing", - "link":"naming-a-company/", - "video":"NrHpgTScOcY", - "difficulty":"Hard", - "code":"2306-naming-a-company", - "kotlin":true, - "java":true, - "javascript":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Valid Palindrome", - "pattern":"Two Pointers", - "link":"valid-palindrome/", - "video":"jJXJ16kPFWg", - "difficulty":"Easy", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0125-valid-palindrome", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true, - "dart":true, - "scala":true - }, - { - "problem":"Valid Palindrome II", - "pattern":"Two Pointers", - "link":"valid-palindrome-ii/", - "video":"JrxRYBwG6EI", - "difficulty":"Easy", - "code":"0680-valid-palindrome-ii", - "python":true, - "cpp":true, - "csharp":true, - "java":true, - "javascript":true, - "typescript":true, - "go":true, - "rust":true, - "c":true, - "kotlin":true - }, - { - "problem":"Minimum Difference Between Highest And Lowest of K Scores", - "pattern":"Two Pointers", - "link":"minimum-difference-between-highest-and-lowest-of-k-scores/", - "video":"JU5XdBZZtlk", - "difficulty":"Easy", - "code":"1984-minimum-difference-between-highest-and-lowest-of-k-scores", - "javascript":true, - "cpp":true, - "python":true, - "typescript":true, - "go":true, - "rust":true, - "java":true, - "kotlin":true - }, - { - "problem":"Merge Strings Alternately", - "pattern":"Two Pointers", - "link":"merge-strings-alternately/", - "video":"LECWOvTo-Sc", - "difficulty":"Easy", - "code":"1768-merge-strings-alternately", - "kotlin":true, - "cpp":true, - "java":true, - "python":true, - "javascript":true, - "typescript":true - }, - { - "problem":"Reverse String", - "pattern":"Two Pointers", - "link":"reverse-string/", - "video":"_d0T_2Lk2qA", - "difficulty":"Easy", - "code":"0344-reverse-string", - "c":true, - "python":true, - "javascript":true, - "typescript":true, - "swift":true, - "cpp":true, - "java":true, - "go":true, - "rust":true, - "kotlin":true, - "dart":true - }, - { - "problem":"Merge Sorted Array", - "pattern":"Two Pointers", - "link":"merge-sorted-array/", - "video":"P1Ic85RarKY", - "difficulty":"Easy", - "code":"0088-merge-sorted-array", - "c":true, - "java":true, - "javascript":true, - "cpp":true, - "python":true, - "typescript":true, - "go":true, - "rust":true, - "kotlin":true - }, - { - "problem":"Move Zeroes", - "pattern":"Two Pointers", - "link":"move-zeroes/", - "video":"aayNRwUN3Do", - "difficulty":"Easy", - "code":"0283-move-zeroes", - "c":true, - "cpp":true, - "javascript":true, - "csharp":true, - "python":true, - "typescript":true, - "go":true, - "swift":true, - "rust":true, - "java":true, - "kotlin":true - }, - { - "problem":"Remove Duplicates From Sorted Array", - "pattern":"Two Pointers", - "link":"remove-duplicates-from-sorted-array/", - "video":"DEJAZBq0FDA", - "difficulty":"Easy", - "code":"0026-remove-duplicates-from-sorted-array", - "python":true, - "javascript":true, - "go":true, - "cpp":true, - "typescript":true, - "swift":true, - "rust":true, - "java":true, - "kotlin":true, - "c":true - }, - { - "problem":"Remove Duplicates From Sorted Array II", - "pattern":"Two Pointers", - "link":"remove-duplicates-from-sorted-array-ii/", - "video":"ycAq8iqh0TI", - "difficulty":"Medium", - "code":"0080-remove-duplicates-from-sorted-array-ii", - "python":true, - "kotlin":true, - "cpp":true, - "csharp":true, - "javascript":true, - "swift":true - }, - { - "neetcode150":true, - "problem":"Two Sum II Input Array Is Sorted", - "pattern":"Two Pointers", - "link":"two-sum-ii-input-array-is-sorted/", - "video":"cQ1Oz4ckceM", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0167-two-sum-ii-input-array-is-sorted", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true, - "scala":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"3Sum", - "pattern":"Two Pointers", - "link":"3sum/", - "video":"jzZsG8n2R9A", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0015-3sum", - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true, - "scala":true, - "c":true - }, - { - "problem":"4Sum", - "pattern":"Two Pointers", - "link":"4sum/", - "video":"EYeR-_1NRlQ", - "difficulty":"Medium", - "code":"0018-4sum", - "python":true, - "javascript":true, - "typescript":true, - "go":true, - "cpp":true, - "kotlin":true, - "java":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Container With Most Water", - "pattern":"Two Pointers", - "link":"container-with-most-water/", - "video":"UuiTKBwPgAo", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0011-container-with-most-water", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true, - "scala":true, - "dart":true - }, - { - "problem":"Number of Subsequences That Satisfy The Given Sum Condition", - "pattern":"Two Pointers", - "link":"number-of-subsequences-that-satisfy-the-given-sum-condition/", - "video":"xCsIkPLS4Ls", - "difficulty":"Medium", - "code":"1498-number-of-subsequences-that-satisfy-the-given-sum-condition", - "cpp":true, - "python":true, - "kotlin":true - }, - { - "problem":"Rotate Array", - "pattern":"Two Pointers", - "link":"rotate-array/", - "video":"BHr381Guz3Y", - "difficulty":"Medium", - "code":"0189-rotate-array", - "cpp":true, - "java":true, - "python":true, - "typescript":true, - "go":true, - "kotlin":true, - "javascript":true - }, - { - "problem":"Array With Elements Not Equal to Average of Neighbors", - "pattern":"Two Pointers", - "link":"array-with-elements-not-equal-to-average-of-neighbors/", - "video":"Wmb3YdVYfqM", - "difficulty":"Medium", - "code":"1968-array-with-elements-not-equal-to-average-of-neighbors", - "c":true, - "cpp":true, - "kotlin":true, - "python":true, - "javascript":true - }, - { - "problem":"Boats to Save People", - "pattern":"Two Pointers", - "link":"boats-to-save-people/", - "video":"XbaxWuHIWUs", - "difficulty":"Medium", - "code":"0881-boats-to-save-people", - "c":true, - "cpp":true, - "typescript":true, - "javascript":true, - "python":true, - "kotlin":true, - "java":true, - "swift":true - }, - { - "neetcode150":true, - "problem":"Trapping Rain Water", - "pattern":"Two Pointers", - "link":"trapping-rain-water/", - "video":"ZI2z5pq0TqA", - "difficulty":"Hard", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0042-trapping-rain-water", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Best Time to Buy And Sell Stock", - "pattern":"Sliding Window", - "link":"best-time-to-buy-and-sell-stock/", - "video":"1pkOgXD63yU", - "difficulty":"Easy", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0121-best-time-to-buy-and-sell-stock", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true, - "scala":true - }, - { - "problem":"Contains Duplicate II", - "pattern":"Sliding Window", - "link":"contains-duplicate-ii/", - "video":"ypn0aZ0nrL4", - "difficulty":"Easy", - "python":true, - "code":"0219-contains-duplicate-ii", - "cpp":true, - "java":true, - "javascript":true, - "kotlin":true, - "rust":true - }, - { - "problem":"Number of Sub Arrays of Size K and Avg Greater than or Equal to Threshold", - "pattern":"Sliding Window", - "link":"number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/", - "video":"D8B4tKxMTnY", - "difficulty":"Medium", - "python":true, - "code":"1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold", - "cpp":true, - "javascript":true, - "kotlin":true, - "java":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Longest Substring Without Repeating Characters", - "pattern":"Sliding Window", - "link":"longest-substring-without-repeating-characters/", - "video":"wiGpQwVHdE0", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0003-longest-substring-without-repeating-characters", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true, - "scala":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Longest Repeating Character Replacement", - "pattern":"Sliding Window", - "link":"longest-repeating-character-replacement/", - "video":"gqXU1UyA8pk", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0424-longest-repeating-character-replacement", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "kotlin":true, - "rust":true, - "swift":true - }, - { - "neetcode150":true, - "problem":"Permutation In String", - "pattern":"Sliding Window", - "link":"permutation-in-string/", - "video":"UbyhOgBN834", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0567-permutation-in-string", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "kotlin":true, - "rust":true - }, - { - "problem":"Frequency of The Most Frequent Element", - "pattern":"Sliding Window", - "link":"frequency-of-the-most-frequent-element/", - "video":"vgBrQ0NM5vE", - "difficulty":"Medium", - "code":"1838-frequency-of-the-most-frequent-element", - "csharp":true, - "javascript":true, - "typescript":true, - "go":true, - "rust":true, - "c":true, - "cpp":true, - "kotlin":true, - "java":true, - "python":true - }, - { - "problem":"Fruits into Basket", - "pattern":"Sliding Window", - "link":"fruit-into-baskets/", - "video":"yYtaV0G3mWQ", - "difficulty":"Medium", - "code":"0904-fruit-into-baskets", - "javascript":true, - "typescript":true, - "go":true, - "kotlin":true, - "rust":true, - "python":true - }, - { - "problem":"Maximum Number of Vowels in a Substring of Given Length", - "pattern":"Sliding Window", - "link":"maximum-number-of-vowels-in-a-substring-of-given-length/", - "video":"kEfPSzgL-Ss", - "difficulty":"Medium", - "code":"1456-maximum-number-of-vowels-in-a-substring-of-given-length", - "kotlin":true, - "cpp":true, - "java":true, - "python":true - }, - { - "problem":"Minimum Number of Flips to Make The Binary String Alternating", - "pattern":"Sliding Window", - "link":"minimum-number-of-flips-to-make-the-binary-string-alternating/", - "video":"MOeuK6gaC2A", - "difficulty":"Medium", - "code":"1888-minimum-number-of-flips-to-make-the-binary-string-alternating", - "javascript":true, - "typescript":true, - "kotlin":true, - "python":true - }, - { - "problem":"Minimum Size Subarray Sum", - "pattern":"Sliding Window", - "link":"minimum-size-subarray-sum/", - "video":"aYqYMIqZx5s", - "difficulty":"Medium", - "code":"0209-minimum-size-subarray-sum", - "c":true, - "cpp":true, - "javascript":true, - "go":true, - "java":true, - "kotlin":true, - "python":true - }, - { - "problem":"Find K Closest Elements", - "pattern":"Sliding Window", - "link":"find-k-closest-elements/", - "video":"o-YDQzHoaKM", - "difficulty":"Medium", - "code":"0658-find-k-closest-elements", - "python":true, - "typescript":true, - "javascript":true, - "kotlin":true - }, - { - "problem":"Minimum Operations to Reduce X to Zero", - "pattern":"Sliding Window", - "link":"minimum-operations-to-reduce-x-to-zero/", - "video":"xumn16n7njs", - "difficulty":"Medium", - "code":"1658-minimum-operations-to-reduce-x-to-zero", - "java":true, - "kotlin":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Minimum Window Substring", - "pattern":"Sliding Window", - "link":"minimum-window-substring/", - "video":"jSto0O4AJbM", - "difficulty":"Hard", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0076-minimum-window-substring", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "kotlin":true, - "rust":true, - "ruby":true, - "swift":true - }, - { - "neetcode150":true, - "problem":"Sliding Window Maximum", - "pattern":"Sliding Window", - "link":"sliding-window-maximum/", - "video":"DfljaUwZsOk", - "difficulty":"Hard", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0239-sliding-window-maximum", - "csharp":true, - "go":true, - "kotlin":true, - "typescript":true, - "ruby":true, - "c":true, - "rust":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Valid Parentheses", - "pattern":"Stack", - "link":"valid-parentheses/", - "video":"WTzjTskDFMg", - "difficulty":"Easy", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0020-valid-parentheses", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true, - "dart":true - }, - { - "problem":"Baseball Game", - "pattern":"Stack", - "link":"baseball-game/", - "video":"Id_tqGdsZQI", - "difficulty":"Easy", - "code":"0682-baseball-game", - "c":true, - "cpp":true, - "python":true, - "java":true, - "typescript":true, - "go":true, - "rust":true, - "kotlin":true, - "csharp":true, - "javascript":true, - "swift":true - }, - { - "problem":"Implement Stack Using Queues", - "pattern":"Stack", - "link":"implement-stack-using-queues/", - "video":"rW4vm0-DLYc", - "difficulty":"Easy", - "code":"0225-implement-stack-using-queues", - "cpp":true, - "go":true, - "c":true, - "java":true, - "python":true, - "javascript":true, - "typescript":true, - "rust":true, - "kotlin":true - }, - { - "neetcode150":true, - "problem":"Min Stack", - "pattern":"Stack", - "link":"min-stack/", - "video":"qkLl7nAwDPo", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0155-min-stack", - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "kotlin":true, - "c":true, - "rust":true, - "swift":true - }, - { - "neetcode150":true, - "problem":"Evaluate Reverse Polish Notation", - "pattern":"Stack", - "link":"evaluate-reverse-polish-notation/", - "video":"iu0082c4HDE", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0150-evaluate-reverse-polish-notation", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true - }, - { - "problem":"Removing Stars From a String", - "pattern":"Stack", - "link":"removing-stars-from-a-string/", - "video":"pRyFZIaKegA", - "difficulty":"Medium", - "code":"2390-removing-stars-from-a-string", - "kotlin":true, - "java":true, - "python":true, - "javascript":true - }, - { - "problem":"Validate Stack Sequences", - "pattern":"Stack", - "link":"validate-stack-sequences/", - "video":"mzua0r94kb8", - "difficulty":"Medium", - "code":"0946-validate-stack-sequences", - "kotlin":true, - "python":true - }, - { - "neetcode150":true, - "problem":"Generate Parentheses", - "pattern":"Stack", - "link":"generate-parentheses/", - "video":"s9fokUqJ76A", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0022-generate-parentheses", - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "kotlin":true, - "c":true, - "rust":true, - "swift":true - }, - { - "problem":"Asteroid Collision", - "pattern":"Stack", - "link":"asteroid-collision/", - "video":"LN7KjRszjk4", - "difficulty":"Medium", - "code":"0735-asteroid-collision", - "java":true, - "javascript":true, - "typescript":true, - "rust":true, - "python":true, - "cpp":true, - "kotlin":true - }, - { - "neetcode150":true, - "problem":"Daily Temperatures", - "pattern":"Stack", - "link":"daily-temperatures/", - "video":"cTBiBSnjO3c", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0739-daily-temperatures", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true - }, - { - "problem":"Online Stock Span", - "pattern":"Stack", - "link":"online-stock-span/", - "video":"slYh0ZNEqSw", - "difficulty":"Medium", - "code":"0901-online-stock-span", - "python":true, - "typescript":true, - "rust":true, - "cpp":true, - "java":true, - "javascript":true, - "kotlin":true - }, - { - "neetcode150":true, - "problem":"Car Fleet", - "pattern":"Stack", - "link":"car-fleet/", - "video":"Pr6T-3yB9RM", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0853-car-fleet", - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "kotlin":true, - "rust":true, - "c":true - }, - { - "problem":"Simplify Path", - "pattern":"Stack", - "link":"simplify-path/", - "video":"qYlHrAKJfyA", - "difficulty":"Medium", - "code":"0071-simplify-path", - "python":true, - "typescript":true, - "rust":true, - "java":true, - "kotlin":true, - "javascript":true - }, - { - "problem":"Decode String", - "pattern":"Stack", - "link":"decode-string/", - "video":"qB0zZpBJlh8", - "difficulty":"Medium", - "code":"0394-decode-string", - "python":true, - "typescript":true, - "rust":true, - "scala":true, - "java":true, - "kotlin":true - }, - { - "problem":"Remove K Digits", - "pattern":"Stack", - "link":"remove-k-digits/", - "video":"cFabMOnJaq0", - "difficulty":"Medium", - "code":"0402-remove-k-digits", - "cpp":true, - "javascript":true, - "typescript":true, - "rust":true, - "kotlin":true, - "java":true, - "python":true - }, - { - "problem":"Remove All Adjacent Duplicates In String II", - "pattern":"Stack", - "link":"remove-all-adjacent-duplicates-in-string-ii/", - "video":"w6LcypDgC4w", - "difficulty":"Medium", - "code":"1209-remove-all-adjacent-duplicates-in-string-ii", - "cpp":true, - "python":true, - "javascript":true, - "typescript":true, - "rust":true, - "kotlin":true - }, - { - "problem":"132 Pattern", - "pattern":"Stack", - "link":"132-pattern/", - "video":"q5ANAl8Z458", - "difficulty":"Medium", - "code":"0456-132-pattern", - "python":true, - "cpp":true, - "java":true, - "javascript":true, - "typescript":true, - "kotlin":true, - "rust":true - }, - { - "problem":"Maximum Frequency Stack", - "pattern":"Stack", - "link":"maximum-frequency-stack/", - "video":"Z6idIicFDOE", - "difficulty":"Hard", - "code":"0895-maximum-frequency-stack", - "javascript":true, - "typescript":true, - "rust":true, - "kotlin":true - }, - { - "neetcode150":true, - "problem":"Largest Rectangle In Histogram", - "pattern":"Stack", - "link":"largest-rectangle-in-histogram/", - "video":"zx5Sw9130L0", - "difficulty":"Hard", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0084-largest-rectangle-in-histogram", - "csharp":true, - "typescript":true, - "go":true, - "kotlin":true, - "rust":true, - "c":true - }, - { - "neetcode150":true, - "problem":"Binary Search", - "pattern":"Binary Search", - "link":"binary-search/", - "video":"s4DPM8ct1pI", - "difficulty":"Easy", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0704-binary-search", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true, - "dart":true - }, - { - "problem":"Search Insert Position", - "pattern":"Binary Search", - "link":"search-insert-position/", - "video":"K-RYzDZkzCI", - "difficulty":"Easy", - "code":"0035-search-insert-position", - "c":true, - "cpp":true, - "python":true, - "javascript":true, - "swift":true, - "csharp":true, - "java":true, - "go":true, - "kotlin":true, - "typescript":true, - "rust":true - }, - { - "problem":"Guess Number Higher Or Lower", - "pattern":"Binary Search", - "link":"guess-number-higher-or-lower/", - "video":"xW4QsTtaCa4", - "difficulty":"Easy", - "code":"0374-guess-number-higher-or-lower", - "c":true, - "python":true, - "cpp":true, - "java":true, - "javascript":true, - "go":true, - "swift":true, - "kotlin":true, - "rust":true - }, - { - "problem":"Arranging Coins", - "pattern":"Binary Search", - "link":"arranging-coins/", - "video":"5rHz_6s2Buw", - "difficulty":"Easy", - "code":"0441-arranging-coins", - "python":true, - "cpp":true, - "kotlin":true, - "java":true, - "javascript":true - }, - { - "problem":"Squares of a Sorted Array", - "pattern":"Binary Search", - "link":"squares-of-a-sorted-array/", - "video":"FPCZsG_AkUg", - "difficulty":"Easy", - "code":"0977-squares-of-a-sorted-array", - "cpp":true, - "python":true, - "javascript":true, - "typescript":true, - "go":true, - "kotlin":true, - "java":true, - "rust":true - }, - { - "problem":"Valid Perfect Square", - "pattern":"Binary Search", - "link":"valid-perfect-square/", - "video":"Cg_wWPHJ2Sk", - "difficulty":"Easy", - "code":"0367-valid-perfect-square", - "python":true, - "javascript":true, - "cpp":true, - "swift":true, - "java":true, - "kotlin":true - }, - { - "problem":"Sqrt(x) ", - "pattern":"Binary Search", - "link":"sqrtx/", - "video":"zdMhGxRWutQ", - "difficulty":"Easy", - "code":"0069-sqrtx", - "kotlin":true, - "c":true, - "cpp":true, - "java":true, - "python":true, - "javascript":true - }, - { - "problem":"Single Element in a Sorted Array", - "pattern":"Binary Search", - "link":"single-element-in-a-sorted-array/", - "video":"HGtqdzyUJ3k", - "difficulty":"Medium", - "code":"0540-single-element-in-a-sorted-array", - "kotlin":true, - "cpp":true, - "java":true, - "python":true, - "javascript":true, - "typescript":true - }, - { - "problem":"Capacity to Ship Packages", - "pattern":"Binary Search", - "link":"capacity-to-ship-packages-within-d-days/", - "video":"ER_oLmdc-nw", - "difficulty":"Medium", - "code":"1011-capacity-to-ship-packages-within-d-days", - "kotlin":true, - "java":true, - "python":true - }, - { - "problem":"Find Peak Element", - "pattern":"Binary Search", - "link":"find-peak-element/", - "video":"kMzJy9es7Hc", - "difficulty":"Medium", - "code":"0162-find-peak-element", - "kotlin":true, - "cpp":true, - "java":true, - "python":true, - "javascript":true - }, - { - "problem":"Successful Pairs of Spells and Potions", - "pattern":"Binary Search", - "link":"successful-pairs-of-spells-and-potions/", - "video":"OKnm5oyAhWg", - "difficulty":"Medium", - "code":"2300-successful-pairs-of-spells-and-potions", - "kotlin":true, - "cpp":true, - "python":true - }, - { - "neetcode150":true, - "problem":"Search a 2D Matrix", - "pattern":"Binary Search", - "link":"search-a-2d-matrix/", - "video":"Ber2pi2C0j0", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0074-search-a-2d-matrix", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "problem":"Koko Eating Bananas", - "pattern":"Binary Search", - "link":"koko-eating-bananas/", - "video":"U2SozAs9RzA", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0875-koko-eating-bananas", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true - }, - { - "problem":"Minimize the Maximum Difference of Pairs", - "pattern":"Binary Search", - "link":"minimize-the-maximum-difference-of-pairs/", - "video":"lf1Pxg7IrzQ", - "difficulty":"Medium", - "code":"2616-minimize-the-maximum-difference-of-pairs", - "java":true, - "kotlin":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Find Minimum In Rotated Sorted Array", - "pattern":"Binary Search", - "link":"find-minimum-in-rotated-sorted-array/", - "video":"nIVW4P8b1VA", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0153-find-minimum-in-rotated-sorted-array", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "swift":true, - "kotlin":true, - "rust":true, - "scala":true, - "ruby":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Search In Rotated Sorted Array", - "pattern":"Binary Search", - "link":"search-in-rotated-sorted-array/", - "video":"U8XENwh8Oy8", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0033-search-in-rotated-sorted-array", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "swift":true, - "kotlin":true, - "rust":true, - "scala":true - }, - { - "problem":"Search In Rotated Sorted Array II", - "pattern":"Binary Search", - "link":"search-in-rotated-sorted-array-ii/", - "video":"oUnF7o88_Xc", - "difficulty":"Medium", - "code":"0081-search-in-rotated-sorted-array-ii", - "java":true, - "kotlin":true - }, - { - "neetcode150":true, - "problem":"Time Based Key Value Store", - "pattern":"Binary Search", - "link":"time-based-key-value-store/", - "video":"fu2cD_6E8Hw", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0981-time-based-key-value-store", - "csharp":true, - "typescript":true, - "go":true, - "kotlin":true, - "ruby":true, - "rust":true, - "c":true - }, - { - "problem":"Find First And Last Position of Element In Sorted Array", - "pattern":"Binary Search", - "link":"find-first-and-last-position-of-element-in-sorted-array/", - "video":"4sQL7R5ySUU", - "difficulty":"Medium", - "code":"0034-find-first-and-last-position-of-element-in-sorted-array", - "csharp":true, - "python":true, - "kotlin":true, - "cpp":true, - "java":true, - "swift":true, - "javascript":true - }, - { - "problem":"Maximum Number of Removable Characters", - "pattern":"Binary Search", - "link":"maximum-number-of-removable-characters/", - "video":"NMP3nRPyX5g", - "difficulty":"Medium", - "code":"1898-maximum-number-of-removable-characters", - "javascript":true, - "kotlin":true - }, - { - "problem":"Populating Next Right Pointers In Each Node", - "pattern":"Binary Search", - "link":"populating-next-right-pointers-in-each-node/", - "video":"U4hFQCa1Cq0", - "difficulty":"Medium", - "code":"0116-populating-next-right-pointers-in-each-node", - "go":true, - "cpp":true, - "javascript":true, - "kotlin":true - }, - { - "problem":"Search Suggestions System", - "pattern":"Binary Search", - "link":"search-suggestions-system/", - "video":"D4T2N0yAr20", - "difficulty":"Medium", - "code":"1268-search-suggestions-system", - "java":true, - "javascript":true, - "kotlin":true - }, - { - "problem":"Split Array Largest Sum", - "pattern":"Binary Search", - "link":"split-array-largest-sum/", - "video":"YUF3_eBdzsk", - "difficulty":"Hard", - "code":"0410-split-array-largest-sum", - "python":true, - "javascript":true, - "kotlin":true - }, - { - "neetcode150":true, - "problem":"Median of Two Sorted Arrays", - "pattern":"Binary Search", - "link":"median-of-two-sorted-arrays/", - "video":"q6IEA26hvXc", - "difficulty":"Hard", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0004-median-of-two-sorted-arrays", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Reverse Linked List", - "pattern":"Linked List", - "link":"reverse-linked-list/", - "video":"G0_I-ZF0S38", - "difficulty":"Easy", - "python":true, - "cpp":true, - "javascript":true, - "java":true, - "code":"0206-reverse-linked-list", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "scala":true, - "rust":true, - "dart":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Merge Two Sorted Lists", - "pattern":"Linked List", - "link":"merge-two-sorted-lists/", - "video":"XIdigk956u0", - "difficulty":"Easy", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0021-merge-two-sorted-lists", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "scala":true, - "dart":true, - "rust":true - }, - { - "problem":"Palindrome Linked List", - "pattern":"Linked List", - "link":"palindrome-linked-list/", - "video":"yOzXms1J6Nk", - "difficulty":"Easy", - "code":"0234-palindrome-linked-list", - "cpp":true, - "javascript":true, - "python":true, - "go":true, - "java":true, - "kotlin":true, - "c":true - }, - { - "problem":"Remove Linked List Elements", - "pattern":"Linked List", - "link":"remove-linked-list-elements/", - "video":"JI71sxtHTng", - "difficulty":"Easy", - "code":"0203-remove-linked-list-elements", - "javascript":true, - "typescript":true, - "go":true, - "cpp":true, - "java":true, - "python":true, - "kotlin":true - }, - { - "problem":"Remove Duplicates From Sorted List", - "pattern":"Linked List", - "link":"remove-duplicates-from-sorted-list/", - "video":"p10f-VpO4nE", - "difficulty":"Easy", - "code":"0083-remove-duplicates-from-sorted-list", - "cpp":true, - "python":true, - "javascript":true, - "go":true, - "java":true, - "kotlin":true, - "c":true - }, - { - "problem":"Middle of the Linked List", - "pattern":"Linked List", - "link":"middle-of-the-linked-list/", - "video":"A2_ldqM4QcY", - "difficulty":"Easy", - "python":true, - "code":"0876-middle-of-the-linked-list", - "c":true, - "cpp":true, - "csharp":true, - "java":true, - "javascript":true, - "typescript":true, - "go":true, - "kotlin":true, - "rust":true, - "swift":true - }, - { - "problem":"Intersection of Two Linked Lists", - "pattern":"Linked List", - "link":"intersection-of-two-linked-lists/", - "video":"D0X0BONOQhI", - "difficulty":"Easy", - "code":"0160-intersection-of-two-linked-lists", - "python":true, - "javascript":true, - "java":true, - "go":true, - "kotlin":true, - "c":true, - "cpp":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Reorder List", - "pattern":"Linked List", - "link":"reorder-list/", - "video":"S5bfdUTrKLM", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0143-reorder-list", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "kotlin":true - }, - { - "problem":"Maximum Twin Sum Of A Linked List", - "pattern":"Linked List", - "link":"maximum-twin-sum-of-a-linked-list/", - "video":"doj95MelfSA", - "difficulty":"Medium", - "code":"2130-maximum-twin-sum-of-a-linked-list", - "python":true, - "java":true, - "kotlin":true, - "cpp":true, - "javascript":true, - "go":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Remove Nth Node From End of List", - "pattern":"Linked List", - "link":"remove-nth-node-from-end-of-list/", - "video":"XVuQxVej6y8", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0019-remove-nth-node-from-end-of-list", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "swift":true, - "kotlin":true, - "rust":true - }, - { - "problem":"Swapping Nodes in a Linked List", - "pattern":"Linked List", - "link":"swapping-nodes-in-a-linked-list/", - "video":"4LsrgMyQIjQ", - "difficulty":"Medium", - "code":"1721-swapping-nodes-in-a-linked-list", - "kotlin":true, - "cpp":true, - "java":true, - "python":true, - "go":true - }, - { - "problem":"LFU Cache", - "pattern":"Linked List", - "link":"lfu-cache/", - "video":"bLEIHn-DgoA", - "difficulty":"Hard", - "code":"0460-lfu-cache", - "javascript":true, - "kotlin":true - }, - { - "neetcode150":true, - "problem":"Copy List With Random Pointer", - "pattern":"Linked List", - "link":"copy-list-with-random-pointer/", - "video":"5Y2EiZST97Y", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0138-copy-list-with-random-pointer", - "c":true, - "csharp":true, - "typescript":true, - "ruby":true, - "swift":true, - "kotlin":true, - "go":true - }, - { - "problem":"Design Linked List", - "pattern":"Linked List", - "link":"design-linked-list/", - "video":"Wf4QhpdVFQo", - "difficulty":"Medium", - "python":true, - "code":"0707-design-linked-list", - "go":true, - "kotlin":true, - "c":true, - "java":true - }, - { - "problem":"Design Browser History", - "pattern":"Linked List", - "link":"design-browser-history/", - "video":"i1G-kKnBu8k", - "difficulty":"Medium", - "python":true, - "code":"1472-design-browser-history", - "javascript":true, - "typescript":true, - "go":true, - "rust":true, - "java":true, - "kotlin":true - }, - { - "neetcode150":true, - "problem":"Add Two Numbers", - "pattern":"Linked List", - "link":"add-two-numbers/", - "video":"wgFPrzTjm7s", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0002-add-two-numbers", - "c":true, - "csharp":true, - "typescript":true, - "ruby":true, - "swift":true, - "kotlin":true, - "scala":true, - "go":true, - "rust":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Linked List Cycle", - "pattern":"Linked List", - "link":"linked-list-cycle/", - "video":"gBTe7lFR3vc", - "difficulty":"Easy", - "python":true, - "cpp":true, - "javascript":true, - "java":true, - "code":"0141-linked-list-cycle", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "scala":true - }, - { - "neetcode150":true, - "problem":"Find The Duplicate Number", - "pattern":"Linked List", - "link":"find-the-duplicate-number/", - "video":"wjYnzkAhcNk", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0287-find-the-duplicate-number", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true - }, - { - "problem":"Swap Nodes In Pairs", - "pattern":"Linked List", - "link":"swap-nodes-in-pairs/", - "video":"o811TZLAWOo", - "difficulty":"Medium", - "code":"0024-swap-nodes-in-pairs", - "python":true, - "go":true, - "java":true, - "kotlin":true, - "c":true, - "cpp":true - }, - { - "problem":"Sort List", - "pattern":"Linked List", - "link":"sort-list/", - "video":"TGveA1oFhrc", - "difficulty":"Medium", - "code":"0148-sort-list", - "java":true, - "python":true, - "c":true, - "cpp":true, - "kotlin":true - }, - { - "problem":"Partition List", - "pattern":"Linked List", - "link":"partition-list/", - "video":"KT1iUciJr4g", - "difficulty":"Medium", - "code":"0086-partition-list", - "python":true, - "java":true, - "kotlin":true - }, - { - "problem":"Rotate List", - "pattern":"Linked List", - "link":"rotate-list/", - "video":"UcGtPs2LE_c", - "difficulty":"Medium", - "code":"0061-rotate-list", - "python":true, - "cpp":true, - "java":true, - "kotlin":true - }, - { - "problem":"Reverse Linked List II", - "pattern":"Linked List", - "link":"reverse-linked-list-ii/", - "video":"RF_M9tX4Eag", - "difficulty":"Medium", - "code":"0092-reverse-linked-list-ii", - "python":true, - "javascript":true, - "cpp":true, - "java":true, - "kotlin":true - }, - { - "problem":"Design Circular Queue", - "pattern":"Linked List", - "link":"design-circular-queue/", - "video":"aBbsfn863oA", - "difficulty":"Medium", - "code":"0622-design-circular-queue", - "python":true, - "go":true, - "kotlin":true, - "java":true - }, - { - "problem":"Insertion Sort List", - "pattern":"Linked List", - "link":"insertion-sort-list/", - "video":"Kk6mXAzqX3Y", - "difficulty":"Medium", - "code":"0147-insertion-sort-list", - "python":true, - "cpp":true, - "kotlin":true - }, - { - "problem":"Split Linked List in Parts", - "pattern":"Linked List", - "link":"split-linked-list-in-parts/", - "video":"-OTlqdrxrVI", - "difficulty":"Medium", - "code":"0725-split-linked-list-in-parts", - "java":true, - "kotlin":true - }, - { - "neetcode150":true, - "problem":"LRU Cache", - "pattern":"Linked List", - "link":"lru-cache/", - "video":"7ABFKPK2hD4", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0146-lru-cache", - "c":true, - "csharp":true, - "ruby":true, - "kotlin":true, - "go":true, - "typescript":true, - "swift":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Merge K Sorted Lists", - "pattern":"Linked List", - "link":"merge-k-sorted-lists/", - "video":"q5a5OiGbT6Q", - "difficulty":"Hard", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0023-merge-k-sorted-lists", - "c":true, - "csharp":true, - "typescript":true, - "kotlin":true, - "go":true, - "swift":true, - "rust":true - }, - { - "neetcode150":true, - "problem":"Reverse Nodes In K Group", - "pattern":"Linked List", - "link":"reverse-nodes-in-k-group/", - "video":"1UOPsfP85V4", - "difficulty":"Hard", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0025-reverse-nodes-in-k-group", - "c":true, - "csharp":true, - "typescript":true, - "kotlin":true, - "go":true, - "swift":true, - "rust":true - }, - { - "problem":"Binary Tree Inorder Traversal", - "pattern":"Trees", - "link":"binary-tree-inorder-traversal/", - "video":"g_S5WuasWUE", - "difficulty":"Easy", - "code":"0094-binary-tree-inorder-traversal", - "c":true, - "python":true, - "javascript":true, - "typescript":true, - "ruby":true, - "csharp":true, - "java":true, - "go":true, - "swift":true, - "kotlin":true, - "rust":true, - "cpp":true - }, - { - "problem":"Binary Tree Preorder Traversal", - "pattern":"Trees", - "link":"binary-tree-preorder-traversal/", - "video":"afTpieEZXck", - "difficulty":"Easy", - "code":"0144-binary-tree-preorder-traversal", - "python":true, - "cpp":true, - "typescript":true, - "kotlin":true - }, - { - "problem":"Binary Tree Postorder Traversal", - "pattern":"Trees", - "link":"binary-tree-postorder-traversal/", - "video":"QhszUQhGGlA", - "difficulty":"Easy", - "code":"0145-binary-tree-postorder-traversal", - "python":true, - "java":true, - "cpp":true, - "typescript":true, - "kotlin":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Invert Binary Tree", - "pattern":"Trees", - "link":"invert-binary-tree/", - "video":"OnSn2XEQ4MY", - "difficulty":"Easy", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0226-invert-binary-tree", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Maximum Depth of Binary Tree", - "pattern":"Trees", - "link":"maximum-depth-of-binary-tree/", - "video":"hTM3phVI6YQ", - "difficulty":"Easy", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0104-maximum-depth-of-binary-tree", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "problem":"Diameter of Binary Tree", - "pattern":"Trees", - "link":"diameter-of-binary-tree/", - "video":"bkxqA8Rfv04", - "difficulty":"Easy", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0543-diameter-of-binary-tree", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "problem":"Balanced Binary Tree", - "pattern":"Trees", - "link":"balanced-binary-tree/", - "video":"QfJsau0ItOY", - "difficulty":"Easy", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0110-balanced-binary-tree", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Same Tree", - "pattern":"Trees", - "link":"same-tree/", - "video":"vRbbcKXCxOw", - "difficulty":"Easy", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0100-same-tree", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Subtree of Another Tree", - "pattern":"Trees", - "link":"subtree-of-another-tree/", - "video":"E36O5SWp-LE", - "difficulty":"Easy", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0572-subtree-of-another-tree", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "scala":true, - "rust":true - }, - { - "problem":"Convert Sorted Array to Binary Search Tree", - "pattern":"Trees", - "link":"convert-sorted-array-to-binary-search-tree/", - "video":"0K0uCMYq5ng", - "difficulty":"Easy", - "code":"0108-convert-sorted-array-to-binary-search-tree", - "c":true, - "javascript":true, - "go":true, - "kotlin":true, - "java":true, - "python":true - }, - { - "problem":"Merge Two Binary Trees", - "pattern":"Trees", - "link":"merge-two-binary-trees/", - "video":"QHH6rIK3dDQ", - "difficulty":"Easy", - "code":"0617-merge-two-binary-trees", - "c":true, - "java":true, - "python":true, - "javascript":true, - "go":true, - "dart":true, - "kotlin":true, - "cpp":true - }, - { - "problem":"Path Sum", - "pattern":"Trees", - "link":"path-sum/", - "video":"LSKQyOz_P8I", - "difficulty":"Easy", - "code":"0112-path-sum", - "go":true, - "c":true, - "csharp":true, - "javascript":true, - "swift":true, - "java":true, - "python":true, - "kotlin":true - }, - { - "problem":"Construct String From Binary Tree", - "pattern":"Trees", - "link":"construct-string-from-binary-tree/", - "video":"b1WpYxnuebQ", - "difficulty":"Easy", - "code":"0606-construct-string-from-binary-tree", - "java":true, - "python":true, - "kotlin":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Lowest Common Ancestor of a Binary Search Tree", - "pattern":"Trees", - "link":"lowest-common-ancestor-of-a-binary-search-tree/", - "video":"gs2LMfuOR9k", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0235-lowest-common-ancestor-of-a-binary-search-tree", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "scala":true, - "rust":true - }, - { - "problem":"Insert into a Binary Search Tree", - "pattern":"Trees", - "link":"insert-into-a-binary-search-tree/", - "video":"Cpg8f79luEA", - "difficulty":"Medium", - "python":true, - "code":"0701-insert-into-a-binary-search-tree", - "kotlin":true, - "cpp":true, - "csharp":true, - "java":true, - "typescript":true - }, - { - "problem":"Delete Node in a BST", - "pattern":"Trees", - "link":"delete-node-in-a-bst/", - "video":"LFzAoJJt92M", - "difficulty":"Medium", - "python":true, - "code":"0450-delete-node-in-a-bst", - "kotlin":true, - "cpp":true, - "java":true, - "typescript":true, - "rust":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Binary Tree Level Order Traversal", - "pattern":"Trees", - "link":"binary-tree-level-order-traversal/", - "video":"6ZnyEApgFYg", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0102-binary-tree-level-order-traversal", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "problem":"Binary Tree Right Side View", - "pattern":"Trees", - "link":"binary-tree-right-side-view/", - "video":"d4zLyf32e3I", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0199-binary-tree-right-side-view", - "c":true, - "csharp":true, - "typescript":true, - "swift":true, - "kotlin":true, - "go":true, - "rust":true - }, - { - "problem":"Minimum Distance between BST Nodes", - "pattern":"Trees", - "link":"minimum-distance-between-bst-nodes/", - "video":"joxx4hTYwcw", - "difficulty":"Easy", - "code":"0783-minimum-distance-between-bst-nodes", - "kotlin":true, - "python":true - }, - { - "problem":"Symmetric Tree ", - "pattern":"Trees", - "link":"symmetric-tree/", - "video":"Mao9uzxwvmc", - "difficulty":"Easy", - "code":"0101-symmetric-tree", - "kotlin":true, - "python":true - }, - { - "problem":"Minimum Time to Collect All Apples in a Tree", - "pattern":"Trees", - "link":"minimum-time-to-collect-all-apples-in-a-tree/", - "video":"Xdt5Z583auM", - "difficulty":"Medium", - "code":"1443-minimum-time-to-collect-all-apples-in-a-tree", - "rust":true, - "kotlin":true - }, - { - "problem":"Binary Tree Zigzag Level Order Traversal", - "pattern":"Trees", - "link":"binary-tree-zigzag-level-order-traversal/", - "video":"igbboQbiwqw", - "difficulty":"Medium", - "code":"0103-binary-tree-zigzag-level-order-traversal", - "kotlin":true, - "cpp":true, - "python":true - }, - { - "problem":"Construct Quad Tree", - "pattern":"Trees", - "link":"construct-quad-tree/", - "video":"UQ-1sBMV0v4", - "difficulty":"Medium", - "code":"0427-construct-quad-tree", - "kotlin":true - }, - { - "problem":"Find Duplicate Subtrees", - "pattern":"Trees", - "link":"find-duplicate-subtrees/", - "video":"kn0Z5_qPPzY", - "difficulty":"Medium", - "code":"0652-find-duplicate-subtrees", - "kotlin":true - }, - { - "problem":"Check Completeness of a Binary Tree", - "pattern":"Trees", - "link":"check-completeness-of-a-binary-tree/", - "video":"olbiZ-EOSig", - "difficulty":"Medium", - "code":"0958-check-completeness-of-a-binary-tree", - "kotlin":true, - "cpp":true - }, - { - "problem":"Construct Binary Tree from Inorder and Postorder Traversal", - "pattern":"Trees", - "link":"construct-binary-tree-from-inorder-and-postorder-traversal/", - "video":"vm63HuIU7kw", - "difficulty":"Medium", - "code":"0106-construct-binary-tree-from-inorder-and-postorder-traversal", - "java":true, - "kotlin":true - }, - { - "problem":"Maximum Width of Binary Tree ", - "pattern":"Trees", - "link":"maximum-width-of-binary-tree/", - "video":"FPzLE2L7uHs", - "difficulty":"Medium", - "code":"0662-maximum-width-of-binary-tree", - "java":true, - "kotlin":true - }, - { - "problem":"Time Needed to Inform All Employees ", - "pattern":"Trees", - "link":"time-needed-to-inform-all-employees/", - "video":"zdBYi0p4L5Q", - "difficulty":"Medium", - "code":"1376-time-needed-to-inform-all-employees", - "kotlin":true - }, - { - "neetcode150":true, - "problem":"Count Good Nodes In Binary Tree", - "pattern":"Trees", - "link":"count-good-nodes-in-binary-tree/", - "video":"7cp5imvDzl4", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"1448-count-good-nodes-in-binary-tree", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "swift":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Validate Binary Search Tree", - "pattern":"Trees", - "link":"validate-binary-search-tree/", - "video":"s6ATEkipzow", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0098-validate-binary-search-tree", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "swift":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Kth Smallest Element In a Bst", - "pattern":"Trees", - "link":"kth-smallest-element-in-a-bst/", - "video":"5LUXSvjmGCw", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0230-kth-smallest-element-in-a-bst", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "swift":true, - "kotlin":true, - "scala":true, - "rust":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Construct Binary Tree From Preorder And Inorder Traversal", - "pattern":"Trees", - "link":"construct-binary-tree-from-preorder-and-inorder-traversal/", - "video":"ihj4IQGZ2zc", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0105-construct-binary-tree-from-preorder-and-inorder-traversal", - "c":true, - "csharp":true, - "typescript":true, - "kotlin":true, - "go":true - }, - { - "problem":"Unique Binary Search Trees", - "pattern":"Trees", - "link":"unique-binary-search-trees/", - "video":"Ox0TenN3Zpg", - "difficulty":"Medium", - "code":"0096-unique-binary-search-trees", - "c":true, - "java":true, - "kotlin":true - }, - { - "problem":"Unique Binary Search Trees II", - "pattern":"Trees", - "link":"unique-binary-search-trees-ii/", - "video":"m907FlQa2Yc", - "difficulty":"Medium", - "code":"0095-unique-binary-search-trees-ii", - "kotlin":true - }, - { - "problem":"Sum Root to Leaf Numbers", - "pattern":"Trees", - "link":"sum-root-to-leaf-numbers/", - "video":"Jk16lZGFWxE", - "difficulty":"Medium", - "code":"0129-sum-root-to-leaf-numbers", - "c":true, - "java":true, - "cpp":true, - "kotlin":true - }, - { - "problem":"House Robber III", - "pattern":"Trees", - "link":"house-robber-iii/", - "video":"nHR8ytpzz7c", - "difficulty":"Medium", - "code":"0337-house-robber-iii", - "java":true, - "kotlin":true - }, - { - "problem":"Flip Equivalent Binary Trees", - "pattern":"Trees", - "link":"flip-equivalent-binary-trees/", - "video":"izRDc1il9Pk", - "difficulty":"Medium", - "code":"0951-flip-equivalent-binary-trees", - "java":true, - "kotlin":true - }, - { - "problem":"Operations On Tree", - "pattern":"Trees", - "link":"operations-on-tree/", - "video":"qK4PtjrVD0U", - "difficulty":"Medium", - "code":"1993-operations-on-tree", - "kotlin":true - }, - { - "problem":"All Possible Full Binary Trees", - "pattern":"Trees", - "link":"all-possible-full-binary-trees/", - "video":"nZtrZPTTCAo", - "difficulty":"Medium", - "code":"0894-all-possible-full-binary-trees", - "python":true, - "java":true, - "kotlin":true - }, - { - "problem":"Find Bottom Left Tree Value", - "pattern":"Trees", - "link":"find-bottom-left-tree-value/", - "video":"u_by_cTsNJA", - "difficulty":"Medium", - "code":"0513-find-bottom-left-tree-value", - "java":true, - "kotlin":true - }, - { - "problem":"Trim a Binary Search Tree", - "pattern":"Trees", - "link":"trim-a-binary-search-tree/", - "video":"jwt5mTjEXGc", - "difficulty":"Medium", - "code":"0669-trim-a-binary-search-tree", - "python":true, - "javascript":true, - "typescript":true, - "go":true, - "java":true, - "kotlin":true - }, - { - "problem":"Binary Search Tree Iterator", - "pattern":"Trees", - "link":"binary-search-tree-iterator/", - "video":"RXy5RzGF5wo", - "difficulty":"Medium", - "code":"0173-binary-search-tree-iterator", - "java":true, - "javascript":true, - "kotlin":true - }, - { - "problem":"Convert Bst to Greater Tree", - "pattern":"Trees", - "link":"convert-bst-to-greater-tree/", - "video":"7vVEJwVvAlI", - "difficulty":"Medium", - "code":"0538-convert-bst-to-greater-tree", - "cpp":true, - "kotlin":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Binary Tree Maximum Path Sum", - "pattern":"Trees", - "link":"binary-tree-maximum-path-sum/", - "video":"Hr5cWUld4vU", - "difficulty":"Hard", - "code":"0124-binary-tree-maximum-path-sum", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "swift":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Serialize And Deserialize Binary Tree", - "pattern":"Trees", - "link":"serialize-and-deserialize-binary-tree/", - "video":"u4JAi2JJhI8", - "difficulty":"Hard", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0297-serialize-and-deserialize-binary-tree", - "c":true, - "csharp":true, - "kotlin":true, - "go":true, - "typescript":true, - "swift":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Implement Trie Prefix Tree", - "pattern":"Tries", - "link":"implement-trie-prefix-tree/", - "video":"oobqoCJlHA0", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0208-implement-trie-prefix-tree", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true, - "scala":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Design Add And Search Words Data Structure", - "pattern":"Tries", - "link":"design-add-and-search-words-data-structure/", - "video":"BTf05gs_8iU", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0211-design-add-and-search-words-data-structure", - "csharp":true, - "typescript":true, - "ruby":true, - "kotlin":true, - "rust":true, - "go":true, - "c":true, - "scala":true - }, - { - "problem":"Extra Characters in a String", - "pattern":"Tries", - "link":"extra-characters-in-a-string/", - "video":"ONstwO1cD7c", - "difficulty":"Medium", - "code":"2707-extra-characters-in-a-string", - "cpp":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Word Search II", - "pattern":"Tries", - "link":"word-search-ii/", - "video":"asbcE9mZz_U", - "difficulty":"Hard", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0212-word-search-ii", - "csharp":true, - "swift":true, - "kotlin":true, - "rust":true, - "go":true, - "c":true - }, - { - "neetcode150":true, - "problem":"Kth Largest Element In a Stream", - "pattern":"Heap / Priority Queue", - "link":"kth-largest-element-in-a-stream/", - "video":"hOjcdrqMoQ8", - "difficulty":"Easy", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0703-kth-largest-element-in-a-stream", - "c":true, - "csharp":true, - "ruby":true, - "swift":true, - "go":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "problem":"Last Stone Weight", - "pattern":"Heap / Priority Queue", - "link":"last-stone-weight/", - "video":"B-QCq79-Vfw", - "difficulty":"Easy", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"1046-last-stone-weight", - "csharp":true, - "typescript":true, - "ruby":true, - "kotlin":true, - "go":true, - "rust":true, - "c":true - }, - { - "neetcode150":true, - "problem":"K Closest Points to Origin", - "pattern":"Heap / Priority Queue", - "link":"k-closest-points-to-origin/", - "video":"rI2EBUEMfTk", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0973-k-closest-points-to-origin", - "csharp":true, - "kotlin":true, - "go":true, - "rust":true, - "c":true - }, - { - "neetcode150":true, - "problem":"Kth Largest Element In An Array", - "pattern":"Heap / Priority Queue", - "link":"kth-largest-element-in-an-array/", - "video":"XEmy13g1Qxc", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0215-kth-largest-element-in-an-array", - "csharp":true, - "typescript":true, - "kotlin":true, - "go":true, - "scala":true, - "c":true, - "rust":true - }, - { - "neetcode150":true, - "problem":"Task Scheduler", - "pattern":"Heap / Priority Queue", - "link":"task-scheduler/", - "video":"s8p8ukTyA2I", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0621-task-scheduler", - "csharp":true, - "typescript":true, - "kotlin":true, - "rust":true, - "c":true - }, - { - "neetcode150":true, - "problem":"Design Twitter", - "pattern":"Heap / Priority Queue", - "link":"design-twitter/", - "video":"pNichitDD2E", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0355-design-twitter", - "csharp":true, - "go":true, - "kotlin":true - }, - { - "problem":"Minimize Deviation in Array", - "pattern":"Heap / Priority Queue", - "link":"minimize-deviation-in-array/", - "video":"boHNFptxo2A", - "difficulty":"Hard", - "code":"1675-minimize-deviation-in-array", - "kotlin":true, - "cpp":true - }, - { - "problem":"Maximum Subsequence Score", - "pattern":"Heap / Priority Queue", - "link":"maximum-subsequence-score/", - "video":"ax1DKi5lJwk", - "difficulty":"Medium", - "code":"2542-maximum-subsequence-score", - "kotlin":true, - "cpp":true - }, - { - "problem":"Single Threaded Cpu", - "pattern":"Heap / Priority Queue", - "link":"single-threaded-cpu/", - "video":"RR1n-d4oYqE", - "difficulty":"Medium", - "code":"1834-single-threaded-cpu", - "java":true, - "python":true, - "javascript":true, - "kotlin":true, - "rust":true - }, - { - "problem":"Seat Reservation Manager", - "pattern":"Heap / Priority Queue", - "link":"seat-reservation-manager/", - "video":"ahobllKXEEY", - "difficulty":"Medium", - "code":"1845-seat-reservation-manager", - "python":true, - "cpp":true, - "kotlin":true - }, - { - "problem":"Process Tasks Using Servers", - "pattern":"Heap / Priority Queue", - "link":"process-tasks-using-servers/", - "video":"XKA22PecuMQ", - "difficulty":"Medium", - "code":"1882-process-tasks-using-servers", - "kotlin":true - }, - { - "problem":"Find The Kth Largest Integer In The Array", - "pattern":"Heap / Priority Queue", - "link":"find-the-kth-largest-integer-in-the-array/", - "video":"lRCaNiqO3xI", - "difficulty":"Medium", - "code":"1985-find-the-kth-largest-integer-in-the-array", - "java":true, - "python":true, - "swift":true, - "cpp":true, - "go":true, - "kotlin":true - }, - { - "problem":"Reorganize String", - "pattern":"Heap / Priority Queue", - "link":"reorganize-string/", - "video":"2g_b1aYTHeg", - "difficulty":"Medium", - "code":"0767-reorganize-string", - "java":true, - "python":true, - "cpp":true, - "kotlin":true - }, - { - "problem":"Longest Happy String", - "pattern":"Heap / Priority Queue", - "link":"longest-happy-string/", - "video":"8u-H6O_XQKE", - "difficulty":"Medium", - "code":"1405-longest-happy-string", - "kotlin":true - }, - { - "problem":"Car Pooling", - "pattern":"Heap / Priority Queue", - "link":"car-pooling/", - "video":"08sn_w4LWEE", - "difficulty":"Medium", - "code":"1094-car-pooling", - "csharp":true, - "cpp":true, - "kotlin":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Find Median From Data Stream", - "pattern":"Heap / Priority Queue", - "link":"find-median-from-data-stream/", - "video":"itmhHWaHupI", - "difficulty":"Hard", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0295-find-median-from-data-stream", - "csharp":true, - "kotlin":true, - "go":true, - "typescript":true - }, - { - "problem":"Maximum Performance of a Team", - "pattern":"Heap / Priority Queue", - "link":"maximum-performance-of-a-team/", - "video":"Y7UTvogADH0", - "difficulty":"Hard", - "code":"1383-maximum-performance-of-a-team", - "csharp":true, - "python":true, - "kotlin":true - }, - { - "problem":"IPO", - "pattern":"Heap / Priority Queue", - "link":"ipo/", - "video":"1IUzNJ6TPEM", - "difficulty":"Hard", - "code":"0502-ipo", - "python":true, - "kotlin":true - }, - { - "neetcode150":true, - "problem":"Subsets", - "pattern":"Backtracking", - "link":"subsets/", - "video":"REOH22Xwdkk", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0078-subsets", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Combination Sum", - "pattern":"Backtracking", - "link":"combination-sum/", - "video":"GBKI9VSKdGg", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0039-combination-sum", - "csharp":true, - "typescript":true, - "go":true, - "kotlin":true, - "ruby":true, - "rust":true, - "c":true, - "swift":true - }, - { - "problem":"Combinations", - "pattern":"Backtracking", - "link":"combinations/", - "video":"q0s6m7AiM7o", - "difficulty":"Medium", - "code":"0077-combinations", - "python":true, - "go":true, - "kotlin":true, - "java":true - }, - { - "neetcode150":true, - "problem":"Permutations", - "pattern":"Backtracking", - "link":"permutations/", - "video":"s7AvT7cGdSo", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0046-permutations", - "csharp":true, - "typescript":true, - "go":true, - "swift":true, - "kotlin":true, - "ruby":true, - "rust":true, - "c":true - }, - { - "neetcode150":true, - "problem":"Subsets II", - "pattern":"Backtracking", - "link":"subsets-ii/", - "video":"Vn2v6ajA7U0", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0090-subsets-ii", - "csharp":true, - "typescript":true, - "go":true, - "kotlin":true, - "ruby":true, - "rust":true, - "c":true - }, - { - "neetcode150":true, - "problem":"Combination Sum II", - "pattern":"Backtracking", - "link":"combination-sum-ii/", - "video":"rSA3t6BDDwg", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0040-combination-sum-ii", - "csharp":true, - "typescript":true, - "go":true, - "kotlin":true, - "ruby":true, - "c":true - }, - { - "problem":"Permutations II", - "pattern":"Backtracking", - "link":"permutations-ii/", - "video":"qhBVWf0YafA", - "difficulty":"Medium", - "code":"0047-permutations-ii", - "python":true, - "go":true, - "kotlin":true, - "java":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Word Search", - "pattern":"Backtracking", - "link":"word-search/", - "video":"pfiQ_PS1g8E", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0079-word-search", - "c":true, - "csharp":true, - "go":true, - "swift":true, - "kotlin":true, - "rust":true, - "ruby":true - }, - { - "neetcode150":true, - "problem":"Palindrome Partitioning", - "pattern":"Backtracking", - "link":"palindrome-partitioning/", - "video":"3jvWodd7ht0", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0131-palindrome-partitioning", - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "rust":true, - "swift":true, - "kotlin":true - }, - { - "problem":"Restore IP Addresses", - "pattern":"Backtracking", - "link":"restore-ip-addresses/", - "video":"61tN4YEdiTM", - "difficulty":"Medium", - "code":"0093-restore-ip-addresses", - "javascript":true, - "typescript":true, - "go":true, - "rust":true, - "kotlin":true - }, - { - "neetcode150":true, - "problem":"Letter Combinations of a Phone Number", - "pattern":"Backtracking", - "link":"letter-combinations-of-a-phone-number/", - "video":"0snEunUacZY", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0017-letter-combinations-of-a-phone-number", - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "rust":true, - "kotlin":true, - "swift":true - }, - { - "problem":"Matchsticks to Square", - "pattern":"Backtracking", - "link":"matchsticks-to-square/", - "video":"hUe0cUKV-YY", - "difficulty":"Medium", - "code":"0473-matchsticks-to-square", - "cpp":true, - "python":true, - "javascript":true, - "java":true, - "kotlin":true - }, - { - "problem":"Splitting a String Into Descending Consecutive Values", - "pattern":"Backtracking", - "link":"splitting-a-string-into-descending-consecutive-values/", - "video":"eDtMmysldaw", - "difficulty":"Medium", - "code":"1849-splitting-a-string-into-descending-consecutive-values", - "python":true, - "cpp":true, - "kotlin":true - }, - { - "problem":"Find Unique Binary String", - "pattern":"Backtracking", - "link":"find-unique-binary-string/", - "video":"aHqn4Dynd1k", - "difficulty":"Medium", - "code":"1980-find-unique-binary-string", - "python":true, - "kotlin":true, - "java":true - }, - { - "problem":"Maximum Length of a Concatenated String With Unique Characters", - "pattern":"Backtracking", - "link":"maximum-length-of-a-concatenated-string-with-unique-characters/", - "video":"d4SPuvkaeoo", - "difficulty":"Medium", - "code":"1239-maximum-length-of-a-concatenated-string-with-unique-characters", - "python":true, - "kotlin":true - }, - { - "problem":"Partition to K Equal Sum Subsets", - "pattern":"Backtracking", - "link":"partition-to-k-equal-sum-subsets/", - "video":"mBk4I0X46oI", - "difficulty":"Medium", - "code":"0698-partition-to-k-equal-sum-subsets", - "kotlin":true, - "python":true, - "java":true - }, - { - "neetcode150":true, - "problem":"N Queens", - "pattern":"Backtracking", - "link":"n-queens/", - "video":"Ph95IHmRp5M", - "difficulty":"Hard", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0051-n-queens", - "csharp":true, - "typescript":true, - "go":true, - "kotlin":true, - "c":true, - "rust":true - }, - { - "problem":"N Queens II", - "pattern":"Backtracking", - "link":"n-queens-ii/", - "video":"nalYyLZgvCY", - "difficulty":"Hard", - "code":"0052-n-queens-ii", - "c":true, - "cpp":true, - "javascript":true, - "python":true, - "kotlin":true - }, - { - "problem":"Island Perimeter", - "pattern":"Graphs", - "link":"island-perimeter/", - "video":"fISIuAFRM2s", - "difficulty":"Easy", - "code":"0463-island-perimeter", - "c":true, - "cpp":true, - "csharp":true, - "python":true, - "java":true, - "javascript":true, - "go":true, - "kotlin":true - }, - { - "problem":"Verifying An Alien Dictionary", - "pattern":"Graphs", - "link":"verifying-an-alien-dictionary/", - "video":"OVgPAJIyX6o", - "difficulty":"Easy", - "code":"0953-verifying-an-alien-dictionary", - "c":true, - "cpp":true, - "java":true, - "python":true, - "javascript":true, - "go":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Number of Islands", - "pattern":"Graphs", - "link":"number-of-islands/", - "video":"pV2kpPD66nE", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0200-number-of-islands", - "c":true, - "csharp":true, - "typescript":true, - "ruby":true, - "swift":true, - "kotlin":true, - "go":true, - "rust":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Clone Graph", - "pattern":"Graphs", - "link":"clone-graph/", - "video":"mQeF6bN8hMk", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0133-clone-graph", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true - }, - { - "neetcode150":true, - "problem":"Max Area of Island", - "pattern":"Graphs", - "link":"max-area-of-island/", - "video":"iJGr1OtmH0c", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0695-max-area-of-island", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "kotlin":true, - "rust":true - }, - { - "problem":"Count Sub Islands", - "pattern":"Graphs", - "link":"count-sub-islands/", - "video":"mLpW3qfbNJ8", - "difficulty":"Medium", - "code":"1905-count-sub-islands", - "c":true, - "csharp":true, - "python":true, - "cpp":true, - "java":true, - "javascript":true, - "go":true, - "kotlin":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Pacific Atlantic Water Flow", - "pattern":"Graphs", - "link":"pacific-atlantic-water-flow/", - "video":"s-VkcjHqkGI", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0417-pacific-atlantic-water-flow", - "c":true, - "csharp":true, - "kotlin":true, - "typescript":true, - "go":true, - "rust":true - }, - { - "neetcode150":true, - "problem":"Surrounded Regions", - "pattern":"Graphs", - "link":"surrounded-regions/", - "video":"9z2BunfoZ5Y", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0130-surrounded-regions", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "swift":true, - "kotlin":true - }, - { - "problem":"Reorder Routes to Make All Paths Lead to The City Zero", - "pattern":"Graphs", - "link":"reorder-routes-to-make-all-paths-lead-to-the-city-zero/", - "video":"m17yOR5_PpI", - "difficulty":"Medium", - "code":"1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero", - "csharp":true, - "cpp":true, - "kotlin":true, - "java":true - }, - { - "neetcode150":true, - "problem":"Rotting Oranges", - "pattern":"Graphs", - "link":"rotting-oranges/", - "video":"y704fEOx0s0", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0994-rotting-oranges", - "c":true, - "csharp":true, - "typescript":true, - "kotlin":true, - "go":true - }, - { - "neetcode150":true, - "problem":"Walls And Gates", - "premium":true, - "freeLink":"https://www.lintcode.com/problem/663/", - "pattern":"Graphs", - "link":"walls-and-gates/", - "video":"e69C6xhiSQE", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0286-walls-and-gates", - "csharp":true - }, - { - "problem":"Snakes And Ladders", - "pattern":"Graphs", - "link":"snakes-and-ladders/", - "video":"6lH4nO3JfLk", - "difficulty":"Medium", - "code":"0909-snakes-and-ladders", - "csharp":true, - "python":true, - "java":true, - "kotlin":true - }, - { - "problem":"Open The Lock", - "pattern":"Graphs", - "link":"open-the-lock/", - "video":"Pzg3bCDY87w", - "difficulty":"Medium", - "code":"0752-open-the-lock", - "csharp":true, - "java":true, - "python":true, - "kotlin":true - }, - { - "problem":"Find Eventual Safe States", - "pattern":"Graphs", - "link":"find-eventual-safe-states/", - "video":"Re_v0j0CRsg", - "difficulty":"Medium", - "code":"0802-find-eventual-safe-states", - "kotlin":true, - "java":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Course Schedule", - "pattern":"Graphs", - "link":"course-schedule/", - "video":"EgI5nU9etnU", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0207-course-schedule", - "csharp":true, - "typescript":true, - "go":true, - "swift":true, - "kotlin":true, - "c":true - }, - { - "neetcode150":true, - "problem":"Course Schedule II", - "pattern":"Graphs", - "link":"course-schedule-ii/", - "video":"Akt3glAwyfY", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0210-course-schedule-ii", - "csharp":true, - "typescript":true, - "go":true, - "kotlin":true - }, - { - "problem":"Course Schedule IV", - "pattern":"Graphs", - "link":"course-schedule-iv/", - "video":"cEW05ofxhn0", - "difficulty":"Medium", - "python":true, - "code":"1462-course-schedule-iv", - "kotlin":true - }, - { - "problem":"Check if Move Is Legal", - "pattern":"Graphs", - "link":"check-if-move-is-legal/", - "video":"KxK33AcQZpQ", - "difficulty":"Medium", - "code":"1958-check-if-move-is-legal", - "cpp":true, - "java":true, - "python":true, - "javascript":true, - "go":true, - "kotlin":true - }, - { - "problem":"Shortest Bridge", - "pattern":"Graphs", - "link":"shortest-bridge/", - "video":"gkINMhbbIbU", - "difficulty":"Medium", - "code":"0934-shortest-bridge", - "kotlin":true, - "javascript":true - }, - { - "problem":"Shortest Path in Binary Matrix", - "pattern":"Graphs", - "video":"YnxUdAO7TAo", - "link":"shortest-path-in-binary-matrix/", - "difficulty":"Medium", - "code":"1091-shortest-path-in-binary-matrix", - "python":true, - "java":true, - "kotlin":true - }, - { - "neetcode150":true, - "problem":"Redundant Connection", - "pattern":"Graphs", - "link":"redundant-connection/", - "video":"FXWRE67PLL0", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0684-redundant-connection", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Number of Connected Components In An Undirected Graph", - "premium":true, - "freeLink":"https://www.lintcode.com/problem/3651/", - "pattern":"Graphs", - "link":"number-of-connected-components-in-an-undirected-graph/", - "video":"8f1XPm4WOUc", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0323-number-of-connected-components-in-an-undirected-graph", - "csharp":true, - "go":true, - "swift":true, - "kotlin":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Graph Valid Tree", - "premium":true, - "freeLink":"https://www.lintcode.com/problem/178/", - "pattern":"Graphs", - "link":"graph-valid-tree/", - "video":"bXsUuownnoQ", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0261-graph-valid-tree", - "csharp":true, - "typescript":true, - "swift":true - }, - { - "problem":"Accounts Merge", - "pattern":"Graphs", - "link":"accounts-merge/", - "video":"6st4IxEF-90", - "difficulty":"Medium", - "code":"0721-accounts-merge", - "python":true, - "kotlin":true, - "java":true - }, - { - "problem":"Find Closest Node to Given Two Nodes", - "pattern":"Graphs", - "link":"find-closest-node-to-given-two-nodes/", - "video":"AZA8orksO4w", - "difficulty":"Medium", - "code":"2359-find-closest-node-to-given-two-nodes", - "kotlin":true - }, - { - "problem":"As Far from Land as Possible", - "pattern":"Graphs", - "link":"as-far-from-land-as-possible/", - "video":"fjxb1hQfrZk", - "difficulty":"Medium", - "code":"1162-as-far-from-land-as-possible", - "kotlin":true - }, - { - "problem":"Shortest Path with Alternating Colors", - "pattern":"Graphs", - "link":"shortest-path-with-alternating-colors/", - "video":"69rcy6lb-HQ", - "difficulty":"Medium", - "code":"1129-shortest-path-with-alternating-colors", - "kotlin":true - }, - { - "problem":"Minimum Fuel Cost to Report to the Capital", - "pattern":"Graphs", - "link":"minimum-fuel-cost-to-report-to-the-capital/", - "video":"I3lnDUIzIG4", - "difficulty":"Medium", - "code":"2477-minimum-fuel-cost-to-report-to-the-capital", - "kotlin":true, - "java":true - }, - { - "problem":"Minimum Score of a Path Between Two Cities", - "pattern":"Graphs", - "link":"minimum-score-of-a-path-between-two-cities/", - "video":"K7-mXA0irhY", - "difficulty":"Medium", - "code":"2492-minimum-score-of-a-path-between-two-cities", - "kotlin":true - }, - { - "problem":"Number of Closed Islands", - "pattern":"Graphs", - "link":"number-of-closed-islands/", - "video":"X8k48xek8g8", - "difficulty":"Medium", - "code":"1254-number-of-closed-islands", - "kotlin":true - }, - { - "problem":"Number of Enclaves", - "pattern":"Graphs", - "link":"number-of-enclaves/", - "video":"gf0zsh1FIgE", - "difficulty":"Medium", - "code":"1020-number-of-enclaves", - "kotlin":true, - "java":true - }, - { - "problem":"Minimum Number of Vertices to Reach all Nodes", - "pattern":"Graphs", - "link":"minimum-number-of-vertices-to-reach-all-nodes/", - "video":"TLzcum7vrTc", - "difficulty":"Medium", - "code":"1557-minimum-number-of-vertices-to-reach-all-nodes", - "java":true, - "kotlin":true - }, - { - "problem":"Is Graph Bipartite?", - "pattern":"Graphs", - "link":"is-graph-bipartite/", - "video":"mev55LTubBY", - "difficulty":"Medium", - "code":"0785-is-graph-bipartite", - "kotlin":true, - "java":true - }, - { - "problem":"Evaluate Division", - "pattern":"Graphs", - "link":"evaluate-division/", - "video":"Uei1fwDoyKk", - "difficulty":"Medium", - "code":"0399-evaluate-division", - "kotlin":true, - "cpp":true - }, - { - "problem":"Detonate the Maximum Bombs", - "pattern":"Graphs", - "link":"detonate-the-maximum-bombs/", - "video":"8NPbAvVXKR4", - "difficulty":"Medium", - "code":"2101-detonate-the-maximum-bombs", - "kotlin":true - }, - { - "problem":"Largest Color Value in a Directed Graph", - "pattern":"Graphs", - "link":"largest-color-value-in-a-directed-graph/", - "video":"xLoDjKczUSk", - "difficulty":"Hard", - "code":"1857-largest-color-value-in-a-directed-graph", - "kotlin":true - }, - { - "problem":"Minimum Number of Days to Eat N Oranges", - "pattern":"Graphs", - "link":"minimum-number-of-days-to-eat-n-oranges/", - "video":"LziQ6Qx9sks", - "difficulty":"Hard", - "code":"1553-minimum-number-of-days-to-eat-n-oranges", - "kotlin":true - }, - { - "neetcode150":true, - "problem":"Word Ladder", - "pattern":"Graphs", - "link":"word-ladder/", - "video":"h9iTnkgv05E", - "difficulty":"Hard", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0127-word-ladder", - "csharp":true, - "typescript":true, - "kotlin":true, - "go":true, - "rust":true - }, - { - "problem":"Path with Minimum Effort", - "pattern":"Advanced Graphs", - "link":"path-with-minimum-effort/", - "video":"XQlxCCx2vI4", - "difficulty":"Medium", - "code":"1631-path-with-minimum-effort", - "kotlin":true - }, - { - "neetcode150":true, - "problem":"Reconstruct Itinerary", - "pattern":"Advanced Graphs", - "link":"reconstruct-itinerary/", - "video":"ZyB_gQ8vqGA", - "difficulty":"Hard", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0332-reconstruct-itinerary", - "csharp":true, - "kotlin":true, - "go":true, - "c":true, - "rust":true - }, - { - "neetcode150":true, - "problem":"Min Cost to Connect All Points", - "pattern":"Advanced Graphs", - "link":"min-cost-to-connect-all-points/", - "video":"f7JOBJIC-NA", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"1584-min-cost-to-connect-all-points", - "csharp":true, - "ruby":true, - "swift":true, - "go":true, - "kotlin":true - }, - { - "neetcode150":true, - "problem":"Network Delay Time", - "pattern":"Advanced Graphs", - "link":"network-delay-time/", - "video":"EaphyqKU4PQ", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0743-network-delay-time", - "csharp":true, - "go":true, - "kotlin":true - }, - { - "problem":"Path with Maximum Probability", - "pattern":"Advanced Graphs", - "link":"path-with-maximum-probability/", - "video":"kPsDTGcrzGM", - "difficulty":"Medium", - "python":true, - "code":"1514-path-with-maximum-probability", - "java":true, - "javascript":true, - "kotlin":true, - "cpp":true - }, - { - "neetcode150":true, - "problem":"Swim In Rising Water", - "pattern":"Advanced Graphs", - "link":"swim-in-rising-water/", - "video":"amvrKlMLuGY", - "difficulty":"Hard", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0778-swim-in-rising-water", - "csharp":true, - "go":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Alien Dictionary", - "premium":true, - "freeLink":"https://www.lintcode.com/problem/892/", - "pattern":"Advanced Graphs", - "link":"alien-dictionary/", - "video":"6kTZYvNNyps", - "difficulty":"Hard", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0269-alien-dictionary", - "csharp":true - }, - { - "neetcode150":true, - "problem":"Cheapest Flights Within K Stops", - "pattern":"Advanced Graphs", - "link":"cheapest-flights-within-k-stops/", - "video":"5eIK3zUdYmE", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0787-cheapest-flights-within-k-stops", - "csharp":true, - "typescript":true, - "go":true, - "kotlin":true - }, - { - "problem":"Number of Good Paths", - "pattern":"Advanced Graphs", - "link":"number-of-good-paths/", - "video":"rv2GBYQm7xM", - "difficulty":"Hard", - "code":"2421-number-of-good-paths", - "javascript":true, - "typescript":true, - "go":true, - "rust":true, - "kotlin":true - }, - { - "problem":"Remove Max Number of Edges to Keep Graph Fully Traversable", - "pattern":"Advanced Graphs", - "link":"remove-max-number-of-edges-to-keep-graph-fully-traversable/", - "video":"booGwg5wYm4", - "difficulty":"Hard", - "code":"1579-remove-max-number-of-edges-to-keep-graph-fully-traversable", - "kotlin":true - }, - { - "problem":"Find Critical and Pseudo Critical Edges in Minimum Spanning Tree", - "pattern":"Advanced Graphs", - "link":"find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/", - "video":"83JnUxrLKJU", - "difficulty":"Hard", - "code":"1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree", - "python":true, - "kotlin":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Climbing Stairs", - "pattern":"1-D Dynamic Programming", - "link":"climbing-stairs/", - "video":"Y0lT9Fck7qI", - "difficulty":"Easy", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0070-climbing-stairs", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true, - "dart":true - }, - { - "neetcode150":true, - "problem":"Min Cost Climbing Stairs", - "pattern":"1-D Dynamic Programming", - "link":"min-cost-climbing-stairs/", - "code":"0746-min-cost-climbing-stairs", - "video":"ktmzAZWkEZ0", - "difficulty":"Easy", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true, - "scala":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"House Robber", - "pattern":"1-D Dynamic Programming", - "link":"house-robber/", - "video":"73r3KWiEvyk", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0198-house-robber", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true, - "scala":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"House Robber II", - "pattern":"1-D Dynamic Programming", - "link":"house-robber-ii/", - "video":"rWAJCfYYOvM", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0213-house-robber-ii", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true, - "scala":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Longest Palindromic Substring", - "pattern":"1-D Dynamic Programming", - "link":"longest-palindromic-substring/", - "video":"XYQecbcd6_c", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0005-longest-palindromic-substring", - "c":true, - "csharp":true, - "typescript":true, - "rust":true, - "go":true, - "kotlin":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Palindromic Substrings", - "pattern":"1-D Dynamic Programming", - "link":"palindromic-substrings/", - "video":"4RACzI5-du8", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0647-palindromic-substrings", - "c":true, - "csharp":true, - "typescript":true, - "rust":true, - "go":true, - "kotlin":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Decode Ways", - "pattern":"1-D Dynamic Programming", - "link":"decode-ways/", - "video":"6aEyTjOwlJU", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0091-decode-ways", - "c":true, - "csharp":true, - "typescript":true, - "kotlin":true, - "scala":true, - "go":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Coin Change", - "pattern":"1-D Dynamic Programming", - "link":"coin-change/", - "video":"H9bfqozjoqs", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0322-coin-change", - "c":true, - "csharp":true, - "typescript":true, - "kotlin":true, - "rust":true, - "go":true, - "scala":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Maximum Product Subarray", - "pattern":"1-D Dynamic Programming", - "link":"maximum-product-subarray/", - "video":"lXVy6YWFcRM", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0152-maximum-product-subarray", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Word Break", - "pattern":"1-D Dynamic Programming", - "link":"word-break/", - "video":"Sx9NNgInc3A", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0139-word-break", - "csharp":true, - "typescript":true, - "go":true, - "kotlin":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Longest Increasing Subsequence", - "pattern":"1-D Dynamic Programming", - "link":"longest-increasing-subsequence/", - "video":"cjWnW0hdF1Y", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0300-longest-increasing-subsequence", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "problem":"Partition Equal Subset Sum", - "pattern":"1-D Dynamic Programming", - "link":"partition-equal-subset-sum/", - "video":"IsvocB5BJhw", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0416-partition-equal-subset-sum", - "csharp":true, - "go":true, - "kotlin":true, - "c":true - }, - { - "problem":"Triangle", - "pattern":"1-D Dynamic Programming", - "link":"triangle/", - "video":"OM1MTokvxs4", - "difficulty":"Medium", - "code":"0120-triangle", - "cpp":true, - "java":true, - "python":true, - "kotlin":true, - "c":true - }, - { - "problem":"Delete And Earn", - "pattern":"1-D Dynamic Programming", - "link":"delete-and-earn/", - "video":"7FCemBxvGw0", - "difficulty":"Medium", - "code":"0740-delete-and-earn", - "python":true, - "go":true, - "kotlin":true, - "c":true, - "cpp":true - }, - { - "problem":"Paint House", - "pattern":"1-D Dynamic Programming", - "link":"paint-house/", - "video":"-w67-4tnH5U", - "difficulty":"Medium", - "code":"0256-paint-house", - "csharp":true - }, - { - "problem":"Combination Sum IV", - "pattern":"1-D Dynamic Programming", - "link":"combination-sum-iv/", - "video":"dw2nMCxG0ik", - "difficulty":"Medium", - "code":"0377-combination-sum-iv", - "python":true, - "cpp":true, - "kotlin":true, - "c":true, - "java":true - }, - { - "problem":"Perfect Squares", - "pattern":"1-D Dynamic Programming", - "link":"perfect-squares/", - "video":"HLZLwjzIVGo", - "difficulty":"Medium", - "code":"0279-perfect-squares", - "java":true, - "go":true, - "cpp":true, - "kotlin":true, - "c":true - }, - { - "problem":"Check if There is a Valid Partition For The Array", - "pattern":"1-D Dynamic Programming", - "link":"check-if-there-is-a-valid-partition-for-the-array/", - "video":"OxXPiwWFdTI", - "difficulty":"Medium", - "code":"2369-check-if-there-is-a-valid-partition-for-the-array", - "kotlin":true - }, - { - "problem":"Maximum Subarray Min Product", - "pattern":"1-D Dynamic Programming", - "link":"maximum-subarray-min-product/", - "video":"YLesLbNkyjA", - "difficulty":"Medium", - "code":"1856-maximum-subarray-min-product", - "kotlin":true, - "c":true, - "java":true - }, - { - "problem":"Minimum Cost For Tickets", - "pattern":"1-D Dynamic Programming", - "link":"minimum-cost-for-tickets/", - "video":"4pY1bsBpIY4", - "difficulty":"Medium", - "code":"0983-minimum-cost-for-tickets", - "cpp":true, - "kotlin":true, - "c":true - }, - { - "problem":"Integer Break", - "pattern":"1-D Dynamic Programming", - "link":"integer-break/", - "video":"in6QbUPMJ3I", - "difficulty":"Medium", - "code":"0343-integer-break", - "cpp":true, - "kotlin":true, - "c":true, - "java":true - }, - { - "problem":"Number of Longest Increasing Subsequence", - "pattern":"1-D Dynamic Programming", - "link":"number-of-longest-increasing-subsequence/", - "video":"Tuc-rjJbsXU", - "difficulty":"Medium", - "code":"0673-number-of-longest-increasing-subsequence", - "python":true, - "kotlin":true, - "c":true - }, - { - "problem":"Stickers to Spell Word", - "pattern":"1-D Dynamic Programming", - "link":"stickers-to-spell-word/", - "video":"hsomLb6mUdI", - "difficulty":"Hard", - "code":"0691-stickers-to-spell-word", - "c":true, - "kotlin":true - }, - { - "problem":"N-th Tribonacci Number", - "pattern":"1-D Dynamic Programming", - "link":"n-th-tribonacci-number/", - "video":"3lpNp5Ojvrw", - "difficulty":"Easy", - "code":"1137-n-th-tribonacci-number", - "python":true, - "javascript":true, - "typescript":true, - "go":true, - "kotlin":true, - "rust":true, - "c":true, - "cpp":true - }, - { - "problem":"Uncrossed Lines", - "pattern":"1-D Dynamic Programming", - "link":"uncrossed-lines/", - "video":"mnJF4vJ7GyE", - "difficulty":"Medium", - "code":"1035-uncrossed-lines", - "kotlin":true, - "c":true - }, - { - "problem":"Solving Questions With Brainpower", - "pattern":"1-D Dynamic Programming", - "link":"solving-questions-with-brainpower/", - "video":"D7TD_ArkfkA", - "difficulty":"Medium", - "code":"2140-solving-questions-with-brainpower", - "kotlin":true, - "c":true, - "cpp":true - }, - { - "problem":"Count Ways to Build Good Strings", - "pattern":"1-D Dynamic Programming", - "link":"count-ways-to-build-good-strings/", - "video":"JKpVHG2mhbk", - "difficulty":"Medium", - "code":"2466-count-ways-to-build-good-strings", - "kotlin":true, - "c":true - }, - { - "problem":"New 21 Game", - "pattern":"1-D Dynamic Programming", - "link":"new-21-game/", - "video":"zKi4LzjK27k", - "difficulty":"Medium", - "code":"0837-new-21-game", - "kotlin":true, - "c":true, - "javascript":true - }, - { - "problem":"Best Team with no Conflicts", - "pattern":"1-D Dynamic Programming", - "link":"best-team-with-no-conflicts/", - "video":"7kURH3btcV4", - "difficulty":"Medium", - "code":"1626-best-team-with-no-conflicts", - "c":true, - "kotlin":true - }, - { - "problem":"Stone Game III", - "pattern":"1-D Dynamic Programming", - "link":"stone-game-iii/", - "video":"HsLG5QW9CFQ", - "difficulty":"Hard", - "code":"1406-stone-game-iii", - "kotlin":true, - "c":true - }, - { - "problem":"Concatenated Words", - "pattern":"1-D Dynamic Programming", - "link":"concatenated-words/", - "video":"iHp7fjw1R28", - "difficulty":"Hard", - "code":"0472-concatenated-words", - "javascript":true, - "typescript":true, - "go":true, - "rust":true, - "kotlin":true - }, - { - "problem":"Maximize Score after N Operations", - "pattern":"1-D Dynamic Programming", - "link":"maximize-score-after-n-operations/", - "video":"RRQVDqp5RSE", - "difficulty":"Hard", - "code":"1799-maximize-score-after-n-operations", - "kotlin":true, - "c":true - }, - { - "problem":"Find the Longest Valid Obstacle Course at Each Position", - "pattern":"1-D Dynamic Programming", - "link":"find-the-longest-valid-obstacle-course-at-each-position/", - "video":"Xq9VT7p0lic", - "difficulty":"Hard", - "code":"1964-find-the-longest-valid-obstacle-course-at-each-position", - "kotlin":true, - "c":true - }, - { - "problem":"Count all Valid Pickup and Delivery Options", - "pattern":"1-D Dynamic Programming", - "link":"count-all-valid-pickup-and-delivery-options/", - "video":"OpgslsirW8s", - "difficulty":"Hard", - "code":"1359-count-all-valid-pickup-and-delivery-options", - "java":true, - "kotlin":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Unique Paths", - "pattern":"2-D Dynamic Programming", - "link":"unique-paths/", - "video":"IlEsdxuD4lY", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0062-unique-paths", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "kotlin":true, - "rust":true - }, - { - "problem":"Unique Paths II", - "pattern":"2-D Dynamic Programming", - "link":"unique-paths-ii/", - "video":"d3UOz7zdE4I", - "difficulty":"Medium", - "python":true, - "code":"0063-unique-paths-ii", - "cpp":true, - "java":true, - "go":true, - "kotlin":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Longest Common Subsequence", - "pattern":"2-D Dynamic Programming", - "link":"longest-common-subsequence/", - "video":"Ua0GhsJSlWM", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"1143-longest-common-subsequence", - "csharp":true, - "typescript":true, - "go":true, - "swift":true, - "kotlin":true, - "rust":true, - "c":true - }, - { - "problem":"Longest Palindromic Subsequence", - "pattern":"2-D Dynamic Programming", - "link":"longest-palindromic-subsequence/", - "video":"bUr8cNWI09Q", - "difficulty":"Medium", - "python":true, - "code":"0516-longest-palindromic-subsequence", - "kotlin":true - }, - { - "problem":"Last Stone Weight II", - "pattern":"2-D Dynamic Programming", - "link":"last-stone-weight-ii/", - "video":"gdXkkmzvR3c", - "difficulty":"Medium", - "python":true, - "code":"1049-last-stone-weight-ii", - "kotlin":true - }, - { - "neetcode150":true, - "problem":"Best Time to Buy And Sell Stock With Cooldown", - "pattern":"2-D Dynamic Programming", - "link":"best-time-to-buy-and-sell-stock-with-cooldown/", - "video":"I7j0F7AHpb8", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0309-best-time-to-buy-and-sell-stock-with-cooldown", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "swift":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "problem":"Coin Change II", - "pattern":"2-D Dynamic Programming", - "link":"coin-change-ii/", - "video":"Mjy4hd2xgrs", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0518-coin-change-ii", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "problem":"Target Sum", - "pattern":"2-D Dynamic Programming", - "link":"target-sum/", - "video":"g0npyaQtAQM", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0494-target-sum", - "csharp":true, - "typescript":true, - "go":true, - "kotlin":true, - "c":true - }, - { - "neetcode150":true, - "problem":"Interleaving String", - "pattern":"2-D Dynamic Programming", - "link":"interleaving-string/", - "video":"3Rw3p9LrgvE", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0097-interleaving-string", - "csharp":true, - "typescript":true, - "go":true, - "scala":true, - "kotlin":true, - "c":true - }, - { - "problem":"Stone Game", - "pattern":"2-D Dynamic Programming", - "link":"stone-game/", - "video":"uhgdXOlGYqE", - "difficulty":"Medium", - "code":"0877-stone-game", - "kotlin":true, - "cpp":true - }, - { - "problem":"Minimum Path Sum", - "pattern":"2-D Dynamic Programming", - "link":"minimum-path-sum/", - "video":"pGMsrvt0fpk", - "difficulty":"Medium", - "code":"0064-minimum-path-sum", - "cpp":true, - "java":true, - "python":true, - "kotlin":true - }, - { - "neetcode150":true, - "problem":"Longest Increasing Path In a Matrix", - "pattern":"2-D Dynamic Programming", - "link":"longest-increasing-path-in-a-matrix/", - "video":"wCc_nd-GiEc", - "difficulty":"Hard", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0329-longest-increasing-path-in-a-matrix", - "c":true, - "csharp":true, - "kotlin":true, - "rust":true - }, - { - "problem":"Maximal Square", - "pattern":"2-D Dynamic Programming", - "link":"maximal-square/", - "video":"6X7Ha2PrDmM", - "difficulty":"Medium", - "code":"0221-maximal-square", - "python":true, - "java":true, - "kotlin":true, - "cpp":true - }, - { - "problem":"Ones and Zeroes", - "pattern":"2-D Dynamic Programming", - "link":"ones-and-zeroes/", - "video":"miZ3qV04b1g", - "difficulty":"Medium", - "python":true, - "code":"0474-ones-and-zeroes", - "kotlin":true, - "cpp":true - }, - { - "problem":"Maximum Alternating Subsequence Sum", - "pattern":"2-D Dynamic Programming", - "link":"maximum-alternating-subsequence-sum/", - "video":"4v42XOuU1XA", - "difficulty":"Medium", - "code":"5782-maximum-alternating-subsequence-sum" - }, - { - "neetcode150":true, - "problem":"Distinct Subsequences", - "pattern":"2-D Dynamic Programming", - "link":"distinct-subsequences/", - "video":"-RDzMJ33nx8", - "difficulty":"Hard", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0115-distinct-subsequences", - "csharp":true, - "typescript":true, - "kotlin":true, - "c":true - }, - { - "neetcode150":true, - "problem":"Edit Distance", - "pattern":"2-D Dynamic Programming", - "link":"edit-distance/", - "video":"XYi2-LPrwm4", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0072-edit-distance", - "csharp":true, - "swift":true, - "scala":true, - "kotlin":true, - "c":true - }, - { - "problem":"Count Vowels Permutation", - "pattern":"2-D Dynamic Programming", - "link":"count-vowels-permutation/", - "video":"VUVpTZVa7Ls", - "difficulty":"Hard", - "code":"1220-count-vowels-permutation", - "python":true, - "java":true, - "go":true, - "cpp":true, - "kotlin":true - }, - { - "neetcode150":true, - "problem":"Burst Balloons", - "pattern":"2-D Dynamic Programming", - "link":"burst-balloons/", - "video":"VFskby7lUbw", - "difficulty":"Hard", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0312-burst-balloons", - "csharp":true, - "typescript":true, - "kotlin":true, - "c":true - }, - { - "problem":"Number of Ways to Rearrange Sticks With K Sticks Visible", - "pattern":"2-D Dynamic Programming", - "link":"number-of-ways-to-rearrange-sticks-with-k-sticks-visible/", - "video":"O761YBjGxGA", - "difficulty":"Hard", - "code":"1866-number-of-ways-to-rearrange-sticks-with-k-sticks-visible", - "kotlin":true - }, - { - "neetcode150":true, - "problem":"Regular Expression Matching", - "pattern":"2-D Dynamic Programming", - "link":"regular-expression-matching/", - "video":"HAA8mgxlov8", - "difficulty":"Hard", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0010-regular-expression-matching", - "csharp":true, - "typescript":true, - "go":true, - "c":true, - "kotlin":true - }, - { - "problem":"Stone Game II", - "pattern":"2-D Dynamic Programming", - "link":"stone-game-ii/", - "video":"I-z-u0zfQtg", - "difficulty":"Medium", - "code":"1140-stone-game-ii", - "kotlin":true - }, - { - "problem":"Flip String to Monotone Increasing", - "pattern":"2-D Dynamic Programming", - "link":"flip-string-to-monotone-increasing/", - "video":"tMq9z5k3umQ", - "difficulty":"Medium", - "code":"0926-flip-string-to-monotone-increasing", - "javascript":true, - "typescript":true, - "go":true, - "kotlin":true, - "rust":true - }, - { - "problem":"Maximum Value of K Coins from Piles", - "pattern":"2-D Dynamic Programming", - "link":"maximum-value-of-k-coins-from-piles/", - "video":"ZRdEd_eun8g", - "difficulty":"Hard", - "code":"2218-maximum-value-of-k-coins-from-piles", - "kotlin":true - }, - { - "problem":"Number of Music Playlists", - "pattern":"2-D Dynamic Programming", - "link":"number-of-music-playlists/", - "video":"gk4qzZSmyrs", - "difficulty":"Hard", - "code":"0920-number-of-music-playlists", - "java":true, - "kotlin":true - }, - { - "problem":"Number of Ways to Form a Target String Given a Dictionary", - "pattern":"2-D Dynamic Programming", - "link":"number-of-ways-to-form-a-target-string-given-a-dictionary/", - "video":"_GF-0T-YjW8", - "difficulty":"Hard", - "code":"1639-number-of-ways-to-form-a-target-string-given-a-dictionary", - "kotlin":true - }, - { - "problem":"Profitable Schemes", - "pattern":"2-D Dynamic Programming", - "link":"profitable-schemes/", - "video":"CcLKQLKvOl8", - "difficulty":"Hard", - "code":"0879-profitable-schemes", - "kotlin":true - }, - { - "problem":"Minimum Cost to Cut a Stick", - "pattern":"2-D Dynamic Programming", - "link":"minimum-cost-to-cut-a-stick/", - "video":"EVxTO5I0d7w", - "difficulty":"Hard", - "code":"1547-minimum-cost-to-cut-a-stick", - "kotlin":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Maximum Subarray", - "pattern":"Greedy", - "link":"maximum-subarray/", - "video":"5WZl3MMT0Eg", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0053-maximum-subarray", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "swift":true, - "kotlin":true, - "rust":true, - "ruby":true - }, - { - "problem":"Maximum Sum Circular Subarray", - "pattern":"Greedy", - "link":"maximum-sum-circular-subarray/", - "video":"fxT9KjakYPM", - "difficulty":"Medium", - "code":"0918-maximum-sum-circular-subarray", - "python":true, - "javascript":true, - "typescript":true, - "go":true, - "rust":true, - "kotlin":true, - "java":true - }, - { - "problem":"Longest Turbulent Array", - "pattern":"Greedy", - "link":"longest-turbulent-subarray/", - "video":"V_iHUhR8Dek", - "difficulty":"Medium", - "code":"0978-longest-turbulent-subarray", - "python":true, - "kotlin":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Jump Game", - "pattern":"Greedy", - "link":"jump-game/", - "video":"Yan0cv2cLy8", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0055-jump-game", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "swift":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "problem":"Jump Game II", - "pattern":"Greedy", - "link":"jump-game-ii/", - "video":"dJ7sWiOoK7g", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0045-jump-game-ii", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "swift":true, - "kotlin":true, - "ruby":true - }, - { - "problem":"Jump Game VII", - "pattern":"Greedy", - "link":"jump-game-vii/", - "video":"v1HpZUnQ4Yo", - "difficulty":"Medium", - "code":"1871-jump-game-vii", - "kotlin":true - }, - { - "neetcode150":true, - "problem":"Gas Station", - "pattern":"Greedy", - "link":"gas-station/", - "video":"lJwbPZGo05A", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0134-gas-station", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "swift":true, - "kotlin":true, - "ruby":true - }, - { - "neetcode150":true, - "problem":"Hand of Straights", - "pattern":"Greedy", - "link":"hand-of-straights/", - "video":"amnrMCVd2YI", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0846-hand-of-straights", - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "kotlin":true, - "c":true - }, - { - "problem":"Minimize Maximum of Array", - "pattern":"Greedy", - "link":"minimize-maximum-of-array/", - "video":"AeHMvcKuR0Y", - "difficulty":"Medium", - "code":"2439-minimize-maximum-of-array", - "kotlin":true - }, - { - "problem":"Dota2 Senate", - "pattern":"Greedy", - "link":"dota2-senate/", - "video":"zZA5KskfMuQ", - "difficulty":"Medium", - "code":"0649-dota2-senate", - "kotlin":true - }, - { - "problem":"Maximum Points You Can Obtain From Cards", - "pattern":"Greedy", - "link":"maximum-points-you-can-obtain-from-cards/", - "video":"TsA4vbtfCvo", - "difficulty":"Medium", - "code":"1423-maximum-points-you-can-obtain-from-cards", - "csharp":true, - "kotlin":true - }, - { - "neetcode150":true, - "problem":"Merge Triplets to Form Target Triplet", - "pattern":"Greedy", - "link":"merge-triplets-to-form-target-triplet/", - "video":"kShkQLQZ9K4", - "difficulty":"Medium", - "code":"1899-merge-triplets-to-form-target-triplet", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "csharp":true, - "typescript":true, - "ruby":true, - "swift":true, - "kotlin":true, - "c":true - }, - { - "neetcode150":true, - "problem":"Partition Labels", - "pattern":"Greedy", - "link":"partition-labels/", - "video":"B7m8UmZE-vw", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0763-partition-labels", - "csharp":true, - "go":true, - "ruby":true, - "kotlin":true, - "c":true - }, - { - "neetcode150":true, - "problem":"Valid Parenthesis String", - "pattern":"Greedy", - "link":"valid-parenthesis-string/", - "video":"QhPdNS143Qg", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0678-valid-parenthesis-string", - "c":true, - "csharp":true, - "typescript":true, - "kotlin":true - }, - { - "problem":"Eliminate Maximum Number of Monsters", - "pattern":"Greedy", - "link":"eliminate-maximum-number-of-monsters/", - "video":"6QQRayzOTD4", - "difficulty":"Medium", - "code":"1921-eliminate-maximum-number-of-monsters", - "cpp":true, - "java":true, - "kotlin":true - }, - { - "problem":"Two City Scheduling", - "pattern":"Greedy", - "link":"two-city-scheduling/", - "video":"d-B_gk_gJtQ", - "difficulty":"Medium", - "code":"1029-two-city-scheduling", - "java":true, - "python":true, - "javascript":true, - "typescript":true, - "go":true, - "rust":true, - "kotlin":true - }, - { - "problem":"Maximum Length of Pair Chain", - "pattern":"Greedy", - "link":"maximum-length-of-pair-chain/", - "video":"LcNNorqMVTw", - "difficulty":"Medium", - "code":"0646-maximum-length-of-pair-chain", - "kotlin":true - }, - { - "problem":"Minimum Deletions to Make Character Frequencies Unique", - "pattern":"Greedy", - "link":"minimum-deletions-to-make-character-frequencies-unique/", - "video":"h8AZEN49gTc", - "difficulty":"Medium", - "code":"1647-minimum-deletions-to-make-character-frequencies-unique", - "java":true, - "kotlin":true - }, - { - "problem":"Candy", - "pattern":"Greedy", - "link":"candy/", - "video":"1IzCRCcK17A", - "difficulty":"Hard", - "code":"135-candy" - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Insert Interval", - "pattern":"Intervals", - "link":"insert-interval/", - "video":"A8NUOmlwOlM", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0057-insert-interval", - "csharp":true, - "typescript":true, - "swift":true, - "rust":true, - "go":true, - "kotlin":true, - "c":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Merge Intervals", - "pattern":"Intervals", - "link":"merge-intervals/", - "video":"44H3cEC2fFM", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0056-merge-intervals", - "csharp":true, - "typescript":true, - "go":true, - "kotlin":true, - "scala":true, - "c":true, - "rust":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Non Overlapping Intervals", - "pattern":"Intervals", - "link":"non-overlapping-intervals/", - "video":"nONCGxWoUfM", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0435-non-overlapping-intervals", - "csharp":true, - "typescript":true, - "go":true, - "scala":true, - "c":true, - "kotlin":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Meeting Rooms", - "premium":true, - "freeLink":"https://www.lintcode.com/problem/920/", - "pattern":"Intervals", - "link":"meeting-rooms/", - "video":"PaJxqZVPhbg", - "difficulty":"Easy", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0252-meeting-rooms", - "csharp":true, - "rust":true, - "kotlin":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Meeting Rooms II", - "premium":true, - "freeLink":"https://www.lintcode.com/problem/919/", - "pattern":"Intervals", - "link":"meeting-rooms-ii/", - "video":"FdzJmTCVyJU", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0253-meeting-rooms-ii", - "csharp":true, - "rust":true, - "kotlin":true - }, - { - "problem":"Remove Covered Intervals", - "pattern":"Intervals", - "link":"remove-covered-intervals/", - "video":"nhAsMabiVkM", - "difficulty":"Medium", - "code":"1288-remove-covered-intervals", - "c":true, - "kotlin":true - }, - { - "neetcode150":true, - "problem":"Minimum Interval to Include Each Query", - "pattern":"Intervals", - "link":"minimum-interval-to-include-each-query/", - "video":"5hQ5WWW5awQ", - "difficulty":"Hard", - "python":true, - "java":true, - "cpp":true, - "code":"1851-minimum-interval-to-include-each-query", - "csharp":true, - "javascript":true, - "kotlin":true - }, - { - "problem":"Data Stream as Disjoint Intervals", - "pattern":"Intervals", - "link":"data-stream-as-disjoint-intervals/", - "video":"FavoZjPIWpo", - "difficulty":"Hard", - "code":"0352-data-stream-as-disjoint-intervals", - "javascript":true, - "typescript":true, - "go":true, - "rust":true, - "kotlin":true - }, - { - "problem":"Excel Sheet Column Title", - "pattern":"Math & Geometry", - "link":"excel-sheet-column-title/", - "video":"X_vJDpCCuoA", - "difficulty":"Easy", - "code":"0168-excel-sheet-column-title", - "java":true, - "python":true, - "kotlin":true - }, - { - "problem":"Greatest Common Divisor of Strings", - "pattern":"Math & Geometry", - "link":"greatest-common-divisor-of-strings/", - "video":"i5I_wrbUdzM", - "difficulty":"Easy", - "code":"1071-greatest-common-divisor-of-strings", - "javascript":true, - "typescript":true, - "go":true, - "kotlin":true, - "rust":true, - "cpp":true - }, - { - "problem":"Count Odd Numbers in an Interval Range", - "pattern":"Math & Geometry", - "link":"count-odd-numbers-in-an-interval-range/", - "video":"wrIWye928JQ", - "difficulty":"Easy", - "code":"1523-count-odd-numbers-in-an-interval-range", - "kotlin":true - }, - { - "problem":"Matrix Diagonal Sum", - "pattern":"Math & Geometry", - "link":"matrix-diagonal-sum/", - "video":"WliTu6gIK7o", - "difficulty":"Easy", - "code":"1572-matrix-diagonal-sum", - "kotlin":true, - "javascript":true - }, - { - "problem":"Maximum Points on a Line", - "pattern":"Math & Geometry", - "link":"max-points-on-a-line/", - "video":"Bb9lOXUOnFw", - "difficulty":"Hard", - "code":"0149-max-points-on-a-line", - "python":true, - "javascript":true, - "typescript":true, - "rust":true, - "cpp":true, - "kotlin":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Rotate Image", - "pattern":"Math & Geometry", - "link":"rotate-image/", - "video":"fMSJSS7eO1w", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0048-rotate-image", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "swift":true, - "ruby":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Spiral Matrix", - "pattern":"Math & Geometry", - "link":"spiral-matrix/", - "video":"BJnMZNwUk1M", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0054-spiral-matrix", - "csharp":true, - "typescript":true, - "kotlin":true, - "go":true, - "ruby":true, - "c":true - }, - { - "problem":"Spiral Matrix II ", - "pattern":"Math & Geometry", - "link":"spiral-matrix-ii/", - "video":"RvLrWFBJ9fM", - "difficulty":"Medium", - "code":"0059-spiral-matrix-ii", - "javascript":true, - "kotlin":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Set Matrix Zeroes", - "pattern":"Math & Geometry", - "link":"set-matrix-zeroes/", - "video":"T41rL0L3Pnw", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0073-set-matrix-zeroes", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "kotlin":true, - "ruby":true - }, - { - "neetcode150":true, - "problem":"Happy Number", - "pattern":"Math & Geometry", - "link":"happy-number/", - "video":"ljz85bxOYJ0", - "difficulty":"Easy", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0202-happy-number", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "swift":true, - "kotlin":true, - "ruby":true, - "rust":true - }, - { - "neetcode150":true, - "problem":"Plus One", - "pattern":"Math & Geometry", - "link":"plus-one/", - "video":"jIaA8boiG1s", - "difficulty":"Easy", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0066-plus-one", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "swift":true, - "kotlin":true, - "ruby":true, - "rust":true - }, - { - "problem":"Palindrome Number", - "pattern":"Math & Geometry", - "link":"palindrome-number/", - "video":"yubRKwixN-U", - "difficulty":"Easy", - "code":"0009-palindrome-number", - "javascript":true, - "typescript":true, - "cpp":true, - "java":true, - "python":true, - "go":true, - "rust":true, - "swift":true, - "c":true, - "kotlin":true - }, - { - "problem":"Ugly Number", - "pattern":"Math & Geometry", - "link":"ugly-number/", - "video":"M0Zay1Qr9ws", - "difficulty":"Easy", - "code":"0263-ugly-number", - "c":true, - "cpp":true, - "java":true, - "python":true, - "javascript":true, - "typescript":true, - "go":true, - "rust":true, - "swift":true, - "kotlin":true - }, - { - "problem":"Shift 2D Grid", - "pattern":"Math & Geometry", - "link":"shift-2d-grid/", - "video":"nJYFh4Dl-as", - "difficulty":"Easy", - "code":"1260-shift-2d-grid", - "cpp":true, - "java":true, - "python":true, - "javascript":true, - "kotlin":true - }, - { - "problem":"Roman to Integer", - "pattern":"Math & Geometry", - "link":"roman-to-integer/", - "video":"3jdxYj3DD98", - "difficulty":"Easy", - "code":"0013-roman-to-integer", - "python":true, - "javascript":true, - "go":true, - "typescript":true, - "rust":true, - "java":true, - "cpp":true, - "kotlin":true - }, - { - "problem":"Integer to Roman", - "pattern":"Math & Geometry", - "link":"integer-to-roman/", - "video":"ohBNdSJyLh8", - "difficulty":"Medium", - "code":"0012-integer-to-roman", - "python":true, - "typescript":true, - "go":true, - "rust":true, - "javascript":true, - "cpp":true, - "java":true, - "kotlin":true - }, - { - "neetcode150":true, - "problem":"Pow(x, n)", - "pattern":"Math & Geometry", - "link":"powx-n/", - "video":"g9YQyYi4IQQ", - "difficulty":"Medium", - "python":true, - "java":true, - "javascript":true, - "cpp":true, - "code":"0050-powx-n", - "c":true, - "csharp":true, - "typescript":true, - "swift":true, - "ruby":true, - "kotlin":true - }, - { - "neetcode150":true, - "problem":"Multiply Strings", - "pattern":"Math & Geometry", - "link":"multiply-strings/", - "video":"1vZswirL8Y8", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0043-multiply-strings", - "csharp":true, - "typescript":true, - "swift":true, - "ruby":true, - "kotlin":true, - "c":true - }, - { - "neetcode150":true, - "problem":"Detect Squares", - "pattern":"Math & Geometry", - "link":"detect-squares/", - "video":"bahebearrDc", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"2013-detect-squares", - "csharp":true, - "kotlin":true, - "ruby":true, - "rust":true - }, - { - "problem":"Robot Bounded In Circle", - "pattern":"Math & Geometry", - "link":"robot-bounded-in-circle/", - "video":"nKv2LnC_g6E", - "difficulty":"Medium", - "code":"1041-robot-bounded-in-circle", - "kotlin":true - }, - { - "problem":"Zigzag Conversion", - "pattern":"Math & Geometry", - "link":"zigzag-conversion/", - "video":"Q2Tw6gcVEwc", - "difficulty":"Medium", - "code":"0006-zigzag-conversion", - "java":true, - "cpp":true, - "go":true, - "kotlin":true - }, - { - "problem":"Find Missing Observations", - "pattern":"Math & Geometry", - "link":"find-missing-observations/", - "video":"86yKkaNi3sU", - "difficulty":"Medium", - "code":"2028-find-missing-observations", - "kotlin":true - }, - { - "neetcode150":true, - "problem":"Single Number", - "pattern":"Bit Manipulation", - "link":"single-number/", - "video":"qMPX1AOa83k", - "difficulty":"Easy", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0136-single-number", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true, - "dart":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Number of 1 Bits", - "pattern":"Bit Manipulation", - "link":"number-of-1-bits/", - "video":"5Km3utixwZs", - "difficulty":"Easy", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0191-number-of-1-bits", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Counting Bits", - "pattern":"Bit Manipulation", - "link":"counting-bits/", - "video":"RyBM56RIWrM", - "difficulty":"Easy", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0338-counting-bits", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Reverse Bits", - "pattern":"Bit Manipulation", - "link":"reverse-bits/", - "video":"UcoN6UjAI64", - "difficulty":"Easy", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0190-reverse-bits", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Missing Number", - "pattern":"Bit Manipulation", - "link":"missing-number/", - "video":"WnPLSRLSANE", - "difficulty":"Easy", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0268-missing-number", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true - }, - { - "problem":"Shuffle the Array", - "pattern":"Bit Manipulation", - "link":"shuffle-the-array/", - "video":"IvIKD_EU8BY", - "difficulty":"Easy", - "code":"1470-shuffle-the-array", - "javascript":true, - "typescript":true, - "go":true, - "kotlin":true, - "rust":true, - "c":true - }, - { - "problem":"Add to Array-Form of Integer", - "pattern":"Bit Manipulation", - "link":"add-to-array-form-of-integer/", - "video":"eBTZQt1TWfk", - "difficulty":"Easy", - "code":"0989-add-to-array-form-of-integer", - "javascript":true, - "typescript":true, - "go":true, - "kotlin":true, - "rust":true, - "c":true - }, - { - "neetcode150":true, - "blind75":true, - "problem":"Sum of Two Integers", - "pattern":"Bit Manipulation", - "link":"sum-of-two-integers/", - "video":"gVUrDV4tZfY", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0371-sum-of-two-integers", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "rust":true - }, - { - "neetcode150":true, - "problem":"Reverse Integer", - "pattern":"Bit Manipulation", - "link":"reverse-integer/", - "video":"HAgLH58IgJQ", - "difficulty":"Medium", - "python":true, - "java":true, - "cpp":true, - "javascript":true, - "code":"0007-reverse-integer", - "c":true, - "csharp":true, - "typescript":true, - "go":true, - "ruby":true, - "swift":true, - "kotlin":true, - "scala":true, - "rust":true - }, - { - "problem":"Add Binary", - "pattern":"Bit Manipulation", - "link":"add-binary/", - "video":"keuWJ47xG8g", - "difficulty":"Easy", - "code":"0067-add-binary", - "cpp":true, - "java":true, - "python":true, - "kotlin":true, - "rust":true, - "c":true - }, - { - "problem":"Create Hello World Function", - "pattern":"JavaScript", - "link":"create-hello-world-function/", - "video":"P9Ldx1eTlRc", - "difficulty":"Easy", - "code":"2667-create-hello-world-function", - "javascript":true, - "typescript":true - }, - { - "problem":"Counter", - "pattern":"JavaScript", - "link":"counter/", - "video":"yEGQQAG5V68", - "difficulty":"Easy", - "code":"2620-counter", - "javascript":true, - "typescript":true - }, - { - "problem":"Counter II", - "pattern":"JavaScript", - "link":"counter-ii/", - "video":"UXNXKGFZD08", - "difficulty":"Easy", - "code":"2665-counter-ii", - "javascript":true - }, - { - "problem":"Apply Transform over each Element in Array", - "pattern":"JavaScript", - "link":"apply-transform-over-each-element-in-array/", - "video":"7FhJHA5jlYk", - "difficulty":"Easy", - "code":"2635-apply-transform-over-each-element-in-array" - }, - { - "problem":"Filter Elements from Array", - "pattern":"JavaScript", - "link":"filter-elements-from-array/", - "video":"w1o81gbEEJU", - "difficulty":"Easy", - "code":"2634-filter-elements-from-array" - }, - { - "problem":"Array Reduce Transformation", - "pattern":"JavaScript", - "link":"array-reduce-transformation/", - "video":"KmTbYfpGxdM", - "difficulty":"Easy", - "code":"2626-array-reduce-transformation" - }, - { - "problem":"Function Composition", - "pattern":"JavaScript", - "link":"function-composition/", - "video":"mIFw1H7Ljco", - "difficulty":"Easy", - "code":"2629-function-composition" - }, - { - "problem":"Allow One Function Call", - "pattern":"JavaScript", - "link":"allow-one-function-call/", - "video":"m_SWhM9iX3s", - "difficulty":"Easy", - "code":"2666-allow-one-function-call" - }, - { - "problem":"Memoize", - "pattern":"JavaScript", - "link":"memoize/", - "video":"oFXyzJt9VeU", - "difficulty":"Medium", - "code":"2623-memoize" - }, - { - "problem":"Curry", - "pattern":"JavaScript", - "link":"curry/", - "video":"pi4kqMWQXxA", - "difficulty":"Medium", - "code":"2632-curry" - }, - { - "problem":"Sleep", - "pattern":"JavaScript", - "link":"sleep/", - "video":"P0D9Z6H7O00", - "difficulty":"Easy", - "code":"2621-sleep" - }, - { - "problem":"Promise Time Limit", - "pattern":"JavaScript", - "link":"promise-time-limit/", - "video":"hfH57rdZhOk", - "difficulty":"Easy", - "code":"2637-promise-time-limit" - }, - { - "problem":"Promise Pool", - "pattern":"JavaScript", - "link":"promise-pool/", - "video":"DB8pAAg-9xw", - "difficulty":"Medium", - "code":"2636-promise-pool" - }, - { - "problem":"Cache With Time Limit", - "pattern":"JavaScript", - "link":"cache-with-time-limit/", - "video":"w772gtNK0Gw", - "difficulty":"Medium", - "code":"2622-cache-with-time-limit" - }, - { - "problem":"Debounce", - "pattern":"JavaScript", - "link":"debounce/", - "video":"1sxSpnxNx5w", - "difficulty":"Medium", - "code":"2627-debounce" - }, - { - "problem":"Throttle", - "pattern":"JavaScript", - "link":"throttle/", - "video":"zyGZV_fIQWk", - "difficulty":"Medium", - "code":"2676-throttle" - }, - { - "problem":"JSON Deep Equal", - "pattern":"JavaScript", - "link":"json-deep-equal/", - "video":"4JVZ-mVqJPg", - "difficulty":"Medium", - "code":"2628-json-deep-equal", - "javascript":true - }, - { - "problem":"Convert Object to JSON String", - "pattern":"JavaScript", - "link":"convert-object-to-json-string/", - "video":"f94fUbHU-FY", - "difficulty":"Medium", - "code":"2633-convert-object-to-json-string" - }, - { - "problem":"Array of Objects to Matrix", - "pattern":"JavaScript", - "link":"array-of-objects-to-matrix/", - "video":"LJwgAMHGcI0", - "difficulty":"Medium", - "code":"2675-array-of-objects-to-matrix" - }, - { - "problem":"Difference Between Two Objects", - "pattern":"JavaScript", - "link":"differences-between-two-objects/", - "video":"gH7oZs1WZfg", - "difficulty":"Medium", - "code":"2700-differences-between-two-objects" - }, - { - "problem":"Chunk Array", - "pattern":"JavaScript", - "link":"chunk-array/", - "video":"VUN-O3B9ceY", - "difficulty":"Easy", - "code":"2677-chunk-array" - }, - { - "problem":"Flatten Deeply Nested Array", - "pattern":"JavaScript", - "link":"flatten-deeply-nested-array/", - "video":"_DetLPKtFNk", - "difficulty":"Medium", - "code":"2625-flatten-deeply-nested-array" - }, - { - "problem":"Array Prototype Last", - "pattern":"JavaScript", - "link":"array-prototype-last/", - "video":"3JdtfMBrUqc", - "difficulty":"Easy", - "code":"2619-array-prototype-last" - }, - { - "problem":"Group By", - "pattern":"JavaScript", - "link":"group-by/", - "video":"zs9axOyYHRE", - "difficulty":"Medium", - "code":"2631-group-by" - }, - { - "problem":"Check if Object Instance of Class", - "pattern":"JavaScript", - "link":"check-if-object-instance-of-class/", - "video":"meIo-Q07Ba8", - "difficulty":"Medium", - "code":"2618-check-if-object-instance-of-class" - }, - { - "problem":"Call Function with Custom Context", - "pattern":"JavaScript", - "link":"call-function-with-custom-context/", - "video":"du_GH-Ooa8E", - "difficulty":"Medium", - "code":"2693-call-function-with-custom-context" - }, - { - "problem":"Event Emitter", - "pattern":"JavaScript", - "link":"event-emitter/", - "video":"M69bjWFarU0", - "difficulty":"Medium", - "code":"2694-event-emitter" - }, - { - "problem":"Array Wrapper", - "pattern":"JavaScript", - "link":"array-wrapper/", - "video":"XoGjPdPTAVA", - "difficulty":"Easy", - "code":"2695-array-wrapper" - }, - { - "problem":"Generate Fibonacci Sequence", - "pattern":"JavaScript", - "link":"generate-fibonacci-sequence/", - "video":"T643rQ70Jlk", - "difficulty":"Easy", - "code":"2648-generate-fibonacci-sequence" - }, - { - "problem":"Nested Array Generator", - "pattern":"JavaScript", - "link":"nested-array-generator/", - "video":"yo-J1jQaZYU", - "difficulty":"Medium", - "code":"2649-nested-array-generator" - } -] \ No newline at end of file + { + "neetcode150": true, + "blind75": true, + "problem": "Contains Duplicate", + "pattern": "Arrays & Hashing", + "link": "contains-duplicate/", + "video": "3OamzN90kPg", + "difficulty": "Easy", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0217-contains-duplicate", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true, + "scala": true, + "dart": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Valid Anagram", + "pattern": "Arrays & Hashing", + "link": "valid-anagram/", + "video": "9UtInBqnCgA", + "difficulty": "Easy", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0242-valid-anagram", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true, + "scala": true, + "dart": true + }, + { + "problem": "Concatenation of Array", + "pattern": "Arrays & Hashing", + "link": "concatenation-of-array/", + "video": "68isPRHgcFQ", + "difficulty": "Easy", + "code": "1929-concatenation-of-array", + "python": true, + "cpp": true, + "java": true, + "javascript": true, + "kotlin": true, + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "swift": true, + "rust": true, + "scala": true, + "dart": true + }, + { + "problem": "Replace Elements With Greatest Element On Right Side", + "pattern": "Arrays & Hashing", + "link": "replace-elements-with-greatest-element-on-right-side/", + "video": "ZHjKhUjcsaU", + "difficulty": "Easy", + "code": "1299-replace-elements-with-greatest-element-on-right-side", + "c": true, + "cpp": true, + "csharp": true, + "java": true, + "python": true, + "javascript": true, + "typescript": true, + "go": true, + "rust": true, + "dart": true, + "kotlin": true, + "swift": true + }, + { + "problem": "Is Subsequence", + "pattern": "Arrays & Hashing", + "link": "is-subsequence/", + "video": "99RVfqklbCE", + "difficulty": "Easy", + "code": "0392-is-subsequence", + "c": true, + "cpp": true, + "csharp": true, + "java": true, + "python": true, + "javascript": true, + "typescript": true, + "go": true, + "rust": true, + "dart": true, + "kotlin": true, + "swift": true + }, + { + "problem": "Length of Last Word", + "pattern": "Arrays & Hashing", + "link": "length-of-last-word/", + "video": "KT9rltZTybQ", + "difficulty": "Easy", + "code": "0058-length-of-last-word", + "c": true, + "cpp": true, + "csharp": true, + "java": true, + "python": true, + "javascript": true, + "typescript": true, + "rust": true, + "go": true, + "swift": true, + "dart": true, + "ruby": true, + "kotlin": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Two Sum", + "pattern": "Arrays & Hashing", + "link": "two-sum/", + "video": "KLlXCFG5TnA", + "difficulty": "Easy", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0001-two-sum", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true, + "scala": true, + "dart": true + }, + { + "problem": "Longest Common Prefix", + "pattern": "Arrays & Hashing", + "link": "longest-common-prefix/", + "video": "0sWShKIJoo4", + "difficulty": "Easy", + "code": "0014-longest-common-prefix", + "cpp": true, + "python": true, + "javascript": true, + "c": true, + "csharp": true, + "java": true, + "typescript": true, + "go": true, + "rust": true, + "dart": true, + "kotlin": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Group Anagrams", + "pattern": "Arrays & Hashing", + "link": "group-anagrams/", + "video": "vzdNOK2oB2E", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0049-group-anagrams", + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true, + "dart": true, + "c": true, + "scala": true + }, + { + "problem": "Pascals Triangle", + "pattern": "Arrays & Hashing", + "link": "pascals-triangle/", + "video": "nPVEaB3AjUM", + "difficulty": "Easy", + "code": "0118-pascals-triangle", + "c": true, + "cpp": true, + "java": true, + "python": true, + "javascript": true, + "typescript": true, + "rust": true, + "csharp": true, + "go": true, + "dart": true, + "kotlin": true + }, + { + "problem": "Remove Element", + "pattern": "Arrays & Hashing", + "link": "remove-element/", + "video": "Pcd1ii9P9ZI", + "difficulty": "Easy", + "code": "0027-remove-element", + "c": true, + "java": true, + "python": true, + "javascript": true, + "typescript": true, + "go": true, + "cpp": true, + "csharp": true, + "swift": true, + "rust": true, + "dart": true, + "kotlin": true + }, + { + "problem": "Unique Email Addresses", + "pattern": "Arrays & Hashing", + "link": "unique-email-addresses/", + "video": "TC_xLIWl7qY", + "difficulty": "Easy", + "code": "0929-unique-email-addresses", + "java": true, + "python": true, + "javascript": true, + "typescript": true, + "swift": true, + "cpp": true, + "csharp": true, + "go": true, + "rust": true, + "c": true, + "kotlin": true + }, + { + "problem": "Isomorphic Strings", + "pattern": "Arrays & Hashing", + "link": "isomorphic-strings/", + "video": "7yF-U1hLEqQ", + "difficulty": "Easy", + "code": "0205-isomorphic-strings", + "c": true, + "java": true, + "python": true, + "javascript": true, + "typescript": true, + "swift": true, + "cpp": true, + "csharp": true, + "go": true, + "rust": true, + "kotlin": true + }, + { + "problem": "Can Place Flowers", + "pattern": "Arrays & Hashing", + "link": "can-place-flowers/", + "video": "ZGxqqjljpUI", + "difficulty": "Easy", + "code": "0605-can-place-flowers", + "c": true, + "cpp": true, + "python": true, + "javascript": true, + "typescript": true, + "csharp": true, + "go": true, + "rust": true, + "java": true, + "kotlin": true, + "swift": true + }, + { + "problem": "Majority Element", + "pattern": "Arrays & Hashing", + "link": "majority-element/", + "video": "7pnhv842keE", + "difficulty": "Easy", + "code": "0169-majority-element", + "c": true, + "cpp": true, + "python": true, + "javascript": true, + "typescript": true, + "swift": true, + "csharp": true, + "java": true, + "go": true, + "kotlin": true, + "rust": true + }, + { + "problem": "Next Greater Element I", + "pattern": "Arrays & Hashing", + "link": "next-greater-element-i/", + "video": "68a1Dc_qVq4", + "difficulty": "Easy", + "code": "0496-next-greater-element-i", + "java": true, + "python": true, + "typescript": true, + "c": true, + "cpp": true, + "csharp": true, + "javascript": true, + "go": true, + "rust": true, + "kotlin": true + }, + { + "problem": "Find Pivot Index", + "pattern": "Arrays & Hashing", + "link": "find-pivot-index/", + "video": "u89i60lYx8U", + "difficulty": "Easy", + "code": "0724-find-pivot-index", + "c": true, + "cpp": true, + "java": true, + "python": true, + "javascript": true, + "typescript": true, + "go": true, + "rust": true, + "csharp": true, + "kotlin": true, + "swift": true + }, + { + "problem": "Range Sum Query - Immutable", + "pattern": "Arrays & Hashing", + "link": "range-sum-query-immutable/", + "video": "2pndAmo_sMA", + "difficulty": "Easy", + "code": "0303-range-sum-query-immutable", + "python": true, + "c": true, + "cpp": true, + "java": true, + "kotlin": true, + "csharp": true, + "javascript": true, + "rust": true + }, + { + "problem": "Find All Numbers Disappeared in An Array", + "pattern": "Arrays & Hashing", + "link": "find-all-numbers-disappeared-in-an-array/", + "video": "8i-f24YFWC4", + "difficulty": "Easy", + "code": "0448-find-all-numbers-disappeared-in-an-array", + "cpp": true, + "java": true, + "python": true, + "javascript": true, + "c": true, + "typescript": true, + "go": true, + "rust": true, + "csharp": true, + "kotlin": true + }, + { + "problem": "Maximum Number of Balloons", + "pattern": "Arrays & Hashing", + "link": "maximum-number-of-balloons/", + "video": "G9xeB2-7PqY", + "difficulty": "Easy", + "code": "1189-maximum-number-of-balloons", + "c": true, + "java": true, + "python": true, + "javascript": true, + "cpp": true, + "typescript": true, + "go": true, + "rust": true, + "csharp": true, + "kotlin": true + }, + { + "problem": "Word Pattern", + "pattern": "Arrays & Hashing", + "link": "word-pattern/", + "video": "W_akoecmCbM", + "difficulty": "Easy", + "code": "0290-word-pattern", + "java": true, + "python": true, + "javascript": true, + "typescript": true, + "c": true, + "cpp": true, + "go": true, + "rust": true, + "csharp": true, + "kotlin": true + }, + { + "problem": "Design HashSet", + "pattern": "Arrays & Hashing", + "link": "design-hashset/", + "video": "VymjPQUXjL8", + "difficulty": "Easy", + "code": "0705-design-hashset", + "kotlin": true, + "c": true, + "cpp": true, + "java": true, + "python": true, + "javascript": true, + "rust": true + }, + { + "problem": "Design HashMap", + "pattern": "Arrays & Hashing", + "link": "design-hashmap/", + "video": "cNWsgbKwwoU", + "difficulty": "Easy", + "code": "0706-design-hashmap", + "python": true, + "c": true, + "cpp": true, + "java": true, + "javascript": true, + "kotlin": true, + "rust": true + }, + { + "problem": "Sort an Array", + "pattern": "Arrays & Hashing", + "link": "sort-an-array/", + "video": "MsYZSinhuFo", + "difficulty": "Medium", + "code": "0912-sort-an-array", + "python": true, + "java": true, + "kotlin": true, + "cpp": true, + "csharp": true, + "javascript": true, + "go": true, + "rust": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Top K Frequent Elements", + "pattern": "Arrays & Hashing", + "link": "top-k-frequent-elements/", + "video": "YPTqKIgVk-k", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0347-top-k-frequent-elements", + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true, + "c": true, + "scala": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Product of Array Except Self", + "pattern": "Arrays & Hashing", + "link": "product-of-array-except-self/", + "video": "bNvIQI2wAjk", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0238-product-of-array-except-self", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "problem": "Valid Sudoku", + "pattern": "Arrays & Hashing", + "link": "valid-sudoku/", + "video": "TjFXEUCMqI8", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0036-valid-sudoku", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "kotlin": true, + "rust": true, + "dart": true, + "scala": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Encode and Decode Strings", + "premium": true, + "freeLink": "https://www.lintcode.com/problem/659/", + "pattern": "Arrays & Hashing", + "link": "encode-and-decode-strings/", + "video": "B1k_sxOSgv8", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0271-encode-and-decode-strings", + "csharp": true, + "go": true, + "ruby": true, + "swift": true, + "rust": true, + "typescript": true, + "kotlin": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Longest Consecutive Sequence", + "pattern": "Arrays & Hashing", + "link": "longest-consecutive-sequence/", + "video": "P6RZZMu_maU", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0128-longest-consecutive-sequence", + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true, + "c": true + }, + { + "problem": "Sort Colors", + "pattern": "Arrays & Hashing", + "link": "sort-colors/", + "video": "4xbWSRZHqac", + "difficulty": "Medium", + "code": "0075-sort-colors", + "c": true, + "java": true, + "javascript": true, + "go": true, + "kotlin": true, + "cpp": true, + "python": true, + "typescript": true, + "csharp": true, + "rust": true, + "swift": true + }, + { + "problem": "Encode and Decode TinyURL", + "pattern": "Arrays & Hashing", + "link": "encode-and-decode-tinyurl/", + "video": "VyBOaboQLGc", + "difficulty": "Medium", + "code": "0535-encode-and-decode-tinyurl", + "javascript": true, + "cpp": true, + "python": true, + "typescript": true, + "go": true, + "rust": true, + "swift": true, + "kotlin": true, + "c": true, + "java": true + }, + { + "problem": "Brick Wall", + "pattern": "Arrays & Hashing", + "link": "brick-wall/", + "video": "Kkmv2h48ekw", + "difficulty": "Medium", + "code": "0554-brick-wall", + "javascript": true, + "typescript": true, + "c": true, + "cpp": true, + "java": true, + "python": true, + "rust": true, + "kotlin": true + }, + { + "problem": "Best Time to Buy And Sell Stock II", + "pattern": "Arrays & Hashing", + "link": "best-time-to-buy-and-sell-stock-ii/", + "video": "3SJ3pUkPQMc", + "difficulty": "Medium", + "code": "0122-best-time-to-buy-and-sell-stock-ii", + "c": true, + "javascript": true, + "go": true, + "cpp": true, + "java": true, + "python": true, + "kotlin": true, + "rust": true + }, + { + "problem": "Subarray Sum Equals K", + "pattern": "Arrays & Hashing", + "link": "subarray-sum-equals-k/", + "video": "fFVZt-6sgyo", + "difficulty": "Medium", + "code": "0560-subarray-sum-equals-k", + "java": true, + "cpp": true, + "go": true, + "c": true, + "python": true, + "javascript": true, + "typescript": true, + "kotlin": true, + "rust": true, + "csharp": true + }, + { + "problem": "Unique Length 3 Palindromic Subsequences", + "pattern": "Arrays & Hashing", + "link": "unique-length-3-palindromic-subsequences/", + "video": "3THUt0vAFLU", + "difficulty": "Medium", + "code": "1930-unique-length-3-palindromic-subsequences", + "cpp": true, + "java": true, + "kotlin": true, + "c": true, + "python": true, + "javascript": true, + "typescript": true, + "rust": true + }, + { + "problem": "Minimum Number of Swaps to Make The String Balanced", + "pattern": "Arrays & Hashing", + "link": "minimum-number-of-swaps-to-make-the-string-balanced/", + "video": "3YDBT9ZrfaU", + "difficulty": "Medium", + "code": "1963-minimum-number-of-swaps-to-make-the-string-balanced", + "javascript": true, + "cpp": true, + "c": true, + "python": true, + "kotlin": true, + "java": true, + "rust": true + }, + { + "problem": "Number of Pairs of Interchangeable Rectangles", + "pattern": "Arrays & Hashing", + "link": "number-of-pairs-of-interchangeable-rectangles/", + "video": "lEQ8ZlLOuyQ", + "difficulty": "Medium", + "code": "2001-number-of-pairs-of-interchangeable-rectangles", + "javascript": true, + "cpp": true, + "python": true, + "c": true, + "java": true, + "rust": true, + "kotlin": true + }, + { + "problem": "Maximum Product of The Length of Two Palindromic Subsequences", + "pattern": "Arrays & Hashing", + "link": "maximum-product-of-the-length-of-two-palindromic-subsequences/", + "video": "aoHbYlO8vDg", + "difficulty": "Medium", + "code": "2002-maximum-product-of-the-length-of-two-palindromic-subsequences", + "cpp": true, + "c": true, + "csharp": true, + "java": true, + "python": true, + "javascript": true, + "typescript": true, + "go": true, + "kotlin": true, + "rust": true + }, + { + "problem": "Grid Game", + "pattern": "Arrays & Hashing", + "link": "grid-game/", + "video": "N4wDSOw65hI", + "difficulty": "Medium", + "code": "2017-grid-game", + "python": true, + "cpp": true, + "kotlin": true, + "java": true, + "javascript": true, + "rust": true + }, + { + "problem": "Find All Anagrams in a String", + "pattern": "Arrays & Hashing", + "link": "find-all-anagrams-in-a-string/", + "video": "G8xtZy0fDKg", + "difficulty": "Medium", + "code": "0438-find-all-anagrams-in-a-string", + "cpp": true, + "csharp": true, + "python": true, + "java": true, + "javascript": true, + "go": true, + "kotlin": true, + "c": true + }, + { + "problem": "Find The Index of The First Occurrence in a String", + "pattern": "Arrays & Hashing", + "link": "find-the-index-of-the-first-occurrence-in-a-string/", + "video": "JoF0Z7nVSrA", + "difficulty": "Easy", + "code": "0028-find-the-index-of-the-first-occurrence-in-a-string", + "python": true, + "cpp": true, + "go": true, + "c": true, + "java": true, + "kotlin": true, + "csharp": true, + "javascript": true + }, + { + "problem": "Wiggle Sort", + "pattern": "Arrays & Hashing", + "premium": true, + "freeLink": "https://www.lintcode.com/problem/508/", + "link": "wiggle-sort/", + "video": "vGsyTE4s34w", + "difficulty": "Medium", + "code": "0280-wiggle-sort", + "cpp": true, + "python": true, + "kotlin": true + }, + { + "problem": "Largest Number", + "pattern": "Arrays & Hashing", + "link": "largest-number/", + "video": "WDx6Y4i4xJ8", + "difficulty": "Medium", + "code": "0179-largest-number", + "typescript": true, + "cpp": true, + "java": true, + "kotlin": true, + "c": true, + "csharp": true, + "python": true, + "javascript": true, + "go": true, + "ruby": true, + "swift": true, + "rust": true, + "scala": true + }, + { + "problem": "Continuous Subarray Sum", + "pattern": "Arrays & Hashing", + "link": "continuous-subarray-sum/", + "video": "OKcrLfR-8mE", + "difficulty": "Medium", + "code": "0523-continuous-subarray-sum", + "java": true, + "python": true, + "cpp": true, + "kotlin": true, + "c": true, + "javascript": true, + "rust": true + }, + { + "problem": "Push Dominoes", + "pattern": "Arrays & Hashing", + "link": "push-dominoes/", + "video": "evUFsOb_iLY", + "difficulty": "Medium", + "code": "0838-push-dominoes", + "typescript": true, + "cpp": true, + "python": true, + "kotlin": true, + "java": true + }, + { + "problem": "Repeated DNA Sequences", + "pattern": "Arrays & Hashing", + "link": "repeated-dna-sequences/", + "video": "FzTYfsmtOso", + "difficulty": "Medium", + "code": "0187-repeated-dna-sequences", + "java": true, + "typescript": true, + "cpp": true, + "kotlin": true, + "python": true, + "javascript": true + }, + { + "problem": "Insert Delete Get Random O(1)", + "pattern": "Arrays & Hashing", + "link": "insert-delete-getrandom-o1/", + "video": "j4KwhBziOpg", + "difficulty": "Medium", + "code": "0380-insert-delete-getrandom-o1", + "java": true, + "typescript": true, + "javascript": true, + "go": true, + "cpp": true, + "swift": true, + "kotlin": true, + "python": true + }, + { + "problem": "Check if a String Contains all Binary Codes of Size K", + "pattern": "Arrays & Hashing", + "link": "check-if-a-string-contains-all-binary-codes-of-size-k/", + "video": "qU32rTy_kOM", + "difficulty": "Medium", + "code": "1461-check-if-a-string-contains-all-binary-codes-of-size-k", + "cpp": true, + "kotlin": true, + "python": true, + "javascript": true + }, + { + "problem": "Range Sum Query 2D Immutable", + "pattern": "Arrays & Hashing", + "link": "range-sum-query-2d-immutable/", + "video": "KE8MQuwE2yA", + "difficulty": "Medium", + "code": "0304-range-sum-query-2d-immutable", + "cpp": true, + "python": true, + "kotlin": true, + "javascript": true + }, + { + "problem": "Non Decreasing Array", + "pattern": "Arrays & Hashing", + "link": "non-decreasing-array/", + "video": "RegQckCegDk", + "difficulty": "Medium", + "code": "0665-non-decreasing-array", + "cpp": true, + "java": true, + "javascript": true, + "typescript": true, + "go": true, + "scala": true, + "kotlin": true, + "python": true, + "csharp": true + }, + { + "problem": "First Missing Positive", + "pattern": "Arrays & Hashing", + "link": "first-missing-positive/", + "video": "8g78yfzMlao", + "difficulty": "Hard", + "code": "0041-first-missing-positive", + "python": true, + "typescript": true, + "cpp": true, + "java": true, + "go": true, + "kotlin": true, + "c": true, + "javascript": true + }, + { + "problem": "Sign of An Array", + "pattern": "Arrays & Hashing", + "link": "sign-of-the-product-of-an-array/", + "video": "ILDLM86jNow", + "difficulty": "Easy", + "code": "1822-sign-of-the-product-of-an-array", + "cpp": true, + "java": true, + "python": true, + "javascript": true, + "typescript": true, + "go": true, + "kotlin": true + }, + { + "problem": "Find the Difference of Two Arrays", + "pattern": "Arrays & Hashing", + "link": "find-the-difference-of-two-arrays/", + "video": "a4wqKR-znBE", + "difficulty": "Easy", + "code": "2215-find-the-difference-of-two-arrays", + "kotlin": true, + "cpp": true, + "csharp": true, + "java": true, + "python": true, + "javascript": true, + "typescript": true + }, + { + "problem": "Design Parking System", + "pattern": "Arrays & Hashing", + "link": "design-parking-system/", + "video": "d5zCHesOrSk", + "difficulty": "Easy", + "code": "1603-design-parking-system", + "kotlin": true, + "java": true, + "python": true, + "javascript": true + }, + { + "problem": "Number of Zero-Filled Subarrays", + "pattern": "Arrays & Hashing", + "link": "number-of-zero-filled-subarrays/", + "video": "G-EWVGCcL_w", + "difficulty": "Medium", + "code": "2348-number-of-zero-filled-subarrays", + "kotlin": true, + "cpp": true, + "java": true, + "python": true + }, + { + "problem": "Optimal Partition of String", + "pattern": "Arrays & Hashing", + "link": "optimal-partition-of-string/", + "video": "CKZPdiXiQf0", + "difficulty": "Medium", + "code": "2405-optimal-partition-of-string", + "kotlin": true, + "java": true + }, + { + "problem": "Design Underground System", + "pattern": "Arrays & Hashing", + "link": "design-underground-system/", + "video": "W5QOLqXskZM", + "difficulty": "Medium", + "code": "1396-design-underground-system", + "kotlin": true, + "java": true, + "javascript": true + }, + { + "problem": "Minimum Penalty for a Shop", + "pattern": "Arrays & Hashing", + "link": "minimum-penalty-for-a-shop/", + "video": "0d7ShRoOFVE", + "difficulty": "Medium", + "code": "2483-minimum-penalty-for-a-shop", + "cpp": true, + "java": true, + "kotlin": true + }, + { + "problem": "Text Justification", + "pattern": "Arrays & Hashing", + "link": "text-justification/", + "video": "TzMl4Z7pVh8", + "difficulty": "Hard", + "code": "0068-naming-a-company", + "python": true, + "kotlin": true + }, + { + "problem": "Naming a Company", + "pattern": "Arrays & Hashing", + "link": "naming-a-company/", + "video": "NrHpgTScOcY", + "difficulty": "Hard", + "code": "2306-naming-a-company", + "kotlin": true, + "java": true, + "javascript": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Valid Palindrome", + "pattern": "Two Pointers", + "link": "valid-palindrome/", + "video": "jJXJ16kPFWg", + "difficulty": "Easy", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0125-valid-palindrome", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true, + "dart": true, + "scala": true + }, + { + "problem": "Valid Palindrome II", + "pattern": "Two Pointers", + "link": "valid-palindrome-ii/", + "video": "JrxRYBwG6EI", + "difficulty": "Easy", + "code": "0680-valid-palindrome-ii", + "python": true, + "cpp": true, + "csharp": true, + "java": true, + "javascript": true, + "typescript": true, + "go": true, + "rust": true, + "c": true, + "kotlin": true + }, + { + "problem": "Minimum Difference Between Highest And Lowest of K Scores", + "pattern": "Two Pointers", + "link": "minimum-difference-between-highest-and-lowest-of-k-scores/", + "video": "JU5XdBZZtlk", + "difficulty": "Easy", + "code": "1984-minimum-difference-between-highest-and-lowest-of-k-scores", + "javascript": true, + "cpp": true, + "python": true, + "typescript": true, + "go": true, + "rust": true, + "java": true, + "kotlin": true + }, + { + "problem": "Merge Strings Alternately", + "pattern": "Two Pointers", + "link": "merge-strings-alternately/", + "video": "LECWOvTo-Sc", + "difficulty": "Easy", + "code": "1768-merge-strings-alternately", + "kotlin": true, + "cpp": true, + "java": true, + "python": true, + "javascript": true, + "typescript": true + }, + { + "problem": "Reverse String", + "pattern": "Two Pointers", + "link": "reverse-string/", + "video": "_d0T_2Lk2qA", + "difficulty": "Easy", + "code": "0344-reverse-string", + "c": true, + "python": true, + "javascript": true, + "typescript": true, + "swift": true, + "cpp": true, + "java": true, + "go": true, + "rust": true, + "kotlin": true, + "dart": true + }, + { + "problem": "Merge Sorted Array", + "pattern": "Two Pointers", + "link": "merge-sorted-array/", + "video": "P1Ic85RarKY", + "difficulty": "Easy", + "code": "0088-merge-sorted-array", + "c": true, + "java": true, + "javascript": true, + "cpp": true, + "python": true, + "typescript": true, + "go": true, + "rust": true, + "kotlin": true + }, + { + "problem": "Move Zeroes", + "pattern": "Two Pointers", + "link": "move-zeroes/", + "video": "aayNRwUN3Do", + "difficulty": "Easy", + "code": "0283-move-zeroes", + "c": true, + "cpp": true, + "javascript": true, + "csharp": true, + "python": true, + "typescript": true, + "go": true, + "swift": true, + "rust": true, + "java": true, + "kotlin": true + }, + { + "problem": "Remove Duplicates From Sorted Array", + "pattern": "Two Pointers", + "link": "remove-duplicates-from-sorted-array/", + "video": "DEJAZBq0FDA", + "difficulty": "Easy", + "code": "0026-remove-duplicates-from-sorted-array", + "python": true, + "javascript": true, + "go": true, + "cpp": true, + "typescript": true, + "swift": true, + "rust": true, + "java": true, + "kotlin": true, + "c": true + }, + { + "problem": "Remove Duplicates From Sorted Array II", + "pattern": "Two Pointers", + "link": "remove-duplicates-from-sorted-array-ii/", + "video": "ycAq8iqh0TI", + "difficulty": "Medium", + "code": "0080-remove-duplicates-from-sorted-array-ii", + "python": true, + "kotlin": true, + "cpp": true, + "csharp": true, + "javascript": true, + "swift": true + }, + { + "neetcode150": true, + "problem": "Two Sum II Input Array Is Sorted", + "pattern": "Two Pointers", + "link": "two-sum-ii-input-array-is-sorted/", + "video": "cQ1Oz4ckceM", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0167-two-sum-ii-input-array-is-sorted", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true, + "scala": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "3Sum", + "pattern": "Two Pointers", + "link": "3sum/", + "video": "jzZsG8n2R9A", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0015-3sum", + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true, + "scala": true, + "c": true + }, + { + "problem": "4Sum", + "pattern": "Two Pointers", + "link": "4sum/", + "video": "EYeR-_1NRlQ", + "difficulty": "Medium", + "code": "0018-4sum", + "python": true, + "javascript": true, + "typescript": true, + "go": true, + "cpp": true, + "kotlin": true, + "java": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Container With Most Water", + "pattern": "Two Pointers", + "link": "container-with-most-water/", + "video": "UuiTKBwPgAo", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0011-container-with-most-water", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true, + "scala": true, + "dart": true + }, + { + "problem": "Number of Subsequences That Satisfy The Given Sum Condition", + "pattern": "Two Pointers", + "link": "number-of-subsequences-that-satisfy-the-given-sum-condition/", + "video": "xCsIkPLS4Ls", + "difficulty": "Medium", + "code": "1498-number-of-subsequences-that-satisfy-the-given-sum-condition", + "cpp": true, + "python": true, + "kotlin": true + }, + { + "problem": "Rotate Array", + "pattern": "Two Pointers", + "link": "rotate-array/", + "video": "BHr381Guz3Y", + "difficulty": "Medium", + "code": "0189-rotate-array", + "cpp": true, + "java": true, + "python": true, + "typescript": true, + "go": true, + "kotlin": true, + "javascript": true + }, + { + "problem": "Array With Elements Not Equal to Average of Neighbors", + "pattern": "Two Pointers", + "link": "array-with-elements-not-equal-to-average-of-neighbors/", + "video": "Wmb3YdVYfqM", + "difficulty": "Medium", + "code": "1968-array-with-elements-not-equal-to-average-of-neighbors", + "c": true, + "cpp": true, + "kotlin": true, + "python": true, + "javascript": true + }, + { + "problem": "Boats to Save People", + "pattern": "Two Pointers", + "link": "boats-to-save-people/", + "video": "XbaxWuHIWUs", + "difficulty": "Medium", + "code": "0881-boats-to-save-people", + "c": true, + "cpp": true, + "typescript": true, + "javascript": true, + "python": true, + "kotlin": true, + "java": true, + "swift": true + }, + { + "neetcode150": true, + "problem": "Trapping Rain Water", + "pattern": "Two Pointers", + "link": "trapping-rain-water/", + "video": "ZI2z5pq0TqA", + "difficulty": "Hard", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0042-trapping-rain-water", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Best Time to Buy And Sell Stock", + "pattern": "Sliding Window", + "link": "best-time-to-buy-and-sell-stock/", + "video": "1pkOgXD63yU", + "difficulty": "Easy", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0121-best-time-to-buy-and-sell-stock", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true, + "scala": true + }, + { + "problem": "Contains Duplicate II", + "pattern": "Sliding Window", + "link": "contains-duplicate-ii/", + "video": "ypn0aZ0nrL4", + "difficulty": "Easy", + "python": true, + "code": "0219-contains-duplicate-ii", + "cpp": true, + "java": true, + "javascript": true, + "kotlin": true, + "rust": true + }, + { + "problem": "Number of Sub Arrays of Size K and Avg Greater than or Equal to Threshold", + "pattern": "Sliding Window", + "link": "number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/", + "video": "D8B4tKxMTnY", + "difficulty": "Medium", + "python": true, + "code": "1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold", + "cpp": true, + "javascript": true, + "kotlin": true, + "java": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Longest Substring Without Repeating Characters", + "pattern": "Sliding Window", + "link": "longest-substring-without-repeating-characters/", + "video": "wiGpQwVHdE0", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0003-longest-substring-without-repeating-characters", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true, + "scala": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Longest Repeating Character Replacement", + "pattern": "Sliding Window", + "link": "longest-repeating-character-replacement/", + "video": "gqXU1UyA8pk", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0424-longest-repeating-character-replacement", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "kotlin": true, + "rust": true, + "swift": true + }, + { + "neetcode150": true, + "problem": "Permutation In String", + "pattern": "Sliding Window", + "link": "permutation-in-string/", + "video": "UbyhOgBN834", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0567-permutation-in-string", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "kotlin": true, + "rust": true + }, + { + "problem": "Frequency of The Most Frequent Element", + "pattern": "Sliding Window", + "link": "frequency-of-the-most-frequent-element/", + "video": "vgBrQ0NM5vE", + "difficulty": "Medium", + "code": "1838-frequency-of-the-most-frequent-element", + "csharp": true, + "javascript": true, + "typescript": true, + "go": true, + "rust": true, + "c": true, + "cpp": true, + "kotlin": true, + "java": true, + "python": true + }, + { + "problem": "Fruits into Basket", + "pattern": "Sliding Window", + "link": "fruit-into-baskets/", + "video": "yYtaV0G3mWQ", + "difficulty": "Medium", + "code": "0904-fruit-into-baskets", + "javascript": true, + "typescript": true, + "go": true, + "kotlin": true, + "rust": true, + "python": true + }, + { + "problem": "Maximum Number of Vowels in a Substring of Given Length", + "pattern": "Sliding Window", + "link": "maximum-number-of-vowels-in-a-substring-of-given-length/", + "video": "kEfPSzgL-Ss", + "difficulty": "Medium", + "code": "1456-maximum-number-of-vowels-in-a-substring-of-given-length", + "kotlin": true, + "cpp": true, + "java": true, + "python": true + }, + { + "problem": "Minimum Number of Flips to Make The Binary String Alternating", + "pattern": "Sliding Window", + "link": "minimum-number-of-flips-to-make-the-binary-string-alternating/", + "video": "MOeuK6gaC2A", + "difficulty": "Medium", + "code": "1888-minimum-number-of-flips-to-make-the-binary-string-alternating", + "javascript": true, + "typescript": true, + "kotlin": true, + "python": true + }, + { + "problem": "Minimum Size Subarray Sum", + "pattern": "Sliding Window", + "link": "minimum-size-subarray-sum/", + "video": "aYqYMIqZx5s", + "difficulty": "Medium", + "code": "0209-minimum-size-subarray-sum", + "c": true, + "cpp": true, + "javascript": true, + "go": true, + "java": true, + "kotlin": true, + "python": true + }, + { + "problem": "Find K Closest Elements", + "pattern": "Sliding Window", + "link": "find-k-closest-elements/", + "video": "o-YDQzHoaKM", + "difficulty": "Medium", + "code": "0658-find-k-closest-elements", + "python": true, + "typescript": true, + "javascript": true, + "kotlin": true + }, + { + "problem": "Minimum Operations to Reduce X to Zero", + "pattern": "Sliding Window", + "link": "minimum-operations-to-reduce-x-to-zero/", + "video": "xumn16n7njs", + "difficulty": "Medium", + "code": "1658-minimum-operations-to-reduce-x-to-zero", + "java": true, + "kotlin": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Minimum Window Substring", + "pattern": "Sliding Window", + "link": "minimum-window-substring/", + "video": "jSto0O4AJbM", + "difficulty": "Hard", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0076-minimum-window-substring", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "kotlin": true, + "rust": true, + "ruby": true, + "swift": true + }, + { + "neetcode150": true, + "problem": "Sliding Window Maximum", + "pattern": "Sliding Window", + "link": "sliding-window-maximum/", + "video": "DfljaUwZsOk", + "difficulty": "Hard", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0239-sliding-window-maximum", + "csharp": true, + "go": true, + "kotlin": true, + "typescript": true, + "ruby": true, + "c": true, + "rust": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Valid Parentheses", + "pattern": "Stack", + "link": "valid-parentheses/", + "video": "WTzjTskDFMg", + "difficulty": "Easy", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0020-valid-parentheses", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true, + "dart": true + }, + { + "problem": "Baseball Game", + "pattern": "Stack", + "link": "baseball-game/", + "video": "Id_tqGdsZQI", + "difficulty": "Easy", + "code": "0682-baseball-game", + "c": true, + "cpp": true, + "python": true, + "java": true, + "typescript": true, + "go": true, + "rust": true, + "kotlin": true, + "csharp": true, + "javascript": true, + "swift": true + }, + { + "problem": "Implement Stack Using Queues", + "pattern": "Stack", + "link": "implement-stack-using-queues/", + "video": "rW4vm0-DLYc", + "difficulty": "Easy", + "code": "0225-implement-stack-using-queues", + "cpp": true, + "go": true, + "c": true, + "java": true, + "python": true, + "javascript": true, + "typescript": true, + "rust": true, + "kotlin": true + }, + { + "neetcode150": true, + "problem": "Min Stack", + "pattern": "Stack", + "link": "min-stack/", + "video": "qkLl7nAwDPo", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0155-min-stack", + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "kotlin": true, + "c": true, + "rust": true, + "swift": true + }, + { + "neetcode150": true, + "problem": "Evaluate Reverse Polish Notation", + "pattern": "Stack", + "link": "evaluate-reverse-polish-notation/", + "video": "iu0082c4HDE", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0150-evaluate-reverse-polish-notation", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true + }, + { + "problem": "Removing Stars From a String", + "pattern": "Stack", + "link": "removing-stars-from-a-string/", + "video": "pRyFZIaKegA", + "difficulty": "Medium", + "code": "2390-removing-stars-from-a-string", + "kotlin": true, + "java": true, + "python": true, + "javascript": true + }, + { + "problem": "Validate Stack Sequences", + "pattern": "Stack", + "link": "validate-stack-sequences/", + "video": "mzua0r94kb8", + "difficulty": "Medium", + "code": "0946-validate-stack-sequences", + "kotlin": true, + "python": true + }, + { + "neetcode150": true, + "problem": "Generate Parentheses", + "pattern": "Stack", + "link": "generate-parentheses/", + "video": "s9fokUqJ76A", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0022-generate-parentheses", + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "kotlin": true, + "c": true, + "rust": true, + "swift": true + }, + { + "problem": "Asteroid Collision", + "pattern": "Stack", + "link": "asteroid-collision/", + "video": "LN7KjRszjk4", + "difficulty": "Medium", + "code": "0735-asteroid-collision", + "java": true, + "javascript": true, + "typescript": true, + "rust": true, + "python": true, + "cpp": true, + "kotlin": true + }, + { + "neetcode150": true, + "problem": "Daily Temperatures", + "pattern": "Stack", + "link": "daily-temperatures/", + "video": "cTBiBSnjO3c", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0739-daily-temperatures", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true + }, + { + "problem": "Online Stock Span", + "pattern": "Stack", + "link": "online-stock-span/", + "video": "slYh0ZNEqSw", + "difficulty": "Medium", + "code": "0901-online-stock-span", + "python": true, + "typescript": true, + "rust": true, + "cpp": true, + "java": true, + "javascript": true, + "kotlin": true + }, + { + "neetcode150": true, + "problem": "Car Fleet", + "pattern": "Stack", + "link": "car-fleet/", + "video": "Pr6T-3yB9RM", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0853-car-fleet", + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "kotlin": true, + "rust": true, + "c": true + }, + { + "problem": "Simplify Path", + "pattern": "Stack", + "link": "simplify-path/", + "video": "qYlHrAKJfyA", + "difficulty": "Medium", + "code": "0071-simplify-path", + "python": true, + "typescript": true, + "rust": true, + "java": true, + "kotlin": true, + "javascript": true + }, + { + "problem": "Decode String", + "pattern": "Stack", + "link": "decode-string/", + "video": "qB0zZpBJlh8", + "difficulty": "Medium", + "code": "0394-decode-string", + "python": true, + "typescript": true, + "rust": true, + "scala": true, + "java": true, + "kotlin": true + }, + { + "problem": "Remove K Digits", + "pattern": "Stack", + "link": "remove-k-digits/", + "video": "cFabMOnJaq0", + "difficulty": "Medium", + "code": "0402-remove-k-digits", + "cpp": true, + "javascript": true, + "typescript": true, + "rust": true, + "kotlin": true, + "java": true, + "python": true + }, + { + "problem": "Remove All Adjacent Duplicates In String II", + "pattern": "Stack", + "link": "remove-all-adjacent-duplicates-in-string-ii/", + "video": "w6LcypDgC4w", + "difficulty": "Medium", + "code": "1209-remove-all-adjacent-duplicates-in-string-ii", + "cpp": true, + "python": true, + "javascript": true, + "typescript": true, + "rust": true, + "kotlin": true + }, + { + "problem": "132 Pattern", + "pattern": "Stack", + "link": "132-pattern/", + "video": "q5ANAl8Z458", + "difficulty": "Medium", + "code": "0456-132-pattern", + "python": true, + "cpp": true, + "java": true, + "javascript": true, + "typescript": true, + "kotlin": true, + "rust": true + }, + { + "problem": "Maximum Frequency Stack", + "pattern": "Stack", + "link": "maximum-frequency-stack/", + "video": "Z6idIicFDOE", + "difficulty": "Hard", + "code": "0895-maximum-frequency-stack", + "javascript": true, + "typescript": true, + "rust": true, + "kotlin": true + }, + { + "neetcode150": true, + "problem": "Largest Rectangle In Histogram", + "pattern": "Stack", + "link": "largest-rectangle-in-histogram/", + "video": "zx5Sw9130L0", + "difficulty": "Hard", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0084-largest-rectangle-in-histogram", + "csharp": true, + "typescript": true, + "go": true, + "kotlin": true, + "rust": true, + "c": true + }, + { + "neetcode150": true, + "problem": "Binary Search", + "pattern": "Binary Search", + "link": "binary-search/", + "video": "s4DPM8ct1pI", + "difficulty": "Easy", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0704-binary-search", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true, + "dart": true + }, + { + "problem": "Search Insert Position", + "pattern": "Binary Search", + "link": "search-insert-position/", + "video": "K-RYzDZkzCI", + "difficulty": "Easy", + "code": "0035-search-insert-position", + "c": true, + "cpp": true, + "python": true, + "javascript": true, + "swift": true, + "csharp": true, + "java": true, + "go": true, + "kotlin": true, + "typescript": true, + "rust": true + }, + { + "problem": "Guess Number Higher Or Lower", + "pattern": "Binary Search", + "link": "guess-number-higher-or-lower/", + "video": "xW4QsTtaCa4", + "difficulty": "Easy", + "code": "0374-guess-number-higher-or-lower", + "c": true, + "python": true, + "cpp": true, + "java": true, + "javascript": true, + "go": true, + "swift": true, + "kotlin": true, + "rust": true + }, + { + "problem": "Arranging Coins", + "pattern": "Binary Search", + "link": "arranging-coins/", + "video": "5rHz_6s2Buw", + "difficulty": "Easy", + "code": "0441-arranging-coins", + "python": true, + "cpp": true, + "kotlin": true, + "java": true, + "javascript": true + }, + { + "problem": "Squares of a Sorted Array", + "pattern": "Binary Search", + "link": "squares-of-a-sorted-array/", + "video": "FPCZsG_AkUg", + "difficulty": "Easy", + "code": "0977-squares-of-a-sorted-array", + "cpp": true, + "python": true, + "javascript": true, + "typescript": true, + "go": true, + "kotlin": true, + "java": true, + "rust": true + }, + { + "problem": "Valid Perfect Square", + "pattern": "Binary Search", + "link": "valid-perfect-square/", + "video": "Cg_wWPHJ2Sk", + "difficulty": "Easy", + "code": "0367-valid-perfect-square", + "python": true, + "javascript": true, + "cpp": true, + "swift": true, + "java": true, + "kotlin": true + }, + { + "problem": "Sqrt(x) ", + "pattern": "Binary Search", + "link": "sqrtx/", + "video": "zdMhGxRWutQ", + "difficulty": "Easy", + "code": "0069-sqrtx", + "kotlin": true, + "c": true, + "cpp": true, + "java": true, + "python": true, + "javascript": true + }, + { + "problem": "Single Element in a Sorted Array", + "pattern": "Binary Search", + "link": "single-element-in-a-sorted-array/", + "video": "HGtqdzyUJ3k", + "difficulty": "Medium", + "code": "0540-single-element-in-a-sorted-array", + "kotlin": true, + "cpp": true, + "java": true, + "python": true, + "javascript": true, + "typescript": true + }, + { + "problem": "Capacity to Ship Packages", + "pattern": "Binary Search", + "link": "capacity-to-ship-packages-within-d-days/", + "video": "ER_oLmdc-nw", + "difficulty": "Medium", + "code": "1011-capacity-to-ship-packages-within-d-days", + "kotlin": true, + "java": true, + "python": true + }, + { + "problem": "Find Peak Element", + "pattern": "Binary Search", + "link": "find-peak-element/", + "video": "kMzJy9es7Hc", + "difficulty": "Medium", + "code": "0162-find-peak-element", + "kotlin": true, + "cpp": true, + "java": true, + "python": true, + "javascript": true + }, + { + "problem": "Successful Pairs of Spells and Potions", + "pattern": "Binary Search", + "link": "successful-pairs-of-spells-and-potions/", + "video": "OKnm5oyAhWg", + "difficulty": "Medium", + "code": "2300-successful-pairs-of-spells-and-potions", + "kotlin": true, + "cpp": true, + "python": true + }, + { + "neetcode150": true, + "problem": "Search a 2D Matrix", + "pattern": "Binary Search", + "link": "search-a-2d-matrix/", + "video": "Ber2pi2C0j0", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0074-search-a-2d-matrix", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "problem": "Koko Eating Bananas", + "pattern": "Binary Search", + "link": "koko-eating-bananas/", + "video": "U2SozAs9RzA", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0875-koko-eating-bananas", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true + }, + { + "problem": "Minimize the Maximum Difference of Pairs", + "pattern": "Binary Search", + "link": "minimize-the-maximum-difference-of-pairs/", + "video": "lf1Pxg7IrzQ", + "difficulty": "Medium", + "code": "2616-minimize-the-maximum-difference-of-pairs", + "java": true, + "kotlin": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Find Minimum In Rotated Sorted Array", + "pattern": "Binary Search", + "link": "find-minimum-in-rotated-sorted-array/", + "video": "nIVW4P8b1VA", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0153-find-minimum-in-rotated-sorted-array", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "swift": true, + "kotlin": true, + "rust": true, + "scala": true, + "ruby": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Search In Rotated Sorted Array", + "pattern": "Binary Search", + "link": "search-in-rotated-sorted-array/", + "video": "U8XENwh8Oy8", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0033-search-in-rotated-sorted-array", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "swift": true, + "kotlin": true, + "rust": true, + "scala": true + }, + { + "problem": "Search In Rotated Sorted Array II", + "pattern": "Binary Search", + "link": "search-in-rotated-sorted-array-ii/", + "video": "oUnF7o88_Xc", + "difficulty": "Medium", + "code": "0081-search-in-rotated-sorted-array-ii", + "java": true, + "kotlin": true + }, + { + "neetcode150": true, + "problem": "Time Based Key Value Store", + "pattern": "Binary Search", + "link": "time-based-key-value-store/", + "video": "fu2cD_6E8Hw", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0981-time-based-key-value-store", + "csharp": true, + "typescript": true, + "go": true, + "kotlin": true, + "ruby": true, + "rust": true, + "c": true + }, + { + "problem": "Find First And Last Position of Element In Sorted Array", + "pattern": "Binary Search", + "link": "find-first-and-last-position-of-element-in-sorted-array/", + "video": "4sQL7R5ySUU", + "difficulty": "Medium", + "code": "0034-find-first-and-last-position-of-element-in-sorted-array", + "csharp": true, + "python": true, + "kotlin": true, + "cpp": true, + "java": true, + "swift": true, + "javascript": true + }, + { + "problem": "Maximum Number of Removable Characters", + "pattern": "Binary Search", + "link": "maximum-number-of-removable-characters/", + "video": "NMP3nRPyX5g", + "difficulty": "Medium", + "code": "1898-maximum-number-of-removable-characters", + "javascript": true, + "kotlin": true + }, + { + "problem": "Populating Next Right Pointers In Each Node", + "pattern": "Binary Search", + "link": "populating-next-right-pointers-in-each-node/", + "video": "U4hFQCa1Cq0", + "difficulty": "Medium", + "code": "0116-populating-next-right-pointers-in-each-node", + "go": true, + "cpp": true, + "javascript": true, + "kotlin": true + }, + { + "problem": "Search Suggestions System", + "pattern": "Binary Search", + "link": "search-suggestions-system/", + "video": "D4T2N0yAr20", + "difficulty": "Medium", + "code": "1268-search-suggestions-system", + "java": true, + "javascript": true, + "kotlin": true + }, + { + "problem": "Split Array Largest Sum", + "pattern": "Binary Search", + "link": "split-array-largest-sum/", + "video": "YUF3_eBdzsk", + "difficulty": "Hard", + "code": "0410-split-array-largest-sum", + "python": true, + "javascript": true, + "kotlin": true + }, + { + "neetcode150": true, + "problem": "Median of Two Sorted Arrays", + "pattern": "Binary Search", + "link": "median-of-two-sorted-arrays/", + "video": "q6IEA26hvXc", + "difficulty": "Hard", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0004-median-of-two-sorted-arrays", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Reverse Linked List", + "pattern": "Linked List", + "link": "reverse-linked-list/", + "video": "G0_I-ZF0S38", + "difficulty": "Easy", + "python": true, + "cpp": true, + "javascript": true, + "java": true, + "code": "0206-reverse-linked-list", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "scala": true, + "rust": true, + "dart": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Merge Two Sorted Lists", + "pattern": "Linked List", + "link": "merge-two-sorted-lists/", + "video": "XIdigk956u0", + "difficulty": "Easy", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0021-merge-two-sorted-lists", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "scala": true, + "dart": true, + "rust": true + }, + { + "problem": "Palindrome Linked List", + "pattern": "Linked List", + "link": "palindrome-linked-list/", + "video": "yOzXms1J6Nk", + "difficulty": "Easy", + "code": "0234-palindrome-linked-list", + "cpp": true, + "javascript": true, + "python": true, + "go": true, + "java": true, + "kotlin": true, + "c": true + }, + { + "problem": "Remove Linked List Elements", + "pattern": "Linked List", + "link": "remove-linked-list-elements/", + "video": "JI71sxtHTng", + "difficulty": "Easy", + "code": "0203-remove-linked-list-elements", + "javascript": true, + "typescript": true, + "go": true, + "cpp": true, + "java": true, + "python": true, + "kotlin": true + }, + { + "problem": "Remove Duplicates From Sorted List", + "pattern": "Linked List", + "link": "remove-duplicates-from-sorted-list/", + "video": "p10f-VpO4nE", + "difficulty": "Easy", + "code": "0083-remove-duplicates-from-sorted-list", + "cpp": true, + "python": true, + "javascript": true, + "go": true, + "java": true, + "kotlin": true, + "c": true + }, + { + "problem": "Middle of the Linked List", + "pattern": "Linked List", + "link": "middle-of-the-linked-list/", + "video": "A2_ldqM4QcY", + "difficulty": "Easy", + "python": true, + "code": "0876-middle-of-the-linked-list", + "c": true, + "cpp": true, + "csharp": true, + "java": true, + "javascript": true, + "typescript": true, + "go": true, + "kotlin": true, + "rust": true, + "swift": true + }, + { + "problem": "Intersection of Two Linked Lists", + "pattern": "Linked List", + "link": "intersection-of-two-linked-lists/", + "video": "D0X0BONOQhI", + "difficulty": "Easy", + "code": "0160-intersection-of-two-linked-lists", + "python": true, + "javascript": true, + "java": true, + "go": true, + "kotlin": true, + "c": true, + "cpp": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Reorder List", + "pattern": "Linked List", + "link": "reorder-list/", + "video": "S5bfdUTrKLM", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0143-reorder-list", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "kotlin": true + }, + { + "problem": "Maximum Twin Sum Of A Linked List", + "pattern": "Linked List", + "link": "maximum-twin-sum-of-a-linked-list/", + "video": "doj95MelfSA", + "difficulty": "Medium", + "code": "2130-maximum-twin-sum-of-a-linked-list", + "python": true, + "java": true, + "kotlin": true, + "cpp": true, + "javascript": true, + "go": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Remove Nth Node From End of List", + "pattern": "Linked List", + "link": "remove-nth-node-from-end-of-list/", + "video": "XVuQxVej6y8", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0019-remove-nth-node-from-end-of-list", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "swift": true, + "kotlin": true, + "rust": true + }, + { + "problem": "Swapping Nodes in a Linked List", + "pattern": "Linked List", + "link": "swapping-nodes-in-a-linked-list/", + "video": "4LsrgMyQIjQ", + "difficulty": "Medium", + "code": "1721-swapping-nodes-in-a-linked-list", + "kotlin": true, + "cpp": true, + "java": true, + "python": true, + "go": true + }, + { + "problem": "LFU Cache", + "pattern": "Linked List", + "link": "lfu-cache/", + "video": "bLEIHn-DgoA", + "difficulty": "Hard", + "code": "0460-lfu-cache", + "javascript": true, + "kotlin": true + }, + { + "neetcode150": true, + "problem": "Copy List With Random Pointer", + "pattern": "Linked List", + "link": "copy-list-with-random-pointer/", + "video": "5Y2EiZST97Y", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0138-copy-list-with-random-pointer", + "c": true, + "csharp": true, + "typescript": true, + "ruby": true, + "swift": true, + "kotlin": true, + "go": true + }, + { + "problem": "Design Linked List", + "pattern": "Linked List", + "link": "design-linked-list/", + "video": "Wf4QhpdVFQo", + "difficulty": "Medium", + "python": true, + "code": "0707-design-linked-list", + "go": true, + "kotlin": true, + "c": true, + "java": true + }, + { + "problem": "Design Browser History", + "pattern": "Linked List", + "link": "design-browser-history/", + "video": "i1G-kKnBu8k", + "difficulty": "Medium", + "python": true, + "code": "1472-design-browser-history", + "javascript": true, + "typescript": true, + "go": true, + "rust": true, + "java": true, + "kotlin": true + }, + { + "neetcode150": true, + "problem": "Add Two Numbers", + "pattern": "Linked List", + "link": "add-two-numbers/", + "video": "wgFPrzTjm7s", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0002-add-two-numbers", + "c": true, + "csharp": true, + "typescript": true, + "ruby": true, + "swift": true, + "kotlin": true, + "scala": true, + "go": true, + "rust": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Linked List Cycle", + "pattern": "Linked List", + "link": "linked-list-cycle/", + "video": "gBTe7lFR3vc", + "difficulty": "Easy", + "python": true, + "cpp": true, + "javascript": true, + "java": true, + "code": "0141-linked-list-cycle", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "scala": true + }, + { + "neetcode150": true, + "problem": "Find The Duplicate Number", + "pattern": "Linked List", + "link": "find-the-duplicate-number/", + "video": "wjYnzkAhcNk", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0287-find-the-duplicate-number", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true + }, + { + "problem": "Swap Nodes In Pairs", + "pattern": "Linked List", + "link": "swap-nodes-in-pairs/", + "video": "o811TZLAWOo", + "difficulty": "Medium", + "code": "0024-swap-nodes-in-pairs", + "python": true, + "go": true, + "java": true, + "kotlin": true, + "c": true, + "cpp": true + }, + { + "problem": "Sort List", + "pattern": "Linked List", + "link": "sort-list/", + "video": "TGveA1oFhrc", + "difficulty": "Medium", + "code": "0148-sort-list", + "java": true, + "python": true, + "c": true, + "cpp": true, + "kotlin": true + }, + { + "problem": "Partition List", + "pattern": "Linked List", + "link": "partition-list/", + "video": "KT1iUciJr4g", + "difficulty": "Medium", + "code": "0086-partition-list", + "python": true, + "java": true, + "kotlin": true + }, + { + "problem": "Rotate List", + "pattern": "Linked List", + "link": "rotate-list/", + "video": "UcGtPs2LE_c", + "difficulty": "Medium", + "code": "0061-rotate-list", + "python": true, + "cpp": true, + "java": true, + "kotlin": true + }, + { + "problem": "Reverse Linked List II", + "pattern": "Linked List", + "link": "reverse-linked-list-ii/", + "video": "RF_M9tX4Eag", + "difficulty": "Medium", + "code": "0092-reverse-linked-list-ii", + "python": true, + "javascript": true, + "cpp": true, + "java": true, + "kotlin": true + }, + { + "problem": "Design Circular Queue", + "pattern": "Linked List", + "link": "design-circular-queue/", + "video": "aBbsfn863oA", + "difficulty": "Medium", + "code": "0622-design-circular-queue", + "python": true, + "go": true, + "kotlin": true, + "java": true + }, + { + "problem": "Insertion Sort List", + "pattern": "Linked List", + "link": "insertion-sort-list/", + "video": "Kk6mXAzqX3Y", + "difficulty": "Medium", + "code": "0147-insertion-sort-list", + "python": true, + "cpp": true, + "kotlin": true + }, + { + "problem": "Split Linked List in Parts", + "pattern": "Linked List", + "link": "split-linked-list-in-parts/", + "video": "-OTlqdrxrVI", + "difficulty": "Medium", + "code": "0725-split-linked-list-in-parts", + "java": true, + "kotlin": true + }, + { + "neetcode150": true, + "problem": "LRU Cache", + "pattern": "Linked List", + "link": "lru-cache/", + "video": "7ABFKPK2hD4", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0146-lru-cache", + "c": true, + "csharp": true, + "ruby": true, + "kotlin": true, + "go": true, + "typescript": true, + "swift": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Merge K Sorted Lists", + "pattern": "Linked List", + "link": "merge-k-sorted-lists/", + "video": "q5a5OiGbT6Q", + "difficulty": "Hard", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0023-merge-k-sorted-lists", + "c": true, + "csharp": true, + "typescript": true, + "kotlin": true, + "go": true, + "swift": true, + "rust": true + }, + { + "neetcode150": true, + "problem": "Reverse Nodes In K Group", + "pattern": "Linked List", + "link": "reverse-nodes-in-k-group/", + "video": "1UOPsfP85V4", + "difficulty": "Hard", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0025-reverse-nodes-in-k-group", + "c": true, + "csharp": true, + "typescript": true, + "kotlin": true, + "go": true, + "swift": true, + "rust": true + }, + { + "problem": "Binary Tree Inorder Traversal", + "pattern": "Trees", + "link": "binary-tree-inorder-traversal/", + "video": "g_S5WuasWUE", + "difficulty": "Easy", + "code": "0094-binary-tree-inorder-traversal", + "c": true, + "python": true, + "javascript": true, + "typescript": true, + "ruby": true, + "csharp": true, + "java": true, + "go": true, + "swift": true, + "kotlin": true, + "rust": true, + "cpp": true + }, + { + "problem": "Binary Tree Preorder Traversal", + "pattern": "Trees", + "link": "binary-tree-preorder-traversal/", + "video": "afTpieEZXck", + "difficulty": "Easy", + "code": "0144-binary-tree-preorder-traversal", + "python": true, + "cpp": true, + "typescript": true, + "kotlin": true + }, + { + "problem": "Binary Tree Postorder Traversal", + "pattern": "Trees", + "link": "binary-tree-postorder-traversal/", + "video": "QhszUQhGGlA", + "difficulty": "Easy", + "code": "0145-binary-tree-postorder-traversal", + "python": true, + "java": true, + "cpp": true, + "typescript": true, + "kotlin": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Invert Binary Tree", + "pattern": "Trees", + "link": "invert-binary-tree/", + "video": "OnSn2XEQ4MY", + "difficulty": "Easy", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0226-invert-binary-tree", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Maximum Depth of Binary Tree", + "pattern": "Trees", + "link": "maximum-depth-of-binary-tree/", + "video": "hTM3phVI6YQ", + "difficulty": "Easy", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0104-maximum-depth-of-binary-tree", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "problem": "Diameter of Binary Tree", + "pattern": "Trees", + "link": "diameter-of-binary-tree/", + "video": "bkxqA8Rfv04", + "difficulty": "Easy", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0543-diameter-of-binary-tree", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "problem": "Balanced Binary Tree", + "pattern": "Trees", + "link": "balanced-binary-tree/", + "video": "QfJsau0ItOY", + "difficulty": "Easy", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0110-balanced-binary-tree", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Same Tree", + "pattern": "Trees", + "link": "same-tree/", + "video": "vRbbcKXCxOw", + "difficulty": "Easy", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0100-same-tree", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Subtree of Another Tree", + "pattern": "Trees", + "link": "subtree-of-another-tree/", + "video": "E36O5SWp-LE", + "difficulty": "Easy", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0572-subtree-of-another-tree", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "scala": true, + "rust": true + }, + { + "problem": "Convert Sorted Array to Binary Search Tree", + "pattern": "Trees", + "link": "convert-sorted-array-to-binary-search-tree/", + "video": "0K0uCMYq5ng", + "difficulty": "Easy", + "code": "0108-convert-sorted-array-to-binary-search-tree", + "c": true, + "javascript": true, + "go": true, + "kotlin": true, + "java": true, + "python": true + }, + { + "problem": "Merge Two Binary Trees", + "pattern": "Trees", + "link": "merge-two-binary-trees/", + "video": "QHH6rIK3dDQ", + "difficulty": "Easy", + "code": "0617-merge-two-binary-trees", + "c": true, + "java": true, + "python": true, + "javascript": true, + "go": true, + "dart": true, + "kotlin": true, + "cpp": true + }, + { + "problem": "Path Sum", + "pattern": "Trees", + "link": "path-sum/", + "video": "LSKQyOz_P8I", + "difficulty": "Easy", + "code": "0112-path-sum", + "go": true, + "c": true, + "csharp": true, + "javascript": true, + "swift": true, + "java": true, + "python": true, + "kotlin": true + }, + { + "problem": "Construct String From Binary Tree", + "pattern": "Trees", + "link": "construct-string-from-binary-tree/", + "video": "b1WpYxnuebQ", + "difficulty": "Easy", + "code": "0606-construct-string-from-binary-tree", + "java": true, + "python": true, + "kotlin": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Lowest Common Ancestor of a Binary Search Tree", + "pattern": "Trees", + "link": "lowest-common-ancestor-of-a-binary-search-tree/", + "video": "gs2LMfuOR9k", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0235-lowest-common-ancestor-of-a-binary-search-tree", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "scala": true, + "rust": true + }, + { + "problem": "Insert into a Binary Search Tree", + "pattern": "Trees", + "link": "insert-into-a-binary-search-tree/", + "video": "Cpg8f79luEA", + "difficulty": "Medium", + "python": true, + "code": "0701-insert-into-a-binary-search-tree", + "kotlin": true, + "cpp": true, + "csharp": true, + "java": true, + "typescript": true + }, + { + "problem": "Delete Node in a BST", + "pattern": "Trees", + "link": "delete-node-in-a-bst/", + "video": "LFzAoJJt92M", + "difficulty": "Medium", + "python": true, + "code": "0450-delete-node-in-a-bst", + "kotlin": true, + "cpp": true, + "java": true, + "typescript": true, + "rust": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Binary Tree Level Order Traversal", + "pattern": "Trees", + "link": "binary-tree-level-order-traversal/", + "video": "6ZnyEApgFYg", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0102-binary-tree-level-order-traversal", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "problem": "Binary Tree Right Side View", + "pattern": "Trees", + "link": "binary-tree-right-side-view/", + "video": "d4zLyf32e3I", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0199-binary-tree-right-side-view", + "c": true, + "csharp": true, + "typescript": true, + "swift": true, + "kotlin": true, + "go": true, + "rust": true + }, + { + "problem": "Minimum Distance between BST Nodes", + "pattern": "Trees", + "link": "minimum-distance-between-bst-nodes/", + "video": "joxx4hTYwcw", + "difficulty": "Easy", + "code": "0783-minimum-distance-between-bst-nodes", + "kotlin": true, + "python": true + }, + { + "problem": "Symmetric Tree ", + "pattern": "Trees", + "link": "symmetric-tree/", + "video": "Mao9uzxwvmc", + "difficulty": "Easy", + "code": "0101-symmetric-tree", + "kotlin": true, + "python": true + }, + { + "problem": "Minimum Time to Collect All Apples in a Tree", + "pattern": "Trees", + "link": "minimum-time-to-collect-all-apples-in-a-tree/", + "video": "Xdt5Z583auM", + "difficulty": "Medium", + "code": "1443-minimum-time-to-collect-all-apples-in-a-tree", + "rust": true, + "kotlin": true + }, + { + "problem": "Binary Tree Zigzag Level Order Traversal", + "pattern": "Trees", + "link": "binary-tree-zigzag-level-order-traversal/", + "video": "igbboQbiwqw", + "difficulty": "Medium", + "code": "0103-binary-tree-zigzag-level-order-traversal", + "kotlin": true, + "cpp": true, + "python": true + }, + { + "problem": "Construct Quad Tree", + "pattern": "Trees", + "link": "construct-quad-tree/", + "video": "UQ-1sBMV0v4", + "difficulty": "Medium", + "code": "0427-construct-quad-tree", + "kotlin": true + }, + { + "problem": "Find Duplicate Subtrees", + "pattern": "Trees", + "link": "find-duplicate-subtrees/", + "video": "kn0Z5_qPPzY", + "difficulty": "Medium", + "code": "0652-find-duplicate-subtrees", + "kotlin": true + }, + { + "problem": "Check Completeness of a Binary Tree", + "pattern": "Trees", + "link": "check-completeness-of-a-binary-tree/", + "video": "olbiZ-EOSig", + "difficulty": "Medium", + "code": "0958-check-completeness-of-a-binary-tree", + "kotlin": true, + "cpp": true + }, + { + "problem": "Construct Binary Tree from Inorder and Postorder Traversal", + "pattern": "Trees", + "link": "construct-binary-tree-from-inorder-and-postorder-traversal/", + "video": "vm63HuIU7kw", + "difficulty": "Medium", + "code": "0106-construct-binary-tree-from-inorder-and-postorder-traversal", + "java": true, + "kotlin": true + }, + { + "problem": "Maximum Width of Binary Tree ", + "pattern": "Trees", + "link": "maximum-width-of-binary-tree/", + "video": "FPzLE2L7uHs", + "difficulty": "Medium", + "code": "0662-maximum-width-of-binary-tree", + "java": true, + "kotlin": true + }, + { + "problem": "Time Needed to Inform All Employees ", + "pattern": "Trees", + "link": "time-needed-to-inform-all-employees/", + "video": "zdBYi0p4L5Q", + "difficulty": "Medium", + "code": "1376-time-needed-to-inform-all-employees", + "kotlin": true + }, + { + "neetcode150": true, + "problem": "Count Good Nodes In Binary Tree", + "pattern": "Trees", + "link": "count-good-nodes-in-binary-tree/", + "video": "7cp5imvDzl4", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "1448-count-good-nodes-in-binary-tree", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "swift": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Validate Binary Search Tree", + "pattern": "Trees", + "link": "validate-binary-search-tree/", + "video": "s6ATEkipzow", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0098-validate-binary-search-tree", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "swift": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Kth Smallest Element In a Bst", + "pattern": "Trees", + "link": "kth-smallest-element-in-a-bst/", + "video": "5LUXSvjmGCw", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0230-kth-smallest-element-in-a-bst", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "swift": true, + "kotlin": true, + "scala": true, + "rust": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Construct Binary Tree From Preorder And Inorder Traversal", + "pattern": "Trees", + "link": "construct-binary-tree-from-preorder-and-inorder-traversal/", + "video": "ihj4IQGZ2zc", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0105-construct-binary-tree-from-preorder-and-inorder-traversal", + "c": true, + "csharp": true, + "typescript": true, + "kotlin": true, + "go": true + }, + { + "problem": "Unique Binary Search Trees", + "pattern": "Trees", + "link": "unique-binary-search-trees/", + "video": "Ox0TenN3Zpg", + "difficulty": "Medium", + "code": "0096-unique-binary-search-trees", + "c": true, + "java": true, + "kotlin": true + }, + { + "problem": "Unique Binary Search Trees II", + "pattern": "Trees", + "link": "unique-binary-search-trees-ii/", + "video": "m907FlQa2Yc", + "difficulty": "Medium", + "code": "0095-unique-binary-search-trees-ii", + "kotlin": true + }, + { + "problem": "Sum Root to Leaf Numbers", + "pattern": "Trees", + "link": "sum-root-to-leaf-numbers/", + "video": "Jk16lZGFWxE", + "difficulty": "Medium", + "code": "0129-sum-root-to-leaf-numbers", + "c": true, + "java": true, + "cpp": true, + "kotlin": true + }, + { + "problem": "House Robber III", + "pattern": "Trees", + "link": "house-robber-iii/", + "video": "nHR8ytpzz7c", + "difficulty": "Medium", + "code": "0337-house-robber-iii", + "java": true, + "kotlin": true + }, + { + "problem": "Flip Equivalent Binary Trees", + "pattern": "Trees", + "link": "flip-equivalent-binary-trees/", + "video": "izRDc1il9Pk", + "difficulty": "Medium", + "code": "0951-flip-equivalent-binary-trees", + "java": true, + "kotlin": true + }, + { + "problem": "Operations On Tree", + "pattern": "Trees", + "link": "operations-on-tree/", + "video": "qK4PtjrVD0U", + "difficulty": "Medium", + "code": "1993-operations-on-tree", + "kotlin": true + }, + { + "problem": "All Possible Full Binary Trees", + "pattern": "Trees", + "link": "all-possible-full-binary-trees/", + "video": "nZtrZPTTCAo", + "difficulty": "Medium", + "code": "0894-all-possible-full-binary-trees", + "python": true, + "java": true, + "kotlin": true + }, + { + "problem": "Find Bottom Left Tree Value", + "pattern": "Trees", + "link": "find-bottom-left-tree-value/", + "video": "u_by_cTsNJA", + "difficulty": "Medium", + "code": "0513-find-bottom-left-tree-value", + "java": true, + "kotlin": true + }, + { + "problem": "Trim a Binary Search Tree", + "pattern": "Trees", + "link": "trim-a-binary-search-tree/", + "video": "jwt5mTjEXGc", + "difficulty": "Medium", + "code": "0669-trim-a-binary-search-tree", + "python": true, + "javascript": true, + "typescript": true, + "go": true, + "java": true, + "kotlin": true + }, + { + "problem": "Binary Search Tree Iterator", + "pattern": "Trees", + "link": "binary-search-tree-iterator/", + "video": "RXy5RzGF5wo", + "difficulty": "Medium", + "code": "0173-binary-search-tree-iterator", + "java": true, + "javascript": true, + "kotlin": true + }, + { + "problem": "Convert Bst to Greater Tree", + "pattern": "Trees", + "link": "convert-bst-to-greater-tree/", + "video": "7vVEJwVvAlI", + "difficulty": "Medium", + "code": "0538-convert-bst-to-greater-tree", + "cpp": true, + "kotlin": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Binary Tree Maximum Path Sum", + "pattern": "Trees", + "link": "binary-tree-maximum-path-sum/", + "video": "Hr5cWUld4vU", + "difficulty": "Hard", + "code": "0124-binary-tree-maximum-path-sum", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "swift": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Serialize And Deserialize Binary Tree", + "pattern": "Trees", + "link": "serialize-and-deserialize-binary-tree/", + "video": "u4JAi2JJhI8", + "difficulty": "Hard", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0297-serialize-and-deserialize-binary-tree", + "c": true, + "csharp": true, + "kotlin": true, + "go": true, + "typescript": true, + "swift": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Implement Trie Prefix Tree", + "pattern": "Tries", + "link": "implement-trie-prefix-tree/", + "video": "oobqoCJlHA0", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0208-implement-trie-prefix-tree", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true, + "scala": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Design Add And Search Words Data Structure", + "pattern": "Tries", + "link": "design-add-and-search-words-data-structure/", + "video": "BTf05gs_8iU", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0211-design-add-and-search-words-data-structure", + "csharp": true, + "typescript": true, + "ruby": true, + "kotlin": true, + "rust": true, + "go": true, + "c": true, + "scala": true + }, + { + "problem": "Extra Characters in a String", + "pattern": "Tries", + "link": "extra-characters-in-a-string/", + "video": "ONstwO1cD7c", + "difficulty": "Medium", + "code": "2707-extra-characters-in-a-string", + "cpp": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Word Search II", + "pattern": "Tries", + "link": "word-search-ii/", + "video": "asbcE9mZz_U", + "difficulty": "Hard", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0212-word-search-ii", + "csharp": true, + "swift": true, + "kotlin": true, + "rust": true, + "go": true, + "c": true + }, + { + "neetcode150": true, + "problem": "Kth Largest Element In a Stream", + "pattern": "Heap / Priority Queue", + "link": "kth-largest-element-in-a-stream/", + "video": "hOjcdrqMoQ8", + "difficulty": "Easy", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0703-kth-largest-element-in-a-stream", + "c": true, + "csharp": true, + "ruby": true, + "swift": true, + "go": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "problem": "Last Stone Weight", + "pattern": "Heap / Priority Queue", + "link": "last-stone-weight/", + "video": "B-QCq79-Vfw", + "difficulty": "Easy", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "1046-last-stone-weight", + "csharp": true, + "typescript": true, + "ruby": true, + "kotlin": true, + "go": true, + "rust": true, + "c": true + }, + { + "neetcode150": true, + "problem": "K Closest Points to Origin", + "pattern": "Heap / Priority Queue", + "link": "k-closest-points-to-origin/", + "video": "rI2EBUEMfTk", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0973-k-closest-points-to-origin", + "csharp": true, + "kotlin": true, + "go": true, + "rust": true, + "c": true + }, + { + "neetcode150": true, + "problem": "Kth Largest Element In An Array", + "pattern": "Heap / Priority Queue", + "link": "kth-largest-element-in-an-array/", + "video": "XEmy13g1Qxc", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0215-kth-largest-element-in-an-array", + "csharp": true, + "typescript": true, + "kotlin": true, + "go": true, + "scala": true, + "c": true, + "rust": true + }, + { + "neetcode150": true, + "problem": "Task Scheduler", + "pattern": "Heap / Priority Queue", + "link": "task-scheduler/", + "video": "s8p8ukTyA2I", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0621-task-scheduler", + "csharp": true, + "typescript": true, + "kotlin": true, + "rust": true, + "c": true + }, + { + "neetcode150": true, + "problem": "Design Twitter", + "pattern": "Heap / Priority Queue", + "link": "design-twitter/", + "video": "pNichitDD2E", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0355-design-twitter", + "csharp": true, + "go": true, + "kotlin": true + }, + { + "problem": "Minimize Deviation in Array", + "pattern": "Heap / Priority Queue", + "link": "minimize-deviation-in-array/", + "video": "boHNFptxo2A", + "difficulty": "Hard", + "code": "1675-minimize-deviation-in-array", + "kotlin": true, + "cpp": true + }, + { + "problem": "Maximum Subsequence Score", + "pattern": "Heap / Priority Queue", + "link": "maximum-subsequence-score/", + "video": "ax1DKi5lJwk", + "difficulty": "Medium", + "code": "2542-maximum-subsequence-score", + "kotlin": true, + "cpp": true + }, + { + "problem": "Single Threaded Cpu", + "pattern": "Heap / Priority Queue", + "link": "single-threaded-cpu/", + "video": "RR1n-d4oYqE", + "difficulty": "Medium", + "code": "1834-single-threaded-cpu", + "java": true, + "python": true, + "javascript": true, + "kotlin": true, + "rust": true + }, + { + "problem": "Seat Reservation Manager", + "pattern": "Heap / Priority Queue", + "link": "seat-reservation-manager/", + "video": "ahobllKXEEY", + "difficulty": "Medium", + "code": "1845-seat-reservation-manager", + "python": true, + "cpp": true, + "kotlin": true + }, + { + "problem": "Process Tasks Using Servers", + "pattern": "Heap / Priority Queue", + "link": "process-tasks-using-servers/", + "video": "XKA22PecuMQ", + "difficulty": "Medium", + "code": "1882-process-tasks-using-servers", + "kotlin": true + }, + { + "problem": "Find The Kth Largest Integer In The Array", + "pattern": "Heap / Priority Queue", + "link": "find-the-kth-largest-integer-in-the-array/", + "video": "lRCaNiqO3xI", + "difficulty": "Medium", + "code": "1985-find-the-kth-largest-integer-in-the-array", + "java": true, + "python": true, + "swift": true, + "cpp": true, + "go": true, + "kotlin": true + }, + { + "problem": "Reorganize String", + "pattern": "Heap / Priority Queue", + "link": "reorganize-string/", + "video": "2g_b1aYTHeg", + "difficulty": "Medium", + "code": "0767-reorganize-string", + "java": true, + "python": true, + "cpp": true, + "kotlin": true + }, + { + "problem": "Longest Happy String", + "pattern": "Heap / Priority Queue", + "link": "longest-happy-string/", + "video": "8u-H6O_XQKE", + "difficulty": "Medium", + "code": "1405-longest-happy-string", + "kotlin": true + }, + { + "problem": "Car Pooling", + "pattern": "Heap / Priority Queue", + "link": "car-pooling/", + "video": "08sn_w4LWEE", + "difficulty": "Medium", + "code": "1094-car-pooling", + "csharp": true, + "cpp": true, + "kotlin": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Find Median From Data Stream", + "pattern": "Heap / Priority Queue", + "link": "find-median-from-data-stream/", + "video": "itmhHWaHupI", + "difficulty": "Hard", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0295-find-median-from-data-stream", + "csharp": true, + "kotlin": true, + "go": true, + "typescript": true + }, + { + "problem": "Maximum Performance of a Team", + "pattern": "Heap / Priority Queue", + "link": "maximum-performance-of-a-team/", + "video": "Y7UTvogADH0", + "difficulty": "Hard", + "code": "1383-maximum-performance-of-a-team", + "csharp": true, + "python": true, + "kotlin": true + }, + { + "problem": "IPO", + "pattern": "Heap / Priority Queue", + "link": "ipo/", + "video": "1IUzNJ6TPEM", + "difficulty": "Hard", + "code": "0502-ipo", + "python": true, + "kotlin": true + }, + { + "neetcode150": true, + "problem": "Subsets", + "pattern": "Backtracking", + "link": "subsets/", + "video": "REOH22Xwdkk", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0078-subsets", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Combination Sum", + "pattern": "Backtracking", + "link": "combination-sum/", + "video": "GBKI9VSKdGg", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0039-combination-sum", + "csharp": true, + "typescript": true, + "go": true, + "kotlin": true, + "ruby": true, + "rust": true, + "c": true, + "swift": true + }, + { + "problem": "Combinations", + "pattern": "Backtracking", + "link": "combinations/", + "video": "q0s6m7AiM7o", + "difficulty": "Medium", + "code": "0077-combinations", + "python": true, + "go": true, + "kotlin": true, + "java": true + }, + { + "neetcode150": true, + "problem": "Permutations", + "pattern": "Backtracking", + "link": "permutations/", + "video": "s7AvT7cGdSo", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0046-permutations", + "csharp": true, + "typescript": true, + "go": true, + "swift": true, + "kotlin": true, + "ruby": true, + "rust": true, + "c": true + }, + { + "neetcode150": true, + "problem": "Subsets II", + "pattern": "Backtracking", + "link": "subsets-ii/", + "video": "Vn2v6ajA7U0", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0090-subsets-ii", + "csharp": true, + "typescript": true, + "go": true, + "kotlin": true, + "ruby": true, + "rust": true, + "c": true + }, + { + "neetcode150": true, + "problem": "Combination Sum II", + "pattern": "Backtracking", + "link": "combination-sum-ii/", + "video": "rSA3t6BDDwg", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0040-combination-sum-ii", + "csharp": true, + "typescript": true, + "go": true, + "kotlin": true, + "ruby": true, + "c": true + }, + { + "problem": "Permutations II", + "pattern": "Backtracking", + "link": "permutations-ii/", + "video": "qhBVWf0YafA", + "difficulty": "Medium", + "code": "0047-permutations-ii", + "python": true, + "go": true, + "kotlin": true, + "java": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Word Search", + "pattern": "Backtracking", + "link": "word-search/", + "video": "pfiQ_PS1g8E", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0079-word-search", + "c": true, + "csharp": true, + "go": true, + "swift": true, + "kotlin": true, + "rust": true, + "ruby": true + }, + { + "neetcode150": true, + "problem": "Palindrome Partitioning", + "pattern": "Backtracking", + "link": "palindrome-partitioning/", + "video": "3jvWodd7ht0", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0131-palindrome-partitioning", + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "rust": true, + "swift": true, + "kotlin": true + }, + { + "problem": "Restore IP Addresses", + "pattern": "Backtracking", + "link": "restore-ip-addresses/", + "video": "61tN4YEdiTM", + "difficulty": "Medium", + "code": "0093-restore-ip-addresses", + "javascript": true, + "typescript": true, + "go": true, + "rust": true, + "kotlin": true + }, + { + "neetcode150": true, + "problem": "Letter Combinations of a Phone Number", + "pattern": "Backtracking", + "link": "letter-combinations-of-a-phone-number/", + "video": "0snEunUacZY", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0017-letter-combinations-of-a-phone-number", + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "rust": true, + "kotlin": true, + "swift": true + }, + { + "problem": "Matchsticks to Square", + "pattern": "Backtracking", + "link": "matchsticks-to-square/", + "video": "hUe0cUKV-YY", + "difficulty": "Medium", + "code": "0473-matchsticks-to-square", + "cpp": true, + "python": true, + "javascript": true, + "java": true, + "kotlin": true + }, + { + "problem": "Splitting a String Into Descending Consecutive Values", + "pattern": "Backtracking", + "link": "splitting-a-string-into-descending-consecutive-values/", + "video": "eDtMmysldaw", + "difficulty": "Medium", + "code": "1849-splitting-a-string-into-descending-consecutive-values", + "python": true, + "cpp": true, + "kotlin": true + }, + { + "problem": "Find Unique Binary String", + "pattern": "Backtracking", + "link": "find-unique-binary-string/", + "video": "aHqn4Dynd1k", + "difficulty": "Medium", + "code": "1980-find-unique-binary-string", + "python": true, + "kotlin": true, + "java": true + }, + { + "problem": "Maximum Length of a Concatenated String With Unique Characters", + "pattern": "Backtracking", + "link": "maximum-length-of-a-concatenated-string-with-unique-characters/", + "video": "d4SPuvkaeoo", + "difficulty": "Medium", + "code": "1239-maximum-length-of-a-concatenated-string-with-unique-characters", + "python": true, + "kotlin": true + }, + { + "problem": "Partition to K Equal Sum Subsets", + "pattern": "Backtracking", + "link": "partition-to-k-equal-sum-subsets/", + "video": "mBk4I0X46oI", + "difficulty": "Medium", + "code": "0698-partition-to-k-equal-sum-subsets", + "kotlin": true, + "python": true, + "java": true + }, + { + "neetcode150": true, + "problem": "N Queens", + "pattern": "Backtracking", + "link": "n-queens/", + "video": "Ph95IHmRp5M", + "difficulty": "Hard", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0051-n-queens", + "csharp": true, + "typescript": true, + "go": true, + "kotlin": true, + "c": true, + "rust": true + }, + { + "problem": "N Queens II", + "pattern": "Backtracking", + "link": "n-queens-ii/", + "video": "nalYyLZgvCY", + "difficulty": "Hard", + "code": "0052-n-queens-ii", + "c": true, + "cpp": true, + "javascript": true, + "python": true, + "kotlin": true + }, + { + "problem": "Island Perimeter", + "pattern": "Graphs", + "link": "island-perimeter/", + "video": "fISIuAFRM2s", + "difficulty": "Easy", + "code": "0463-island-perimeter", + "c": true, + "cpp": true, + "csharp": true, + "python": true, + "java": true, + "javascript": true, + "go": true, + "kotlin": true + }, + { + "problem": "Verifying An Alien Dictionary", + "pattern": "Graphs", + "link": "verifying-an-alien-dictionary/", + "video": "OVgPAJIyX6o", + "difficulty": "Easy", + "code": "0953-verifying-an-alien-dictionary", + "c": true, + "cpp": true, + "java": true, + "python": true, + "javascript": true, + "go": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Number of Islands", + "pattern": "Graphs", + "link": "number-of-islands/", + "video": "pV2kpPD66nE", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0200-number-of-islands", + "c": true, + "csharp": true, + "typescript": true, + "ruby": true, + "swift": true, + "kotlin": true, + "go": true, + "rust": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Clone Graph", + "pattern": "Graphs", + "link": "clone-graph/", + "video": "mQeF6bN8hMk", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0133-clone-graph", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true + }, + { + "neetcode150": true, + "problem": "Max Area of Island", + "pattern": "Graphs", + "link": "max-area-of-island/", + "video": "iJGr1OtmH0c", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0695-max-area-of-island", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "kotlin": true, + "rust": true + }, + { + "problem": "Count Sub Islands", + "pattern": "Graphs", + "link": "count-sub-islands/", + "video": "mLpW3qfbNJ8", + "difficulty": "Medium", + "code": "1905-count-sub-islands", + "c": true, + "csharp": true, + "python": true, + "cpp": true, + "java": true, + "javascript": true, + "go": true, + "kotlin": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Pacific Atlantic Water Flow", + "pattern": "Graphs", + "link": "pacific-atlantic-water-flow/", + "video": "s-VkcjHqkGI", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0417-pacific-atlantic-water-flow", + "c": true, + "csharp": true, + "kotlin": true, + "typescript": true, + "go": true, + "rust": true + }, + { + "neetcode150": true, + "problem": "Surrounded Regions", + "pattern": "Graphs", + "link": "surrounded-regions/", + "video": "9z2BunfoZ5Y", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0130-surrounded-regions", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "swift": true, + "kotlin": true + }, + { + "problem": "Reorder Routes to Make All Paths Lead to The City Zero", + "pattern": "Graphs", + "link": "reorder-routes-to-make-all-paths-lead-to-the-city-zero/", + "video": "m17yOR5_PpI", + "difficulty": "Medium", + "code": "1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero", + "csharp": true, + "cpp": true, + "kotlin": true, + "java": true + }, + { + "neetcode150": true, + "problem": "Rotting Oranges", + "pattern": "Graphs", + "link": "rotting-oranges/", + "video": "y704fEOx0s0", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0994-rotting-oranges", + "c": true, + "csharp": true, + "typescript": true, + "kotlin": true, + "go": true + }, + { + "neetcode150": true, + "problem": "Walls And Gates", + "premium": true, + "freeLink": "https://www.lintcode.com/problem/663/", + "pattern": "Graphs", + "link": "walls-and-gates/", + "video": "e69C6xhiSQE", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0286-walls-and-gates", + "csharp": true + }, + { + "problem": "Snakes And Ladders", + "pattern": "Graphs", + "link": "snakes-and-ladders/", + "video": "6lH4nO3JfLk", + "difficulty": "Medium", + "code": "0909-snakes-and-ladders", + "csharp": true, + "python": true, + "java": true, + "kotlin": true + }, + { + "problem": "Open The Lock", + "pattern": "Graphs", + "link": "open-the-lock/", + "video": "Pzg3bCDY87w", + "difficulty": "Medium", + "code": "0752-open-the-lock", + "csharp": true, + "java": true, + "python": true, + "kotlin": true + }, + { + "problem": "Find Eventual Safe States", + "pattern": "Graphs", + "link": "find-eventual-safe-states/", + "video": "Re_v0j0CRsg", + "difficulty": "Medium", + "code": "0802-find-eventual-safe-states", + "kotlin": true, + "java": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Course Schedule", + "pattern": "Graphs", + "link": "course-schedule/", + "video": "EgI5nU9etnU", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0207-course-schedule", + "csharp": true, + "typescript": true, + "go": true, + "swift": true, + "kotlin": true, + "c": true + }, + { + "neetcode150": true, + "problem": "Course Schedule II", + "pattern": "Graphs", + "link": "course-schedule-ii/", + "video": "Akt3glAwyfY", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0210-course-schedule-ii", + "csharp": true, + "typescript": true, + "go": true, + "kotlin": true + }, + { + "problem": "Course Schedule IV", + "pattern": "Graphs", + "link": "course-schedule-iv/", + "video": "cEW05ofxhn0", + "difficulty": "Medium", + "python": true, + "code": "1462-course-schedule-iv", + "kotlin": true + }, + { + "problem": "Check if Move Is Legal", + "pattern": "Graphs", + "link": "check-if-move-is-legal/", + "video": "KxK33AcQZpQ", + "difficulty": "Medium", + "code": "1958-check-if-move-is-legal", + "cpp": true, + "java": true, + "python": true, + "javascript": true, + "go": true, + "kotlin": true + }, + { + "problem": "Shortest Bridge", + "pattern": "Graphs", + "link": "shortest-bridge/", + "video": "gkINMhbbIbU", + "difficulty": "Medium", + "code": "0934-shortest-bridge", + "kotlin": true, + "javascript": true + }, + { + "problem": "Shortest Path in Binary Matrix", + "pattern": "Graphs", + "video": "YnxUdAO7TAo", + "link": "shortest-path-in-binary-matrix/", + "difficulty": "Medium", + "code": "1091-shortest-path-in-binary-matrix", + "python": true, + "java": true, + "kotlin": true + }, + { + "neetcode150": true, + "problem": "Redundant Connection", + "pattern": "Graphs", + "link": "redundant-connection/", + "video": "FXWRE67PLL0", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0684-redundant-connection", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Number of Connected Components In An Undirected Graph", + "premium": true, + "freeLink": "https://www.lintcode.com/problem/3651/", + "pattern": "Graphs", + "link": "number-of-connected-components-in-an-undirected-graph/", + "video": "8f1XPm4WOUc", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0323-number-of-connected-components-in-an-undirected-graph", + "csharp": true, + "go": true, + "swift": true, + "kotlin": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Graph Valid Tree", + "premium": true, + "freeLink": "https://www.lintcode.com/problem/178/", + "pattern": "Graphs", + "link": "graph-valid-tree/", + "video": "bXsUuownnoQ", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0261-graph-valid-tree", + "csharp": true, + "typescript": true, + "swift": true + }, + { + "problem": "Accounts Merge", + "pattern": "Graphs", + "link": "accounts-merge/", + "video": "6st4IxEF-90", + "difficulty": "Medium", + "code": "0721-accounts-merge", + "python": true, + "kotlin": true, + "java": true + }, + { + "problem": "Find Closest Node to Given Two Nodes", + "pattern": "Graphs", + "link": "find-closest-node-to-given-two-nodes/", + "video": "AZA8orksO4w", + "difficulty": "Medium", + "code": "2359-find-closest-node-to-given-two-nodes", + "kotlin": true + }, + { + "problem": "As Far from Land as Possible", + "pattern": "Graphs", + "link": "as-far-from-land-as-possible/", + "video": "fjxb1hQfrZk", + "difficulty": "Medium", + "code": "1162-as-far-from-land-as-possible", + "kotlin": true + }, + { + "problem": "Shortest Path with Alternating Colors", + "pattern": "Graphs", + "link": "shortest-path-with-alternating-colors/", + "video": "69rcy6lb-HQ", + "difficulty": "Medium", + "code": "1129-shortest-path-with-alternating-colors", + "kotlin": true + }, + { + "problem": "Minimum Fuel Cost to Report to the Capital", + "pattern": "Graphs", + "link": "minimum-fuel-cost-to-report-to-the-capital/", + "video": "I3lnDUIzIG4", + "difficulty": "Medium", + "code": "2477-minimum-fuel-cost-to-report-to-the-capital", + "kotlin": true, + "java": true + }, + { + "problem": "Minimum Score of a Path Between Two Cities", + "pattern": "Graphs", + "link": "minimum-score-of-a-path-between-two-cities/", + "video": "K7-mXA0irhY", + "difficulty": "Medium", + "code": "2492-minimum-score-of-a-path-between-two-cities", + "kotlin": true + }, + { + "problem": "Number of Closed Islands", + "pattern": "Graphs", + "link": "number-of-closed-islands/", + "video": "X8k48xek8g8", + "difficulty": "Medium", + "code": "1254-number-of-closed-islands", + "kotlin": true + }, + { + "problem": "Number of Enclaves", + "pattern": "Graphs", + "link": "number-of-enclaves/", + "video": "gf0zsh1FIgE", + "difficulty": "Medium", + "code": "1020-number-of-enclaves", + "kotlin": true, + "java": true + }, + { + "problem": "Minimum Number of Vertices to Reach all Nodes", + "pattern": "Graphs", + "link": "minimum-number-of-vertices-to-reach-all-nodes/", + "video": "TLzcum7vrTc", + "difficulty": "Medium", + "code": "1557-minimum-number-of-vertices-to-reach-all-nodes", + "java": true, + "kotlin": true + }, + { + "problem": "Is Graph Bipartite?", + "pattern": "Graphs", + "link": "is-graph-bipartite/", + "video": "mev55LTubBY", + "difficulty": "Medium", + "code": "0785-is-graph-bipartite", + "kotlin": true, + "java": true + }, + { + "problem": "Evaluate Division", + "pattern": "Graphs", + "link": "evaluate-division/", + "video": "Uei1fwDoyKk", + "difficulty": "Medium", + "code": "0399-evaluate-division", + "kotlin": true, + "cpp": true + }, + { + "problem": "Detonate the Maximum Bombs", + "pattern": "Graphs", + "link": "detonate-the-maximum-bombs/", + "video": "8NPbAvVXKR4", + "difficulty": "Medium", + "code": "2101-detonate-the-maximum-bombs", + "kotlin": true + }, + { + "problem": "Largest Color Value in a Directed Graph", + "pattern": "Graphs", + "link": "largest-color-value-in-a-directed-graph/", + "video": "xLoDjKczUSk", + "difficulty": "Hard", + "code": "1857-largest-color-value-in-a-directed-graph", + "kotlin": true + }, + { + "problem": "Minimum Number of Days to Eat N Oranges", + "pattern": "Graphs", + "link": "minimum-number-of-days-to-eat-n-oranges/", + "video": "LziQ6Qx9sks", + "difficulty": "Hard", + "code": "1553-minimum-number-of-days-to-eat-n-oranges", + "kotlin": true + }, + { + "neetcode150": true, + "problem": "Word Ladder", + "pattern": "Graphs", + "link": "word-ladder/", + "video": "h9iTnkgv05E", + "difficulty": "Hard", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0127-word-ladder", + "csharp": true, + "typescript": true, + "kotlin": true, + "go": true, + "rust": true + }, + { + "problem": "Path with Minimum Effort", + "pattern": "Advanced Graphs", + "link": "path-with-minimum-effort/", + "video": "XQlxCCx2vI4", + "difficulty": "Medium", + "code": "1631-path-with-minimum-effort", + "kotlin": true + }, + { + "neetcode150": true, + "problem": "Reconstruct Itinerary", + "pattern": "Advanced Graphs", + "link": "reconstruct-itinerary/", + "video": "ZyB_gQ8vqGA", + "difficulty": "Hard", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0332-reconstruct-itinerary", + "csharp": true, + "kotlin": true, + "go": true, + "c": true, + "rust": true + }, + { + "neetcode150": true, + "problem": "Min Cost to Connect All Points", + "pattern": "Advanced Graphs", + "link": "min-cost-to-connect-all-points/", + "video": "f7JOBJIC-NA", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "1584-min-cost-to-connect-all-points", + "csharp": true, + "ruby": true, + "swift": true, + "go": true, + "kotlin": true + }, + { + "neetcode150": true, + "problem": "Network Delay Time", + "pattern": "Advanced Graphs", + "link": "network-delay-time/", + "video": "EaphyqKU4PQ", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0743-network-delay-time", + "csharp": true, + "go": true, + "kotlin": true + }, + { + "problem": "Path with Maximum Probability", + "pattern": "Advanced Graphs", + "link": "path-with-maximum-probability/", + "video": "kPsDTGcrzGM", + "difficulty": "Medium", + "python": true, + "code": "1514-path-with-maximum-probability", + "java": true, + "javascript": true, + "kotlin": true, + "cpp": true + }, + { + "neetcode150": true, + "problem": "Swim In Rising Water", + "pattern": "Advanced Graphs", + "link": "swim-in-rising-water/", + "video": "amvrKlMLuGY", + "difficulty": "Hard", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0778-swim-in-rising-water", + "csharp": true, + "go": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Alien Dictionary", + "premium": true, + "freeLink": "https://www.lintcode.com/problem/892/", + "pattern": "Advanced Graphs", + "link": "alien-dictionary/", + "video": "6kTZYvNNyps", + "difficulty": "Hard", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0269-alien-dictionary", + "csharp": true + }, + { + "neetcode150": true, + "problem": "Cheapest Flights Within K Stops", + "pattern": "Advanced Graphs", + "link": "cheapest-flights-within-k-stops/", + "video": "5eIK3zUdYmE", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0787-cheapest-flights-within-k-stops", + "csharp": true, + "typescript": true, + "go": true, + "kotlin": true + }, + { + "problem": "Number of Good Paths", + "pattern": "Advanced Graphs", + "link": "number-of-good-paths/", + "video": "rv2GBYQm7xM", + "difficulty": "Hard", + "code": "2421-number-of-good-paths", + "javascript": true, + "typescript": true, + "go": true, + "rust": true, + "kotlin": true + }, + { + "problem": "Remove Max Number of Edges to Keep Graph Fully Traversable", + "pattern": "Advanced Graphs", + "link": "remove-max-number-of-edges-to-keep-graph-fully-traversable/", + "video": "booGwg5wYm4", + "difficulty": "Hard", + "code": "1579-remove-max-number-of-edges-to-keep-graph-fully-traversable", + "kotlin": true + }, + { + "problem": "Find Critical and Pseudo Critical Edges in Minimum Spanning Tree", + "pattern": "Advanced Graphs", + "link": "find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/", + "video": "83JnUxrLKJU", + "difficulty": "Hard", + "code": "1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree", + "python": true, + "kotlin": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Climbing Stairs", + "pattern": "1-D Dynamic Programming", + "link": "climbing-stairs/", + "video": "Y0lT9Fck7qI", + "difficulty": "Easy", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0070-climbing-stairs", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true, + "dart": true + }, + { + "neetcode150": true, + "problem": "Min Cost Climbing Stairs", + "pattern": "1-D Dynamic Programming", + "link": "min-cost-climbing-stairs/", + "code": "0746-min-cost-climbing-stairs", + "video": "ktmzAZWkEZ0", + "difficulty": "Easy", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true, + "scala": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "House Robber", + "pattern": "1-D Dynamic Programming", + "link": "house-robber/", + "video": "73r3KWiEvyk", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0198-house-robber", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true, + "scala": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "House Robber II", + "pattern": "1-D Dynamic Programming", + "link": "house-robber-ii/", + "video": "rWAJCfYYOvM", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0213-house-robber-ii", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true, + "scala": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Longest Palindromic Substring", + "pattern": "1-D Dynamic Programming", + "link": "longest-palindromic-substring/", + "video": "XYQecbcd6_c", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0005-longest-palindromic-substring", + "c": true, + "csharp": true, + "typescript": true, + "rust": true, + "go": true, + "kotlin": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Palindromic Substrings", + "pattern": "1-D Dynamic Programming", + "link": "palindromic-substrings/", + "video": "4RACzI5-du8", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0647-palindromic-substrings", + "c": true, + "csharp": true, + "typescript": true, + "rust": true, + "go": true, + "kotlin": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Decode Ways", + "pattern": "1-D Dynamic Programming", + "link": "decode-ways/", + "video": "6aEyTjOwlJU", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0091-decode-ways", + "c": true, + "csharp": true, + "typescript": true, + "kotlin": true, + "scala": true, + "go": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Coin Change", + "pattern": "1-D Dynamic Programming", + "link": "coin-change/", + "video": "H9bfqozjoqs", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0322-coin-change", + "c": true, + "csharp": true, + "typescript": true, + "kotlin": true, + "rust": true, + "go": true, + "scala": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Maximum Product Subarray", + "pattern": "1-D Dynamic Programming", + "link": "maximum-product-subarray/", + "video": "lXVy6YWFcRM", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0152-maximum-product-subarray", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Word Break", + "pattern": "1-D Dynamic Programming", + "link": "word-break/", + "video": "Sx9NNgInc3A", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0139-word-break", + "csharp": true, + "typescript": true, + "go": true, + "kotlin": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Longest Increasing Subsequence", + "pattern": "1-D Dynamic Programming", + "link": "longest-increasing-subsequence/", + "video": "cjWnW0hdF1Y", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0300-longest-increasing-subsequence", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "problem": "Partition Equal Subset Sum", + "pattern": "1-D Dynamic Programming", + "link": "partition-equal-subset-sum/", + "video": "IsvocB5BJhw", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0416-partition-equal-subset-sum", + "csharp": true, + "go": true, + "kotlin": true, + "c": true + }, + { + "problem": "Triangle", + "pattern": "1-D Dynamic Programming", + "link": "triangle/", + "video": "OM1MTokvxs4", + "difficulty": "Medium", + "code": "0120-triangle", + "cpp": true, + "java": true, + "python": true, + "kotlin": true, + "c": true + }, + { + "problem": "Delete And Earn", + "pattern": "1-D Dynamic Programming", + "link": "delete-and-earn/", + "video": "7FCemBxvGw0", + "difficulty": "Medium", + "code": "0740-delete-and-earn", + "python": true, + "go": true, + "kotlin": true, + "c": true, + "cpp": true + }, + { + "problem": "Paint House", + "pattern": "1-D Dynamic Programming", + "link": "paint-house/", + "video": "-w67-4tnH5U", + "difficulty": "Medium", + "code": "0256-paint-house", + "csharp": true + }, + { + "problem": "Combination Sum IV", + "pattern": "1-D Dynamic Programming", + "link": "combination-sum-iv/", + "video": "dw2nMCxG0ik", + "difficulty": "Medium", + "code": "0377-combination-sum-iv", + "python": true, + "cpp": true, + "kotlin": true, + "c": true, + "java": true + }, + { + "problem": "Perfect Squares", + "pattern": "1-D Dynamic Programming", + "link": "perfect-squares/", + "video": "HLZLwjzIVGo", + "difficulty": "Medium", + "code": "0279-perfect-squares", + "java": true, + "go": true, + "cpp": true, + "kotlin": true, + "c": true + }, + { + "problem": "Check if There is a Valid Partition For The Array", + "pattern": "1-D Dynamic Programming", + "link": "check-if-there-is-a-valid-partition-for-the-array/", + "video": "OxXPiwWFdTI", + "difficulty": "Medium", + "code": "2369-check-if-there-is-a-valid-partition-for-the-array", + "kotlin": true + }, + { + "problem": "Maximum Subarray Min Product", + "pattern": "1-D Dynamic Programming", + "link": "maximum-subarray-min-product/", + "video": "YLesLbNkyjA", + "difficulty": "Medium", + "code": "1856-maximum-subarray-min-product", + "kotlin": true, + "c": true, + "java": true + }, + { + "problem": "Minimum Cost For Tickets", + "pattern": "1-D Dynamic Programming", + "link": "minimum-cost-for-tickets/", + "video": "4pY1bsBpIY4", + "difficulty": "Medium", + "code": "0983-minimum-cost-for-tickets", + "cpp": true, + "kotlin": true, + "c": true + }, + { + "problem": "Integer Break", + "pattern": "1-D Dynamic Programming", + "link": "integer-break/", + "video": "in6QbUPMJ3I", + "difficulty": "Medium", + "code": "0343-integer-break", + "cpp": true, + "kotlin": true, + "c": true, + "java": true + }, + { + "problem": "Number of Longest Increasing Subsequence", + "pattern": "1-D Dynamic Programming", + "link": "number-of-longest-increasing-subsequence/", + "video": "Tuc-rjJbsXU", + "difficulty": "Medium", + "code": "0673-number-of-longest-increasing-subsequence", + "python": true, + "kotlin": true, + "c": true + }, + { + "problem": "Stickers to Spell Word", + "pattern": "1-D Dynamic Programming", + "link": "stickers-to-spell-word/", + "video": "hsomLb6mUdI", + "difficulty": "Hard", + "code": "0691-stickers-to-spell-word", + "c": true, + "kotlin": true + }, + { + "problem": "N-th Tribonacci Number", + "pattern": "1-D Dynamic Programming", + "link": "n-th-tribonacci-number/", + "video": "3lpNp5Ojvrw", + "difficulty": "Easy", + "code": "1137-n-th-tribonacci-number", + "python": true, + "javascript": true, + "typescript": true, + "go": true, + "kotlin": true, + "rust": true, + "c": true, + "cpp": true + }, + { + "problem": "Uncrossed Lines", + "pattern": "1-D Dynamic Programming", + "link": "uncrossed-lines/", + "video": "mnJF4vJ7GyE", + "difficulty": "Medium", + "code": "1035-uncrossed-lines", + "kotlin": true, + "c": true + }, + { + "problem": "Solving Questions With Brainpower", + "pattern": "1-D Dynamic Programming", + "link": "solving-questions-with-brainpower/", + "video": "D7TD_ArkfkA", + "difficulty": "Medium", + "code": "2140-solving-questions-with-brainpower", + "kotlin": true, + "c": true, + "cpp": true + }, + { + "problem": "Count Ways to Build Good Strings", + "pattern": "1-D Dynamic Programming", + "link": "count-ways-to-build-good-strings/", + "video": "JKpVHG2mhbk", + "difficulty": "Medium", + "code": "2466-count-ways-to-build-good-strings", + "kotlin": true, + "c": true + }, + { + "problem": "New 21 Game", + "pattern": "1-D Dynamic Programming", + "link": "new-21-game/", + "video": "zKi4LzjK27k", + "difficulty": "Medium", + "code": "0837-new-21-game", + "kotlin": true, + "c": true, + "javascript": true + }, + { + "problem": "Best Team with no Conflicts", + "pattern": "1-D Dynamic Programming", + "link": "best-team-with-no-conflicts/", + "video": "7kURH3btcV4", + "difficulty": "Medium", + "code": "1626-best-team-with-no-conflicts", + "c": true, + "kotlin": true + }, + { + "problem": "Stone Game III", + "pattern": "1-D Dynamic Programming", + "link": "stone-game-iii/", + "video": "HsLG5QW9CFQ", + "difficulty": "Hard", + "code": "1406-stone-game-iii", + "kotlin": true, + "c": true + }, + { + "problem": "Concatenated Words", + "pattern": "1-D Dynamic Programming", + "link": "concatenated-words/", + "video": "iHp7fjw1R28", + "difficulty": "Hard", + "code": "0472-concatenated-words", + "javascript": true, + "typescript": true, + "go": true, + "rust": true, + "kotlin": true + }, + { + "problem": "Maximize Score after N Operations", + "pattern": "1-D Dynamic Programming", + "link": "maximize-score-after-n-operations/", + "video": "RRQVDqp5RSE", + "difficulty": "Hard", + "code": "1799-maximize-score-after-n-operations", + "kotlin": true, + "c": true + }, + { + "problem": "Find the Longest Valid Obstacle Course at Each Position", + "pattern": "1-D Dynamic Programming", + "link": "find-the-longest-valid-obstacle-course-at-each-position/", + "video": "Xq9VT7p0lic", + "difficulty": "Hard", + "code": "1964-find-the-longest-valid-obstacle-course-at-each-position", + "kotlin": true, + "c": true + }, + { + "problem": "Count all Valid Pickup and Delivery Options", + "pattern": "1-D Dynamic Programming", + "link": "count-all-valid-pickup-and-delivery-options/", + "video": "OpgslsirW8s", + "difficulty": "Hard", + "code": "1359-count-all-valid-pickup-and-delivery-options", + "java": true, + "kotlin": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Unique Paths", + "pattern": "2-D Dynamic Programming", + "link": "unique-paths/", + "video": "IlEsdxuD4lY", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0062-unique-paths", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "kotlin": true, + "rust": true + }, + { + "problem": "Unique Paths II", + "pattern": "2-D Dynamic Programming", + "link": "unique-paths-ii/", + "video": "d3UOz7zdE4I", + "difficulty": "Medium", + "python": true, + "code": "0063-unique-paths-ii", + "cpp": true, + "java": true, + "go": true, + "kotlin": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Longest Common Subsequence", + "pattern": "2-D Dynamic Programming", + "link": "longest-common-subsequence/", + "video": "Ua0GhsJSlWM", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "1143-longest-common-subsequence", + "csharp": true, + "typescript": true, + "go": true, + "swift": true, + "kotlin": true, + "rust": true, + "c": true + }, + { + "problem": "Longest Palindromic Subsequence", + "pattern": "2-D Dynamic Programming", + "link": "longest-palindromic-subsequence/", + "video": "bUr8cNWI09Q", + "difficulty": "Medium", + "python": true, + "code": "0516-longest-palindromic-subsequence", + "kotlin": true + }, + { + "problem": "Last Stone Weight II", + "pattern": "2-D Dynamic Programming", + "link": "last-stone-weight-ii/", + "video": "gdXkkmzvR3c", + "difficulty": "Medium", + "python": true, + "code": "1049-last-stone-weight-ii", + "kotlin": true + }, + { + "neetcode150": true, + "problem": "Best Time to Buy And Sell Stock With Cooldown", + "pattern": "2-D Dynamic Programming", + "link": "best-time-to-buy-and-sell-stock-with-cooldown/", + "video": "I7j0F7AHpb8", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0309-best-time-to-buy-and-sell-stock-with-cooldown", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "swift": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "problem": "Coin Change II", + "pattern": "2-D Dynamic Programming", + "link": "coin-change-ii/", + "video": "Mjy4hd2xgrs", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0518-coin-change-ii", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "problem": "Target Sum", + "pattern": "2-D Dynamic Programming", + "link": "target-sum/", + "video": "g0npyaQtAQM", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0494-target-sum", + "csharp": true, + "typescript": true, + "go": true, + "kotlin": true, + "c": true + }, + { + "neetcode150": true, + "problem": "Interleaving String", + "pattern": "2-D Dynamic Programming", + "link": "interleaving-string/", + "video": "3Rw3p9LrgvE", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0097-interleaving-string", + "csharp": true, + "typescript": true, + "go": true, + "scala": true, + "kotlin": true, + "c": true + }, + { + "problem": "Stone Game", + "pattern": "2-D Dynamic Programming", + "link": "stone-game/", + "video": "uhgdXOlGYqE", + "difficulty": "Medium", + "code": "0877-stone-game", + "kotlin": true, + "cpp": true + }, + { + "problem": "Minimum Path Sum", + "pattern": "2-D Dynamic Programming", + "link": "minimum-path-sum/", + "video": "pGMsrvt0fpk", + "difficulty": "Medium", + "code": "0064-minimum-path-sum", + "cpp": true, + "java": true, + "python": true, + "kotlin": true + }, + { + "neetcode150": true, + "problem": "Longest Increasing Path In a Matrix", + "pattern": "2-D Dynamic Programming", + "link": "longest-increasing-path-in-a-matrix/", + "video": "wCc_nd-GiEc", + "difficulty": "Hard", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0329-longest-increasing-path-in-a-matrix", + "c": true, + "csharp": true, + "kotlin": true, + "rust": true + }, + { + "problem": "Maximal Square", + "pattern": "2-D Dynamic Programming", + "link": "maximal-square/", + "video": "6X7Ha2PrDmM", + "difficulty": "Medium", + "code": "0221-maximal-square", + "python": true, + "java": true, + "kotlin": true, + "cpp": true + }, + { + "problem": "Ones and Zeroes", + "pattern": "2-D Dynamic Programming", + "link": "ones-and-zeroes/", + "video": "miZ3qV04b1g", + "difficulty": "Medium", + "python": true, + "code": "0474-ones-and-zeroes", + "kotlin": true, + "cpp": true + }, + { + "problem": "Maximum Alternating Subsequence Sum", + "pattern": "2-D Dynamic Programming", + "link": "maximum-alternating-subsequence-sum/", + "video": "4v42XOuU1XA", + "difficulty": "Medium", + "code": "5782-maximum-alternating-subsequence-sum" + }, + { + "neetcode150": true, + "problem": "Distinct Subsequences", + "pattern": "2-D Dynamic Programming", + "link": "distinct-subsequences/", + "video": "-RDzMJ33nx8", + "difficulty": "Hard", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0115-distinct-subsequences", + "csharp": true, + "typescript": true, + "kotlin": true, + "c": true + }, + { + "neetcode150": true, + "problem": "Edit Distance", + "pattern": "2-D Dynamic Programming", + "link": "edit-distance/", + "video": "XYi2-LPrwm4", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0072-edit-distance", + "csharp": true, + "swift": true, + "scala": true, + "kotlin": true, + "c": true + }, + { + "problem": "Count Vowels Permutation", + "pattern": "2-D Dynamic Programming", + "link": "count-vowels-permutation/", + "video": "VUVpTZVa7Ls", + "difficulty": "Hard", + "code": "1220-count-vowels-permutation", + "python": true, + "java": true, + "go": true, + "cpp": true, + "kotlin": true + }, + { + "neetcode150": true, + "problem": "Burst Balloons", + "pattern": "2-D Dynamic Programming", + "link": "burst-balloons/", + "video": "VFskby7lUbw", + "difficulty": "Hard", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0312-burst-balloons", + "csharp": true, + "typescript": true, + "kotlin": true, + "c": true + }, + { + "problem": "Number of Ways to Rearrange Sticks With K Sticks Visible", + "pattern": "2-D Dynamic Programming", + "link": "number-of-ways-to-rearrange-sticks-with-k-sticks-visible/", + "video": "O761YBjGxGA", + "difficulty": "Hard", + "code": "1866-number-of-ways-to-rearrange-sticks-with-k-sticks-visible", + "kotlin": true + }, + { + "neetcode150": true, + "problem": "Regular Expression Matching", + "pattern": "2-D Dynamic Programming", + "link": "regular-expression-matching/", + "video": "HAA8mgxlov8", + "difficulty": "Hard", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0010-regular-expression-matching", + "csharp": true, + "typescript": true, + "go": true, + "c": true, + "kotlin": true + }, + { + "problem": "Stone Game II", + "pattern": "2-D Dynamic Programming", + "link": "stone-game-ii/", + "video": "I-z-u0zfQtg", + "difficulty": "Medium", + "code": "1140-stone-game-ii", + "kotlin": true + }, + { + "problem": "Flip String to Monotone Increasing", + "pattern": "2-D Dynamic Programming", + "link": "flip-string-to-monotone-increasing/", + "video": "tMq9z5k3umQ", + "difficulty": "Medium", + "code": "0926-flip-string-to-monotone-increasing", + "javascript": true, + "typescript": true, + "go": true, + "kotlin": true, + "rust": true + }, + { + "problem": "Maximum Value of K Coins from Piles", + "pattern": "2-D Dynamic Programming", + "link": "maximum-value-of-k-coins-from-piles/", + "video": "ZRdEd_eun8g", + "difficulty": "Hard", + "code": "2218-maximum-value-of-k-coins-from-piles", + "kotlin": true + }, + { + "problem": "Number of Music Playlists", + "pattern": "2-D Dynamic Programming", + "link": "number-of-music-playlists/", + "video": "gk4qzZSmyrs", + "difficulty": "Hard", + "code": "0920-number-of-music-playlists", + "java": true, + "kotlin": true + }, + { + "problem": "Number of Ways to Form a Target String Given a Dictionary", + "pattern": "2-D Dynamic Programming", + "link": "number-of-ways-to-form-a-target-string-given-a-dictionary/", + "video": "_GF-0T-YjW8", + "difficulty": "Hard", + "code": "1639-number-of-ways-to-form-a-target-string-given-a-dictionary", + "kotlin": true + }, + { + "problem": "Profitable Schemes", + "pattern": "2-D Dynamic Programming", + "link": "profitable-schemes/", + "video": "CcLKQLKvOl8", + "difficulty": "Hard", + "code": "0879-profitable-schemes", + "kotlin": true + }, + { + "problem": "Minimum Cost to Cut a Stick", + "pattern": "2-D Dynamic Programming", + "link": "minimum-cost-to-cut-a-stick/", + "video": "EVxTO5I0d7w", + "difficulty": "Hard", + "code": "1547-minimum-cost-to-cut-a-stick", + "kotlin": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Maximum Subarray", + "pattern": "Greedy", + "link": "maximum-subarray/", + "video": "5WZl3MMT0Eg", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0053-maximum-subarray", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "swift": true, + "kotlin": true, + "rust": true, + "ruby": true + }, + { + "problem": "Maximum Sum Circular Subarray", + "pattern": "Greedy", + "link": "maximum-sum-circular-subarray/", + "video": "fxT9KjakYPM", + "difficulty": "Medium", + "code": "0918-maximum-sum-circular-subarray", + "python": true, + "javascript": true, + "typescript": true, + "go": true, + "rust": true, + "kotlin": true, + "java": true + }, + { + "problem": "Longest Turbulent Array", + "pattern": "Greedy", + "link": "longest-turbulent-subarray/", + "video": "V_iHUhR8Dek", + "difficulty": "Medium", + "code": "0978-longest-turbulent-subarray", + "python": true, + "kotlin": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Jump Game", + "pattern": "Greedy", + "link": "jump-game/", + "video": "Yan0cv2cLy8", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0055-jump-game", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "swift": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "problem": "Jump Game II", + "pattern": "Greedy", + "link": "jump-game-ii/", + "video": "dJ7sWiOoK7g", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0045-jump-game-ii", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "swift": true, + "kotlin": true, + "ruby": true + }, + { + "problem": "Jump Game VII", + "pattern": "Greedy", + "link": "jump-game-vii/", + "video": "v1HpZUnQ4Yo", + "difficulty": "Medium", + "code": "1871-jump-game-vii", + "kotlin": true + }, + { + "neetcode150": true, + "problem": "Gas Station", + "pattern": "Greedy", + "link": "gas-station/", + "video": "lJwbPZGo05A", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0134-gas-station", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "swift": true, + "kotlin": true, + "ruby": true + }, + { + "neetcode150": true, + "problem": "Hand of Straights", + "pattern": "Greedy", + "link": "hand-of-straights/", + "video": "amnrMCVd2YI", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0846-hand-of-straights", + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "kotlin": true, + "c": true + }, + { + "problem": "Minimize Maximum of Array", + "pattern": "Greedy", + "link": "minimize-maximum-of-array/", + "video": "AeHMvcKuR0Y", + "difficulty": "Medium", + "code": "2439-minimize-maximum-of-array", + "kotlin": true + }, + { + "problem": "Dota2 Senate", + "pattern": "Greedy", + "link": "dota2-senate/", + "video": "zZA5KskfMuQ", + "difficulty": "Medium", + "code": "0649-dota2-senate", + "kotlin": true + }, + { + "problem": "Maximum Points You Can Obtain From Cards", + "pattern": "Greedy", + "link": "maximum-points-you-can-obtain-from-cards/", + "video": "TsA4vbtfCvo", + "difficulty": "Medium", + "code": "1423-maximum-points-you-can-obtain-from-cards", + "csharp": true, + "kotlin": true + }, + { + "neetcode150": true, + "problem": "Merge Triplets to Form Target Triplet", + "pattern": "Greedy", + "link": "merge-triplets-to-form-target-triplet/", + "video": "kShkQLQZ9K4", + "difficulty": "Medium", + "code": "1899-merge-triplets-to-form-target-triplet", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "csharp": true, + "typescript": true, + "ruby": true, + "swift": true, + "kotlin": true, + "c": true + }, + { + "neetcode150": true, + "problem": "Partition Labels", + "pattern": "Greedy", + "link": "partition-labels/", + "video": "B7m8UmZE-vw", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0763-partition-labels", + "csharp": true, + "go": true, + "ruby": true, + "kotlin": true, + "c": true + }, + { + "neetcode150": true, + "problem": "Valid Parenthesis String", + "pattern": "Greedy", + "link": "valid-parenthesis-string/", + "video": "QhPdNS143Qg", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0678-valid-parenthesis-string", + "c": true, + "csharp": true, + "typescript": true, + "kotlin": true + }, + { + "problem": "Eliminate Maximum Number of Monsters", + "pattern": "Greedy", + "link": "eliminate-maximum-number-of-monsters/", + "video": "6QQRayzOTD4", + "difficulty": "Medium", + "code": "1921-eliminate-maximum-number-of-monsters", + "cpp": true, + "java": true, + "kotlin": true + }, + { + "problem": "Two City Scheduling", + "pattern": "Greedy", + "link": "two-city-scheduling/", + "video": "d-B_gk_gJtQ", + "difficulty": "Medium", + "code": "1029-two-city-scheduling", + "java": true, + "python": true, + "javascript": true, + "typescript": true, + "go": true, + "rust": true, + "kotlin": true + }, + { + "problem": "Maximum Length of Pair Chain", + "pattern": "Greedy", + "link": "maximum-length-of-pair-chain/", + "video": "LcNNorqMVTw", + "difficulty": "Medium", + "code": "0646-maximum-length-of-pair-chain", + "kotlin": true + }, + { + "problem": "Minimum Deletions to Make Character Frequencies Unique", + "pattern": "Greedy", + "link": "minimum-deletions-to-make-character-frequencies-unique/", + "video": "h8AZEN49gTc", + "difficulty": "Medium", + "code": "1647-minimum-deletions-to-make-character-frequencies-unique", + "java": true, + "kotlin": true + }, + { + "problem": "Candy", + "pattern": "Greedy", + "link": "candy/", + "video": "1IzCRCcK17A", + "difficulty": "Hard", + "code": "135-candy" + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Insert Interval", + "pattern": "Intervals", + "link": "insert-interval/", + "video": "A8NUOmlwOlM", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0057-insert-interval", + "csharp": true, + "typescript": true, + "swift": true, + "rust": true, + "go": true, + "kotlin": true, + "c": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Merge Intervals", + "pattern": "Intervals", + "link": "merge-intervals/", + "video": "44H3cEC2fFM", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0056-merge-intervals", + "csharp": true, + "typescript": true, + "go": true, + "kotlin": true, + "scala": true, + "c": true, + "rust": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Non Overlapping Intervals", + "pattern": "Intervals", + "link": "non-overlapping-intervals/", + "video": "nONCGxWoUfM", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0435-non-overlapping-intervals", + "csharp": true, + "typescript": true, + "go": true, + "scala": true, + "c": true, + "kotlin": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Meeting Rooms", + "premium": true, + "freeLink": "https://www.lintcode.com/problem/920/", + "pattern": "Intervals", + "link": "meeting-rooms/", + "video": "PaJxqZVPhbg", + "difficulty": "Easy", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0252-meeting-rooms", + "csharp": true, + "rust": true, + "kotlin": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Meeting Rooms II", + "premium": true, + "freeLink": "https://www.lintcode.com/problem/919/", + "pattern": "Intervals", + "link": "meeting-rooms-ii/", + "video": "FdzJmTCVyJU", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0253-meeting-rooms-ii", + "csharp": true, + "rust": true, + "kotlin": true + }, + { + "problem": "Remove Covered Intervals", + "pattern": "Intervals", + "link": "remove-covered-intervals/", + "video": "nhAsMabiVkM", + "difficulty": "Medium", + "code": "1288-remove-covered-intervals", + "c": true, + "kotlin": true + }, + { + "neetcode150": true, + "problem": "Minimum Interval to Include Each Query", + "pattern": "Intervals", + "link": "minimum-interval-to-include-each-query/", + "video": "5hQ5WWW5awQ", + "difficulty": "Hard", + "python": true, + "java": true, + "cpp": true, + "code": "1851-minimum-interval-to-include-each-query", + "csharp": true, + "javascript": true, + "kotlin": true + }, + { + "problem": "Data Stream as Disjoint Intervals", + "pattern": "Intervals", + "link": "data-stream-as-disjoint-intervals/", + "video": "FavoZjPIWpo", + "difficulty": "Hard", + "code": "0352-data-stream-as-disjoint-intervals", + "javascript": true, + "typescript": true, + "go": true, + "rust": true, + "kotlin": true + }, + { + "problem": "Excel Sheet Column Title", + "pattern": "Math & Geometry", + "link": "excel-sheet-column-title/", + "video": "X_vJDpCCuoA", + "difficulty": "Easy", + "code": "0168-excel-sheet-column-title", + "java": true, + "python": true, + "kotlin": true + }, + { + "problem": "Greatest Common Divisor of Strings", + "pattern": "Math & Geometry", + "link": "greatest-common-divisor-of-strings/", + "video": "i5I_wrbUdzM", + "difficulty": "Easy", + "code": "1071-greatest-common-divisor-of-strings", + "javascript": true, + "typescript": true, + "go": true, + "kotlin": true, + "rust": true, + "cpp": true + }, + { + "problem": "Count Odd Numbers in an Interval Range", + "pattern": "Math & Geometry", + "link": "count-odd-numbers-in-an-interval-range/", + "video": "wrIWye928JQ", + "difficulty": "Easy", + "code": "1523-count-odd-numbers-in-an-interval-range", + "kotlin": true + }, + { + "problem": "Matrix Diagonal Sum", + "pattern": "Math & Geometry", + "link": "matrix-diagonal-sum/", + "video": "WliTu6gIK7o", + "difficulty": "Easy", + "code": "1572-matrix-diagonal-sum", + "kotlin": true, + "javascript": true + }, + { + "problem": "Maximum Points on a Line", + "pattern": "Math & Geometry", + "link": "max-points-on-a-line/", + "video": "Bb9lOXUOnFw", + "difficulty": "Hard", + "code": "0149-max-points-on-a-line", + "python": true, + "javascript": true, + "typescript": true, + "rust": true, + "cpp": true, + "kotlin": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Rotate Image", + "pattern": "Math & Geometry", + "link": "rotate-image/", + "video": "fMSJSS7eO1w", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0048-rotate-image", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "swift": true, + "ruby": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Spiral Matrix", + "pattern": "Math & Geometry", + "link": "spiral-matrix/", + "video": "BJnMZNwUk1M", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0054-spiral-matrix", + "csharp": true, + "typescript": true, + "kotlin": true, + "go": true, + "ruby": true, + "c": true + }, + { + "problem": "Spiral Matrix II ", + "pattern": "Math & Geometry", + "link": "spiral-matrix-ii/", + "video": "RvLrWFBJ9fM", + "difficulty": "Medium", + "code": "0059-spiral-matrix-ii", + "javascript": true, + "kotlin": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Set Matrix Zeroes", + "pattern": "Math & Geometry", + "link": "set-matrix-zeroes/", + "video": "T41rL0L3Pnw", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0073-set-matrix-zeroes", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "kotlin": true, + "ruby": true + }, + { + "neetcode150": true, + "problem": "Happy Number", + "pattern": "Math & Geometry", + "link": "happy-number/", + "video": "ljz85bxOYJ0", + "difficulty": "Easy", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0202-happy-number", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "swift": true, + "kotlin": true, + "ruby": true, + "rust": true + }, + { + "neetcode150": true, + "problem": "Plus One", + "pattern": "Math & Geometry", + "link": "plus-one/", + "video": "jIaA8boiG1s", + "difficulty": "Easy", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0066-plus-one", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "swift": true, + "kotlin": true, + "ruby": true, + "rust": true + }, + { + "problem": "Palindrome Number", + "pattern": "Math & Geometry", + "link": "palindrome-number/", + "video": "yubRKwixN-U", + "difficulty": "Easy", + "code": "0009-palindrome-number", + "javascript": true, + "typescript": true, + "cpp": true, + "java": true, + "python": true, + "go": true, + "rust": true, + "swift": true, + "c": true, + "kotlin": true + }, + { + "problem": "Ugly Number", + "pattern": "Math & Geometry", + "link": "ugly-number/", + "video": "M0Zay1Qr9ws", + "difficulty": "Easy", + "code": "0263-ugly-number", + "c": true, + "cpp": true, + "java": true, + "python": true, + "javascript": true, + "typescript": true, + "go": true, + "rust": true, + "swift": true, + "kotlin": true + }, + { + "problem": "Shift 2D Grid", + "pattern": "Math & Geometry", + "link": "shift-2d-grid/", + "video": "nJYFh4Dl-as", + "difficulty": "Easy", + "code": "1260-shift-2d-grid", + "cpp": true, + "java": true, + "python": true, + "javascript": true, + "kotlin": true + }, + { + "problem": "Roman to Integer", + "pattern": "Math & Geometry", + "link": "roman-to-integer/", + "video": "3jdxYj3DD98", + "difficulty": "Easy", + "code": "0013-roman-to-integer", + "python": true, + "javascript": true, + "go": true, + "typescript": true, + "rust": true, + "java": true, + "cpp": true, + "kotlin": true + }, + { + "problem": "Integer to Roman", + "pattern": "Math & Geometry", + "link": "integer-to-roman/", + "video": "ohBNdSJyLh8", + "difficulty": "Medium", + "code": "0012-integer-to-roman", + "python": true, + "typescript": true, + "go": true, + "rust": true, + "javascript": true, + "cpp": true, + "java": true, + "kotlin": true + }, + { + "neetcode150": true, + "problem": "Pow(x, n)", + "pattern": "Math & Geometry", + "link": "powx-n/", + "video": "g9YQyYi4IQQ", + "difficulty": "Medium", + "python": true, + "java": true, + "javascript": true, + "cpp": true, + "code": "0050-powx-n", + "c": true, + "csharp": true, + "typescript": true, + "swift": true, + "ruby": true, + "kotlin": true + }, + { + "neetcode150": true, + "problem": "Multiply Strings", + "pattern": "Math & Geometry", + "link": "multiply-strings/", + "video": "1vZswirL8Y8", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0043-multiply-strings", + "csharp": true, + "typescript": true, + "swift": true, + "ruby": true, + "kotlin": true, + "c": true + }, + { + "neetcode150": true, + "problem": "Detect Squares", + "pattern": "Math & Geometry", + "link": "detect-squares/", + "video": "bahebearrDc", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "2013-detect-squares", + "csharp": true, + "kotlin": true, + "ruby": true, + "rust": true + }, + { + "problem": "Robot Bounded In Circle", + "pattern": "Math & Geometry", + "link": "robot-bounded-in-circle/", + "video": "nKv2LnC_g6E", + "difficulty": "Medium", + "code": "1041-robot-bounded-in-circle", + "kotlin": true + }, + { + "problem": "Zigzag Conversion", + "pattern": "Math & Geometry", + "link": "zigzag-conversion/", + "video": "Q2Tw6gcVEwc", + "difficulty": "Medium", + "code": "0006-zigzag-conversion", + "java": true, + "cpp": true, + "go": true, + "kotlin": true + }, + { + "problem": "Find Missing Observations", + "pattern": "Math & Geometry", + "link": "find-missing-observations/", + "video": "86yKkaNi3sU", + "difficulty": "Medium", + "code": "2028-find-missing-observations", + "kotlin": true + }, + { + "neetcode150": true, + "problem": "Single Number", + "pattern": "Bit Manipulation", + "link": "single-number/", + "video": "qMPX1AOa83k", + "difficulty": "Easy", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0136-single-number", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true, + "dart": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Number of 1 Bits", + "pattern": "Bit Manipulation", + "link": "number-of-1-bits/", + "video": "5Km3utixwZs", + "difficulty": "Easy", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0191-number-of-1-bits", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Counting Bits", + "pattern": "Bit Manipulation", + "link": "counting-bits/", + "video": "RyBM56RIWrM", + "difficulty": "Easy", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0338-counting-bits", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Reverse Bits", + "pattern": "Bit Manipulation", + "link": "reverse-bits/", + "video": "UcoN6UjAI64", + "difficulty": "Easy", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0190-reverse-bits", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Missing Number", + "pattern": "Bit Manipulation", + "link": "missing-number/", + "video": "WnPLSRLSANE", + "difficulty": "Easy", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0268-missing-number", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true + }, + { + "problem": "Shuffle the Array", + "pattern": "Bit Manipulation", + "link": "shuffle-the-array/", + "video": "IvIKD_EU8BY", + "difficulty": "Easy", + "code": "1470-shuffle-the-array", + "javascript": true, + "typescript": true, + "go": true, + "kotlin": true, + "rust": true, + "c": true + }, + { + "problem": "Add to Array-Form of Integer", + "pattern": "Bit Manipulation", + "link": "add-to-array-form-of-integer/", + "video": "eBTZQt1TWfk", + "difficulty": "Easy", + "code": "0989-add-to-array-form-of-integer", + "javascript": true, + "typescript": true, + "go": true, + "kotlin": true, + "rust": true, + "c": true + }, + { + "neetcode150": true, + "blind75": true, + "problem": "Sum of Two Integers", + "pattern": "Bit Manipulation", + "link": "sum-of-two-integers/", + "video": "gVUrDV4tZfY", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0371-sum-of-two-integers", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "rust": true + }, + { + "neetcode150": true, + "problem": "Reverse Integer", + "pattern": "Bit Manipulation", + "link": "reverse-integer/", + "video": "HAgLH58IgJQ", + "difficulty": "Medium", + "python": true, + "java": true, + "cpp": true, + "javascript": true, + "code": "0007-reverse-integer", + "c": true, + "csharp": true, + "typescript": true, + "go": true, + "ruby": true, + "swift": true, + "kotlin": true, + "scala": true, + "rust": true + }, + { + "problem": "Add Binary", + "pattern": "Bit Manipulation", + "link": "add-binary/", + "video": "keuWJ47xG8g", + "difficulty": "Easy", + "code": "0067-add-binary", + "cpp": true, + "java": true, + "python": true, + "kotlin": true, + "rust": true, + "c": true + }, + { + "problem": "Create Hello World Function", + "pattern": "JavaScript", + "link": "create-hello-world-function/", + "video": "P9Ldx1eTlRc", + "difficulty": "Easy", + "code": "2667-create-hello-world-function", + "javascript": true, + "typescript": true + }, + { + "problem": "Counter", + "pattern": "JavaScript", + "link": "counter/", + "video": "yEGQQAG5V68", + "difficulty": "Easy", + "code": "2620-counter", + "javascript": true, + "typescript": true + }, + { + "problem": "Counter II", + "pattern": "JavaScript", + "link": "counter-ii/", + "video": "UXNXKGFZD08", + "difficulty": "Easy", + "code": "2665-counter-ii", + "javascript": true + }, + { + "problem": "Apply Transform over each Element in Array", + "pattern": "JavaScript", + "link": "apply-transform-over-each-element-in-array/", + "video": "7FhJHA5jlYk", + "difficulty": "Easy", + "code": "2635-apply-transform-over-each-element-in-array" + }, + { + "problem": "Filter Elements from Array", + "pattern": "JavaScript", + "link": "filter-elements-from-array/", + "video": "w1o81gbEEJU", + "difficulty": "Easy", + "code": "2634-filter-elements-from-array" + }, + { + "problem": "Array Reduce Transformation", + "pattern": "JavaScript", + "link": "array-reduce-transformation/", + "video": "KmTbYfpGxdM", + "difficulty": "Easy", + "code": "2626-array-reduce-transformation" + }, + { + "problem": "Function Composition", + "pattern": "JavaScript", + "link": "function-composition/", + "video": "mIFw1H7Ljco", + "difficulty": "Easy", + "code": "2629-function-composition" + }, + { + "problem": "Allow One Function Call", + "pattern": "JavaScript", + "link": "allow-one-function-call/", + "video": "m_SWhM9iX3s", + "difficulty": "Easy", + "code": "2666-allow-one-function-call" + }, + { + "problem": "Memoize", + "pattern": "JavaScript", + "link": "memoize/", + "video": "oFXyzJt9VeU", + "difficulty": "Medium", + "code": "2623-memoize" + }, + { + "problem": "Curry", + "pattern": "JavaScript", + "link": "curry/", + "video": "pi4kqMWQXxA", + "difficulty": "Medium", + "code": "2632-curry" + }, + { + "problem": "Sleep", + "pattern": "JavaScript", + "link": "sleep/", + "video": "P0D9Z6H7O00", + "difficulty": "Easy", + "code": "2621-sleep" + }, + { + "problem": "Promise Time Limit", + "pattern": "JavaScript", + "link": "promise-time-limit/", + "video": "hfH57rdZhOk", + "difficulty": "Easy", + "code": "2637-promise-time-limit" + }, + { + "problem": "Promise Pool", + "pattern": "JavaScript", + "link": "promise-pool/", + "video": "DB8pAAg-9xw", + "difficulty": "Medium", + "code": "2636-promise-pool" + }, + { + "problem": "Cache With Time Limit", + "pattern": "JavaScript", + "link": "cache-with-time-limit/", + "video": "w772gtNK0Gw", + "difficulty": "Medium", + "code": "2622-cache-with-time-limit" + }, + { + "problem": "Debounce", + "pattern": "JavaScript", + "link": "debounce/", + "video": "1sxSpnxNx5w", + "difficulty": "Medium", + "code": "2627-debounce" + }, + { + "problem": "Throttle", + "pattern": "JavaScript", + "link": "throttle/", + "video": "zyGZV_fIQWk", + "difficulty": "Medium", + "code": "2676-throttle" + }, + { + "problem": "JSON Deep Equal", + "pattern": "JavaScript", + "link": "json-deep-equal/", + "video": "4JVZ-mVqJPg", + "difficulty": "Medium", + "code": "2628-json-deep-equal", + "javascript": true + }, + { + "problem": "Convert Object to JSON String", + "pattern": "JavaScript", + "link": "convert-object-to-json-string/", + "video": "f94fUbHU-FY", + "difficulty": "Medium", + "code": "2633-convert-object-to-json-string" + }, + { + "problem": "Array of Objects to Matrix", + "pattern": "JavaScript", + "link": "array-of-objects-to-matrix/", + "video": "LJwgAMHGcI0", + "difficulty": "Medium", + "code": "2675-array-of-objects-to-matrix" + }, + { + "problem": "Difference Between Two Objects", + "pattern": "JavaScript", + "link": "differences-between-two-objects/", + "video": "gH7oZs1WZfg", + "difficulty": "Medium", + "code": "2700-differences-between-two-objects" + }, + { + "problem": "Chunk Array", + "pattern": "JavaScript", + "link": "chunk-array/", + "video": "VUN-O3B9ceY", + "difficulty": "Easy", + "code": "2677-chunk-array" + }, + { + "problem": "Flatten Deeply Nested Array", + "pattern": "JavaScript", + "link": "flatten-deeply-nested-array/", + "video": "_DetLPKtFNk", + "difficulty": "Medium", + "code": "2625-flatten-deeply-nested-array" + }, + { + "problem": "Array Prototype Last", + "pattern": "JavaScript", + "link": "array-prototype-last/", + "video": "3JdtfMBrUqc", + "difficulty": "Easy", + "code": "2619-array-prototype-last" + }, + { + "problem": "Group By", + "pattern": "JavaScript", + "link": "group-by/", + "video": "zs9axOyYHRE", + "difficulty": "Medium", + "code": "2631-group-by" + }, + { + "problem": "Check if Object Instance of Class", + "pattern": "JavaScript", + "link": "check-if-object-instance-of-class/", + "video": "meIo-Q07Ba8", + "difficulty": "Medium", + "code": "2618-check-if-object-instance-of-class" + }, + { + "problem": "Call Function with Custom Context", + "pattern": "JavaScript", + "link": "call-function-with-custom-context/", + "video": "du_GH-Ooa8E", + "difficulty": "Medium", + "code": "2693-call-function-with-custom-context" + }, + { + "problem": "Event Emitter", + "pattern": "JavaScript", + "link": "event-emitter/", + "video": "M69bjWFarU0", + "difficulty": "Medium", + "code": "2694-event-emitter" + }, + { + "problem": "Array Wrapper", + "pattern": "JavaScript", + "link": "array-wrapper/", + "video": "XoGjPdPTAVA", + "difficulty": "Easy", + "code": "2695-array-wrapper" + }, + { + "problem": "Generate Fibonacci Sequence", + "pattern": "JavaScript", + "link": "generate-fibonacci-sequence/", + "video": "T643rQ70Jlk", + "difficulty": "Easy", + "code": "2648-generate-fibonacci-sequence" + }, + { + "problem": "Nested Array Generator", + "pattern": "JavaScript", + "link": "nested-array-generator/", + "video": "yo-J1jQaZYU", + "difficulty": "Medium", + "code": "2649-nested-array-generator" + } +] diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 83d524dd0..3fdb8d878 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,25 +1,26 @@ # Contributing + **Please read the [guidelines below](#contributing-guidelines) before opening a PR** Solutions from these languages will be linked from [NeetCode.io](https://neetcode.io): -* Python -* C++ -* Java -* Javascript +- Python +- C++ +- Java +- Javascript -Solutions are also welcome for any other *supported* language on leetcode.com! +Solutions are also welcome for any other _supported_ language on leetcode.com! To contribute, please fork this repo and open a PR adding a [missing solution](./README.md#missing-solutions) from the supported languages. -If you would like to have collaborator permissions on the repo to merge your own PRs or review others' PRs please let me know. +If you would like to have collaborator permissions on the repo to merge your own PRs or review others' PRs please let me know. ## Contributing Guidelines - **Match the casing of files and directories** - - For files, it's **`/-name-of-problem.`** (e.g. `java/0001-two-sum.java`) - - Make sure the `problem-number` is formatted as four digits adding leading zeroes if necessary - - You can find the `name-of-problem` in the leetcode URL, e.g https://leetcode.com/problems/ _**two-sum**_ / + - For files, it's **`/-name-of-problem.`** (e.g. `java/0001-two-sum.java`) + - Make sure the `problem-number` is formatted as four digits adding leading zeroes if necessary + - You can find the `name-of-problem` in the leetcode URL, e.g https://leetcode.com/problems/ _**two-sum**_ / - **Give your PR a succinct and accurate title** (e.g. _"Create: 0001-two-sum.py"_) - Prefer **one solution/change per PR** (not a hard and fast rule, but will typically make the review cycle shorter) - **Follow the** [PR template](./.github/pull_request_template.md) and add additional information when needed @@ -32,21 +33,25 @@ If you would like to have collaborator permissions on the repo to merge your own **Q:** What should my solution include? **A:** You can keep your solution exactly the same as the one you submit to leetcode, you don't need to write tests or your own implementation of leetcode's built-ins. + ## **Q:** What if there are multiple ways to solve the problem? **A:** Multiple solutions to the same problem are accepted (as long as they differ in approach or time/memory complexity), although the first solution should always follow the same algorithm shown on [the channel](https://www.youtube.com/c/neetcode). Please make sure distinct solutions are grouped together in the same file, with appropriately differentiating names (e.g. `isValidBstIterative` and `isValidBstRecursive`) + ## **Q:** What if my solution has a lower runtime but the same time/memory complexity? **A:** Leetcode's runtime measurement can be severely inaccurate varying based on server load, time of day and many other factors. In general, readability and clarity of the code (in the context of interviews) are features more important than performance gains, however changes that transparently improve performance will be accepted. + ## **Q:** What if the problem I want to add isn't in the Neetcode 150 list or Missing Solutions table? **A:** Questions outside of the Neetcode 150 list can be added but please prioritise adding the listed solutions first. + ## Thanks for contributing 🚀 diff --git a/README.md b/README.md index 621435471..c8eff4144 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,22 @@ # Leetcode solutions for 🚀 [NeetCode.io](https://neetcode.io) + > This repo hosts the solutions found on [NeetCode.io](https://neetcode.io) including the solutions shown on the [NeetCode YouTube channel](https://www.youtube.com/c/neetcode). The site will periodically be updated with new solutions from this repo!
Solutions from these languages will be linked from [NeetCode.io](https://neetcode.io): + > Python, Java, JavaScript, C++, Go, Swift, C#, TypeScript, Rust, Kotlin, Ruby, C, Scala and Dart -Solutions are also welcome for any other *supported* language on leetcode.com! +Solutions are also welcome for any other _supported_ language on leetcode.com! ## Contributing -**Please read the [contributing guidlines](./CONTRIBUTING.md) before opening a PR** +**Please read the [contributing guidlines](./CONTRIBUTING.md) before opening a PR** To contribute, please fork this repo and open a PR adding a [missing solution](#missing-solutions) from the supported languages. -If you would like to have collaborator permissions on the repo to merge your own PRs or review others' PRs please let me know. +If you would like to have collaborator permissions on the repo to merge your own PRs or review others' PRs please let me know. ## Credits @@ -26,550 +28,548 @@ If you would like to have collaborator permissions on the repo to merge your own ### Arrays & Hashing -Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS ----- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- -[0217 - Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) |
|
[✔️](c%2F0217-contains-duplicate.c)
|
[✔️](cpp%2F0217-contains-duplicate.cpp)
|
[✔️](csharp%2F0217-contains-duplicate.cs)
|
[✔️](dart%2F0217-contains-duplicate.dart)
|
[✔️](go%2F0217-contains-duplicate.go)
|
|
[✔️](java%2F0217-contains-duplicate.java)
|
[✔️](javascript%2F0217-contains-duplicate.js)
|
[✔️](kotlin%2F0217-contains-duplicate.kt)
|
[✔️](python%2F0217-contains-duplicate.py)
|
[✔️](ruby%2F0217-contains-duplicate.rb)
|
[✔️](rust%2F0217-contains-duplicate.rs)
|
[✔️](scala%2F0217-contains-duplicate.scala)
|
[✔️](swift%2F0217-contains-duplicate.swift)
|
[✔️](typescript%2F0217-contains-duplicate.ts)
-[0242 - Valid Anagram](https://leetcode.com/problems/valid-anagram/) |
|
[✔️](c%2F0242-valid-anagram.c)
|
[✔️](cpp%2F0242-valid-anagram.cpp)
|
[✔️](csharp%2F0242-valid-anagram.cs)
|
[✔️](dart%2F0242-valid-anagram.dart)
|
[✔️](go%2F0242-valid-anagram.go)
|
|
[✔️](java%2F0242-valid-anagram.java)
|
[✔️](javascript%2F0242-valid-anagram.js)
|
[✔️](kotlin%2F0242-valid-anagram.kt)
|
[✔️](python%2F0242-valid-anagram.py)
|
[✔️](ruby%2F0242-valid-anagram.rb)
|
[✔️](rust%2F0242-valid-anagram.rs)
|
[✔️](scala%2F0242-valid-anagram.scala)
|
[✔️](swift%2F0242-valid-anagram.swift)
|
[✔️](typescript%2F0242-valid-anagram.ts)
-[1929 - Concatenation of Array](https://leetcode.com/problems/concatenation-of-array/) |
|
[✔️](c%2F1929-concatenation-of-array.c)
|
[✔️](cpp%2F1929-concatenation-of-array.cpp)
|
[✔️](csharp%2F1929-concatenation-of-array.cs)
|
[✔️](dart%2F1929-concatenation-of-array.dart)
|
[✔️](go%2F1929-concatenation-of-array.go)
|
|
[✔️](java%2F1929-concatenation-of-array.java)
|
[✔️](javascript%2F1929-concatenation-of-array.js)
|
[✔️](kotlin%2F1929-concatenation-of-array.kt)
|
[✔️](python%2F1929-concatenation-of-array.py)
|
[✔️](ruby%2F1929-concatenation-of-array.rb)
|
[✔️](rust%2F1929-concatenation-of-array.rs)
|
[✔️](scala%2F1929-concatenation-of-array.scala)
|
[✔️](swift%2F1929-concatenation-of-array.swift)
|
[✔️](typescript%2F1929-concatenation-of-array.ts)
-[1299 - Replace Elements With Greatest Element On Right Side](https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/) |
|
[✔️](c%2F1299-Replace-Elements-With-Greatest-Element-On-Right-Side.c)
|
[✔️](cpp%2F1299-Replace-Elements-with-Greatest-Element-on-Right-Side.cpp)
|
[✔️](csharp%2F1299-Replace-Elements-With-Greatest-Element-On-Right-Side.cs)
|
[✔️](dart%2F1299-replace-elements-with-greatest-element-on-right-side.dart)
|
[✔️](go%2F1299-Replace-Elements-With-Greatest-Element-On-Right-Side.go)
|
|
[✔️](java%2F1299-Replace-Elements-With-Greatest-Element-On-Right-Side.java)
|
[✔️](javascript%2F1299-Replace-Elements-with-Greatest-Element-on-Right-Side.js)
|
[✔️](kotlin%2F1299-replace-elements-with-greatest-element-on-right-side.kt)
|
[✔️](python%2F1299-replace-elements-with-greatest-element-on-right-side.py)
|
[✔️](ruby%2F1299-replace-elements-with-greatest-element-on-right-side.rb)
|
[✔️](rust%2F1299-Replace-Elements-With-Greatest-Element-On-Right-Side.rs)
|
|
[✔️](swift%2F1299-replace-elements-with-greatest-element-on-right-side.swift)
|
[✔️](typescript%2F1299-Replace-Elements-With-Greatest-Element-On-Right-Side.ts)
-[0392 - Is Subsequence](https://leetcode.com/problems/is-subsequence/) |
|
[✔️](c%2F0392-is-subsequence.c)
|
[✔️](cpp%2F0392-is-subsequence.cpp)
|
[✔️](csharp%2F0392-is-subsequence.cs)
|
[✔️](dart%2F0392-is-subsequence.dart)
|
[✔️](go%2F0392-is-subsequence.go)
|
|
[✔️](java%2F0392-is-subsequence.java)
|
[✔️](javascript%2F0392-is-subsequence.js)
|
[✔️](kotlin%2F0392-is-subsequence.kt)
|
[✔️](python%2F0392-is-subsequence.py)
|
[✔️](ruby%2F0392-is-subsequence.rb)
|
[✔️](rust%2F0392-is-subsequence.rs)
|
|
[✔️](swift%2F0392-is-subsequence.swift)
|
[✔️](typescript%2F0392-is-subsequence.ts)
-[0058 - Length of Last Word](https://leetcode.com/problems/length-of-last-word/) |
|
[✔️](c%2F0058-length-of-last-word.c)
|
[✔️](cpp%2F0058-length-of-last-word.cpp)
|
[✔️](csharp%2F0058-length-of-last-word.cs)
|
[✔️](dart%2F0058-length-of-last-word.dart)
|
[✔️](go%2F0058-Length-of-Last-Word.go)
|
|
[✔️](java%2F0058-length-of-last-word.java)
|
[✔️](javascript%2F0058-length-of-last-word.js)
|
[✔️](kotlin%2F0058-length-of-last-word.kt)
|
[✔️](python%2F0058-length-of-last-word.py)
|
[✔️](ruby%2F0058-length-of-last-word.rb)
|
[✔️](rust%2F0058-length-of-last-word.rs)
|
[✔️](scala%2F0058-length-of-last-word.scala)
|
[✔️](swift%2F0058-Length-of-Last-Word.swift)
|
[✔️](typescript%2F0058-length-of-last-word.ts)
-[0001 - Two Sum](https://leetcode.com/problems/two-sum/) |
|
[✔️](c%2F0001-two-sum.c)
|
[✔️](cpp%2F0001-two-sum.cpp)
|
[✔️](csharp%2F0001-two-sum.cs)
|
[✔️](dart%2F0001-two-sum.dart)
|
[✔️](go%2F0001-two-sum.go)
|
|
[✔️](java%2F0001-two-sum.java)
|
[✔️](javascript%2F0001-two-sum.js)
|
[✔️](kotlin%2F0001-two-sum.kt)
|
[✔️](python%2F0001-two-sum.py)
|
[✔️](ruby%2F0001-two-sum.rb)
|
[✔️](rust%2F0001-two-sum.rs)
|
[✔️](scala%2F0001-two-sum.scala)
|
[✔️](swift%2F0001-two-sum.swift)
|
[✔️](typescript%2F0001-two-sum.ts)
-[0014 - Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) |
|
[✔️](c%2F0014-Longest-Common-Prefix.c)
|
[✔️](cpp%2F0014-longest-common-prefix.cpp)
|
[✔️](csharp%2F0014-longest-common-prefix.cs)
|
[✔️](dart%2F0014-longest-common-prefix.dart)
|
[✔️](go%2F0014-longest-common-prefix.go)
|
|
[✔️](java%2F0014-longest-common-prefix.java)
|
[✔️](javascript%2F0014-longest-common-prefix.js)
|
[✔️](kotlin%2F0014-longest-common-prefix.kt)
|
[✔️](python%2F0014-longest-common-prefix.py)
|
|
[✔️](rust%2F0014-longest-common-prefix.rs)
|
|
[✔️](swift%2F0014-longest-common-prefix.swift)
|
[✔️](typescript%2F0014-longest-common-prefix.ts)
-[0049 - Group Anagrams](https://leetcode.com/problems/group-anagrams/) |
|
[✔️](c%2F0049-group-anagrams.c)
|
[✔️](cpp%2F0049-group-anagrams.cpp)
|
[✔️](csharp%2F0049-group-anagrams.cs)
|
[✔️](dart%2F0049-group-anagrams.dart)
|
[✔️](go%2F0049-group-anagrams.go)
|
|
[✔️](java%2F0049-group-anagrams.java)
|
[✔️](javascript%2F0049-group-anagrams.js)
|
[✔️](kotlin%2F0049-group-anagrams.kt)
|
[✔️](python%2F0049-group-anagrams.py)
|
[✔️](ruby%2F0049-group-anagrams.rb)
|
[✔️](rust%2F0049-group-anagrams.rs)
|
[✔️](scala%2F0049-group-anagrams.scala)
|
[✔️](swift%2F0049-group-anagrams.swift)
|
[✔️](typescript%2F0049-group-anagrams.ts)
-[0118 - Pascals Triangle](https://leetcode.com/problems/pascals-triangle/) |
|
[✔️](c%2F0118-pascals-triangle.c)
|
[✔️](cpp%2F0118-pascals-triangle.cpp)
|
[✔️](csharp%2F0118-pascals-triangle.cs)
|
[✔️](dart%2F0118-pascals-triangle.dart)
|
[✔️](go%2F0118-pascals-triangle.go)
|
|
[✔️](java%2F0118-pascals-triangle.java)
|
[✔️](javascript%2F0118-pascals-triangle.js)
|
[✔️](kotlin%2F0118-pascals-triangle.kt)
|
[✔️](python%2F0118-pascals-triangle.py)
|
|
[✔️](rust%2F0118-pascals-triangle.rs)
|
|
|
[✔️](typescript%2F0118-pascals-triangle.ts)
-[0027 - Remove Element](https://leetcode.com/problems/remove-element/) |
|
[✔️](c%2F0027-remove-element.c)
|
[✔️](cpp%2F0027-remove-element.cpp)
|
[✔️](csharp%2F0027-remove-element.cs)
|
[✔️](dart%2F0027-remove-element.dart)
|
[✔️](go%2F0027-remove-element.go)
|
|
[✔️](java%2F0027-remove-element.java)
|
[✔️](javascript%2F0027-remove-element.js)
|
[✔️](kotlin%2F0027-remove-element.kt)
|
[✔️](python%2F0027-remove-element.py)
|
|
[✔️](rust%2F0027-remove-element.rs)
|
|
[✔️](swift%2F0027-Remove-Element.swift)
|
[✔️](typescript%2F0027-remove-element.ts)
-[0929 - Unique Email Addresses](https://leetcode.com/problems/unique-email-addresses/) |
|
[✔️](c%2F0929-unique-email-addresses.c)
|
[✔️](cpp%2F0929-unique-email-addresses.cpp)
|
[✔️](csharp%2F0929-unique-email-addresses.cs)
|
[✔️](dart%2F0929-unique-email-addresses.dart)
|
[✔️](go%2F0929-unique-email-addresses.go)
|
|
[✔️](java%2F0929-unique-email-addresses.java)
|
[✔️](javascript%2F0929-unique-email-addresses.js)
|
[✔️](kotlin%2F0929-unique-email-addresses.kt)
|
[✔️](python%2F0929-unique-email-addresses.py)
|
|
[✔️](rust%2F0929-unique-email-addresses.rs)
|
|
[✔️](swift%2F0929-unique-email-addresses.swift)
|
[✔️](typescript%2F0929-unique-email-addresses.ts)
-[0205 - Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) |
|
[✔️](c%2F0205-isomorphic-strings.c)
|
[✔️](cpp%2F0205-Isomorphic-Strings.cpp)
|
[✔️](csharp%2F0205-isomorphic-strings.cs)
|
|
[✔️](go%2F0205-isomorphic-strings.go)
|
|
[✔️](java%2F0205-isomorphic-strings.java)
|
[✔️](javascript%2F0205-isomorphic-strings.js)
|
[✔️](kotlin%2F0205-isomorphic-strings.kt)
|
[✔️](python%2F0205-isomorphic-strings.py)
|
|
[✔️](rust%2F0205-isomorphic-strings.rs)
|
|
[✔️](swift%2F0205-isomorphic-strings.swift)
|
[✔️](typescript%2F0205-isomorphic-strings.ts)
-[0605 - Can Place Flowers](https://leetcode.com/problems/can-place-flowers/) |
|
[✔️](c%2F0605-can-place-flowers.c)
|
[✔️](cpp%2F0605-can-place-flowers.cpp)
|
[✔️](csharp%2F0605-can-place-flowers.cs)
|
|
[✔️](go%2F0605-can-place-flowers.go)
|
|
[✔️](java%2F0605-can-place-flowers.java)
|
[✔️](javascript%2F0605-can-place-flowers.js)
|
[✔️](kotlin%2F0605-can-place-flowers.kt)
|
[✔️](python%2F0605-can-place-flowers.py)
|
|
[✔️](rust%2F0605-can-place-flowers.rs)
|
|
[✔️](swift%2F0605-can-place-flowers.swift)
|
[✔️](typescript%2F0605-can-place-flowers.ts)
-[0169 - Majority Element](https://leetcode.com/problems/majority-element/) |
|
[✔️](c%2F0169-majority-element.c)
|
[✔️](cpp%2F0169-majority-element.cpp)
|
[✔️](csharp%2F0169-majority-element.cs)
|
[✔️](dart%2F0169-majority-element.dart)
|
[✔️](go%2F0169-majority-element.go)
|
|
[✔️](java%2F0169-majority-element.java)
|
[✔️](javascript%2F0169-majority-element.js)
|
[✔️](kotlin%2F0169-majority-element.kt)
|
[✔️](python%2F0169-majority-element.py)
|
|
[✔️](rust%2F0169-majority-element.rs)
|
|
[✔️](swift%2F0169-majority-element.swift)
|
[✔️](typescript%2F0169-majority-element.ts)
-[0496 - Next Greater Element I](https://leetcode.com/problems/next-greater-element-i/) |
|
[✔️](c%2F0496-next-greater-element-i.c)
|
[✔️](cpp%2F0496-next-greater-element-i.cpp)
|
[✔️](csharp%2F0496-next-greater-element-i.cs)
|
|
[✔️](go%2F0496-next-greater-element-i.go)
|
|
[✔️](java%2F0496-next-greater-element-i.java)
|
[✔️](javascript%2F0496-next-greater-element-i.js)
|
[✔️](kotlin%2F0496-next-greater-element-i.kt)
|
[✔️](python%2F0496-next-greater-element-i.py)
|
|
[✔️](rust%2F0496-next-greater-element-I.rs)
|
|
|
[✔️](typescript%2F0496-next-greater-element-i.ts)
-[0724 - Find Pivot Index](https://leetcode.com/problems/find-pivot-index/) |
|
[✔️](c%2F0724-find-pivot-index.c)
|
[✔️](cpp%2F0724-find-pivot-index.cpp)
|
[✔️](csharp%2F0724-find-pivot-index.cs)
|
|
[✔️](go%2F0724-find-pivot-index.go)
|
|
[✔️](java%2F0724-find-pivot-index.java)
|
[✔️](javascript%2F0724-find-pivot-index.js)
|
[✔️](kotlin%2F0724-find-pivot-index.kt)
|
[✔️](python%2F0724-find-pivot-index.py)
|
|
[✔️](rust%2F0724-find-pivot-index.rs)
|
|
[✔️](swift%2F0724-find-pivot-index.swift)
|
[✔️](typescript%2F0724-find-pivot-index.ts)
-[0303 - Range Sum Query - Immutable](https://leetcode.com/problems/range-sum-query-immutable/) |
|
[✔️](c%2F0303-range-sum-query-immutable.c)
|
[✔️](cpp%2F0303-range-sum-query-immutable.cpp)
|
[✔️](csharp%2F0303-range-sum-query-immutable.cs)
|
|
[✔️](go%2F0303-range-sum-query.go)
|
|
[✔️](java%2F0303-range-sum-query-immutable.java)
|
[✔️](javascript%2F0303-range-sum-query-immutable.js)
|
[✔️](kotlin%2F0303-range-sum-query-immutable.kt)
|
[✔️](python%2F0303-range-sum-query-immutable.py)
|
|
[✔️](rust%2F0303-range-sum-query-immutable.rs)
|
|
[✔️](swift%2F0303-range-sum-query-immutable.swift)
|
[✔️](typescript%2F0303-range-sum-query-immutable.ts)
-[0448 - Find All Numbers Disappeared in An Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) |
|
[✔️](c%2F0448-Find-All-Numbers-Disappeared-in-an-Array.c)
|
[✔️](cpp%2F0448-find-all-numbers-disappeared-in-an-array.cpp)
|
[✔️](csharp%2F0448-find-all-numbers-disappeared-in-an-array.cs)
|
|
[✔️](go%2F0448-find-all-numbers-disappeared-in-an-array.go)
|
|
[✔️](java%2F0448-find-all-numbers-disappeared-in-an-array.java)
|
[✔️](javascript%2F0448-find-all-numbers-disappeared-in-an-array.js)
|
[✔️](kotlin%2F0448-find-all-numbers-disappeared-in-an-array.kt)
|
[✔️](python%2F0448-find-all-numbers-disappeared-in-an-array.py)
|
|
[✔️](rust%2F0448-find-all-numbers-disappeared-in-an-array.rs)
|
|
|
[✔️](typescript%2F0448-find-all-numbers-disappeared-in-an-array.ts)
-[1189 - Maximum Number of Balloons](https://leetcode.com/problems/maximum-number-of-balloons/) |
|
[✔️](c%2F1189-Maximum-Number-of-Balloons.c)
|
[✔️](cpp%2F1189-maximum-number-of-balloons.cpp)
|
[✔️](csharp%2F1189-maximum-number-of-balloons.cs)
|
|
[✔️](go%2F1189-maximum-number-of-balloons.go)
|
|
[✔️](java%2F1189-maximum-number-of-balloons.java)
|
[✔️](javascript%2F1189-maximum-number-of-balloons.js)
|
[✔️](kotlin%2F1189-maximum-number-of-balloons.kt)
|
[✔️](python%2F1189-maximum-number-of-balloons.py)
|
|
[✔️](rust%2F1189-maximum-number-of-balloons.rs)
|
|
|
[✔️](typescript%2F1189-maximum-number-of-balloons.ts)
-[0290 - Word Pattern](https://leetcode.com/problems/word-pattern/) |
|
[✔️](c%2F0290-Word-Pattern.c)
|
[✔️](cpp%2F0290-word-pattern.cpp)
|
[✔️](csharp%2F0290-word-pattern.cs)
|
|
[✔️](go%2F0290-word-pattern.go)
|
|
[✔️](java%2F0290-word-pattern.java)
|
[✔️](javascript%2F0290-word-pattern.js)
|
[✔️](kotlin%2F0290-word-pattern.kt)
|
[✔️](python%2F0290-word-pattern.py)
|
|
[✔️](rust%2F0290-word-pattern.rs)
|
|
|
[✔️](typescript%2F0290-word-pattern.ts)
-[0705 - Design HashSet](https://leetcode.com/problems/design-hashset/) |
|
[✔️](c%2F0705-design-hashset.c)
|
[✔️](cpp%2F0705-design-hashset.cpp)
|
[✔️](csharp%2F0705-design-hashset.cs)
|
|
|
|
[✔️](java%2F0705-design-hashset.java)
|
[✔️](javascript%2F0705-design-hashset.js)
|
[✔️](kotlin%2F0705-design-hashset.kt)
|
[✔️](python%2F0705-design-hashset.py)
|
|
[✔️](rust%2F0705-design-hashset.rs)
|
|
[✔️](swift%2F0705-design-hashset.swift)
|
[✔️](typescript%2F0705-design-hashset.ts)
-[0706 - Design HashMap](https://leetcode.com/problems/design-hashmap/) |
|
[✔️](c%2F0706-design-hashmap.c)
|
[✔️](cpp%2F0706-design-hashmap.cpp)
|
[✔️](csharp%2F0706-design-hashmap.cs)
|
|
[✔️](go%2F0706-design-hashmap.go)
|
|
[✔️](java%2F0706-design-hashmap.java)
|
[✔️](javascript%2F0706-design-hashmap.js)
|
[✔️](kotlin%2F0706-design-hashmap.kt)
|
[✔️](python%2F0706-design-hashmap.py)
|
|
[✔️](rust%2F0706-design-hashmap.rs)
|
|
[✔️](swift%2F0706-design-hashmap.swift)
|
-[0912 - Sort an Array](https://leetcode.com/problems/sort-an-array/) |
|
[✔️](c%2F0912-sort-an-array.c)
|
[✔️](cpp%2F0912-sort-an-array.cpp)
|
[✔️](csharp%2F0912-sort-an-array.cs)
|
|
[✔️](go%2F0912-sort-an-array.go)
|
|
[✔️](java%2F0912-sort-an-array.java)
|
[✔️](javascript%2F0912-sort-an-array.js)
|
[✔️](kotlin%2F0912-sort-an-array.kt)
|
[✔️](python%2F0912-sort-an-array.py)
|
|
[✔️](rust%2F0912-sort-an-array.rs)
|
|
[✔️](swift%2F0912-sort-an-array.swift)
|
-[0347 - Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) |
|
[✔️](c%2F0347-top-k-frequent-elements.c)
|
[✔️](cpp%2F0347-top-k-frequent-elements.cpp)
|
[✔️](csharp%2F0347-top-k-frequent-elements.cs)
|
[✔️](dart%2F0347-top-k-frequent-elements.dart)
|
[✔️](go%2F0347-top-k-frequent-elements.go)
|
|
[✔️](java%2F0347-top-k-frequent-elements.java)
|
[✔️](javascript%2F0347-top-k-frequent-elements.js)
|
[✔️](kotlin%2F0347-top-k-frequent-elements.kt)
|
[✔️](python%2F0347-top-k-frequent-elements.py)
|
[✔️](ruby%2F0347-top-k-frequent-elements.rb)
|
[✔️](rust%2F0347-top-k-frequent-elements.rs)
|
[✔️](scala%2F0347-top-k-frequent-elements.scala)
|
[✔️](swift%2F0347-top-k-frequent-elements.swift)
|
[✔️](typescript%2F0347-top-k-frequent-elements.ts)
-[0238 - Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) |
|
[✔️](c%2F0238-product-of-array-except-self.c)
|
[✔️](cpp%2F0238-product-of-array-except-self.cpp)
|
[✔️](csharp%2F0238-product-of-array-except-self.cs)
|
|
[✔️](go%2F0238-product-of-array-except-self.go)
|
|
[✔️](java%2F0238-product-of-array-except-self.java)
|
[✔️](javascript%2F0238-product-of-array-except-self.js)
|
[✔️](kotlin%2F0238-product-of-array-except-self.kt)
|
[✔️](python%2F0238-product-of-array-except-self.py)
|
[✔️](ruby%2F0238-product-of-array-except-self.rb)
|
[✔️](rust%2F0238-product-of-array-except-self.rs)
|
|
[✔️](swift%2F0238-product-of-array-except-self.swift)
|
[✔️](typescript%2F0238-product-of-array-except-self.ts)
-[0036 - Valid Sudoku](https://leetcode.com/problems/valid-sudoku/) |
|
[✔️](c%2F0036-valid-sudoku.c)
|
[✔️](cpp%2F0036-valid-sudoku.cpp)
|
[✔️](csharp%2F0036-valid-sudoku.cs)
|
[✔️](dart%2F0036-valid-sudoku.dart)
|
[✔️](go%2F0036-valid-sudoku.go)
|
|
[✔️](java%2F0036-valid-sudoku.java)
|
[✔️](javascript%2F0036-valid-sudoku.js)
|
[✔️](kotlin%2F0036-valid-sudoku.kt)
|
[✔️](python%2F0036-valid-sudoku.py)
|
[✔️](ruby%2F0036-valid-sudoku.rb)
|
[✔️](rust%2F0036-valid-sudoku.rs)
|
[✔️](scala%2F0036-valid-sudoku.scala)
|
|
[✔️](typescript%2F0036-valid-sudoku.ts)
-[0271 - Encode and Decode Strings](https://leetcode.com/problems/encode-and-decode-strings/) |
|
|
[✔️](cpp%2F0271-encode-and-decode-strings.cpp)
|
[✔️](csharp%2F0271-encode-and-decode-strings.cs)
|
|
[✔️](go%2F0271-encode-and-decode-strings.go)
|
|
[✔️](java%2F0271-encode-and-decode-strings.java)
|
[✔️](javascript%2F0271-encode-and-decode-strings.js)
|
[✔️](kotlin%2F0271-encode-and-decode-strings.kt)
|
[✔️](python%2F0271-encode-and-decode-strings.py)
|
[✔️](ruby%2F0271-encode-and-decode-strings.rb)
|
[✔️](rust%2F0271-encode-and-decode-strings.rs)
|
|
[✔️](swift%2F0271-encode-and-decode-strings.swift)
|
[✔️](typescript%2F0271-encode-and-decode-strings.ts)
-[0128 - Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/) |
|
[✔️](c%2F0128-longest-consecutive-sequence.c)
|
[✔️](cpp%2F0128-longest-consecutive-sequence.cpp)
|
[✔️](csharp%2F0128-longest-consecutive-sequence.cs)
|
|
[✔️](go%2F0128-longest-consecutive-sequence.go)
|
|
[✔️](java%2F0128-longest-consecutive-sequence.java)
|
[✔️](javascript%2F0128-longest-consecutive-sequence.js)
|
[✔️](kotlin%2F0128-longest-consecutive-sequence.kt)
|
[✔️](python%2F0128-longest-consecutive-sequence.py)
|
[✔️](ruby%2F0128-longest-consecutive-sequence.rb)
|
[✔️](rust%2F0128-longest-consecutive-sequence.rs)
|
|
[✔️](swift%2F0128-longest-consecutive-sequence.swift)
|
[✔️](typescript%2F0128-longest-consecutive-sequence.ts)
-[0075 - Sort Colors](https://leetcode.com/problems/sort-colors/) |
|
[✔️](c%2F0075-sort-colors.c)
|
[✔️](cpp%2F0075-Sort-colors.cpp)
|
[✔️](csharp%2F0075-sort-colors.cs)
|
|
[✔️](go%2F0075-sort-colors.go)
|
|
[✔️](java%2F0075-sort-colors.java)
|
[✔️](javascript%2F0075-sort-colors.js)
|
[✔️](kotlin%2F0075-sort-colors.kt)
|
[✔️](python%2F0075-sort-colors.py)
|
|
[✔️](rust%2F0075-sort-colors.rs)
|
|
[✔️](swift%2F0075-sort-colors.swift)
|
[✔️](typescript%2F0075-sort-colors.ts)
-[0535 - Encode and Decode TinyURL](https://leetcode.com/problems/encode-and-decode-tinyurl/) |
|
[✔️](c%2F0535-encode-and-decode-tinyurl.c)
|
[✔️](cpp%2F0535-encode-and-decode-tinyurl.cpp)
|
[✔️](csharp%2F0535-encode-and-decode-tinyurl.cs)
|
|
[✔️](go%2F0535-encode-and-decode-tinyurl.go)
|
|
[✔️](java%2F0535-encode-and-decode-tinyurl.java)
|
[✔️](javascript%2F0535-encode-and-decode-tinyurl.js)
|
[✔️](kotlin%2F0535-encode-and-decode-tinyurl.kt)
|
[✔️](python%2F0535-encode-and-decode-tinyurl.py)
|
|
[✔️](rust%2F0535-encode-and-decode-tinyURL.rs)
|
|
[✔️](swift%2F0535-Encode-and-Decode-TinyURL.Swift)
|
[✔️](typescript%2F0535-encode-and-decode-tinyurl.ts)
-[0554 - Brick Wall](https://leetcode.com/problems/brick-wall/) |
|
[✔️](c%2F0554-Brick-Wall.c)
|
[✔️](cpp%2F0554-brick-wall.cpp)
|
[✔️](csharp%2F0554-brick-wall.cs)
|
|
[✔️](go%2F0554-brick-wall.go)
|
|
[✔️](java%2F0554-brick-wall.java)
|
[✔️](javascript%2F0554-brick-wall.js)
|
[✔️](kotlin%2F0554-brick-wall.kt)
|
[✔️](python%2F0554-brick-wall.py)
|
|
[✔️](rust%2F0554-brick-wall.rs)
|
|
|
[✔️](typescript%2F0554-brick-wall.ts)
-[0122 - Best Time to Buy And Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/) |
|
[✔️](c%2F0122-best-time-to-buy-and-sell-stock-ii.c)
|
[✔️](cpp%2F0122-best-time-to-buy-and-sell-stock-ii.cpp)
|
|
|
[✔️](go%2F0122-best-time-to-buy-and-sell-stock-ii.go)
|
|
[✔️](java%2F0122-best-time-to-buy-and-sell-stock-II.java)
|
[✔️](javascript%2F0122-best-time-to-buy-and-sell-stock-ii.js)
|
[✔️](kotlin%2F0122-best-time-to-buy-and-sell-stock-ii.kt)
|
[✔️](python%2F0122-best-time-to-buy-and-sell-stock-ii.py)
|
|
[✔️](rust%2F0122-best-time-to-buy-and-sell-stock-ii.rs)
|
|
|
-[0560 - Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k/) |
|
[✔️](c%2F0560-subarray-sum-equals-k.c)
|
[✔️](cpp%2F0560-subarray-sum-equals-k.cpp)
|
[✔️](csharp%2F0560-subarray-sum-equals-k.cs)
|
|
[✔️](go%2F0560-subarray-sum-equals-k.go)
|
|
[✔️](java%2F0560-subarray-sum-equals-k.java)
|
[✔️](javascript%2F0560-subarray-sum-equals-k.js)
|
[✔️](kotlin%2F0560-subarray-sum-equals-k.kt)
|
[✔️](python%2F0560-subarray-sum-equals-k.py)
|
|
[✔️](rust%2F0560-subarray-sum-equals-k.rs)
|
|
[✔️](swift%2F0560-subarray-sum-equals-k.swift)
|
[✔️](typescript%2F0560-subarray-sum-equals-k.ts)
-[1930 - Unique Length 3 Palindromic Subsequences](https://leetcode.com/problems/unique-length-3-palindromic-subsequences/) |
|
[✔️](c%2F1930-unique-length-3-palindromic-subsequences.c)
|
[✔️](cpp%2F1930-unique-length-3-palindromic-subsequences.cpp)
|
|
|
|
|
[✔️](java%2F1930-unique-length-3-palindromic-subsequences.java)
|
[✔️](javascript%2F1930-unique-length-3-palindromic-subsequences.js)
|
[✔️](kotlin%2F1930-unique-length-3-palindromic-subsequences.kt)
|
[✔️](python%2F1930-unique-length-3-palindromic-subsequences.py)
|
|
[✔️](rust%2F1930-unique-length-3-palindromic-subsequences.rs)
|
|
|
[✔️](typescript%2F1930-unique-length-3-palindromic-subsequences.ts)
-[1963 - Minimum Number of Swaps to Make The String Balanced](https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-string-balanced/) |
|
[✔️](c%2F1963-minimum-number-of-swaps-to-make-the-string-balanced.c)
|
[✔️](cpp%2F1963-minimum-number-of-swaps-to-make-the-string-balanced.cpp)
|
[✔️](csharp%2F1963-minimum-number-of-swaps-to-make-the-string-balanced.cs)
|
|
[✔️](go%2F1963-minimum-number-of-swaps-to-make-the-string-balanced.go)
|
|
[✔️](java%2F1963-minimum-number-of-swaps-to-make-the-string-balanced.java)
|
[✔️](javascript%2F1963-minimum-number-of-swaps-to-make-the-string-balanced.js)
|
[✔️](kotlin%2F1963-minimum-number-of-swaps-to-make-the-string-balanced.kt)
|
[✔️](python%2F1963-minimum-number-of-swaps-to-make-the-string-balanced.py)
|
|
[✔️](rust%2F1963-minimum-number-of-swaps-to-make-the-string-balanced.rs)
|
|
|
-[2001 - Number of Pairs of Interchangeable Rectangles](https://leetcode.com/problems/number-of-pairs-of-interchangeable-rectangles/) |
|
[✔️](c%2F2001-number-of-pairs-of-interchangeable-rectangles.c)
|
[✔️](cpp%2F2001-number-of-pairs-of-interchangeable-rectangles.cpp)
|
|
|
|
|
[✔️](java%2F2001-number-of-pairs-of-interchangeable-rectangles.java)
|
[✔️](javascript%2F2001-number-of-pairs-of-interchangeable-rectangles.js)
|
[✔️](kotlin%2F2001-number-of-pairs-of-interchangeable-rectangles.kt)
|
[✔️](python%2F2001-number-of-pairs-of-interchangeable-rectangles.py)
|
|
[✔️](rust%2F2001-number-of-pairs-of-interchangeable-rectangles.rs)
|
|
|
-[2002 - Maximum Product of The Length of Two Palindromic Subsequences](https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-subsequences/) |
|
[✔️](c%2F2002-maximum-product-of-the-length-of-two-palindromic-subsequences.c)
|
[✔️](cpp%2F2002-maximum-product-of-the-length-of-two-palindromic-subsequences.cpp)
|
[✔️](csharp%2F2002-maximum-product-of-the-length-of-two-palindromic-subsequences.cs)
|
|
[✔️](go%2F2002-maximum-product-of-the-length-of-two-palindromic-subsequences.go)
|
|
[✔️](java%2F2002-maximum-product-of-the-length-of-two-palindromic-subsequences.java)
|
[✔️](javascript%2F2002-maximum-product-of-the-length-of-two-palindromic-subsequences.js)
|
[✔️](kotlin%2F2002-maximum-product-of-the-length-of-two-palindromic-subsequences.kt)
|
[✔️](python%2F2002-maximum-product-of-the-length-of-two-palindromic-subsequences.py)
|
|
[✔️](rust%2F2002-maximum-product-of-the-length-of-two-palindromic-subsequences.rs)
|
|
|
[✔️](typescript%2F2002-maximum-product-of-the-length-of-two-palindromic-subsequences.ts)
-[2017 - Grid Game](https://leetcode.com/problems/grid-game/) |
|
|
[✔️](cpp%2F2017-grid-game.cpp)
|
|
|
|
|
[✔️](java%2F2017-grid-game.java)
|
[✔️](javascript%2F2017-grid-game.js)
|
[✔️](kotlin%2F2017-grid-game.kt)
|
[✔️](python%2F2017-grid-game.py)
|
|
[✔️](rust%2F2017-grid-game.rs)
|
|
|
-[0438 - Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/) |
|
[✔️](c%2F0438-find-all-anagrams-in-a-string.c)
|
[✔️](cpp%2F0438-find-all-anagrams-in-a-string.cpp)
|
[✔️](csharp%2F0438-find-all-anagrams-in-a-string.cs)
|
|
[✔️](go%2F0438-find-all-anagrams-in-a-string.go)
|
|
[✔️](java%2F0438-find-all-anagrams-in-a-string.java)
|
[✔️](javascript%2F0438-find-all-anagrams-in-a-string.js)
|
[✔️](kotlin%2F0438-find-all-anagrams-in-a-string.kt)
|
[✔️](python%2F0438-find-all-anagrams-in-a-string.py)
|
|
[✔️](rust%2F0438-find-all-anagrams-in-a-string.rs)
|
|
|
[✔️](typescript%2F0438-find-all-anagrams-in-a-string.ts)
-[0028 - Find The Index of The First Occurrence in a String](https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/) |
|
[✔️](c%2F0028-find-the-index-of-the-first-occurrence-in-a-string.c)
|
[✔️](cpp%2F0028-find-the-index-of-the-first-occurrence-in-a-string.cpp)
|
[✔️](csharp%2F0028-find-the-index-of-the-first-occurrence-in-a-string.cs)
|
[✔️](dart%2F0028-find-the-index-of-the-first-occurrence-in-a-string.dart)
|
[✔️](go%2F0028-find-the-index-of-the-first-occurrence-in-a-string.go)
|
|
[✔️](java%2F0028-find-the-index-of-the-first-occurrence-in-a-string.java)
|
[✔️](javascript%2F0028-find-the-index-of-the-first-occurrence-in-a-string.js)
|
[✔️](kotlin%2F0028-find-the-index-of-the-first-occurrence-in-a-string.kt)
|
[✔️](python%2F0028-find-the-index-of-the-first-occurrence-in-a-string.py)
|
|
[✔️](rust%2F0028-find-the-index-of-the-first-occurrence-in-a-string.rs)
|
|
|
-[0280 - Wiggle Sort](https://leetcode.com/problems/wiggle-sort/) |
|
|
[✔️](cpp%2F0280-wiggle-sort.cpp)
|
|
|
|
|
[✔️](java%2F0280-wiggle-sort.java)
|
|
[✔️](kotlin%2F0280-wiggle-sort.kt)
|
[✔️](python%2F0280-wiggle-sort.py)
|
|
|
|
|
-[0179 - Largest Number](https://leetcode.com/problems/largest-number/) |
|
[✔️](c%2F0179-largest-number.c)
|
[✔️](cpp%2F0179-largest-number.cpp)
|
[✔️](csharp%2F0179-largest-number.cs)
|
|
[✔️](go%2F0179-largest-number.go)
|
|
[✔️](java%2F0179-largest-number.java)
|
[✔️](javascript%2F0179-largest-number.js)
|
[✔️](kotlin%2F0179-largest-number.kt)
|
[✔️](python%2F0179-largest-number.py)
|
[✔️](ruby%2F0179-largest-number.rb)
|
[✔️](rust%2F0179-largest-number.rs)
|
[✔️](scala%2F0179-largest-number.scala)
|
[✔️](swift%2F0179-largest-number.swift)
|
[✔️](typescript%2F0179-largest-number.ts)
-[0523 - Continuous Subarray Sum](https://leetcode.com/problems/continuous-subarray-sum/) |
|
[✔️](c%2F0523-continuous-subarray-sum.c)
|
[✔️](cpp%2F0523-continuous-subarray-sum.cpp)
|
[✔️](csharp%2F0523-continuous-subarray-sum.cs)
|
|
|
|
[✔️](java%2F0523-continuous-subarray-sum.java)
|
[✔️](javascript%2F0523-continuous-subarray-sum.js)
|
[✔️](kotlin%2F0523-continuous-subarray-sum.kt)
|
[✔️](python%2F0523-continuous-subarray-sum.py)
|
|
[✔️](rust%2F0523-continuous-subarray-sum.rs)
|
|
|
-[0838 - Push Dominoes](https://leetcode.com/problems/push-dominoes/) |
|
|
[✔️](cpp%2F0838-push-dominoes.cpp)
|
|
|
|
|
[✔️](java%2F0838-push-dominoes.java)
|
[✔️](javascript%2F0838-push-dominoes.js)
|
[✔️](kotlin%2F0838-push-dominoes.kt)
|
[✔️](python%2F0838-push-dominoes.py)
|
|
|
|
|
[✔️](typescript%2F0838-push-dominoes.ts)
-[0187 - Repeated DNA Sequences](https://leetcode.com/problems/repeated-dna-sequences/) |
|
|
[✔️](cpp%2F0187-repeated-dna-sequences.cpp)
|
[✔️](csharp%2F0187-repeated-dna-sequences.cs)
|
|
[✔️](go%2F0187-repeated-dna-sequences.go)
|
|
[✔️](java%2F0187-repeated-dna-sequences.java)
|
[✔️](javascript%2F0187-repeated-dna-sequences.js)
|
[✔️](kotlin%2F0187-repeated-dna-sequences.kt)
|
[✔️](python%2F0187-repeated-dna-sequences.py)
|
|
|
|
|
[✔️](typescript%2F0187-repeated-dna-sequences.ts)
-[0380 - Insert Delete Get Random O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/) |
|
|
[✔️](cpp%2F0380-insert-delete-getrandom-o1.cpp)
|
|
|
[✔️](go%2F0380-insert-delete-getrandom-o1.go)
|
|
[✔️](java%2F0380-insert-delete-getrandom-o1.java)
|
[✔️](javascript%2F0380-insert-delete-getrandom-o1.js)
|
[✔️](kotlin%2F0380-insert-delete-getrandom-o1.kt)
|
[✔️](python%2F0380-insert-delete-getrandom-o1.py)
|
|
[✔️](rust%2F0380-insert-delete-getrandom-o1.rs)
|
|
[✔️](swift%2F0380-insert-delete-getrandom-o1.swift)
|
[✔️](typescript%2F0380-insert-delete-getrandom-o1.ts)
-[1461 - Check if a String Contains all Binary Codes of Size K](https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/) |
|
|
[✔️](cpp%2F1461-check-if-a-string-contains-all-binary-codes-of-size-k.cpp)
|
|
|
|
|
[✔️](java%2F1461-check-if-a-string-contains-all-binary-codes-of-size-k.java)
|
[✔️](javascript%2F1461-check-if-a-string-contains-all-binary-codes-of-size-k.js)
|
[✔️](kotlin%2F1461-check-if-a-string-contains-all-binary-codes-of-size-k.kt)
|
[✔️](python%2F1461-check-if-a-string-contains-all-binary-codes-of-size-k.py)
|
|
|
|
|
-[0304 - Range Sum Query 2D Immutable](https://leetcode.com/problems/range-sum-query-2d-immutable/) |
|
|
[✔️](cpp%2F0304-range-sum-query-2d-immutable.cpp)
|
|
|
|
|
[✔️](java%2F0304-range-sum-query-2d-immutable.java)
|
[✔️](javascript%2F0304-range-sum-query-2d-immutable.js)
|
[✔️](kotlin%2F0304-range-sum-query-2d-immutable.kt)
|
[✔️](python%2F0304-range-sum-query-2d-immutable.py)
|
|
|
|
[✔️](swift%2F0304-range-sum-query-2d-immutable.swift)
|
-[0665 - Non Decreasing Array](https://leetcode.com/problems/non-decreasing-array/) |
|
[✔️](c%2F0665-non-decreasing-array.c)
|
[✔️](cpp%2F0665-non-decreasing-array.cpp)
|
[✔️](csharp%2F0665-non-decreasing-array.cs)
|
|
[✔️](go%2F0665-non-decreasing-array.go)
|
|
[✔️](java%2F0665-non-decreasing-array.java)
|
[✔️](javascript%2F0665-non-decreasing-array.js)
|
[✔️](kotlin%2F0665-non-decreasing-array.kt)
|
[✔️](python%2F0665-non-decreasing-array.py)
|
|
|
[✔️](scala%2F0665-non-decreasing-array.scala)
|
|
[✔️](typescript%2F0665-non-decreasing-array.ts)
-[0041 - First Missing Positive](https://leetcode.com/problems/first-missing-positive/) |
|
[✔️](c%2F0041-first-missing-positive.c)
|
[✔️](cpp%2F0041-first-missing-positive.cpp)
|
|
|
[✔️](go%2F0041-first-missing-positive.go)
|
|
[✔️](java%2F0041-first-missing-positive.java)
|
[✔️](javascript%2F0041-first-missing-positive.js)
|
[✔️](kotlin%2F0041-first-missing-positive.kt)
|
[✔️](python%2F0041-first-missing-positive.py)
|
|
|
|
|
[✔️](typescript%2F0041-first-missing-positive.ts)
-[1822 - Sign of An Array](https://leetcode.com/problems/sign-of-the-product-of-an-array/) |
|
[✔️](c%2F1822-sign-of-the-product-of-an-array.c)
|
[✔️](cpp%2F1822-sign-of-the-product-of-an-array.cpp)
|
|
|
[✔️](go%2F1822-sign-of-the-product-of-an-array.go)
|
|
[✔️](java%2F1822-sign-of-the-product-of-an-array.java)
|
[✔️](javascript%2F1822-sign-of-the-product-of-an-array.js)
|
[✔️](kotlin%2F1822-sign-of-the-product-of-an-array.kt)
|
[✔️](python%2F1822-sign-of-the-product-of-an-array.py)
|
|
[✔️](rust%2F1822-sign-of-the-product-of-an-array.rs)
|
|
|
[✔️](typescript%2F1822-sign-of-the-product-of-an-array.ts)
-[2215 - Find the Difference of Two Arrays](https://leetcode.com/problems/find-the-difference-of-two-arrays/) |
|
[✔️](c%2F2215-find-the-difference-of-two-arrays.c)
|
[✔️](cpp%2F2215-find-the-difference-of-two-arrays.cpp)
|
[✔️](csharp%2F2215-find-the-difference-of-two-arrays.cs)
|
|
|
|
[✔️](java%2F2215-find-the-difference-of-two-arrays.java)
|
[✔️](javascript%2F2215-find-the-difference-of-two-arrays.js)
|
[✔️](kotlin%2F2215-find-the-difference-of-two-arrays.kt)
|
[✔️](python%2F2215-find-the-difference-of-two-arrays.py)
|
|
|
|
|
[✔️](typescript%2F2215-find-the-difference-of-two-arrays.ts)
-[1603 - Design Parking System](https://leetcode.com/problems/design-parking-system/) |
|
|
[✔️](cpp%2F1603-design-parking-system.cpp)
|
[✔️](csharp%2F1603-design-parking-system.cs)
|
|
|
|
[✔️](java%2F1603-design-parking-system.java)
|
[✔️](javascript%2F1603-design-parking-system.js)
|
[✔️](kotlin%2F1603-design-parking-system.kt)
|
[✔️](python%2F1603-design-parking-system.py)
|
|
|
|
|
-[2348 - Number of Zero-Filled Subarrays](https://leetcode.com/problems/number-of-zero-filled-subarrays/) |
|
|
[✔️](cpp%2F2348-number-of-zero-filled-subarrays.cpp)
|
|
|
|
|
[✔️](java%2F2348-number-of-zero-filled-subarrays.java)
|
[✔️](javascript%2F2348-number-of-zero-filled-subarrays.js)
|
[✔️](kotlin%2F2348-number-of-zero-filled-subarrays.kt)
|
[✔️](python%2F2348-number-of-zero-filled-subarrays.py)
|
|
|
|
|
-[2405 - Optimal Partition of String](https://leetcode.com/problems/optimal-partition-of-string/) |
|
|
[✔️](cpp%2F2405-optimal-partition-of-string.cpp)
|
|
|
|
|
[✔️](java%2F2405-optimal-partition-of-string.java)
|
|
[✔️](kotlin%2F2405-optimal-partition-of-string.kt)
|
[✔️](python%2F2405-optimal-partition-of-string.py)
|
|
|
|
|
-[1396 - Design Underground System](https://leetcode.com/problems/design-underground-system/) |
|
|
|
[✔️](csharp%2F1396-design-underground-system.cs)
|
|
|
|
[✔️](java%2F1396-design-underground-system.java)
|
[✔️](javascript%2F1396-design-underground-system.js)
|
[✔️](kotlin%2F1396-design-underground-system.kt)
|
[✔️](python%2F1396-design-underground-system.py)
|
|
|
|
|
-[2483 - Minimum Penalty for a Shop](https://leetcode.com/problems/minimum-penalty-for-a-shop/) |
|
|
[✔️](cpp%2F2483-minimum-penalty-for-a-shop.cpp)
|
|
|
|
|
[✔️](java%2F2483-minimum-penalty-for-a-shop.java)
|
|
[✔️](kotlin%2F2483-minimum-penalty-for-a-shop.kt)
|
[✔️](python%2F2483-minimum-penalty-for-a-shop.py)
|
|
|
|
|
-[0068 - Text Justification](https://leetcode.com/problems/text-justification/) |
|
|
|
|
|
|
|
[✔️](java%2F0068-text-justification.java)
|
|
[✔️](kotlin%2F0068-text-justification.kt)
|
[✔️](python%2F0068-text-justification.py)
|
|
|
|
|
-[2306 - Naming a Company](https://leetcode.com/problems/naming-a-company/) |
|
|
[✔️](cpp%2F2306-naming-a-company.cpp)
|
|
|
|
|
[✔️](java%2F2306-naming-a-company.java)
|
[✔️](javascript%2F2306-naming-a-company.js)
|
[✔️](kotlin%2F2306-naming-a-company.kt)
|
[✔️](python%2F2306-naming-a-company.py)
|
|
|
|
|
+| Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------- | +| [0217 - Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) |
|
[✔️](c%2F0217-contains-duplicate.c)
|
[✔️](cpp%2F0217-contains-duplicate.cpp)
|
[✔️](csharp%2F0217-contains-duplicate.cs)
|
[✔️](dart%2F0217-contains-duplicate.dart)
|
[✔️](go%2F0217-contains-duplicate.go)
|
|
[✔️](java%2F0217-contains-duplicate.java)
|
[✔️](javascript%2F0217-contains-duplicate.js)
|
[✔️](kotlin%2F0217-contains-duplicate.kt)
|
[✔️](python%2F0217-contains-duplicate.py)
|
[✔️](ruby%2F0217-contains-duplicate.rb)
|
[✔️](rust%2F0217-contains-duplicate.rs)
|
[✔️](scala%2F0217-contains-duplicate.scala)
|
[✔️](swift%2F0217-contains-duplicate.swift)
|
[✔️](typescript%2F0217-contains-duplicate.ts)
| +| [0242 - Valid Anagram](https://leetcode.com/problems/valid-anagram/) |
|
[✔️](c%2F0242-valid-anagram.c)
|
[✔️](cpp%2F0242-valid-anagram.cpp)
|
[✔️](csharp%2F0242-valid-anagram.cs)
|
[✔️](dart%2F0242-valid-anagram.dart)
|
[✔️](go%2F0242-valid-anagram.go)
|
|
[✔️](java%2F0242-valid-anagram.java)
|
[✔️](javascript%2F0242-valid-anagram.js)
|
[✔️](kotlin%2F0242-valid-anagram.kt)
|
[✔️](python%2F0242-valid-anagram.py)
|
[✔️](ruby%2F0242-valid-anagram.rb)
|
[✔️](rust%2F0242-valid-anagram.rs)
|
[✔️](scala%2F0242-valid-anagram.scala)
|
[✔️](swift%2F0242-valid-anagram.swift)
|
[✔️](typescript%2F0242-valid-anagram.ts)
| +| [1929 - Concatenation of Array](https://leetcode.com/problems/concatenation-of-array/) |
|
[✔️](c%2F1929-concatenation-of-array.c)
|
[✔️](cpp%2F1929-concatenation-of-array.cpp)
|
[✔️](csharp%2F1929-concatenation-of-array.cs)
|
[✔️](dart%2F1929-concatenation-of-array.dart)
|
[✔️](go%2F1929-concatenation-of-array.go)
|
|
[✔️](java%2F1929-concatenation-of-array.java)
|
[✔️](javascript%2F1929-concatenation-of-array.js)
|
[✔️](kotlin%2F1929-concatenation-of-array.kt)
|
[✔️](python%2F1929-concatenation-of-array.py)
|
[✔️](ruby%2F1929-concatenation-of-array.rb)
|
[✔️](rust%2F1929-concatenation-of-array.rs)
|
[✔️](scala%2F1929-concatenation-of-array.scala)
|
[✔️](swift%2F1929-concatenation-of-array.swift)
|
[✔️](typescript%2F1929-concatenation-of-array.ts)
| +| [1299 - Replace Elements With Greatest Element On Right Side](https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/) |
|
[✔️](c%2F1299-Replace-Elements-With-Greatest-Element-On-Right-Side.c)
|
[✔️](cpp%2F1299-Replace-Elements-with-Greatest-Element-on-Right-Side.cpp)
|
[✔️](csharp%2F1299-Replace-Elements-With-Greatest-Element-On-Right-Side.cs)
|
[✔️](dart%2F1299-replace-elements-with-greatest-element-on-right-side.dart)
|
[✔️](go%2F1299-Replace-Elements-With-Greatest-Element-On-Right-Side.go)
|
|
[✔️](java%2F1299-Replace-Elements-With-Greatest-Element-On-Right-Side.java)
|
[✔️](javascript%2F1299-Replace-Elements-with-Greatest-Element-on-Right-Side.js)
|
[✔️](kotlin%2F1299-replace-elements-with-greatest-element-on-right-side.kt)
|
[✔️](python%2F1299-replace-elements-with-greatest-element-on-right-side.py)
|
[✔️](ruby%2F1299-replace-elements-with-greatest-element-on-right-side.rb)
|
[✔️](rust%2F1299-Replace-Elements-With-Greatest-Element-On-Right-Side.rs)
|
|
[✔️](swift%2F1299-replace-elements-with-greatest-element-on-right-side.swift)
|
[✔️](typescript%2F1299-Replace-Elements-With-Greatest-Element-On-Right-Side.ts)
| +| [0392 - Is Subsequence](https://leetcode.com/problems/is-subsequence/) |
|
[✔️](c%2F0392-is-subsequence.c)
|
[✔️](cpp%2F0392-is-subsequence.cpp)
|
[✔️](csharp%2F0392-is-subsequence.cs)
|
[✔️](dart%2F0392-is-subsequence.dart)
|
[✔️](go%2F0392-is-subsequence.go)
|
|
[✔️](java%2F0392-is-subsequence.java)
|
[✔️](javascript%2F0392-is-subsequence.js)
|
[✔️](kotlin%2F0392-is-subsequence.kt)
|
[✔️](python%2F0392-is-subsequence.py)
|
[✔️](ruby%2F0392-is-subsequence.rb)
|
[✔️](rust%2F0392-is-subsequence.rs)
|
|
[✔️](swift%2F0392-is-subsequence.swift)
|
[✔️](typescript%2F0392-is-subsequence.ts)
| +| [0058 - Length of Last Word](https://leetcode.com/problems/length-of-last-word/) |
|
[✔️](c%2F0058-length-of-last-word.c)
|
[✔️](cpp%2F0058-length-of-last-word.cpp)
|
[✔️](csharp%2F0058-length-of-last-word.cs)
|
[✔️](dart%2F0058-length-of-last-word.dart)
|
[✔️](go%2F0058-Length-of-Last-Word.go)
|
|
[✔️](java%2F0058-length-of-last-word.java)
|
[✔️](javascript%2F0058-length-of-last-word.js)
|
[✔️](kotlin%2F0058-length-of-last-word.kt)
|
[✔️](python%2F0058-length-of-last-word.py)
|
[✔️](ruby%2F0058-length-of-last-word.rb)
|
[✔️](rust%2F0058-length-of-last-word.rs)
|
[✔️](scala%2F0058-length-of-last-word.scala)
|
[✔️](swift%2F0058-Length-of-Last-Word.swift)
|
[✔️](typescript%2F0058-length-of-last-word.ts)
| +| [0001 - Two Sum](https://leetcode.com/problems/two-sum/) |
|
[✔️](c%2F0001-two-sum.c)
|
[✔️](cpp%2F0001-two-sum.cpp)
|
[✔️](csharp%2F0001-two-sum.cs)
|
[✔️](dart%2F0001-two-sum.dart)
|
[✔️](go%2F0001-two-sum.go)
|
|
[✔️](java%2F0001-two-sum.java)
|
[✔️](javascript%2F0001-two-sum.js)
|
[✔️](kotlin%2F0001-two-sum.kt)
|
[✔️](python%2F0001-two-sum.py)
|
[✔️](ruby%2F0001-two-sum.rb)
|
[✔️](rust%2F0001-two-sum.rs)
|
[✔️](scala%2F0001-two-sum.scala)
|
[✔️](swift%2F0001-two-sum.swift)
|
[✔️](typescript%2F0001-two-sum.ts)
| +| [0014 - Longest Common Prefix](https://leetcode.com/problems/longest-common-prefix/) |
|
[✔️](c%2F0014-Longest-Common-Prefix.c)
|
[✔️](cpp%2F0014-longest-common-prefix.cpp)
|
[✔️](csharp%2F0014-longest-common-prefix.cs)
|
[✔️](dart%2F0014-longest-common-prefix.dart)
|
[✔️](go%2F0014-longest-common-prefix.go)
|
|
[✔️](java%2F0014-longest-common-prefix.java)
|
[✔️](javascript%2F0014-longest-common-prefix.js)
|
[✔️](kotlin%2F0014-longest-common-prefix.kt)
|
[✔️](python%2F0014-longest-common-prefix.py)
|
|
[✔️](rust%2F0014-longest-common-prefix.rs)
|
|
[✔️](swift%2F0014-longest-common-prefix.swift)
|
[✔️](typescript%2F0014-longest-common-prefix.ts)
| +| [0049 - Group Anagrams](https://leetcode.com/problems/group-anagrams/) |
|
[✔️](c%2F0049-group-anagrams.c)
|
[✔️](cpp%2F0049-group-anagrams.cpp)
|
[✔️](csharp%2F0049-group-anagrams.cs)
|
[✔️](dart%2F0049-group-anagrams.dart)
|
[✔️](go%2F0049-group-anagrams.go)
|
|
[✔️](java%2F0049-group-anagrams.java)
|
[✔️](javascript%2F0049-group-anagrams.js)
|
[✔️](kotlin%2F0049-group-anagrams.kt)
|
[✔️](python%2F0049-group-anagrams.py)
|
[✔️](ruby%2F0049-group-anagrams.rb)
|
[✔️](rust%2F0049-group-anagrams.rs)
|
[✔️](scala%2F0049-group-anagrams.scala)
|
[✔️](swift%2F0049-group-anagrams.swift)
|
[✔️](typescript%2F0049-group-anagrams.ts)
| +| [0118 - Pascals Triangle](https://leetcode.com/problems/pascals-triangle/) |
|
[✔️](c%2F0118-pascals-triangle.c)
|
[✔️](cpp%2F0118-pascals-triangle.cpp)
|
[✔️](csharp%2F0118-pascals-triangle.cs)
|
[✔️](dart%2F0118-pascals-triangle.dart)
|
[✔️](go%2F0118-pascals-triangle.go)
|
|
[✔️](java%2F0118-pascals-triangle.java)
|
[✔️](javascript%2F0118-pascals-triangle.js)
|
[✔️](kotlin%2F0118-pascals-triangle.kt)
|
[✔️](python%2F0118-pascals-triangle.py)
|
|
[✔️](rust%2F0118-pascals-triangle.rs)
|
|
|
[✔️](typescript%2F0118-pascals-triangle.ts)
| +| [0027 - Remove Element](https://leetcode.com/problems/remove-element/) |
|
[✔️](c%2F0027-remove-element.c)
|
[✔️](cpp%2F0027-remove-element.cpp)
|
[✔️](csharp%2F0027-remove-element.cs)
|
[✔️](dart%2F0027-remove-element.dart)
|
[✔️](go%2F0027-remove-element.go)
|
|
[✔️](java%2F0027-remove-element.java)
|
[✔️](javascript%2F0027-remove-element.js)
|
[✔️](kotlin%2F0027-remove-element.kt)
|
[✔️](python%2F0027-remove-element.py)
|
|
[✔️](rust%2F0027-remove-element.rs)
|
|
[✔️](swift%2F0027-Remove-Element.swift)
|
[✔️](typescript%2F0027-remove-element.ts)
| +| [0929 - Unique Email Addresses](https://leetcode.com/problems/unique-email-addresses/) |
|
[✔️](c%2F0929-unique-email-addresses.c)
|
[✔️](cpp%2F0929-unique-email-addresses.cpp)
|
[✔️](csharp%2F0929-unique-email-addresses.cs)
|
[✔️](dart%2F0929-unique-email-addresses.dart)
|
[✔️](go%2F0929-unique-email-addresses.go)
|
|
[✔️](java%2F0929-unique-email-addresses.java)
|
[✔️](javascript%2F0929-unique-email-addresses.js)
|
[✔️](kotlin%2F0929-unique-email-addresses.kt)
|
[✔️](python%2F0929-unique-email-addresses.py)
|
|
[✔️](rust%2F0929-unique-email-addresses.rs)
|
|
[✔️](swift%2F0929-unique-email-addresses.swift)
|
[✔️](typescript%2F0929-unique-email-addresses.ts)
| +| [0205 - Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/) |
|
[✔️](c%2F0205-isomorphic-strings.c)
|
[✔️](cpp%2F0205-Isomorphic-Strings.cpp)
|
[✔️](csharp%2F0205-isomorphic-strings.cs)
|
|
[✔️](go%2F0205-isomorphic-strings.go)
|
|
[✔️](java%2F0205-isomorphic-strings.java)
|
[✔️](javascript%2F0205-isomorphic-strings.js)
|
[✔️](kotlin%2F0205-isomorphic-strings.kt)
|
[✔️](python%2F0205-isomorphic-strings.py)
|
|
[✔️](rust%2F0205-isomorphic-strings.rs)
|
|
[✔️](swift%2F0205-isomorphic-strings.swift)
|
[✔️](typescript%2F0205-isomorphic-strings.ts)
| +| [0605 - Can Place Flowers](https://leetcode.com/problems/can-place-flowers/) |
|
[✔️](c%2F0605-can-place-flowers.c)
|
[✔️](cpp%2F0605-can-place-flowers.cpp)
|
[✔️](csharp%2F0605-can-place-flowers.cs)
|
|
[✔️](go%2F0605-can-place-flowers.go)
|
|
[✔️](java%2F0605-can-place-flowers.java)
|
[✔️](javascript%2F0605-can-place-flowers.js)
|
[✔️](kotlin%2F0605-can-place-flowers.kt)
|
[✔️](python%2F0605-can-place-flowers.py)
|
|
[✔️](rust%2F0605-can-place-flowers.rs)
|
|
[✔️](swift%2F0605-can-place-flowers.swift)
|
[✔️](typescript%2F0605-can-place-flowers.ts)
| +| [0169 - Majority Element](https://leetcode.com/problems/majority-element/) |
|
[✔️](c%2F0169-majority-element.c)
|
[✔️](cpp%2F0169-majority-element.cpp)
|
[✔️](csharp%2F0169-majority-element.cs)
|
[✔️](dart%2F0169-majority-element.dart)
|
[✔️](go%2F0169-majority-element.go)
|
|
[✔️](java%2F0169-majority-element.java)
|
[✔️](javascript%2F0169-majority-element.js)
|
[✔️](kotlin%2F0169-majority-element.kt)
|
[✔️](python%2F0169-majority-element.py)
|
|
[✔️](rust%2F0169-majority-element.rs)
|
|
[✔️](swift%2F0169-majority-element.swift)
|
[✔️](typescript%2F0169-majority-element.ts)
| +| [0496 - Next Greater Element I](https://leetcode.com/problems/next-greater-element-i/) |
|
[✔️](c%2F0496-next-greater-element-i.c)
|
[✔️](cpp%2F0496-next-greater-element-i.cpp)
|
[✔️](csharp%2F0496-next-greater-element-i.cs)
|
|
[✔️](go%2F0496-next-greater-element-i.go)
|
|
[✔️](java%2F0496-next-greater-element-i.java)
|
[✔️](javascript%2F0496-next-greater-element-i.js)
|
[✔️](kotlin%2F0496-next-greater-element-i.kt)
|
[✔️](python%2F0496-next-greater-element-i.py)
|
|
[✔️](rust%2F0496-next-greater-element-I.rs)
|
|
|
[✔️](typescript%2F0496-next-greater-element-i.ts)
| +| [0724 - Find Pivot Index](https://leetcode.com/problems/find-pivot-index/) |
|
[✔️](c%2F0724-find-pivot-index.c)
|
[✔️](cpp%2F0724-find-pivot-index.cpp)
|
[✔️](csharp%2F0724-find-pivot-index.cs)
|
|
[✔️](go%2F0724-find-pivot-index.go)
|
|
[✔️](java%2F0724-find-pivot-index.java)
|
[✔️](javascript%2F0724-find-pivot-index.js)
|
[✔️](kotlin%2F0724-find-pivot-index.kt)
|
[✔️](python%2F0724-find-pivot-index.py)
|
|
[✔️](rust%2F0724-find-pivot-index.rs)
|
|
[✔️](swift%2F0724-find-pivot-index.swift)
|
[✔️](typescript%2F0724-find-pivot-index.ts)
| +| [0303 - Range Sum Query - Immutable](https://leetcode.com/problems/range-sum-query-immutable/) |
|
[✔️](c%2F0303-range-sum-query-immutable.c)
|
[✔️](cpp%2F0303-range-sum-query-immutable.cpp)
|
[✔️](csharp%2F0303-range-sum-query-immutable.cs)
|
|
[✔️](go%2F0303-range-sum-query.go)
|
|
[✔️](java%2F0303-range-sum-query-immutable.java)
|
[✔️](javascript%2F0303-range-sum-query-immutable.js)
|
[✔️](kotlin%2F0303-range-sum-query-immutable.kt)
|
[✔️](python%2F0303-range-sum-query-immutable.py)
|
|
[✔️](rust%2F0303-range-sum-query-immutable.rs)
|
|
[✔️](swift%2F0303-range-sum-query-immutable.swift)
|
[✔️](typescript%2F0303-range-sum-query-immutable.ts)
| +| [0448 - Find All Numbers Disappeared in An Array](https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/) |
|
[✔️](c%2F0448-Find-All-Numbers-Disappeared-in-an-Array.c)
|
[✔️](cpp%2F0448-find-all-numbers-disappeared-in-an-array.cpp)
|
[✔️](csharp%2F0448-find-all-numbers-disappeared-in-an-array.cs)
|
|
[✔️](go%2F0448-find-all-numbers-disappeared-in-an-array.go)
|
|
[✔️](java%2F0448-find-all-numbers-disappeared-in-an-array.java)
|
[✔️](javascript%2F0448-find-all-numbers-disappeared-in-an-array.js)
|
[✔️](kotlin%2F0448-find-all-numbers-disappeared-in-an-array.kt)
|
[✔️](python%2F0448-find-all-numbers-disappeared-in-an-array.py)
|
|
[✔️](rust%2F0448-find-all-numbers-disappeared-in-an-array.rs)
|
|
|
[✔️](typescript%2F0448-find-all-numbers-disappeared-in-an-array.ts)
| +| [1189 - Maximum Number of Balloons](https://leetcode.com/problems/maximum-number-of-balloons/) |
|
[✔️](c%2F1189-Maximum-Number-of-Balloons.c)
|
[✔️](cpp%2F1189-maximum-number-of-balloons.cpp)
|
[✔️](csharp%2F1189-maximum-number-of-balloons.cs)
|
|
[✔️](go%2F1189-maximum-number-of-balloons.go)
|
|
[✔️](java%2F1189-maximum-number-of-balloons.java)
|
[✔️](javascript%2F1189-maximum-number-of-balloons.js)
|
[✔️](kotlin%2F1189-maximum-number-of-balloons.kt)
|
[✔️](python%2F1189-maximum-number-of-balloons.py)
|
|
[✔️](rust%2F1189-maximum-number-of-balloons.rs)
|
|
|
[✔️](typescript%2F1189-maximum-number-of-balloons.ts)
| +| [0290 - Word Pattern](https://leetcode.com/problems/word-pattern/) |
|
[✔️](c%2F0290-Word-Pattern.c)
|
[✔️](cpp%2F0290-word-pattern.cpp)
|
[✔️](csharp%2F0290-word-pattern.cs)
|
|
[✔️](go%2F0290-word-pattern.go)
|
|
[✔️](java%2F0290-word-pattern.java)
|
[✔️](javascript%2F0290-word-pattern.js)
|
[✔️](kotlin%2F0290-word-pattern.kt)
|
[✔️](python%2F0290-word-pattern.py)
|
|
[✔️](rust%2F0290-word-pattern.rs)
|
|
|
[✔️](typescript%2F0290-word-pattern.ts)
| +| [0705 - Design HashSet](https://leetcode.com/problems/design-hashset/) |
|
[✔️](c%2F0705-design-hashset.c)
|
[✔️](cpp%2F0705-design-hashset.cpp)
|
[✔️](csharp%2F0705-design-hashset.cs)
|
|
|
|
[✔️](java%2F0705-design-hashset.java)
|
[✔️](javascript%2F0705-design-hashset.js)
|
[✔️](kotlin%2F0705-design-hashset.kt)
|
[✔️](python%2F0705-design-hashset.py)
|
|
[✔️](rust%2F0705-design-hashset.rs)
|
|
[✔️](swift%2F0705-design-hashset.swift)
|
[✔️](typescript%2F0705-design-hashset.ts)
| +| [0706 - Design HashMap](https://leetcode.com/problems/design-hashmap/) |
|
[✔️](c%2F0706-design-hashmap.c)
|
[✔️](cpp%2F0706-design-hashmap.cpp)
|
[✔️](csharp%2F0706-design-hashmap.cs)
|
|
[✔️](go%2F0706-design-hashmap.go)
|
|
[✔️](java%2F0706-design-hashmap.java)
|
[✔️](javascript%2F0706-design-hashmap.js)
|
[✔️](kotlin%2F0706-design-hashmap.kt)
|
[✔️](python%2F0706-design-hashmap.py)
|
|
[✔️](rust%2F0706-design-hashmap.rs)
|
|
[✔️](swift%2F0706-design-hashmap.swift)
|
| +| [0912 - Sort an Array](https://leetcode.com/problems/sort-an-array/) |
|
[✔️](c%2F0912-sort-an-array.c)
|
[✔️](cpp%2F0912-sort-an-array.cpp)
|
[✔️](csharp%2F0912-sort-an-array.cs)
|
|
[✔️](go%2F0912-sort-an-array.go)
|
|
[✔️](java%2F0912-sort-an-array.java)
|
[✔️](javascript%2F0912-sort-an-array.js)
|
[✔️](kotlin%2F0912-sort-an-array.kt)
|
[✔️](python%2F0912-sort-an-array.py)
|
|
[✔️](rust%2F0912-sort-an-array.rs)
|
|
[✔️](swift%2F0912-sort-an-array.swift)
|
| +| [0347 - Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) |
|
[✔️](c%2F0347-top-k-frequent-elements.c)
|
[✔️](cpp%2F0347-top-k-frequent-elements.cpp)
|
[✔️](csharp%2F0347-top-k-frequent-elements.cs)
|
[✔️](dart%2F0347-top-k-frequent-elements.dart)
|
[✔️](go%2F0347-top-k-frequent-elements.go)
|
|
[✔️](java%2F0347-top-k-frequent-elements.java)
|
[✔️](javascript%2F0347-top-k-frequent-elements.js)
|
[✔️](kotlin%2F0347-top-k-frequent-elements.kt)
|
[✔️](python%2F0347-top-k-frequent-elements.py)
|
[✔️](ruby%2F0347-top-k-frequent-elements.rb)
|
[✔️](rust%2F0347-top-k-frequent-elements.rs)
|
[✔️](scala%2F0347-top-k-frequent-elements.scala)
|
[✔️](swift%2F0347-top-k-frequent-elements.swift)
|
[✔️](typescript%2F0347-top-k-frequent-elements.ts)
| +| [0238 - Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) |
|
[✔️](c%2F0238-product-of-array-except-self.c)
|
[✔️](cpp%2F0238-product-of-array-except-self.cpp)
|
[✔️](csharp%2F0238-product-of-array-except-self.cs)
|
|
[✔️](go%2F0238-product-of-array-except-self.go)
|
|
[✔️](java%2F0238-product-of-array-except-self.java)
|
[✔️](javascript%2F0238-product-of-array-except-self.js)
|
[✔️](kotlin%2F0238-product-of-array-except-self.kt)
|
[✔️](python%2F0238-product-of-array-except-self.py)
|
[✔️](ruby%2F0238-product-of-array-except-self.rb)
|
[✔️](rust%2F0238-product-of-array-except-self.rs)
|
|
[✔️](swift%2F0238-product-of-array-except-self.swift)
|
[✔️](typescript%2F0238-product-of-array-except-self.ts)
| +| [0036 - Valid Sudoku](https://leetcode.com/problems/valid-sudoku/) |
|
[✔️](c%2F0036-valid-sudoku.c)
|
[✔️](cpp%2F0036-valid-sudoku.cpp)
|
[✔️](csharp%2F0036-valid-sudoku.cs)
|
[✔️](dart%2F0036-valid-sudoku.dart)
|
[✔️](go%2F0036-valid-sudoku.go)
|
|
[✔️](java%2F0036-valid-sudoku.java)
|
[✔️](javascript%2F0036-valid-sudoku.js)
|
[✔️](kotlin%2F0036-valid-sudoku.kt)
|
[✔️](python%2F0036-valid-sudoku.py)
|
[✔️](ruby%2F0036-valid-sudoku.rb)
|
[✔️](rust%2F0036-valid-sudoku.rs)
|
[✔️](scala%2F0036-valid-sudoku.scala)
|
|
[✔️](typescript%2F0036-valid-sudoku.ts)
| +| [0271 - Encode and Decode Strings](https://leetcode.com/problems/encode-and-decode-strings/) |
|
|
[✔️](cpp%2F0271-encode-and-decode-strings.cpp)
|
[✔️](csharp%2F0271-encode-and-decode-strings.cs)
|
|
[✔️](go%2F0271-encode-and-decode-strings.go)
|
|
[✔️](java%2F0271-encode-and-decode-strings.java)
|
[✔️](javascript%2F0271-encode-and-decode-strings.js)
|
[✔️](kotlin%2F0271-encode-and-decode-strings.kt)
|
[✔️](python%2F0271-encode-and-decode-strings.py)
|
[✔️](ruby%2F0271-encode-and-decode-strings.rb)
|
[✔️](rust%2F0271-encode-and-decode-strings.rs)
|
|
[✔️](swift%2F0271-encode-and-decode-strings.swift)
|
[✔️](typescript%2F0271-encode-and-decode-strings.ts)
| +| [0128 - Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/) |
|
[✔️](c%2F0128-longest-consecutive-sequence.c)
|
[✔️](cpp%2F0128-longest-consecutive-sequence.cpp)
|
[✔️](csharp%2F0128-longest-consecutive-sequence.cs)
|
|
[✔️](go%2F0128-longest-consecutive-sequence.go)
|
|
[✔️](java%2F0128-longest-consecutive-sequence.java)
|
[✔️](javascript%2F0128-longest-consecutive-sequence.js)
|
[✔️](kotlin%2F0128-longest-consecutive-sequence.kt)
|
[✔️](python%2F0128-longest-consecutive-sequence.py)
|
[✔️](ruby%2F0128-longest-consecutive-sequence.rb)
|
[✔️](rust%2F0128-longest-consecutive-sequence.rs)
|
|
[✔️](swift%2F0128-longest-consecutive-sequence.swift)
|
[✔️](typescript%2F0128-longest-consecutive-sequence.ts)
| +| [0075 - Sort Colors](https://leetcode.com/problems/sort-colors/) |
|
[✔️](c%2F0075-sort-colors.c)
|
[✔️](cpp%2F0075-Sort-colors.cpp)
|
[✔️](csharp%2F0075-sort-colors.cs)
|
|
[✔️](go%2F0075-sort-colors.go)
|
|
[✔️](java%2F0075-sort-colors.java)
|
[✔️](javascript%2F0075-sort-colors.js)
|
[✔️](kotlin%2F0075-sort-colors.kt)
|
[✔️](python%2F0075-sort-colors.py)
|
|
[✔️](rust%2F0075-sort-colors.rs)
|
|
[✔️](swift%2F0075-sort-colors.swift)
|
[✔️](typescript%2F0075-sort-colors.ts)
| +| [0535 - Encode and Decode TinyURL](https://leetcode.com/problems/encode-and-decode-tinyurl/) |
|
[✔️](c%2F0535-encode-and-decode-tinyurl.c)
|
[✔️](cpp%2F0535-encode-and-decode-tinyurl.cpp)
|
[✔️](csharp%2F0535-encode-and-decode-tinyurl.cs)
|
|
[✔️](go%2F0535-encode-and-decode-tinyurl.go)
|
|
[✔️](java%2F0535-encode-and-decode-tinyurl.java)
|
[✔️](javascript%2F0535-encode-and-decode-tinyurl.js)
|
[✔️](kotlin%2F0535-encode-and-decode-tinyurl.kt)
|
[✔️](python%2F0535-encode-and-decode-tinyurl.py)
|
|
[✔️](rust%2F0535-encode-and-decode-tinyURL.rs)
|
|
[✔️](swift%2F0535-Encode-and-Decode-TinyURL.Swift)
|
[✔️](typescript%2F0535-encode-and-decode-tinyurl.ts)
| +| [0554 - Brick Wall](https://leetcode.com/problems/brick-wall/) |
|
[✔️](c%2F0554-Brick-Wall.c)
|
[✔️](cpp%2F0554-brick-wall.cpp)
|
[✔️](csharp%2F0554-brick-wall.cs)
|
|
[✔️](go%2F0554-brick-wall.go)
|
|
[✔️](java%2F0554-brick-wall.java)
|
[✔️](javascript%2F0554-brick-wall.js)
|
[✔️](kotlin%2F0554-brick-wall.kt)
|
[✔️](python%2F0554-brick-wall.py)
|
|
[✔️](rust%2F0554-brick-wall.rs)
|
|
|
[✔️](typescript%2F0554-brick-wall.ts)
| +| [0122 - Best Time to Buy And Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/) |
|
[✔️](c%2F0122-best-time-to-buy-and-sell-stock-ii.c)
|
[✔️](cpp%2F0122-best-time-to-buy-and-sell-stock-ii.cpp)
|
|
|
[✔️](go%2F0122-best-time-to-buy-and-sell-stock-ii.go)
|
|
[✔️](java%2F0122-best-time-to-buy-and-sell-stock-II.java)
|
[✔️](javascript%2F0122-best-time-to-buy-and-sell-stock-ii.js)
|
[✔️](kotlin%2F0122-best-time-to-buy-and-sell-stock-ii.kt)
|
[✔️](python%2F0122-best-time-to-buy-and-sell-stock-ii.py)
|
|
[✔️](rust%2F0122-best-time-to-buy-and-sell-stock-ii.rs)
|
|
|
| +| [0560 - Subarray Sum Equals K](https://leetcode.com/problems/subarray-sum-equals-k/) |
|
[✔️](c%2F0560-subarray-sum-equals-k.c)
|
[✔️](cpp%2F0560-subarray-sum-equals-k.cpp)
|
[✔️](csharp%2F0560-subarray-sum-equals-k.cs)
|
|
[✔️](go%2F0560-subarray-sum-equals-k.go)
|
|
[✔️](java%2F0560-subarray-sum-equals-k.java)
|
[✔️](javascript%2F0560-subarray-sum-equals-k.js)
|
[✔️](kotlin%2F0560-subarray-sum-equals-k.kt)
|
[✔️](python%2F0560-subarray-sum-equals-k.py)
|
|
[✔️](rust%2F0560-subarray-sum-equals-k.rs)
|
|
[✔️](swift%2F0560-subarray-sum-equals-k.swift)
|
[✔️](typescript%2F0560-subarray-sum-equals-k.ts)
| +| [1930 - Unique Length 3 Palindromic Subsequences](https://leetcode.com/problems/unique-length-3-palindromic-subsequences/) |
|
[✔️](c%2F1930-unique-length-3-palindromic-subsequences.c)
|
[✔️](cpp%2F1930-unique-length-3-palindromic-subsequences.cpp)
|
|
|
|
|
[✔️](java%2F1930-unique-length-3-palindromic-subsequences.java)
|
[✔️](javascript%2F1930-unique-length-3-palindromic-subsequences.js)
|
[✔️](kotlin%2F1930-unique-length-3-palindromic-subsequences.kt)
|
[✔️](python%2F1930-unique-length-3-palindromic-subsequences.py)
|
|
[✔️](rust%2F1930-unique-length-3-palindromic-subsequences.rs)
|
|
|
[✔️](typescript%2F1930-unique-length-3-palindromic-subsequences.ts)
| +| [1963 - Minimum Number of Swaps to Make The String Balanced](https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-string-balanced/) |
|
[✔️](c%2F1963-minimum-number-of-swaps-to-make-the-string-balanced.c)
|
[✔️](cpp%2F1963-minimum-number-of-swaps-to-make-the-string-balanced.cpp)
|
[✔️](csharp%2F1963-minimum-number-of-swaps-to-make-the-string-balanced.cs)
|
|
[✔️](go%2F1963-minimum-number-of-swaps-to-make-the-string-balanced.go)
|
|
[✔️](java%2F1963-minimum-number-of-swaps-to-make-the-string-balanced.java)
|
[✔️](javascript%2F1963-minimum-number-of-swaps-to-make-the-string-balanced.js)
|
[✔️](kotlin%2F1963-minimum-number-of-swaps-to-make-the-string-balanced.kt)
|
[✔️](python%2F1963-minimum-number-of-swaps-to-make-the-string-balanced.py)
|
|
[✔️](rust%2F1963-minimum-number-of-swaps-to-make-the-string-balanced.rs)
|
|
|
| +| [2001 - Number of Pairs of Interchangeable Rectangles](https://leetcode.com/problems/number-of-pairs-of-interchangeable-rectangles/) |
|
[✔️](c%2F2001-number-of-pairs-of-interchangeable-rectangles.c)
|
[✔️](cpp%2F2001-number-of-pairs-of-interchangeable-rectangles.cpp)
|
|
|
|
|
[✔️](java%2F2001-number-of-pairs-of-interchangeable-rectangles.java)
|
[✔️](javascript%2F2001-number-of-pairs-of-interchangeable-rectangles.js)
|
[✔️](kotlin%2F2001-number-of-pairs-of-interchangeable-rectangles.kt)
|
[✔️](python%2F2001-number-of-pairs-of-interchangeable-rectangles.py)
|
|
[✔️](rust%2F2001-number-of-pairs-of-interchangeable-rectangles.rs)
|
|
|
| +| [2002 - Maximum Product of The Length of Two Palindromic Subsequences](https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-subsequences/) |
|
[✔️](c%2F2002-maximum-product-of-the-length-of-two-palindromic-subsequences.c)
|
[✔️](cpp%2F2002-maximum-product-of-the-length-of-two-palindromic-subsequences.cpp)
|
[✔️](csharp%2F2002-maximum-product-of-the-length-of-two-palindromic-subsequences.cs)
|
|
[✔️](go%2F2002-maximum-product-of-the-length-of-two-palindromic-subsequences.go)
|
|
[✔️](java%2F2002-maximum-product-of-the-length-of-two-palindromic-subsequences.java)
|
[✔️](javascript%2F2002-maximum-product-of-the-length-of-two-palindromic-subsequences.js)
|
[✔️](kotlin%2F2002-maximum-product-of-the-length-of-two-palindromic-subsequences.kt)
|
[✔️](python%2F2002-maximum-product-of-the-length-of-two-palindromic-subsequences.py)
|
|
[✔️](rust%2F2002-maximum-product-of-the-length-of-two-palindromic-subsequences.rs)
|
|
|
[✔️](typescript%2F2002-maximum-product-of-the-length-of-two-palindromic-subsequences.ts)
| +| [2017 - Grid Game](https://leetcode.com/problems/grid-game/) |
|
|
[✔️](cpp%2F2017-grid-game.cpp)
|
|
|
|
|
[✔️](java%2F2017-grid-game.java)
|
[✔️](javascript%2F2017-grid-game.js)
|
[✔️](kotlin%2F2017-grid-game.kt)
|
[✔️](python%2F2017-grid-game.py)
|
|
[✔️](rust%2F2017-grid-game.rs)
|
|
|
| +| [0438 - Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/) |
|
[✔️](c%2F0438-find-all-anagrams-in-a-string.c)
|
[✔️](cpp%2F0438-find-all-anagrams-in-a-string.cpp)
|
[✔️](csharp%2F0438-find-all-anagrams-in-a-string.cs)
|
|
[✔️](go%2F0438-find-all-anagrams-in-a-string.go)
|
|
[✔️](java%2F0438-find-all-anagrams-in-a-string.java)
|
[✔️](javascript%2F0438-find-all-anagrams-in-a-string.js)
|
[✔️](kotlin%2F0438-find-all-anagrams-in-a-string.kt)
|
[✔️](python%2F0438-find-all-anagrams-in-a-string.py)
|
|
[✔️](rust%2F0438-find-all-anagrams-in-a-string.rs)
|
|
|
[✔️](typescript%2F0438-find-all-anagrams-in-a-string.ts)
| +| [0028 - Find The Index of The First Occurrence in a String](https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/) |
|
[✔️](c%2F0028-find-the-index-of-the-first-occurrence-in-a-string.c)
|
[✔️](cpp%2F0028-find-the-index-of-the-first-occurrence-in-a-string.cpp)
|
[✔️](csharp%2F0028-find-the-index-of-the-first-occurrence-in-a-string.cs)
|
[✔️](dart%2F0028-find-the-index-of-the-first-occurrence-in-a-string.dart)
|
[✔️](go%2F0028-find-the-index-of-the-first-occurrence-in-a-string.go)
|
|
[✔️](java%2F0028-find-the-index-of-the-first-occurrence-in-a-string.java)
|
[✔️](javascript%2F0028-find-the-index-of-the-first-occurrence-in-a-string.js)
|
[✔️](kotlin%2F0028-find-the-index-of-the-first-occurrence-in-a-string.kt)
|
[✔️](python%2F0028-find-the-index-of-the-first-occurrence-in-a-string.py)
|
|
[✔️](rust%2F0028-find-the-index-of-the-first-occurrence-in-a-string.rs)
|
|
|
| +| [0280 - Wiggle Sort](https://leetcode.com/problems/wiggle-sort/) |
|
|
[✔️](cpp%2F0280-wiggle-sort.cpp)
|
|
|
|
|
[✔️](java%2F0280-wiggle-sort.java)
|
|
[✔️](kotlin%2F0280-wiggle-sort.kt)
|
[✔️](python%2F0280-wiggle-sort.py)
|
|
|
|
|
| +| [0179 - Largest Number](https://leetcode.com/problems/largest-number/) |
|
[✔️](c%2F0179-largest-number.c)
|
[✔️](cpp%2F0179-largest-number.cpp)
|
[✔️](csharp%2F0179-largest-number.cs)
|
|
[✔️](go%2F0179-largest-number.go)
|
|
[✔️](java%2F0179-largest-number.java)
|
[✔️](javascript%2F0179-largest-number.js)
|
[✔️](kotlin%2F0179-largest-number.kt)
|
[✔️](python%2F0179-largest-number.py)
|
[✔️](ruby%2F0179-largest-number.rb)
|
[✔️](rust%2F0179-largest-number.rs)
|
[✔️](scala%2F0179-largest-number.scala)
|
[✔️](swift%2F0179-largest-number.swift)
|
[✔️](typescript%2F0179-largest-number.ts)
| +| [0523 - Continuous Subarray Sum](https://leetcode.com/problems/continuous-subarray-sum/) |
|
[✔️](c%2F0523-continuous-subarray-sum.c)
|
[✔️](cpp%2F0523-continuous-subarray-sum.cpp)
|
[✔️](csharp%2F0523-continuous-subarray-sum.cs)
|
|
|
|
[✔️](java%2F0523-continuous-subarray-sum.java)
|
[✔️](javascript%2F0523-continuous-subarray-sum.js)
|
[✔️](kotlin%2F0523-continuous-subarray-sum.kt)
|
[✔️](python%2F0523-continuous-subarray-sum.py)
|
|
[✔️](rust%2F0523-continuous-subarray-sum.rs)
|
|
|
| +| [0838 - Push Dominoes](https://leetcode.com/problems/push-dominoes/) |
|
|
[✔️](cpp%2F0838-push-dominoes.cpp)
|
|
|
|
|
[✔️](java%2F0838-push-dominoes.java)
|
[✔️](javascript%2F0838-push-dominoes.js)
|
[✔️](kotlin%2F0838-push-dominoes.kt)
|
[✔️](python%2F0838-push-dominoes.py)
|
|
|
|
|
[✔️](typescript%2F0838-push-dominoes.ts)
| +| [0187 - Repeated DNA Sequences](https://leetcode.com/problems/repeated-dna-sequences/) |
|
|
[✔️](cpp%2F0187-repeated-dna-sequences.cpp)
|
[✔️](csharp%2F0187-repeated-dna-sequences.cs)
|
|
[✔️](go%2F0187-repeated-dna-sequences.go)
|
|
[✔️](java%2F0187-repeated-dna-sequences.java)
|
[✔️](javascript%2F0187-repeated-dna-sequences.js)
|
[✔️](kotlin%2F0187-repeated-dna-sequences.kt)
|
[✔️](python%2F0187-repeated-dna-sequences.py)
|
|
|
|
|
[✔️](typescript%2F0187-repeated-dna-sequences.ts)
| +| [0380 - Insert Delete Get Random O(1)](https://leetcode.com/problems/insert-delete-getrandom-o1/) |
|
|
[✔️](cpp%2F0380-insert-delete-getrandom-o1.cpp)
|
|
|
[✔️](go%2F0380-insert-delete-getrandom-o1.go)
|
|
[✔️](java%2F0380-insert-delete-getrandom-o1.java)
|
[✔️](javascript%2F0380-insert-delete-getrandom-o1.js)
|
[✔️](kotlin%2F0380-insert-delete-getrandom-o1.kt)
|
[✔️](python%2F0380-insert-delete-getrandom-o1.py)
|
|
[✔️](rust%2F0380-insert-delete-getrandom-o1.rs)
|
|
[✔️](swift%2F0380-insert-delete-getrandom-o1.swift)
|
[✔️](typescript%2F0380-insert-delete-getrandom-o1.ts)
| +| [1461 - Check if a String Contains all Binary Codes of Size K](https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/) |
|
|
[✔️](cpp%2F1461-check-if-a-string-contains-all-binary-codes-of-size-k.cpp)
|
|
|
|
|
[✔️](java%2F1461-check-if-a-string-contains-all-binary-codes-of-size-k.java)
|
[✔️](javascript%2F1461-check-if-a-string-contains-all-binary-codes-of-size-k.js)
|
[✔️](kotlin%2F1461-check-if-a-string-contains-all-binary-codes-of-size-k.kt)
|
[✔️](python%2F1461-check-if-a-string-contains-all-binary-codes-of-size-k.py)
|
|
|
|
|
| +| [0304 - Range Sum Query 2D Immutable](https://leetcode.com/problems/range-sum-query-2d-immutable/) |
|
|
[✔️](cpp%2F0304-range-sum-query-2d-immutable.cpp)
|
|
|
|
|
[✔️](java%2F0304-range-sum-query-2d-immutable.java)
|
[✔️](javascript%2F0304-range-sum-query-2d-immutable.js)
|
[✔️](kotlin%2F0304-range-sum-query-2d-immutable.kt)
|
[✔️](python%2F0304-range-sum-query-2d-immutable.py)
|
|
|
|
[✔️](swift%2F0304-range-sum-query-2d-immutable.swift)
|
| +| [0665 - Non Decreasing Array](https://leetcode.com/problems/non-decreasing-array/) |
|
[✔️](c%2F0665-non-decreasing-array.c)
|
[✔️](cpp%2F0665-non-decreasing-array.cpp)
|
[✔️](csharp%2F0665-non-decreasing-array.cs)
|
|
[✔️](go%2F0665-non-decreasing-array.go)
|
|
[✔️](java%2F0665-non-decreasing-array.java)
|
[✔️](javascript%2F0665-non-decreasing-array.js)
|
[✔️](kotlin%2F0665-non-decreasing-array.kt)
|
[✔️](python%2F0665-non-decreasing-array.py)
|
|
|
[✔️](scala%2F0665-non-decreasing-array.scala)
|
|
[✔️](typescript%2F0665-non-decreasing-array.ts)
| +| [0041 - First Missing Positive](https://leetcode.com/problems/first-missing-positive/) |
|
[✔️](c%2F0041-first-missing-positive.c)
|
[✔️](cpp%2F0041-first-missing-positive.cpp)
|
|
|
[✔️](go%2F0041-first-missing-positive.go)
|
|
[✔️](java%2F0041-first-missing-positive.java)
|
[✔️](javascript%2F0041-first-missing-positive.js)
|
[✔️](kotlin%2F0041-first-missing-positive.kt)
|
[✔️](python%2F0041-first-missing-positive.py)
|
|
|
|
|
[✔️](typescript%2F0041-first-missing-positive.ts)
| +| [1822 - Sign of An Array](https://leetcode.com/problems/sign-of-the-product-of-an-array/) |
|
[✔️](c%2F1822-sign-of-the-product-of-an-array.c)
|
[✔️](cpp%2F1822-sign-of-the-product-of-an-array.cpp)
|
|
|
[✔️](go%2F1822-sign-of-the-product-of-an-array.go)
|
|
[✔️](java%2F1822-sign-of-the-product-of-an-array.java)
|
[✔️](javascript%2F1822-sign-of-the-product-of-an-array.js)
|
[✔️](kotlin%2F1822-sign-of-the-product-of-an-array.kt)
|
[✔️](python%2F1822-sign-of-the-product-of-an-array.py)
|
|
[✔️](rust%2F1822-sign-of-the-product-of-an-array.rs)
|
|
|
[✔️](typescript%2F1822-sign-of-the-product-of-an-array.ts)
| +| [2215 - Find the Difference of Two Arrays](https://leetcode.com/problems/find-the-difference-of-two-arrays/) |
|
[✔️](c%2F2215-find-the-difference-of-two-arrays.c)
|
[✔️](cpp%2F2215-find-the-difference-of-two-arrays.cpp)
|
[✔️](csharp%2F2215-find-the-difference-of-two-arrays.cs)
|
|
|
|
[✔️](java%2F2215-find-the-difference-of-two-arrays.java)
|
[✔️](javascript%2F2215-find-the-difference-of-two-arrays.js)
|
[✔️](kotlin%2F2215-find-the-difference-of-two-arrays.kt)
|
[✔️](python%2F2215-find-the-difference-of-two-arrays.py)
|
|
|
|
|
[✔️](typescript%2F2215-find-the-difference-of-two-arrays.ts)
| +| [1603 - Design Parking System](https://leetcode.com/problems/design-parking-system/) |
|
|
[✔️](cpp%2F1603-design-parking-system.cpp)
|
[✔️](csharp%2F1603-design-parking-system.cs)
|
|
|
|
[✔️](java%2F1603-design-parking-system.java)
|
[✔️](javascript%2F1603-design-parking-system.js)
|
[✔️](kotlin%2F1603-design-parking-system.kt)
|
[✔️](python%2F1603-design-parking-system.py)
|
|
|
|
|
| +| [2348 - Number of Zero-Filled Subarrays](https://leetcode.com/problems/number-of-zero-filled-subarrays/) |
|
|
[✔️](cpp%2F2348-number-of-zero-filled-subarrays.cpp)
|
|
|
|
|
[✔️](java%2F2348-number-of-zero-filled-subarrays.java)
|
[✔️](javascript%2F2348-number-of-zero-filled-subarrays.js)
|
[✔️](kotlin%2F2348-number-of-zero-filled-subarrays.kt)
|
[✔️](python%2F2348-number-of-zero-filled-subarrays.py)
|
|
|
|
|
| +| [2405 - Optimal Partition of String](https://leetcode.com/problems/optimal-partition-of-string/) |
|
|
[✔️](cpp%2F2405-optimal-partition-of-string.cpp)
|
|
|
|
|
[✔️](java%2F2405-optimal-partition-of-string.java)
|
|
[✔️](kotlin%2F2405-optimal-partition-of-string.kt)
|
[✔️](python%2F2405-optimal-partition-of-string.py)
|
|
|
|
|
| +| [1396 - Design Underground System](https://leetcode.com/problems/design-underground-system/) |
|
|
|
[✔️](csharp%2F1396-design-underground-system.cs)
|
|
|
|
[✔️](java%2F1396-design-underground-system.java)
|
[✔️](javascript%2F1396-design-underground-system.js)
|
[✔️](kotlin%2F1396-design-underground-system.kt)
|
[✔️](python%2F1396-design-underground-system.py)
|
|
|
|
|
| +| [2483 - Minimum Penalty for a Shop](https://leetcode.com/problems/minimum-penalty-for-a-shop/) |
|
|
[✔️](cpp%2F2483-minimum-penalty-for-a-shop.cpp)
|
|
|
|
|
[✔️](java%2F2483-minimum-penalty-for-a-shop.java)
|
|
[✔️](kotlin%2F2483-minimum-penalty-for-a-shop.kt)
|
[✔️](python%2F2483-minimum-penalty-for-a-shop.py)
|
|
|
|
|
| +| [0068 - Text Justification](https://leetcode.com/problems/text-justification/) |
|
|
|
|
|
|
|
[✔️](java%2F0068-text-justification.java)
|
|
[✔️](kotlin%2F0068-text-justification.kt)
|
[✔️](python%2F0068-text-justification.py)
|
|
|
|
|
| +| [2306 - Naming a Company](https://leetcode.com/problems/naming-a-company/) |
|
|
[✔️](cpp%2F2306-naming-a-company.cpp)
|
|
|
|
|
[✔️](java%2F2306-naming-a-company.java)
|
[✔️](javascript%2F2306-naming-a-company.js)
|
[✔️](kotlin%2F2306-naming-a-company.kt)
|
[✔️](python%2F2306-naming-a-company.py)
|
|
|
|
|
| ### Two Pointers -Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS ----- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- -[0125 - Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) |
|
[✔️](c%2F0125-valid-palindrome.c)
|
[✔️](cpp%2F0125-valid-palindrome.cpp)
|
[✔️](csharp%2F0125-valid-palindrome.cs)
|
[✔️](dart%2F0125-valid-palindrome.dart)
|
[✔️](go%2F0125-valid-palindrome.go)
|
|
[✔️](java%2F0125-valid-palindrome.java)
|
[✔️](javascript%2F0125-valid-palindrome.js)
|
[✔️](kotlin%2F0125-valid-palindrome.kt)
|
[✔️](python%2F0125-valid-palindrome.py)
|
[✔️](ruby%2F0125-valid-palindrome.rb)
|
[✔️](rust%2F0125-valid-palindrome.rs)
|
[✔️](scala%2F0125-valid-palindrome.scala)
|
[✔️](swift%2F0125-valid-palindrome.swift)
|
[✔️](typescript%2F0125-valid-palindrome.ts)
-[0680 - Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii/) |
|
[✔️](c%2F0680-valid-palindrome-ii.c)
|
[✔️](cpp%2F0680-valid-palindrome-ii.cpp)
|
[✔️](csharp%2F0680-valid-palindrome-ii.cs)
|
|
[✔️](go%2F0680-valid-palindrome-ii.go)
|
|
[✔️](java%2F0680-valid-palindrome-ii.java)
|
[✔️](javascript%2F0680-valid-palindrome-ii.js)
|
[✔️](kotlin%2F0680-valid-palindrome-ii.kt)
|
[✔️](python%2F0680-valid-palindrome-ii.py)
|
|
[✔️](rust%2F0680-valid-palindrome-II.rs)
|
|
|
[✔️](typescript%2F0680-valid-palindrome-ii.ts)
-[1984 - Minimum Difference Between Highest And Lowest of K Scores](https://leetcode.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores/) |
|
[✔️](c%2F1984-minimum-difference-between-highest-and-lowest-of-k-scores.c)
|
[✔️](cpp%2F1984-minimum-difference-between-highest-and-lowest-of-k-scores.cpp)
|
[✔️](csharp%2F1984-minimum-difference-between-highest-and-lowest-of-k-scores.cs)
|
|
[✔️](go%2F1984-minimum-difference-between-highest-and-lowest-of-k-scores.go)
|
|
[✔️](java%2F1984-minimum-difference-between-highest-and-lowest-of-k-scores.java)
|
[✔️](javascript%2F1984-Minimum-Difference-Between-Highest-and-Lowest-of-K-Scores.js)
|
[✔️](kotlin%2F1984-minimum-difference-between-highest-and-lowest-of-k-scores.kt)
|
[✔️](python%2F1984-minimum-difference-between-highest-and-lowest-of-k-scores.py)
|
|
[✔️](rust%2F1984-minimum-difference-between-highest-and-lowest-of-k-scores.rs)
|
|
|
[✔️](typescript%2F1984-minimum-difference-between-highest-and-lowest-of-k-scores.ts)
-[1768 - Merge Strings Alternately](https://leetcode.com/problems/merge-strings-alternately/) |
|
|
[✔️](cpp%2F1768-merge-strings-alternately.cpp)
|
[✔️](csharp%2F1768-merge-strings-alternately.cs)
|
|
|
|
[✔️](java%2F1768-merge-strings-alternately.java)
|
[✔️](javascript%2F1768-merge-strings-alternately.js)
|
[✔️](kotlin%2F1768-merge-strings-alternately.kt)
|
[✔️](python%2F1768-merge-strings-alternately.py)
|
|
|
|
|
[✔️](typescript%2F1768-merge-strings-alternately.ts)
-[0344 - Reverse String](https://leetcode.com/problems/reverse-string/) |
|
[✔️](c%2F0344-reverse-string.c)
|
[✔️](cpp%2F0344-Reverse-String.cpp)
|
[✔️](csharp%2F0344-reverse-string.cs)
|
[✔️](dart%2F0344-reverse-string.dart)
|
[✔️](go%2F0344-reverse-string.go)
|
|
[✔️](java%2F0344-reverse-string.java)
|
[✔️](javascript%2F0344-reverse-string.js)
|
[✔️](kotlin%2F0344-reverse-string.kt)
|
[✔️](python%2F0344-reverse-string.py)
|
|
[✔️](rust%2F0344-reverse-string.rs)
|
|
[✔️](swift%2F0344-reverse-string.swift)
|
[✔️](typescript%2F0344-reverse-string.ts)
-[0088 - Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/) |
|
[✔️](c%2F0088-merge-sorted-array.c)
|
[✔️](cpp%2F0088-Merge-sorted-array.cpp)
|
[✔️](csharp%2F0088-merge-sorted-array.cs)
|
|
[✔️](go%2F0088-merge-sorted-array.go)
|
|
[✔️](java%2F0088-merge-sorted-array.java)
|
[✔️](javascript%2F0088-merge-sorted-array.js)
|
[✔️](kotlin%2F0088-merge-sorted-array.kt)
|
[✔️](python%2F0088-merge-sorted-array.py)
|
|
[✔️](rust%2F0088-merge-sorted-array.rs)
|
|
|
[✔️](typescript%2F0088-merge-sorted-array.ts)
-[0283 - Move Zeroes](https://leetcode.com/problems/move-zeroes/) |
|
[✔️](c%2F0283-move-zeroes.c)
|
[✔️](cpp%2F0283-move-zeroes.cpp)
|
[✔️](csharp%2F0283-move-zeroes.cs)
|
|
[✔️](go%2F0283-move-zeroes.go)
|
|
[✔️](java%2F0283-move-zeroes.java)
|
[✔️](javascript%2F0283-move-zeroes.js)
|
[✔️](kotlin%2F0283-move-zeroes.kt)
|
[✔️](python%2F0283-move-zeroes.py)
|
|
[✔️](rust%2F0283-move-zeroes.rs)
|
|
[✔️](swift%2F0283-Move-Zeroes.Swift)
|
[✔️](typescript%2F0283-move-zeroes.ts)
-[0026 - Remove Duplicates From Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/) |
|
[✔️](c%2F0026-remove-duplicates-from-sorted-array.c)
|
[✔️](cpp%2F0026-remove-duplicates-from-sorted-array.cpp)
|
[✔️](csharp%2F0026-remove-duplicates-from-sorted-array.cs)
|
|
[✔️](go%2F0026-remove-duplicates-from-sorted-array.go)
|
|
[✔️](java%2F0026-remove-duplicates-from-sorted-array.java)
|
[✔️](javascript%2F0026-remove-duplicates-from-sorted-array.js)
|
[✔️](kotlin%2F0026-remove-duplicates-from-sorted-array.kt)
|
[✔️](python%2F0026-remove-duplicates-from-sorted-array.py)
|
|
[✔️](rust%2F0026-remove-duplicates-from-sorted-array.rs)
|
|
[✔️](swift%2F0026-Remove-Duplicates-from-Sorted-Array.swift)
|
[✔️](typescript%2F0026-remove-duplicates-from-sorted-array.ts)
-[0080 - Remove Duplicates From Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/) |
|
[✔️](c%2F0080-remove-duplicates-from-sorted-array-ii.c)
|
[✔️](cpp%2F0080-remove-duplicates-from-sorted-array-ii.cpp)
|
[✔️](csharp%2F0080-remove-duplicates-from-sorted-array-ii.cs)
|
|
|
|
[✔️](java%2F0080-remove-duplicates-from-sorted-array-ii.java)
|
[✔️](javascript%2F0080-remove-duplicates-from-sorted-array-ii.js)
|
[✔️](kotlin%2F0080-remove-duplicates-from-sorted-array-ii.kt)
|
[✔️](python%2F0080-remove-duplicates-from-sorted-array-ii.py)
|
|
[✔️](rust%2F0080-remove-duplicates-from-sorted-array-ii.rs)
|
|
[✔️](swift%2F0080-remove-duplicates-from-sorted-array-ii.swift)
|
-[0167 - Two Sum II Input Array Is Sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) |
|
[✔️](c%2F0167-two-sum-ii-input-array-is-sorted.c)
|
[✔️](cpp%2F0167-two-sum-ii-input-array-is-sorted.cpp)
|
[✔️](csharp%2F0167-two-sum-ii-input-array-is-sorted.cs)
|
|
[✔️](go%2F0167-two-sum-ii-input-array-is-sorted.go)
|
|
[✔️](java%2F0167-two-sum-ii-input-array-is-sorted.java)
|
[✔️](javascript%2F0167-two-sum-ii-input-array-is-sorted.js)
|
[✔️](kotlin%2F0167-two-sum-ii-input-array-is-sorted.kt)
|
[✔️](python%2F0167-two-sum-ii-input-array-is-sorted.py)
|
[✔️](ruby%2F0167-two-sum-ii-input-array-is-sorted.rb)
|
[✔️](rust%2F0167-two-sum-ii-input-array-is-sorted.rs)
|
[✔️](scala%2F0167-two-sum-ii-input-array-is-sorted.scala)
|
[✔️](swift%2F0167-two-sum-ii-input-array-is-sorted.swift)
|
[✔️](typescript%2F0167-two-sum-ii-input-array-is-sorted.ts)
-[0015 - 3Sum](https://leetcode.com/problems/3sum/) |
|
[✔️](c%2F0015-3sum.c)
|
[✔️](cpp%2F0015-3sum.cpp)
|
[✔️](csharp%2F0015-3sum.cs)
|
[✔️](dart%2F0015-3sum.dart)
|
[✔️](go%2F0015-3sum.go)
|
|
[✔️](java%2F0015-3sum.java)
|
[✔️](javascript%2F0015-3sum.js)
|
[✔️](kotlin%2F0015-3sum.kt)
|
[✔️](python%2F0015-3sum.py)
|
[✔️](ruby%2F0015-3sum.rb)
|
[✔️](rust%2F0015-3sum.rs)
|
[✔️](scala%2F0015-3sum.scala)
|
[✔️](swift%2F0015-3sum.swift)
|
[✔️](typescript%2F0015-3sum.ts)
-[0018 - 4Sum](https://leetcode.com/problems/4sum/) |
|
|
[✔️](cpp%2F0018-4sum.cpp)
|
|
|
[✔️](go%2F0018-4Sum.go)
|
|
[✔️](java%2F0018-4sum.java)
|
[✔️](javascript%2F0018-4sum.js)
|
[✔️](kotlin%2F0018-4sum.kt)
|
[✔️](python%2F0018-4sum.py)
|
|
|
|
[✔️](swift%2F0018-4sum.swift)
|
[✔️](typescript%2F0018-4sum.ts)
-[0011 - Container With Most Water](https://leetcode.com/problems/container-with-most-water/) |
|
[✔️](c%2F0011-container-with-most-water.c)
|
[✔️](cpp%2F0011-container-with-most-water.cpp)
|
[✔️](csharp%2F0011-container-with-most-water.cs)
|
[✔️](dart%2F0011-container-with-most-water.dart)
|
[✔️](go%2F0011-container-with-most-water.go)
|
|
[✔️](java%2F0011-container-with-most-water.java)
|
[✔️](javascript%2F0011-container-with-most-water.js)
|
[✔️](kotlin%2F0011-container-with-most-water.kt)
|
[✔️](python%2F0011-container-with-most-water.py)
|
[✔️](ruby%2F0011-container-with-most-water.rb)
|
[✔️](rust%2F0011-container-with-most-water.rs)
|
[✔️](scala%2F0011-container-with-most-water.scala)
|
[✔️](swift%2F0011-container-with-most-water.swift)
|
[✔️](typescript%2F0011-container-with-most-water.ts)
-[1498 - Number of Subsequences That Satisfy The Given Sum Condition](https://leetcode.com/problems/number-of-subsequences-that-satisfy-the-given-sum-condition/) |
|
|
[✔️](cpp%2F1498-number-of-subsequences-that-satisfy-the-given-sum-condition.cpp)
|
|
|
|
|
[✔️](java%2F1498-number-of-subsequences-that-satisfy-the-given-sum-condition.java)
|
|
[✔️](kotlin%2F1498-number-of-subsequences-that-satisfy-the-given-sum-condition.kt)
|
[✔️](python%2F1498-number-of-subsequences-that-satisfy-the-given-sum-condition.py)
|
|
|
|
|
-[0189 - Rotate Array](https://leetcode.com/problems/rotate-array/) |
|
|
[✔️](cpp%2F0189-rotate-array.cpp)
|
|
|
[✔️](go%2F0189-rotate-array.go)
|
|
[✔️](java%2F0189-rotate-array.java)
|
[✔️](javascript%2F0189-rotate-array.js)
|
[✔️](kotlin%2F0189-rotate-array.kt)
|
[✔️](python%2F0189-rotate-array.py)
|
|
|
|
|
[✔️](typescript%2F0189-rotate-array.ts)
-[1968 - Array With Elements Not Equal to Average of Neighbors](https://leetcode.com/problems/array-with-elements-not-equal-to-average-of-neighbors/) |
|
[✔️](c%2F1968-array-with-elements-not-equal-to-average-of-neighbors.c)
|
[✔️](cpp%2F1968-array-with-elements-not-equal-to-average-of-neighbors.cpp)
|
|
|
[✔️](go%2F1968-array-with-elements-not-equal-to-average-of-neighbors.go)
|
|
[✔️](java%2F1968-array-with-elements-not-equal-to-average-of-neighbors.java)
|
[✔️](javascript%2F1968-array-with-elements-not-equal-to-average-of-neighbors.js)
|
[✔️](kotlin%2F1968-array-with-elements-not-equal-to-average-of-neighbors.kt)
|
[✔️](python%2F1968-array-with-elements-not-equal-to-average-of-neighbors.py)
|
|
|
|
|
-[0881 - Boats to Save People](https://leetcode.com/problems/boats-to-save-people/) |
|
[✔️](c%2F0881-boats-to-save-people.c)
|
[✔️](cpp%2F0881-boats-to-save-people.cpp)
|
|
|
[✔️](go%2F0881-boats-to-save-people.go)
|
|
[✔️](java%2F0881-boats-to-save-people.java)
|
[✔️](javascript%2F0881-boats-to-save-people.js)
|
[✔️](kotlin%2F0881-boats-to-save-people.kt)
|
[✔️](python%2F0881-boats-to-save-people.py)
|
|
|
|
[✔️](swift%2F0881-boats-to-save-people.swift)
|
[✔️](typescript%2F0881-boats-to-save-people.ts)
-[0042 - Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/) |
|
[✔️](c%2F0042-trapping-rain-water.c)
|
[✔️](cpp%2F0042-trapping-rain-water.cpp)
|
[✔️](csharp%2F0042-trapping-rain-water.cs)
|
[✔️](dart%2F0042-trapping-rain-water.dart)
|
[✔️](go%2F0042-trapping-rain-water.go)
|
|
[✔️](java%2F0042-trapping-rain-water.java)
|
[✔️](javascript%2F0042-trapping-rain-water.js)
|
[✔️](kotlin%2F0042-trapping-rain-water.kt)
|
[✔️](python%2F0042-trapping-rain-water.py)
|
[✔️](ruby%2F0042-trapping-rain-water.rb)
|
[✔️](rust%2F0042-trapping-rain-water.rs)
|
|
[✔️](swift%2F0042-trapping-rain-water.swift)
|
[✔️](typescript%2F0042-trapping-rain-water.ts)
+| Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | +| [0125 - Valid Palindrome](https://leetcode.com/problems/valid-palindrome/) |
|
[✔️](c%2F0125-valid-palindrome.c)
|
[✔️](cpp%2F0125-valid-palindrome.cpp)
|
[✔️](csharp%2F0125-valid-palindrome.cs)
|
[✔️](dart%2F0125-valid-palindrome.dart)
|
[✔️](go%2F0125-valid-palindrome.go)
|
|
[✔️](java%2F0125-valid-palindrome.java)
|
[✔️](javascript%2F0125-valid-palindrome.js)
|
[✔️](kotlin%2F0125-valid-palindrome.kt)
|
[✔️](python%2F0125-valid-palindrome.py)
|
[✔️](ruby%2F0125-valid-palindrome.rb)
|
[✔️](rust%2F0125-valid-palindrome.rs)
|
[✔️](scala%2F0125-valid-palindrome.scala)
|
[✔️](swift%2F0125-valid-palindrome.swift)
|
[✔️](typescript%2F0125-valid-palindrome.ts)
| +| [0680 - Valid Palindrome II](https://leetcode.com/problems/valid-palindrome-ii/) |
|
[✔️](c%2F0680-valid-palindrome-ii.c)
|
[✔️](cpp%2F0680-valid-palindrome-ii.cpp)
|
[✔️](csharp%2F0680-valid-palindrome-ii.cs)
|
|
[✔️](go%2F0680-valid-palindrome-ii.go)
|
|
[✔️](java%2F0680-valid-palindrome-ii.java)
|
[✔️](javascript%2F0680-valid-palindrome-ii.js)
|
[✔️](kotlin%2F0680-valid-palindrome-ii.kt)
|
[✔️](python%2F0680-valid-palindrome-ii.py)
|
|
[✔️](rust%2F0680-valid-palindrome-II.rs)
|
|
|
[✔️](typescript%2F0680-valid-palindrome-ii.ts)
| +| [1984 - Minimum Difference Between Highest And Lowest of K Scores](https://leetcode.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores/) |
|
[✔️](c%2F1984-minimum-difference-between-highest-and-lowest-of-k-scores.c)
|
[✔️](cpp%2F1984-minimum-difference-between-highest-and-lowest-of-k-scores.cpp)
|
[✔️](csharp%2F1984-minimum-difference-between-highest-and-lowest-of-k-scores.cs)
|
|
[✔️](go%2F1984-minimum-difference-between-highest-and-lowest-of-k-scores.go)
|
|
[✔️](java%2F1984-minimum-difference-between-highest-and-lowest-of-k-scores.java)
|
[✔️](javascript%2F1984-Minimum-Difference-Between-Highest-and-Lowest-of-K-Scores.js)
|
[✔️](kotlin%2F1984-minimum-difference-between-highest-and-lowest-of-k-scores.kt)
|
[✔️](python%2F1984-minimum-difference-between-highest-and-lowest-of-k-scores.py)
|
|
[✔️](rust%2F1984-minimum-difference-between-highest-and-lowest-of-k-scores.rs)
|
|
|
[✔️](typescript%2F1984-minimum-difference-between-highest-and-lowest-of-k-scores.ts)
| +| [1768 - Merge Strings Alternately](https://leetcode.com/problems/merge-strings-alternately/) |
|
|
[✔️](cpp%2F1768-merge-strings-alternately.cpp)
|
[✔️](csharp%2F1768-merge-strings-alternately.cs)
|
|
|
|
[✔️](java%2F1768-merge-strings-alternately.java)
|
[✔️](javascript%2F1768-merge-strings-alternately.js)
|
[✔️](kotlin%2F1768-merge-strings-alternately.kt)
|
[✔️](python%2F1768-merge-strings-alternately.py)
|
|
|
|
|
[✔️](typescript%2F1768-merge-strings-alternately.ts)
| +| [0344 - Reverse String](https://leetcode.com/problems/reverse-string/) |
|
[✔️](c%2F0344-reverse-string.c)
|
[✔️](cpp%2F0344-Reverse-String.cpp)
|
[✔️](csharp%2F0344-reverse-string.cs)
|
[✔️](dart%2F0344-reverse-string.dart)
|
[✔️](go%2F0344-reverse-string.go)
|
|
[✔️](java%2F0344-reverse-string.java)
|
[✔️](javascript%2F0344-reverse-string.js)
|
[✔️](kotlin%2F0344-reverse-string.kt)
|
[✔️](python%2F0344-reverse-string.py)
|
|
[✔️](rust%2F0344-reverse-string.rs)
|
|
[✔️](swift%2F0344-reverse-string.swift)
|
[✔️](typescript%2F0344-reverse-string.ts)
| +| [0088 - Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/) |
|
[✔️](c%2F0088-merge-sorted-array.c)
|
[✔️](cpp%2F0088-Merge-sorted-array.cpp)
|
[✔️](csharp%2F0088-merge-sorted-array.cs)
|
|
[✔️](go%2F0088-merge-sorted-array.go)
|
|
[✔️](java%2F0088-merge-sorted-array.java)
|
[✔️](javascript%2F0088-merge-sorted-array.js)
|
[✔️](kotlin%2F0088-merge-sorted-array.kt)
|
[✔️](python%2F0088-merge-sorted-array.py)
|
|
[✔️](rust%2F0088-merge-sorted-array.rs)
|
|
|
[✔️](typescript%2F0088-merge-sorted-array.ts)
| +| [0283 - Move Zeroes](https://leetcode.com/problems/move-zeroes/) |
|
[✔️](c%2F0283-move-zeroes.c)
|
[✔️](cpp%2F0283-move-zeroes.cpp)
|
[✔️](csharp%2F0283-move-zeroes.cs)
|
|
[✔️](go%2F0283-move-zeroes.go)
|
|
[✔️](java%2F0283-move-zeroes.java)
|
[✔️](javascript%2F0283-move-zeroes.js)
|
[✔️](kotlin%2F0283-move-zeroes.kt)
|
[✔️](python%2F0283-move-zeroes.py)
|
|
[✔️](rust%2F0283-move-zeroes.rs)
|
|
[✔️](swift%2F0283-Move-Zeroes.Swift)
|
[✔️](typescript%2F0283-move-zeroes.ts)
| +| [0026 - Remove Duplicates From Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/) |
|
[✔️](c%2F0026-remove-duplicates-from-sorted-array.c)
|
[✔️](cpp%2F0026-remove-duplicates-from-sorted-array.cpp)
|
[✔️](csharp%2F0026-remove-duplicates-from-sorted-array.cs)
|
|
[✔️](go%2F0026-remove-duplicates-from-sorted-array.go)
|
|
[✔️](java%2F0026-remove-duplicates-from-sorted-array.java)
|
[✔️](javascript%2F0026-remove-duplicates-from-sorted-array.js)
|
[✔️](kotlin%2F0026-remove-duplicates-from-sorted-array.kt)
|
[✔️](python%2F0026-remove-duplicates-from-sorted-array.py)
|
|
[✔️](rust%2F0026-remove-duplicates-from-sorted-array.rs)
|
|
[✔️](swift%2F0026-Remove-Duplicates-from-Sorted-Array.swift)
|
[✔️](typescript%2F0026-remove-duplicates-from-sorted-array.ts)
| +| [0080 - Remove Duplicates From Sorted Array II](https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/) |
|
[✔️](c%2F0080-remove-duplicates-from-sorted-array-ii.c)
|
[✔️](cpp%2F0080-remove-duplicates-from-sorted-array-ii.cpp)
|
[✔️](csharp%2F0080-remove-duplicates-from-sorted-array-ii.cs)
|
|
|
|
[✔️](java%2F0080-remove-duplicates-from-sorted-array-ii.java)
|
[✔️](javascript%2F0080-remove-duplicates-from-sorted-array-ii.js)
|
[✔️](kotlin%2F0080-remove-duplicates-from-sorted-array-ii.kt)
|
[✔️](python%2F0080-remove-duplicates-from-sorted-array-ii.py)
|
|
[✔️](rust%2F0080-remove-duplicates-from-sorted-array-ii.rs)
|
|
[✔️](swift%2F0080-remove-duplicates-from-sorted-array-ii.swift)
|
| +| [0167 - Two Sum II Input Array Is Sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) |
|
[✔️](c%2F0167-two-sum-ii-input-array-is-sorted.c)
|
[✔️](cpp%2F0167-two-sum-ii-input-array-is-sorted.cpp)
|
[✔️](csharp%2F0167-two-sum-ii-input-array-is-sorted.cs)
|
|
[✔️](go%2F0167-two-sum-ii-input-array-is-sorted.go)
|
|
[✔️](java%2F0167-two-sum-ii-input-array-is-sorted.java)
|
[✔️](javascript%2F0167-two-sum-ii-input-array-is-sorted.js)
|
[✔️](kotlin%2F0167-two-sum-ii-input-array-is-sorted.kt)
|
[✔️](python%2F0167-two-sum-ii-input-array-is-sorted.py)
|
[✔️](ruby%2F0167-two-sum-ii-input-array-is-sorted.rb)
|
[✔️](rust%2F0167-two-sum-ii-input-array-is-sorted.rs)
|
[✔️](scala%2F0167-two-sum-ii-input-array-is-sorted.scala)
|
[✔️](swift%2F0167-two-sum-ii-input-array-is-sorted.swift)
|
[✔️](typescript%2F0167-two-sum-ii-input-array-is-sorted.ts)
| +| [0015 - 3Sum](https://leetcode.com/problems/3sum/) |
|
[✔️](c%2F0015-3sum.c)
|
[✔️](cpp%2F0015-3sum.cpp)
|
[✔️](csharp%2F0015-3sum.cs)
|
[✔️](dart%2F0015-3sum.dart)
|
[✔️](go%2F0015-3sum.go)
|
|
[✔️](java%2F0015-3sum.java)
|
[✔️](javascript%2F0015-3sum.js)
|
[✔️](kotlin%2F0015-3sum.kt)
|
[✔️](python%2F0015-3sum.py)
|
[✔️](ruby%2F0015-3sum.rb)
|
[✔️](rust%2F0015-3sum.rs)
|
[✔️](scala%2F0015-3sum.scala)
|
[✔️](swift%2F0015-3sum.swift)
|
[✔️](typescript%2F0015-3sum.ts)
| +| [0018 - 4Sum](https://leetcode.com/problems/4sum/) |
|
|
[✔️](cpp%2F0018-4sum.cpp)
|
|
|
[✔️](go%2F0018-4Sum.go)
|
|
[✔️](java%2F0018-4sum.java)
|
[✔️](javascript%2F0018-4sum.js)
|
[✔️](kotlin%2F0018-4sum.kt)
|
[✔️](python%2F0018-4sum.py)
|
|
|
|
[✔️](swift%2F0018-4sum.swift)
|
[✔️](typescript%2F0018-4sum.ts)
| +| [0011 - Container With Most Water](https://leetcode.com/problems/container-with-most-water/) |
|
[✔️](c%2F0011-container-with-most-water.c)
|
[✔️](cpp%2F0011-container-with-most-water.cpp)
|
[✔️](csharp%2F0011-container-with-most-water.cs)
|
[✔️](dart%2F0011-container-with-most-water.dart)
|
[✔️](go%2F0011-container-with-most-water.go)
|
|
[✔️](java%2F0011-container-with-most-water.java)
|
[✔️](javascript%2F0011-container-with-most-water.js)
|
[✔️](kotlin%2F0011-container-with-most-water.kt)
|
[✔️](python%2F0011-container-with-most-water.py)
|
[✔️](ruby%2F0011-container-with-most-water.rb)
|
[✔️](rust%2F0011-container-with-most-water.rs)
|
[✔️](scala%2F0011-container-with-most-water.scala)
|
[✔️](swift%2F0011-container-with-most-water.swift)
|
[✔️](typescript%2F0011-container-with-most-water.ts)
| +| [1498 - Number of Subsequences That Satisfy The Given Sum Condition](https://leetcode.com/problems/number-of-subsequences-that-satisfy-the-given-sum-condition/) |
|
|
[✔️](cpp%2F1498-number-of-subsequences-that-satisfy-the-given-sum-condition.cpp)
|
|
|
|
|
[✔️](java%2F1498-number-of-subsequences-that-satisfy-the-given-sum-condition.java)
|
|
[✔️](kotlin%2F1498-number-of-subsequences-that-satisfy-the-given-sum-condition.kt)
|
[✔️](python%2F1498-number-of-subsequences-that-satisfy-the-given-sum-condition.py)
|
|
|
|
|
| +| [0189 - Rotate Array](https://leetcode.com/problems/rotate-array/) |
|
|
[✔️](cpp%2F0189-rotate-array.cpp)
|
|
|
[✔️](go%2F0189-rotate-array.go)
|
|
[✔️](java%2F0189-rotate-array.java)
|
[✔️](javascript%2F0189-rotate-array.js)
|
[✔️](kotlin%2F0189-rotate-array.kt)
|
[✔️](python%2F0189-rotate-array.py)
|
|
|
|
|
[✔️](typescript%2F0189-rotate-array.ts)
| +| [1968 - Array With Elements Not Equal to Average of Neighbors](https://leetcode.com/problems/array-with-elements-not-equal-to-average-of-neighbors/) |
|
[✔️](c%2F1968-array-with-elements-not-equal-to-average-of-neighbors.c)
|
[✔️](cpp%2F1968-array-with-elements-not-equal-to-average-of-neighbors.cpp)
|
|
|
[✔️](go%2F1968-array-with-elements-not-equal-to-average-of-neighbors.go)
|
|
[✔️](java%2F1968-array-with-elements-not-equal-to-average-of-neighbors.java)
|
[✔️](javascript%2F1968-array-with-elements-not-equal-to-average-of-neighbors.js)
|
[✔️](kotlin%2F1968-array-with-elements-not-equal-to-average-of-neighbors.kt)
|
[✔️](python%2F1968-array-with-elements-not-equal-to-average-of-neighbors.py)
|
|
|
|
|
| +| [0881 - Boats to Save People](https://leetcode.com/problems/boats-to-save-people/) |
|
[✔️](c%2F0881-boats-to-save-people.c)
|
[✔️](cpp%2F0881-boats-to-save-people.cpp)
|
|
|
[✔️](go%2F0881-boats-to-save-people.go)
|
|
[✔️](java%2F0881-boats-to-save-people.java)
|
[✔️](javascript%2F0881-boats-to-save-people.js)
|
[✔️](kotlin%2F0881-boats-to-save-people.kt)
|
[✔️](python%2F0881-boats-to-save-people.py)
|
|
|
|
[✔️](swift%2F0881-boats-to-save-people.swift)
|
[✔️](typescript%2F0881-boats-to-save-people.ts)
| +| [0042 - Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/) |
|
[✔️](c%2F0042-trapping-rain-water.c)
|
[✔️](cpp%2F0042-trapping-rain-water.cpp)
|
[✔️](csharp%2F0042-trapping-rain-water.cs)
|
[✔️](dart%2F0042-trapping-rain-water.dart)
|
[✔️](go%2F0042-trapping-rain-water.go)
|
|
[✔️](java%2F0042-trapping-rain-water.java)
|
[✔️](javascript%2F0042-trapping-rain-water.js)
|
[✔️](kotlin%2F0042-trapping-rain-water.kt)
|
[✔️](python%2F0042-trapping-rain-water.py)
|
[✔️](ruby%2F0042-trapping-rain-water.rb)
|
[✔️](rust%2F0042-trapping-rain-water.rs)
|
|
[✔️](swift%2F0042-trapping-rain-water.swift)
|
[✔️](typescript%2F0042-trapping-rain-water.ts)
| ### Sliding Window -Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS ----- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- -[0121 - Best Time to Buy And Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) |
|
[✔️](c%2F0121-best-time-to-buy-and-sell-stock.c)
|
[✔️](cpp%2F0121-best-time-to-buy-and-sell-stock.cpp)
|
[✔️](csharp%2F0121-best-time-to-buy-and-sell-stock.cs)
|
[✔️](dart%2F0121-best-time-to-buy-and-sell-stock.dart)
|
[✔️](go%2F0121-best-time-to-buy-and-sell-stock.go)
|
|
[✔️](java%2F0121-best-time-to-buy-and-sell-stock.java)
|
[✔️](javascript%2F0121-best-time-to-buy-and-sell-stock.js)
|
[✔️](kotlin%2F0121-best-time-to-buy-and-sell-stock.kt)
|
[✔️](python%2F0121-best-time-to-buy-and-sell-stock.py)
|
[✔️](ruby%2F0121-best-time-to-buy-and-sell-stock.rb)
|
[✔️](rust%2F0121-best-time-to-buy-and-sell-stock.rs)
|
[✔️](scala%2F0121-best-time-to-buy-and-sell-stock.scala)
|
[✔️](swift%2F0121-best-time-to-buy-and-sell-stock.swift)
|
[✔️](typescript%2F0121-best-time-to-buy-and-sell-stock.ts)
-[0219 - Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/) |
|
|
[✔️](cpp%2F0219-contains-duplicate-ii.cpp)
|
[✔️](csharp%2F0219-contains-duplicate-ii.cs)
|
|
[✔️](go%2F0219-contains-duplicate-ii.go)
|
|
[✔️](java%2F0219-contains-duplicate-ii.java)
|
[✔️](javascript%2F0219-contains-duplicate-ii.js)
|
[✔️](kotlin%2F0219-contains-duplicate-ii.kt)
|
[✔️](python%2F0219-contains-duplicate-ii.py)
|
|
[✔️](rust%2F0219-contains-duplicate-ii.rs)
|
|
[✔️](swift%2F0219-contains-duplicate-ii.swift)
|
[✔️](typescript%2F0219-contains-duplicate-ii.ts)
-[1343 - Number of Sub Arrays of Size K and Avg Greater than or Equal to Threshold](https://leetcode.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/) |
|
|
[✔️](cpp%2F1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.cpp)
|
[✔️](csharp%2F1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.cs)
|
|
[✔️](go%2F1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.go)
|
|
[✔️](java%2F1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.java)
|
[✔️](javascript%2F1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.js)
|
[✔️](kotlin%2F1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.kt)
|
[✔️](python%2F1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.py)
|
|
|
|
[✔️](swift%2F1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.swift)
|
-[0003 - Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) |
|
[✔️](c%2F0003-longest-substring-without-repeating-characters.c)
|
[✔️](cpp%2F0003-longest-substring-without-repeating-characters.cpp)
|
[✔️](csharp%2F0003-longest-substring-without-repeating-characters.cs)
|
[✔️](dart%2F0003-longest-substring-without-repeating-characters.dart)
|
[✔️](go%2F0003-longest-substring-without-repeating-characters.go)
|
|
[✔️](java%2F0003-longest-substring-without-repeating-characters.java)
|
[✔️](javascript%2F0003-longest-substring-without-repeating-characters.js)
|
[✔️](kotlin%2F0003-longest-substring-without-repeating-characters.kt)
|
[✔️](python%2F0003-longest-substring-without-repeating-characters.py)
|
[✔️](ruby%2F0003-longest-substring-without-repeating-characters.rb)
|
[✔️](rust%2F0003-longest-substring-without-repeating-characters.rs)
|
[✔️](scala%2F0003-longest-substring-without-repeating-characters.scala)
|
[✔️](swift%2F0003-longest-substring-without-repeating-characters.swift)
|
[✔️](typescript%2F0003-longest-substring-without-repeating-characters.ts)
-[0424 - Longest Repeating Character Replacement](https://leetcode.com/problems/longest-repeating-character-replacement/) |
|
[✔️](c%2F0424-longest-repeating-character-replacement.c)
|
[✔️](cpp%2F0424-longest-repeating-character-replacement.cpp)
|
[✔️](csharp%2F0424-longest-repeating-character-replacement.cs)
|
|
[✔️](go%2F0424-longest-repeating-character-replacement.go)
|
|
[✔️](java%2F0424-longest-repeating-character-replacement.java)
|
[✔️](javascript%2F0424-longest-repeating-character-replacement.js)
|
[✔️](kotlin%2F0424-longest-repeating-character-replacement.kt)
|
[✔️](python%2F0424-longest-repeating-character-replacement.py)
|
[✔️](ruby%2F0424-longest-repeating-character-replacement.rb)
|
[✔️](rust%2F0424-longest-repeating-character-replacement.rs)
|
|
[✔️](swift%2F0424-longest-repeating-character-replacement.swift)
|
[✔️](typescript%2F0424-longest-repeating-character-replacement.ts)
-[0567 - Permutation In String](https://leetcode.com/problems/permutation-in-string/) |
|
[✔️](c%2F0567-permutation-in-string.c)
|
[✔️](cpp%2F0567-permutation-in-string.cpp)
|
[✔️](csharp%2F0567-permutation-in-string.cs)
|
|
[✔️](go%2F0567-permutation-in-string.go)
|
|
[✔️](java%2F0567-permutation-in-string.java)
|
[✔️](javascript%2F0567-permutation-in-string.js)
|
[✔️](kotlin%2F0567-permutation-in-string.kt)
|
[✔️](python%2F0567-permutation-in-string.py)
|
|
[✔️](rust%2F0567-permutation-in-string.rs)
|
|
[✔️](swift%2F0567-permutation-in-string.swift)
|
[✔️](typescript%2F0567-permutation-in-string.ts)
-[1838 - Frequency of The Most Frequent Element](https://leetcode.com/problems/frequency-of-the-most-frequent-element/) |
|
[✔️](c%2F1838-frequency-of-the-most-frequent-element.c)
|
[✔️](cpp%2F1838-frequency-of-the-most-frequent-element.cpp)
|
[✔️](csharp%2F1838-Frequency-Of-The-Most-Frequent-Element.cs)
|
|
[✔️](go%2F1838-frequency-of-the-most-frequent-element.go)
|
|
[✔️](java%2F1838-frequency-of-the-most-frequent-element.java)
|
[✔️](javascript%2F1838-frequency-of-the-most-frequent-element.js)
|
[✔️](kotlin%2F1838-frequency-of-the-most-frequent-element.kt)
|
[✔️](python%2F1838-frequency-of-the-most-frequent-element.py)
|
|
[✔️](rust%2F1838-frequency-of-the-most-frequent-element.rs)
|
|
|
[✔️](typescript%2F1838-frequency-of-the-most-frequent-element.ts)
-[0904 - Fruits into Basket](https://leetcode.com/problems/fruit-into-baskets/) |
|
|
[✔️](cpp%2F0904-fruit-into-baskets.cpp)
|
|
|
[✔️](go%2F0904-fruit-into-baskets.go)
|
|
[✔️](java%2F0904-fruit-into-baskets.java)
|
[✔️](javascript%2F0904-fruit-into-baskets.js)
|
[✔️](kotlin%2F0904-fruit-into-baskets.kt)
|
[✔️](python%2F0904-fruit-into-baskets.py)
|
|
[✔️](rust%2F0904-fruit-into-baskets.rs)
|
|
|
[✔️](typescript%2F0904-fruit-into-baskets.ts)
-[1456 - Maximum Number of Vowels in a Substring of Given Length](https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/) |
|
[✔️](c%2F1456-maximum-number-of-vowels-in-a-substring-of-given-length.c)
|
[✔️](cpp%2F1456-maximum-number-of-vowels-in-a-substring-of-given-length.cpp)
|
|
|
[✔️](go%2F1456-maximum-number-of-vowels-in-a-substring-of-given-length.go)
|
|
[✔️](java%2F1456-maximum-number-of-vowels-in-a-substring-of-given-length.java)
|
|
[✔️](kotlin%2F1456-maximum-number-of-vowels-in-a-substring-of-given-length.kt)
|
[✔️](python%2F1456-maximum-number-of-vowels-in-a-substring-of-given-length.py)
|
|
|
|
|
-[1888 - Minimum Number of Flips to Make The Binary String Alternating](https://leetcode.com/problems/minimum-number-of-flips-to-make-the-binary-string-alternating/) |
|
|
[✔️](cpp%2F1888-minimum-number-of-flips-to-make-the-binary-string-alternating.cpp)
|
|
|
|
|
|
[✔️](javascript%2F1888-minimum-number-of-flips-to-make-the-binary-string-alternating.js)
|
[✔️](kotlin%2F1888-minimum-number-of-flips-to-make-the-binary-string-alternating.kt)
|
[✔️](python%2F1888-minimum-number-of-flips-to-make-the-binary-string-alternating.py)
|
|
|
|
|
[✔️](typescript%2F1888-minimum-number-of-flips-to-make-the-binary-string-alternating.ts)
-[0209 - Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) |
|
[✔️](c%2F0209-minimum-size-subarray-sum.c)
|
[✔️](cpp%2F0209-minimum-size-subarray-sum.cpp)
|
|
|
[✔️](go%2F0209-minimum-size-subarray-sum.go)
|
|
[✔️](java%2F0209-minimum-size-subarray-sum.java)
|
[✔️](javascript%2F0209-minimum-size-subarray-sum.js)
|
[✔️](kotlin%2F0209-minimum-size-subarray-sum.kt)
|
[✔️](python%2F0209-minimum-size-subarray-sum.py)
|
|
|
|
[✔️](swift%2F0209-minimum-size-subarray-sum.swift)
|
-[0658 - Find K Closest Elements](https://leetcode.com/problems/find-k-closest-elements/) |
|
|
|
|
|
[✔️](go%2F0658-find-k-closest-elements.go)
|
|
[✔️](java%2F0658-find-k-closest-elements.java)
|
[✔️](javascript%2F0658-find-k-closest-elements.js)
|
[✔️](kotlin%2F0658-find-k-closest-elements.kt)
|
[✔️](python%2F0658-find-k-closest-elements.py)
|
|
[✔️](rust%2F0658-find-k-closest-elements.rs)
|
|
|
[✔️](typescript%2F0658-find-k-closest-elements.ts)
-[1658 - Minimum Operations to Reduce X to Zero](https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/) |
|
|
|
|
|
[✔️](go%2F1658-minimum-operations-to-reduce-x-to-zero.go)
|
|
[✔️](java%2F1658-minimum-operations-to-reduce-x-to-zero.java)
|
|
[✔️](kotlin%2F1658-minimum-operations-to-reduce-x-to-zero.kt)
|
[✔️](python%2F1658-minimum-operations-to-reduce-x-to-zero.py)
|
|
|
|
|
-[0076 - Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/) |
|
[✔️](c%2F0076-minimum-window-substring.c)
|
[✔️](cpp%2F0076-minimum-window-substring.cpp)
|
[✔️](csharp%2F0076-minimum-window-substring.cs)
|
|
[✔️](go%2F0076-minimum-window-substring.go)
|
|
[✔️](java%2F0076-minimum-window-substring.java)
|
[✔️](javascript%2F0076-minimum-window-substring.js)
|
[✔️](kotlin%2F0076-minimum-window-substring.kt)
|
[✔️](python%2F0076-minimum-window-substring.py)
|
[✔️](ruby%2F0076-minimum-window-substring.rb)
|
[✔️](rust%2F0076-minimum-window-substring.rs)
|
|
[✔️](swift%2F0076-minimum-window-substring.swift)
|
[✔️](typescript%2F0076-minimum-window-substring.ts)
-[0239 - Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/) |
|
[✔️](c%2F0239-sliding-window-maximum.c)
|
[✔️](cpp%2F0239-sliding-window-maximum.cpp)
|
[✔️](csharp%2F0239-sliding-window-maximum.cs)
|
|
[✔️](go%2F0239-sliding-window-maximum.go)
|
|
[✔️](java%2F0239-sliding-window-maximum.java)
|
[✔️](javascript%2F0239-sliding-window-maximum.js)
|
[✔️](kotlin%2F0239-sliding-window-maximum.kt)
|
[✔️](python%2F0239-sliding-window-maximum.py)
|
[✔️](ruby%2F0239-sliding-window-maximum.rb)
|
[✔️](rust%2F0239-sliding-window-maximum.rs)
|
|
[✔️](swift%2F0239-sliding-window-maximum.swift)
|
[✔️](typescript%2F0239-sliding-window-maximum.ts)
+| Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | +| [0121 - Best Time to Buy And Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) |
|
[✔️](c%2F0121-best-time-to-buy-and-sell-stock.c)
|
[✔️](cpp%2F0121-best-time-to-buy-and-sell-stock.cpp)
|
[✔️](csharp%2F0121-best-time-to-buy-and-sell-stock.cs)
|
[✔️](dart%2F0121-best-time-to-buy-and-sell-stock.dart)
|
[✔️](go%2F0121-best-time-to-buy-and-sell-stock.go)
|
|
[✔️](java%2F0121-best-time-to-buy-and-sell-stock.java)
|
[✔️](javascript%2F0121-best-time-to-buy-and-sell-stock.js)
|
[✔️](kotlin%2F0121-best-time-to-buy-and-sell-stock.kt)
|
[✔️](python%2F0121-best-time-to-buy-and-sell-stock.py)
|
[✔️](ruby%2F0121-best-time-to-buy-and-sell-stock.rb)
|
[✔️](rust%2F0121-best-time-to-buy-and-sell-stock.rs)
|
[✔️](scala%2F0121-best-time-to-buy-and-sell-stock.scala)
|
[✔️](swift%2F0121-best-time-to-buy-and-sell-stock.swift)
|
[✔️](typescript%2F0121-best-time-to-buy-and-sell-stock.ts)
| +| [0219 - Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/) |
|
|
[✔️](cpp%2F0219-contains-duplicate-ii.cpp)
|
[✔️](csharp%2F0219-contains-duplicate-ii.cs)
|
|
[✔️](go%2F0219-contains-duplicate-ii.go)
|
|
[✔️](java%2F0219-contains-duplicate-ii.java)
|
[✔️](javascript%2F0219-contains-duplicate-ii.js)
|
[✔️](kotlin%2F0219-contains-duplicate-ii.kt)
|
[✔️](python%2F0219-contains-duplicate-ii.py)
|
|
[✔️](rust%2F0219-contains-duplicate-ii.rs)
|
|
[✔️](swift%2F0219-contains-duplicate-ii.swift)
|
[✔️](typescript%2F0219-contains-duplicate-ii.ts)
| +| [1343 - Number of Sub Arrays of Size K and Avg Greater than or Equal to Threshold](https://leetcode.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/) |
|
|
[✔️](cpp%2F1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.cpp)
|
[✔️](csharp%2F1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.cs)
|
|
[✔️](go%2F1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.go)
|
|
[✔️](java%2F1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.java)
|
[✔️](javascript%2F1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.js)
|
[✔️](kotlin%2F1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.kt)
|
[✔️](python%2F1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.py)
|
|
|
|
[✔️](swift%2F1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.swift)
|
| +| [0003 - Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) |
|
[✔️](c%2F0003-longest-substring-without-repeating-characters.c)
|
[✔️](cpp%2F0003-longest-substring-without-repeating-characters.cpp)
|
[✔️](csharp%2F0003-longest-substring-without-repeating-characters.cs)
|
[✔️](dart%2F0003-longest-substring-without-repeating-characters.dart)
|
[✔️](go%2F0003-longest-substring-without-repeating-characters.go)
|
|
[✔️](java%2F0003-longest-substring-without-repeating-characters.java)
|
[✔️](javascript%2F0003-longest-substring-without-repeating-characters.js)
|
[✔️](kotlin%2F0003-longest-substring-without-repeating-characters.kt)
|
[✔️](python%2F0003-longest-substring-without-repeating-characters.py)
|
[✔️](ruby%2F0003-longest-substring-without-repeating-characters.rb)
|
[✔️](rust%2F0003-longest-substring-without-repeating-characters.rs)
|
[✔️](scala%2F0003-longest-substring-without-repeating-characters.scala)
|
[✔️](swift%2F0003-longest-substring-without-repeating-characters.swift)
|
[✔️](typescript%2F0003-longest-substring-without-repeating-characters.ts)
| +| [0424 - Longest Repeating Character Replacement](https://leetcode.com/problems/longest-repeating-character-replacement/) |
|
[✔️](c%2F0424-longest-repeating-character-replacement.c)
|
[✔️](cpp%2F0424-longest-repeating-character-replacement.cpp)
|
[✔️](csharp%2F0424-longest-repeating-character-replacement.cs)
|
|
[✔️](go%2F0424-longest-repeating-character-replacement.go)
|
|
[✔️](java%2F0424-longest-repeating-character-replacement.java)
|
[✔️](javascript%2F0424-longest-repeating-character-replacement.js)
|
[✔️](kotlin%2F0424-longest-repeating-character-replacement.kt)
|
[✔️](python%2F0424-longest-repeating-character-replacement.py)
|
[✔️](ruby%2F0424-longest-repeating-character-replacement.rb)
|
[✔️](rust%2F0424-longest-repeating-character-replacement.rs)
|
|
[✔️](swift%2F0424-longest-repeating-character-replacement.swift)
|
[✔️](typescript%2F0424-longest-repeating-character-replacement.ts)
| +| [0567 - Permutation In String](https://leetcode.com/problems/permutation-in-string/) |
|
[✔️](c%2F0567-permutation-in-string.c)
|
[✔️](cpp%2F0567-permutation-in-string.cpp)
|
[✔️](csharp%2F0567-permutation-in-string.cs)
|
|
[✔️](go%2F0567-permutation-in-string.go)
|
|
[✔️](java%2F0567-permutation-in-string.java)
|
[✔️](javascript%2F0567-permutation-in-string.js)
|
[✔️](kotlin%2F0567-permutation-in-string.kt)
|
[✔️](python%2F0567-permutation-in-string.py)
|
|
[✔️](rust%2F0567-permutation-in-string.rs)
|
|
[✔️](swift%2F0567-permutation-in-string.swift)
|
[✔️](typescript%2F0567-permutation-in-string.ts)
| +| [1838 - Frequency of The Most Frequent Element](https://leetcode.com/problems/frequency-of-the-most-frequent-element/) |
|
[✔️](c%2F1838-frequency-of-the-most-frequent-element.c)
|
[✔️](cpp%2F1838-frequency-of-the-most-frequent-element.cpp)
|
[✔️](csharp%2F1838-Frequency-Of-The-Most-Frequent-Element.cs)
|
|
[✔️](go%2F1838-frequency-of-the-most-frequent-element.go)
|
|
[✔️](java%2F1838-frequency-of-the-most-frequent-element.java)
|
[✔️](javascript%2F1838-frequency-of-the-most-frequent-element.js)
|
[✔️](kotlin%2F1838-frequency-of-the-most-frequent-element.kt)
|
[✔️](python%2F1838-frequency-of-the-most-frequent-element.py)
|
|
[✔️](rust%2F1838-frequency-of-the-most-frequent-element.rs)
|
|
|
[✔️](typescript%2F1838-frequency-of-the-most-frequent-element.ts)
| +| [0904 - Fruits into Basket](https://leetcode.com/problems/fruit-into-baskets/) |
|
|
[✔️](cpp%2F0904-fruit-into-baskets.cpp)
|
|
|
[✔️](go%2F0904-fruit-into-baskets.go)
|
|
[✔️](java%2F0904-fruit-into-baskets.java)
|
[✔️](javascript%2F0904-fruit-into-baskets.js)
|
[✔️](kotlin%2F0904-fruit-into-baskets.kt)
|
[✔️](python%2F0904-fruit-into-baskets.py)
|
|
[✔️](rust%2F0904-fruit-into-baskets.rs)
|
|
|
[✔️](typescript%2F0904-fruit-into-baskets.ts)
| +| [1456 - Maximum Number of Vowels in a Substring of Given Length](https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/) |
|
[✔️](c%2F1456-maximum-number-of-vowels-in-a-substring-of-given-length.c)
|
[✔️](cpp%2F1456-maximum-number-of-vowels-in-a-substring-of-given-length.cpp)
|
|
|
[✔️](go%2F1456-maximum-number-of-vowels-in-a-substring-of-given-length.go)
|
|
[✔️](java%2F1456-maximum-number-of-vowels-in-a-substring-of-given-length.java)
|
|
[✔️](kotlin%2F1456-maximum-number-of-vowels-in-a-substring-of-given-length.kt)
|
[✔️](python%2F1456-maximum-number-of-vowels-in-a-substring-of-given-length.py)
|
|
|
|
|
| +| [1888 - Minimum Number of Flips to Make The Binary String Alternating](https://leetcode.com/problems/minimum-number-of-flips-to-make-the-binary-string-alternating/) |
|
|
[✔️](cpp%2F1888-minimum-number-of-flips-to-make-the-binary-string-alternating.cpp)
|
|
|
|
|
|
[✔️](javascript%2F1888-minimum-number-of-flips-to-make-the-binary-string-alternating.js)
|
[✔️](kotlin%2F1888-minimum-number-of-flips-to-make-the-binary-string-alternating.kt)
|
[✔️](python%2F1888-minimum-number-of-flips-to-make-the-binary-string-alternating.py)
|
|
|
|
|
[✔️](typescript%2F1888-minimum-number-of-flips-to-make-the-binary-string-alternating.ts)
| +| [0209 - Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/) |
|
[✔️](c%2F0209-minimum-size-subarray-sum.c)
|
[✔️](cpp%2F0209-minimum-size-subarray-sum.cpp)
|
|
|
[✔️](go%2F0209-minimum-size-subarray-sum.go)
|
|
[✔️](java%2F0209-minimum-size-subarray-sum.java)
|
[✔️](javascript%2F0209-minimum-size-subarray-sum.js)
|
[✔️](kotlin%2F0209-minimum-size-subarray-sum.kt)
|
[✔️](python%2F0209-minimum-size-subarray-sum.py)
|
|
|
|
[✔️](swift%2F0209-minimum-size-subarray-sum.swift)
|
| +| [0658 - Find K Closest Elements](https://leetcode.com/problems/find-k-closest-elements/) |
|
|
|
|
|
[✔️](go%2F0658-find-k-closest-elements.go)
|
|
[✔️](java%2F0658-find-k-closest-elements.java)
|
[✔️](javascript%2F0658-find-k-closest-elements.js)
|
[✔️](kotlin%2F0658-find-k-closest-elements.kt)
|
[✔️](python%2F0658-find-k-closest-elements.py)
|
|
[✔️](rust%2F0658-find-k-closest-elements.rs)
|
|
|
[✔️](typescript%2F0658-find-k-closest-elements.ts)
| +| [1658 - Minimum Operations to Reduce X to Zero](https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/) |
|
|
|
|
|
[✔️](go%2F1658-minimum-operations-to-reduce-x-to-zero.go)
|
|
[✔️](java%2F1658-minimum-operations-to-reduce-x-to-zero.java)
|
|
[✔️](kotlin%2F1658-minimum-operations-to-reduce-x-to-zero.kt)
|
[✔️](python%2F1658-minimum-operations-to-reduce-x-to-zero.py)
|
|
|
|
|
| +| [0076 - Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/) |
|
[✔️](c%2F0076-minimum-window-substring.c)
|
[✔️](cpp%2F0076-minimum-window-substring.cpp)
|
[✔️](csharp%2F0076-minimum-window-substring.cs)
|
|
[✔️](go%2F0076-minimum-window-substring.go)
|
|
[✔️](java%2F0076-minimum-window-substring.java)
|
[✔️](javascript%2F0076-minimum-window-substring.js)
|
[✔️](kotlin%2F0076-minimum-window-substring.kt)
|
[✔️](python%2F0076-minimum-window-substring.py)
|
[✔️](ruby%2F0076-minimum-window-substring.rb)
|
[✔️](rust%2F0076-minimum-window-substring.rs)
|
|
[✔️](swift%2F0076-minimum-window-substring.swift)
|
[✔️](typescript%2F0076-minimum-window-substring.ts)
| +| [0239 - Sliding Window Maximum](https://leetcode.com/problems/sliding-window-maximum/) |
|
[✔️](c%2F0239-sliding-window-maximum.c)
|
[✔️](cpp%2F0239-sliding-window-maximum.cpp)
|
[✔️](csharp%2F0239-sliding-window-maximum.cs)
|
|
[✔️](go%2F0239-sliding-window-maximum.go)
|
|
[✔️](java%2F0239-sliding-window-maximum.java)
|
[✔️](javascript%2F0239-sliding-window-maximum.js)
|
[✔️](kotlin%2F0239-sliding-window-maximum.kt)
|
[✔️](python%2F0239-sliding-window-maximum.py)
|
[✔️](ruby%2F0239-sliding-window-maximum.rb)
|
[✔️](rust%2F0239-sliding-window-maximum.rs)
|
|
[✔️](swift%2F0239-sliding-window-maximum.swift)
|
[✔️](typescript%2F0239-sliding-window-maximum.ts)
| ### Stack -Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS ----- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- -[0020 - Valid Parentheses](https://leetcode.com/problems/valid-parentheses/) |
|
[✔️](c%2F0020-valid-parentheses.c)
|
[✔️](cpp%2F0020-valid-parentheses.cpp)
|
[✔️](csharp%2F0020-valid-parentheses.cs)
|
[✔️](dart%2F0020-valid-parentheses.dart)
|
[✔️](go%2F0020-valid-parentheses.go)
|
|
[✔️](java%2F0020-valid-parentheses.java)
|
[✔️](javascript%2F0020-valid-parentheses.js)
|
[✔️](kotlin%2F0020-valid-parentheses.kt)
|
[✔️](python%2F0020-valid-parentheses.py)
|
[✔️](ruby%2F0020-valid-parentheses.rb)
|
[✔️](rust%2F0020-valid-parentheses.rs)
|
|
[✔️](swift%2F0020-valid-parentheses.swift)
|
[✔️](typescript%2F0020-valid-parentheses.ts)
-[0682 - Baseball Game](https://leetcode.com/problems/baseball-game/) |
|
[✔️](c%2F0682-baseball-game.c)
|
[✔️](cpp%2F0682-baseball-game.cpp)
|
[✔️](csharp%2F0682-baseball-game.cs)
|
|
[✔️](go%2F0682-baseball-game.go)
|
|
[✔️](java%2F0682-baseball-game.java)
|
[✔️](javascript%2F0682-Baseball-Game.js)
|
[✔️](kotlin%2F0682-baseball-game.kt)
|
[✔️](python%2F0682-baseball-game.py)
|
|
[✔️](rust%2F0682-baseball-game.rs)
|
|
[✔️](swift%2F0682-baseball-game.swift)
|
[✔️](typescript%2F0682-baseball-game.ts)
-[0225 - Implement Stack Using Queues](https://leetcode.com/problems/implement-stack-using-queues/) |
|
[✔️](c%2F0225-implement-stack-using-queues.c)
|
[✔️](cpp%2F0225-implement-stack-using-queues.cpp)
|
[✔️](csharp%2F0225-implement-stack-using-queues.cs)
|
|
[✔️](go%2F0225-implement-stack-using-queues.go)
|
|
[✔️](java%2F0225-implement-stack-using-queues.java)
|
[✔️](javascript%2F0225-implement-stack-using-queues.js)
|
[✔️](kotlin%2F0225-implement-stack-using-queues.kt)
|
[✔️](python%2F0225-implement-stack-using-queues.py)
|
|
[✔️](rust%2F0225-implement-stack-using-queues.rs)
|
|
[✔️](swift%2F0225-implement-stack-using-queues.swift)
|
[✔️](typescript%2F0225-implement-stack-using-queues.ts)
-[0155 - Min Stack](https://leetcode.com/problems/min-stack/) |
|
[✔️](c%2F0155-min-stack.c)
|
[✔️](cpp%2F0155-min-stack.cpp)
|
[✔️](csharp%2F0155-min-stack.cs)
|
[✔️](dart%2F0155-min-stack.dart)
|
[✔️](go%2F0155-min-stack.go)
|
|
[✔️](java%2F0155-min-stack.java)
|
[✔️](javascript%2F0155-min-stack.js)
|
[✔️](kotlin%2F0155-min-stack.kt)
|
[✔️](python%2F0155-min-stack.py)
|
[✔️](ruby%2F0155-min-stack.rb)
|
[✔️](rust%2F0155-min-stack.rs)
|
|
[✔️](swift%2F0155-min-stack.swift)
|
[✔️](typescript%2F0155-min-stack.ts)
-[0150 - Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/) |
|
[✔️](c%2F0150-evaluate-reverse-polish-notation.c)
|
[✔️](cpp%2F0150-evaluate-reverse-polish-notation.cpp)
|
[✔️](csharp%2F0150-evaluate-reverse-polish-notation.cs)
|
[✔️](dart%2F0150-evaluate-reverse-polish-notation.dart)
|
[✔️](go%2F0150-evaluate-reverse-polish-notation.go)
|
|
[✔️](java%2F0150-evaluate-reverse-polish-notation.java)
|
[✔️](javascript%2F0150-evaluate-reverse-polish-notation.js)
|
[✔️](kotlin%2F0150-evaluate-reverse-polish-notation.kt)
|
[✔️](python%2F0150-evaluate-reverse-polish-notation.py)
|
[✔️](ruby%2F0150-evaluate-reverse-polish-notation.rb)
|
[✔️](rust%2F0150-evaluate-reverse-polish-notation.rs)
|
|
[✔️](swift%2F0150-evaluate-reverse-polish-notation.swift)
|
[✔️](typescript%2F0150-evaluate-reverse-polish-notation.ts)
-[2390 - Removing Stars From a String](https://leetcode.com/problems/removing-stars-from-a-string/) |
|
|
[✔️](cpp%2F2390-removing-stars-from-a-string.cpp)
|
[✔️](csharp%2F2390-removing-stars-from-a-string.cs)
|
|
|
|
[✔️](java%2F2390-removing-stars-from-a-string.java)
|
[✔️](javascript%2F2390-removing-stars-from-a-string.js)
|
[✔️](kotlin%2F2390-removing-stars-from-a-string.kt)
|
[✔️](python%2F2390-removing-stars-from-a-string.py)
|
|
|
|
|
[✔️](typescript%2F2390-removing-stars-from-a-string.ts)
-[0946 - Validate Stack Sequences](https://leetcode.com/problems/validate-stack-sequences/) |
|
|
[✔️](cpp%2F0946-validate-stack-sequences.cpp)
|
|
|
|
|
[✔️](java%2F0946-validate-stack-sequences.java)
|
|
[✔️](kotlin%2F0946-validate-stack-sequences.kt)
|
[✔️](python%2F0946-validate-stack-sequences.py)
|
|
|
|
|
-[0022 - Generate Parentheses](https://leetcode.com/problems/generate-parentheses/) |
|
[✔️](c%2F0022-generate-parentheses.c)
|
[✔️](cpp%2F0022-generate-parentheses.cpp)
|
[✔️](csharp%2F0022-generate-parentheses.cs)
|
|
[✔️](go%2F0022-generate-parentheses.go)
|
|
[✔️](java%2F0022-generate-parentheses.java)
|
[✔️](javascript%2F0022-generate-parentheses.js)
|
[✔️](kotlin%2F0022-generate-parentheses.kt)
|
[✔️](python%2F0022-generate-parentheses.py)
|
[✔️](ruby%2F0022-generate-parentheses.rb)
|
[✔️](rust%2F0022-generate-parentheses.rs)
|
|
[✔️](swift%2F0022-generate-parentheses.swift)
|
[✔️](typescript%2F0022-generate-parentheses.ts)
-[0735 - Asteroid Collision](https://leetcode.com/problems/asteroid-collision/) |
|
|
[✔️](cpp%2F0735-asteroid-collision.cpp)
|
|
|
[✔️](go%2F0735-asteroid-collision.go)
|
|
[✔️](java%2F0735-asteroid-collision.java)
|
[✔️](javascript%2F0735-asteroid-collision.js)
|
[✔️](kotlin%2F0735-asteroid-collision.kt)
|
[✔️](python%2F0735-asteroid-collision.py)
|
|
[✔️](rust%2F0735-asteroid-collision.rs)
|
|
[✔️](swift%2F0735-asteroid-collision.swift)
|
[✔️](typescript%2F0735-asteroid-collision.ts)
-[0739 - Daily Temperatures](https://leetcode.com/problems/daily-temperatures/) |
|
[✔️](c%2F0739-daily-temperatures.c)
|
[✔️](cpp%2F0739-daily-temperatures.cpp)
|
[✔️](csharp%2F0739-daily-temperatures.cs)
|
|
[✔️](go%2F0739-daily-temperatures.go)
|
|
[✔️](java%2F0739-daily-temperatures.java)
|
[✔️](javascript%2F0739-daily-temperatures.js)
|
[✔️](kotlin%2F0739-daily-temperatures.kt)
|
[✔️](python%2F0739-daily-temperatures.py)
|
[✔️](ruby%2F0739-daily-temperatures.rb)
|
[✔️](rust%2F0739-daily-temperatures.rs)
|
|
[✔️](swift%2F0739-daily-temperatures.swift)
|
[✔️](typescript%2F0739-daily-temperatures.ts)
-[0901 - Online Stock Span](https://leetcode.com/problems/online-stock-span/) |
|
|
[✔️](cpp%2F0901-online-stock-span.cpp)
|
|
|
|
|
[✔️](java%2F0901-online-stock-span.java)
|
[✔️](javascript%2F0901-online-stock-span.js)
|
[✔️](kotlin%2F0901-online-stock-span.kt)
|
[✔️](python%2F0901-online-stock-span.py)
|
|
[✔️](rust%2F0901-online-stock-span.rs)
|
|
|
[✔️](typescript%2F0901-online-stock-span.ts)
-[0853 - Car Fleet](https://leetcode.com/problems/car-fleet/) |
|
[✔️](c%2F0853-car-fleet.c)
|
[✔️](cpp%2F0853-car-fleet.cpp)
|
[✔️](csharp%2F0853-car-fleet.cs)
|
|
[✔️](go%2F0853-car-fleet.go)
|
|
[✔️](java%2F0853-car-fleet.java)
|
[✔️](javascript%2F0853-car-fleet.js)
|
[✔️](kotlin%2F0853-car-fleet.kt)
|
[✔️](python%2F0853-car-fleet.py)
|
[✔️](ruby%2F0853-car-fleet.rb)
|
[✔️](rust%2F0853-car-fleet.rs)
|
|
[✔️](swift%2F0853-car-fleet.swift)
|
[✔️](typescript%2F0853-car-fleet.ts)
-[0071 - Simplify Path](https://leetcode.com/problems/simplify-path/) |
|
|
[✔️](cpp%2F0071-simplify-path.cpp)
|
|
|
|
|
[✔️](java%2F0071-simplify-path.java)
|
[✔️](javascript%2F0071-simplify-path.js)
|
[✔️](kotlin%2F0071-simplify-path.kt)
|
[✔️](python%2F0071-simplify-path.py)
|
|
[✔️](rust%2F0071-simplify-path.rs)
|
|
|
[✔️](typescript%2F0071-simplify-path.ts)
-[0394 - Decode String](https://leetcode.com/problems/decode-string/) |
|
|
[✔️](cpp%2F0394-decode-string.cpp)
|
|
|
|
|
[✔️](java%2F0394-decode-string.java)
|
|
[✔️](kotlin%2F0394-decode-string.kt)
|
[✔️](python%2F0394-decode-string.py)
|
|
[✔️](rust%2F0394-decode-string.rs)
|
[✔️](scala%2F0394-decode-string.scala)
|
|
[✔️](typescript%2F0394-decode-string.ts)
-[0402 - Remove K Digits](https://leetcode.com/problems/remove-k-digits/) |
|
|
[✔️](cpp%2F0402-remove-k-digits.cpp)
|
|
|
|
|
[✔️](java%2F0402-remove-k-digits.java)
|
[✔️](javascript%2F0402-remove-k-digits.js)
|
[✔️](kotlin%2F0402-remove-k-digits.kt)
|
[✔️](python%2F0402-remove-k-digits.py)
|
|
[✔️](rust%2F0402-remove-k-digits.rs)
|
|
|
[✔️](typescript%2F0402-remove-k-digits.ts)
-[1209 - Remove All Adjacent Duplicates In String II](https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/) |
|
|
[✔️](cpp%2F1209-Remove-All-Adjacent-Duplicates-in-String-II.cpp)
|
|
|
|
|
[✔️](java%2F1209-remove-all-adjacent-duplicates-in-string-ii.java)
|
[✔️](javascript%2F1209-Remove-All-Adjacent-Duplicates-in-String-II.js)
|
[✔️](kotlin%2F1209-remove-all-adjacent-duplicates-in-string-ii.kt)
|
[✔️](python%2F1209-remove-all-adjacent-duplicates-in-string-ii.py)
|
|
[✔️](rust%2F1209-remove-all-adjacent-duplicates-in-string-II.rs)
|
|
|
[✔️](typescript%2F1209-remove-all-adjacent-duplicates-in-string-II.ts)
-[0456 - 132 Pattern](https://leetcode.com/problems/132-pattern/) |
|
|
[✔️](cpp%2F0456-132-pattern.cpp)
|
|
|
|
|
[✔️](java%2F0456-132-pattern.java)
|
[✔️](javascript%2F0456-132-pattern.js)
|
[✔️](kotlin%2F0456-132-pattern.kt)
|
[✔️](python%2F0456-132-pattern.py)
|
|
[✔️](rust%2F0456-132-pattern.rs)
|
|
|
[✔️](typescript%2F0456-132-pattern.ts)
-[0895 - Maximum Frequency Stack](https://leetcode.com/problems/maximum-frequency-stack/) |
|
|
[✔️](cpp%2F0895-maximum-frequency-stack.cpp)
|
|
|
|
|
[✔️](java%2F0895-maximum-frequency-stack.java)
|
[✔️](javascript%2F0895-maximum-frequency-stack.js)
|
[✔️](kotlin%2F0895-maximum-frequency-stack.kt)
|
[✔️](python%2F0895-maximum-frequency-stack.py)
|
|
[✔️](rust%2F0895-maximum-frequency-stack.rs)
|
|
|
[✔️](typescript%2F0895-maximum-frequency-stack.ts)
-[0084 - Largest Rectangle In Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/) |
|
[✔️](c%2F0084-largest-rectangle-in-histogram.c)
|
[✔️](cpp%2F0084-largest-rectangle-in-histogram.cpp)
|
[✔️](csharp%2F0084-largest-rectangle-in-histogram.cs)
|
|
[✔️](go%2F0084-largest-rectangle-in-histogram.go)
|
|
[✔️](java%2F0084-largest-rectangle-in-histogram.java)
|
[✔️](javascript%2F0084-largest-rectangle-in-histogram.js)
|
[✔️](kotlin%2F0084-largest-rectangle-in-histogram.kt)
|
[✔️](python%2F0084-largest-rectangle-in-histogram.py)
|
[✔️](ruby%2F0084-largest-rectangle-in-histogram.rb)
|
[✔️](rust%2F0084-largest-rectangle-in-histogram.rs)
|
|
[✔️](swift%2F0084-largest-rectangle-in-histogram.swift)
|
[✔️](typescript%2F0084-largest-rectangle-in-histogram.ts)
+| Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS | +| ------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | +| [0020 - Valid Parentheses](https://leetcode.com/problems/valid-parentheses/) |
|
[✔️](c%2F0020-valid-parentheses.c)
|
[✔️](cpp%2F0020-valid-parentheses.cpp)
|
[✔️](csharp%2F0020-valid-parentheses.cs)
|
[✔️](dart%2F0020-valid-parentheses.dart)
|
[✔️](go%2F0020-valid-parentheses.go)
|
|
[✔️](java%2F0020-valid-parentheses.java)
|
[✔️](javascript%2F0020-valid-parentheses.js)
|
[✔️](kotlin%2F0020-valid-parentheses.kt)
|
[✔️](python%2F0020-valid-parentheses.py)
|
[✔️](ruby%2F0020-valid-parentheses.rb)
|
[✔️](rust%2F0020-valid-parentheses.rs)
|
|
[✔️](swift%2F0020-valid-parentheses.swift)
|
[✔️](typescript%2F0020-valid-parentheses.ts)
| +| [0682 - Baseball Game](https://leetcode.com/problems/baseball-game/) |
|
[✔️](c%2F0682-baseball-game.c)
|
[✔️](cpp%2F0682-baseball-game.cpp)
|
[✔️](csharp%2F0682-baseball-game.cs)
|
|
[✔️](go%2F0682-baseball-game.go)
|
|
[✔️](java%2F0682-baseball-game.java)
|
[✔️](javascript%2F0682-Baseball-Game.js)
|
[✔️](kotlin%2F0682-baseball-game.kt)
|
[✔️](python%2F0682-baseball-game.py)
|
|
[✔️](rust%2F0682-baseball-game.rs)
|
|
[✔️](swift%2F0682-baseball-game.swift)
|
[✔️](typescript%2F0682-baseball-game.ts)
| +| [0225 - Implement Stack Using Queues](https://leetcode.com/problems/implement-stack-using-queues/) |
|
[✔️](c%2F0225-implement-stack-using-queues.c)
|
[✔️](cpp%2F0225-implement-stack-using-queues.cpp)
|
[✔️](csharp%2F0225-implement-stack-using-queues.cs)
|
|
[✔️](go%2F0225-implement-stack-using-queues.go)
|
|
[✔️](java%2F0225-implement-stack-using-queues.java)
|
[✔️](javascript%2F0225-implement-stack-using-queues.js)
|
[✔️](kotlin%2F0225-implement-stack-using-queues.kt)
|
[✔️](python%2F0225-implement-stack-using-queues.py)
|
|
[✔️](rust%2F0225-implement-stack-using-queues.rs)
|
|
[✔️](swift%2F0225-implement-stack-using-queues.swift)
|
[✔️](typescript%2F0225-implement-stack-using-queues.ts)
| +| [0155 - Min Stack](https://leetcode.com/problems/min-stack/) |
|
[✔️](c%2F0155-min-stack.c)
|
[✔️](cpp%2F0155-min-stack.cpp)
|
[✔️](csharp%2F0155-min-stack.cs)
|
[✔️](dart%2F0155-min-stack.dart)
|
[✔️](go%2F0155-min-stack.go)
|
|
[✔️](java%2F0155-min-stack.java)
|
[✔️](javascript%2F0155-min-stack.js)
|
[✔️](kotlin%2F0155-min-stack.kt)
|
[✔️](python%2F0155-min-stack.py)
|
[✔️](ruby%2F0155-min-stack.rb)
|
[✔️](rust%2F0155-min-stack.rs)
|
|
[✔️](swift%2F0155-min-stack.swift)
|
[✔️](typescript%2F0155-min-stack.ts)
| +| [0150 - Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/) |
|
[✔️](c%2F0150-evaluate-reverse-polish-notation.c)
|
[✔️](cpp%2F0150-evaluate-reverse-polish-notation.cpp)
|
[✔️](csharp%2F0150-evaluate-reverse-polish-notation.cs)
|
[✔️](dart%2F0150-evaluate-reverse-polish-notation.dart)
|
[✔️](go%2F0150-evaluate-reverse-polish-notation.go)
|
|
[✔️](java%2F0150-evaluate-reverse-polish-notation.java)
|
[✔️](javascript%2F0150-evaluate-reverse-polish-notation.js)
|
[✔️](kotlin%2F0150-evaluate-reverse-polish-notation.kt)
|
[✔️](python%2F0150-evaluate-reverse-polish-notation.py)
|
[✔️](ruby%2F0150-evaluate-reverse-polish-notation.rb)
|
[✔️](rust%2F0150-evaluate-reverse-polish-notation.rs)
|
|
[✔️](swift%2F0150-evaluate-reverse-polish-notation.swift)
|
[✔️](typescript%2F0150-evaluate-reverse-polish-notation.ts)
| +| [2390 - Removing Stars From a String](https://leetcode.com/problems/removing-stars-from-a-string/) |
|
|
[✔️](cpp%2F2390-removing-stars-from-a-string.cpp)
|
[✔️](csharp%2F2390-removing-stars-from-a-string.cs)
|
|
|
|
[✔️](java%2F2390-removing-stars-from-a-string.java)
|
[✔️](javascript%2F2390-removing-stars-from-a-string.js)
|
[✔️](kotlin%2F2390-removing-stars-from-a-string.kt)
|
[✔️](python%2F2390-removing-stars-from-a-string.py)
|
|
|
|
|
[✔️](typescript%2F2390-removing-stars-from-a-string.ts)
| +| [0946 - Validate Stack Sequences](https://leetcode.com/problems/validate-stack-sequences/) |
|
|
[✔️](cpp%2F0946-validate-stack-sequences.cpp)
|
|
|
|
|
[✔️](java%2F0946-validate-stack-sequences.java)
|
|
[✔️](kotlin%2F0946-validate-stack-sequences.kt)
|
[✔️](python%2F0946-validate-stack-sequences.py)
|
|
|
|
|
| +| [0022 - Generate Parentheses](https://leetcode.com/problems/generate-parentheses/) |
|
[✔️](c%2F0022-generate-parentheses.c)
|
[✔️](cpp%2F0022-generate-parentheses.cpp)
|
[✔️](csharp%2F0022-generate-parentheses.cs)
|
|
[✔️](go%2F0022-generate-parentheses.go)
|
|
[✔️](java%2F0022-generate-parentheses.java)
|
[✔️](javascript%2F0022-generate-parentheses.js)
|
[✔️](kotlin%2F0022-generate-parentheses.kt)
|
[✔️](python%2F0022-generate-parentheses.py)
|
[✔️](ruby%2F0022-generate-parentheses.rb)
|
[✔️](rust%2F0022-generate-parentheses.rs)
|
|
[✔️](swift%2F0022-generate-parentheses.swift)
|
[✔️](typescript%2F0022-generate-parentheses.ts)
| +| [0735 - Asteroid Collision](https://leetcode.com/problems/asteroid-collision/) |
|
|
[✔️](cpp%2F0735-asteroid-collision.cpp)
|
|
|
[✔️](go%2F0735-asteroid-collision.go)
|
|
[✔️](java%2F0735-asteroid-collision.java)
|
[✔️](javascript%2F0735-asteroid-collision.js)
|
[✔️](kotlin%2F0735-asteroid-collision.kt)
|
[✔️](python%2F0735-asteroid-collision.py)
|
|
[✔️](rust%2F0735-asteroid-collision.rs)
|
|
[✔️](swift%2F0735-asteroid-collision.swift)
|
[✔️](typescript%2F0735-asteroid-collision.ts)
| +| [0739 - Daily Temperatures](https://leetcode.com/problems/daily-temperatures/) |
|
[✔️](c%2F0739-daily-temperatures.c)
|
[✔️](cpp%2F0739-daily-temperatures.cpp)
|
[✔️](csharp%2F0739-daily-temperatures.cs)
|
|
[✔️](go%2F0739-daily-temperatures.go)
|
|
[✔️](java%2F0739-daily-temperatures.java)
|
[✔️](javascript%2F0739-daily-temperatures.js)
|
[✔️](kotlin%2F0739-daily-temperatures.kt)
|
[✔️](python%2F0739-daily-temperatures.py)
|
[✔️](ruby%2F0739-daily-temperatures.rb)
|
[✔️](rust%2F0739-daily-temperatures.rs)
|
|
[✔️](swift%2F0739-daily-temperatures.swift)
|
[✔️](typescript%2F0739-daily-temperatures.ts)
| +| [0901 - Online Stock Span](https://leetcode.com/problems/online-stock-span/) |
|
|
[✔️](cpp%2F0901-online-stock-span.cpp)
|
|
|
|
|
[✔️](java%2F0901-online-stock-span.java)
|
[✔️](javascript%2F0901-online-stock-span.js)
|
[✔️](kotlin%2F0901-online-stock-span.kt)
|
[✔️](python%2F0901-online-stock-span.py)
|
|
[✔️](rust%2F0901-online-stock-span.rs)
|
|
|
[✔️](typescript%2F0901-online-stock-span.ts)
| +| [0853 - Car Fleet](https://leetcode.com/problems/car-fleet/) |
|
[✔️](c%2F0853-car-fleet.c)
|
[✔️](cpp%2F0853-car-fleet.cpp)
|
[✔️](csharp%2F0853-car-fleet.cs)
|
|
[✔️](go%2F0853-car-fleet.go)
|
|
[✔️](java%2F0853-car-fleet.java)
|
[✔️](javascript%2F0853-car-fleet.js)
|
[✔️](kotlin%2F0853-car-fleet.kt)
|
[✔️](python%2F0853-car-fleet.py)
|
[✔️](ruby%2F0853-car-fleet.rb)
|
[✔️](rust%2F0853-car-fleet.rs)
|
|
[✔️](swift%2F0853-car-fleet.swift)
|
[✔️](typescript%2F0853-car-fleet.ts)
| +| [0071 - Simplify Path](https://leetcode.com/problems/simplify-path/) |
|
|
[✔️](cpp%2F0071-simplify-path.cpp)
|
|
|
|
|
[✔️](java%2F0071-simplify-path.java)
|
[✔️](javascript%2F0071-simplify-path.js)
|
[✔️](kotlin%2F0071-simplify-path.kt)
|
[✔️](python%2F0071-simplify-path.py)
|
|
[✔️](rust%2F0071-simplify-path.rs)
|
|
|
[✔️](typescript%2F0071-simplify-path.ts)
| +| [0394 - Decode String](https://leetcode.com/problems/decode-string/) |
|
|
[✔️](cpp%2F0394-decode-string.cpp)
|
|
|
|
|
[✔️](java%2F0394-decode-string.java)
|
|
[✔️](kotlin%2F0394-decode-string.kt)
|
[✔️](python%2F0394-decode-string.py)
|
|
[✔️](rust%2F0394-decode-string.rs)
|
[✔️](scala%2F0394-decode-string.scala)
|
|
[✔️](typescript%2F0394-decode-string.ts)
| +| [0402 - Remove K Digits](https://leetcode.com/problems/remove-k-digits/) |
|
|
[✔️](cpp%2F0402-remove-k-digits.cpp)
|
|
|
|
|
[✔️](java%2F0402-remove-k-digits.java)
|
[✔️](javascript%2F0402-remove-k-digits.js)
|
[✔️](kotlin%2F0402-remove-k-digits.kt)
|
[✔️](python%2F0402-remove-k-digits.py)
|
|
[✔️](rust%2F0402-remove-k-digits.rs)
|
|
|
[✔️](typescript%2F0402-remove-k-digits.ts)
| +| [1209 - Remove All Adjacent Duplicates In String II](https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/) |
|
|
[✔️](cpp%2F1209-Remove-All-Adjacent-Duplicates-in-String-II.cpp)
|
|
|
|
|
[✔️](java%2F1209-remove-all-adjacent-duplicates-in-string-ii.java)
|
[✔️](javascript%2F1209-Remove-All-Adjacent-Duplicates-in-String-II.js)
|
[✔️](kotlin%2F1209-remove-all-adjacent-duplicates-in-string-ii.kt)
|
[✔️](python%2F1209-remove-all-adjacent-duplicates-in-string-ii.py)
|
|
[✔️](rust%2F1209-remove-all-adjacent-duplicates-in-string-II.rs)
|
|
|
[✔️](typescript%2F1209-remove-all-adjacent-duplicates-in-string-II.ts)
| +| [0456 - 132 Pattern](https://leetcode.com/problems/132-pattern/) |
|
|
[✔️](cpp%2F0456-132-pattern.cpp)
|
|
|
|
|
[✔️](java%2F0456-132-pattern.java)
|
[✔️](javascript%2F0456-132-pattern.js)
|
[✔️](kotlin%2F0456-132-pattern.kt)
|
[✔️](python%2F0456-132-pattern.py)
|
|
[✔️](rust%2F0456-132-pattern.rs)
|
|
|
[✔️](typescript%2F0456-132-pattern.ts)
| +| [0895 - Maximum Frequency Stack](https://leetcode.com/problems/maximum-frequency-stack/) |
|
|
[✔️](cpp%2F0895-maximum-frequency-stack.cpp)
|
|
|
|
|
[✔️](java%2F0895-maximum-frequency-stack.java)
|
[✔️](javascript%2F0895-maximum-frequency-stack.js)
|
[✔️](kotlin%2F0895-maximum-frequency-stack.kt)
|
[✔️](python%2F0895-maximum-frequency-stack.py)
|
|
[✔️](rust%2F0895-maximum-frequency-stack.rs)
|
|
|
[✔️](typescript%2F0895-maximum-frequency-stack.ts)
| +| [0084 - Largest Rectangle In Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/) |
|
[✔️](c%2F0084-largest-rectangle-in-histogram.c)
|
[✔️](cpp%2F0084-largest-rectangle-in-histogram.cpp)
|
[✔️](csharp%2F0084-largest-rectangle-in-histogram.cs)
|
|
[✔️](go%2F0084-largest-rectangle-in-histogram.go)
|
|
[✔️](java%2F0084-largest-rectangle-in-histogram.java)
|
[✔️](javascript%2F0084-largest-rectangle-in-histogram.js)
|
[✔️](kotlin%2F0084-largest-rectangle-in-histogram.kt)
|
[✔️](python%2F0084-largest-rectangle-in-histogram.py)
|
[✔️](ruby%2F0084-largest-rectangle-in-histogram.rb)
|
[✔️](rust%2F0084-largest-rectangle-in-histogram.rs)
|
|
[✔️](swift%2F0084-largest-rectangle-in-histogram.swift)
|
[✔️](typescript%2F0084-largest-rectangle-in-histogram.ts)
| ### Binary Search -Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS ----- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- -[0704 - Binary Search](https://leetcode.com/problems/binary-search/) |
|
[✔️](c%2F0704-binary-search.c)
|
[✔️](cpp%2F0704-binary-search.cpp)
|
[✔️](csharp%2F0704-binary-search.cs)
|
[✔️](dart%2F0704-binary-search.dart)
|
[✔️](go%2F0704-binary-search.go)
|
|
[✔️](java%2F0704-binary-search.java)
|
[✔️](javascript%2F0704-binary-search.js)
|
[✔️](kotlin%2F0704-binary-search.kt)
|
[✔️](python%2F0704-binary-search.py)
|
[✔️](ruby%2F0704-binary-search.rb)
|
[✔️](rust%2F0704-binary-search.rs)
|
[✔️](scala%2F0704-binary-search.scala)
|
[✔️](swift%2F0704-binary-search.swift)
|
[✔️](typescript%2F0704-binary-search.ts)
-[0035 - Search Insert Position](https://leetcode.com/problems/search-insert-position/) |
|
[✔️](c%2F0035-search-insert-position.c)
|
[✔️](cpp%2F0035-search-insert-position.cpp)
|
[✔️](csharp%2F0035-search-insert-position.cs)
|
|
[✔️](go%2F0035-search-insert-position.go)
|
|
[✔️](java%2F0035-search-insert-position.java)
|
[✔️](javascript%2F0035-search-insert-position.js)
|
[✔️](kotlin%2F0035-search-insert-position.kt)
|
[✔️](python%2F0035-search-insert-position.py)
|
[✔️](ruby%2F0035-search-insert-position.rb)
|
[✔️](rust%2F0035-search-insert-position.rs)
|
|
[✔️](swift%2F0035-search-insert-position.swift)
|
[✔️](typescript%2F0035-search-insert-position.ts)
-[0374 - Guess Number Higher Or Lower](https://leetcode.com/problems/guess-number-higher-or-lower/) |
|
[✔️](c%2F0374-guess-number-higher-or-lower.c)
|
[✔️](cpp%2F0374-guess-number-higher-or-lower.cpp)
|
[✔️](csharp%2F0374-guess-number-higher-or-lower.cs)
|
|
[✔️](go%2F0374-guess-number-higher-or-lower.go)
|
|
[✔️](java%2F0374-guess-number-higher-or-lower.java)
|
[✔️](javascript%2F0374-guess-number-higher-or-lower.js)
|
[✔️](kotlin%2F0374-guess-number-higher-or-lower.kt)
|
[✔️](python%2F0374-guess-number-higher-or-lower.py)
|
|
[✔️](rust%2F0374-guess-number-higher-or-lower.rs)
|
|
[✔️](swift%2F0374-guess-number-higher-or-lower.swift)
|
-[0441 - Arranging Coins](https://leetcode.com/problems/arranging-coins/) |
|
|
[✔️](cpp%2F0441-arranging-coins.cpp)
|
|
|
|
|
[✔️](java%2F0441-arranging-coins.java)
|
[✔️](javascript%2F0441-arranging-coins.js)
|
[✔️](kotlin%2F0441-arranging-coins.kt)
|
[✔️](python%2F0441-arranging-coins.py)
|
|
[✔️](rust%2F0441-arranging-coins.rs)
|
|
|
-[0977 - Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/) |
|
|
[✔️](cpp%2F0977-squares-of-a-sorted-array.cpp)
|
|
|
[✔️](go%2F0977-squares-of-a-sorted-array.go)
|
|
[✔️](java%2F0977-squares-of-a-sorted-array.java)
|
[✔️](javascript%2F0977-squares-of-a-sorted-array.js)
|
[✔️](kotlin%2F0977-squares-of-a-sorted-array.kt)
|
[✔️](python%2F0977-squares-of-a-sorted-array.py)
|
|
[✔️](rust%2F0977-squares-of-a-sorted-array.rs)
|
|
[✔️](swift%2F0977-squares-of-a-sorted-array.swift)
|
[✔️](typescript%2F0977-squares-of-a-sorted-array.ts)
-[0367 - Valid Perfect Square](https://leetcode.com/problems/valid-perfect-square/) |
|
[✔️](c%2F0367-valid-perfect-square.c)
|
[✔️](cpp%2F0367-valid-perfect-square.cpp)
|
|
|
[✔️](go%2F0367-valid-perfect-square.go)
|
|
[✔️](java%2F0367-valid-perfect-square.java)
|
[✔️](javascript%2F0367-valid-perfect-square.js)
|
[✔️](kotlin%2F0367-valid-perfect-square.kt)
|
[✔️](python%2F0367-valid-perfect-square.py)
|
|
|
|
[✔️](swift%2F0367-valid-perfect-square.swift)
|
-[0069 - Sqrt(x) ](https://leetcode.com/problems/sqrtx/) |
|
[✔️](c%2F0069-sqrtx.c)
|
[✔️](cpp%2F0069-sqrtx.cpp)
|
[✔️](csharp%2F0069-sqrtx.cs)
|
|
|
|
[✔️](java%2F0069-sqrtx.java)
|
[✔️](javascript%2F0069-sqrtx.js)
|
[✔️](kotlin%2F0069-sqrtx.kt)
|
[✔️](python%2F0069-sqrtx.py)
|
|
|
|
|
-[0540 - Single Element in a Sorted Array](https://leetcode.com/problems/single-element-in-a-sorted-array/) |
|
[✔️](c%2F0540-single-element-in-a-sorted-array.c)
|
[✔️](cpp%2F0540-single-element-in-a-sorted-array.cpp)
|
|
|
|
|
[✔️](java%2F0540-single-element-in-a-sorted-array.java)
|
[✔️](javascript%2F0540-single-element-in-a-sorted-array.js)
|
[✔️](kotlin%2F0540-single-element-in-a-sorted-array.kt)
|
[✔️](python%2F0540-single-element-in-a-sorted-array.py)
|
|
|
|
|
[✔️](typescript%2F0540-single-element-in-a-sorted-array.ts)
-[1011 - Capacity to Ship Packages](https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/) |
|
|
[✔️](cpp%2F1011-capacity-to-ship-packages-within-d-days.cpp)
|
|
|
|
|
[✔️](java%2F1011-capacity-to-ship-packages-within-d-days.java)
|
|
[✔️](kotlin%2F1011-capacity-to-ship-packages-within-d-days.kt)
|
[✔️](python%2F1011-capacity-to-ship-packages-within-d-days.py)
|
|
|
|
|
-[0162 - Find Peak Element](https://leetcode.com/problems/find-peak-element/) |
|
[✔️](c%2F0162-find-peak-element.c)
|
[✔️](cpp%2F0162-find-peak-element.cpp)
|
|
|
|
|
[✔️](java%2F0162-find-peak-element.java)
|
[✔️](javascript%2F0162-find-peak-element.js)
|
[✔️](kotlin%2F0162-find-peak-element.kt)
|
[✔️](python%2F0162-find-peak-element.py)
|
|
|
|
|
-[2300 - Successful Pairs of Spells and Potions](https://leetcode.com/problems/successful-pairs-of-spells-and-potions/) |
|
|
[✔️](cpp%2F2300-successful-pairs-of-spells-and-potions.cpp)
|
|
|
|
|
[✔️](java%2F2300-successful-pairs-of-spells-and-potions.java)
|
|
[✔️](kotlin%2F2300-successful-pairs-of-spells-and-potions.kt)
|
[✔️](python%2F2300-successful-pairs-of-spells-and-potions.py)
|
|
|
|
|
-[0074 - Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/) |
|
[✔️](c%2F0074-search-a-2d-matrix.c)
|
[✔️](cpp%2F0074-search-a-2d-matrix.cpp)
|
[✔️](csharp%2F0074-search-a-2d-matrix.cs)
|
|
[✔️](go%2F0074-search-a-2d-matrix.go)
|
|
[✔️](java%2F0074-search-a-2d-matrix.java)
|
[✔️](javascript%2F0074-search-a-2d-matrix.js)
|
[✔️](kotlin%2F0074-search-a-2d-matrix.kt)
|
[✔️](python%2F0074-search-a-2d-matrix.py)
|
[✔️](ruby%2F0074-search-a-2d-matrix.rb)
|
[✔️](rust%2F0074-search-a-2d-matrix.rs)
|
|
[✔️](swift%2F0074-search-a-2d-matrix.swift)
|
[✔️](typescript%2F0074-search-a-2d-matrix.ts)
-[0875 - Koko Eating Bananas](https://leetcode.com/problems/koko-eating-bananas/) |
|
[✔️](c%2F0875-koko-eating-bananas.c)
|
[✔️](cpp%2F0875-koko-eating-bananas.cpp)
|
[✔️](csharp%2F0875-koko-eating-bananas.cs)
|
|
[✔️](go%2F0875-koko-eating-bananas.go)
|
|
[✔️](java%2F0875-koko-eating-bananas.java)
|
[✔️](javascript%2F0875-koko-eating-bananas.js)
|
[✔️](kotlin%2F0875-koko-eating-bananas.kt)
|
[✔️](python%2F0875-koko-eating-bananas.py)
|
[✔️](ruby%2F0875-koko-eating-bananas.rb)
|
[✔️](rust%2F0875-koko-eating-bananas.rs)
|
|
[✔️](swift%2F0875-koko-eating-bananas.swift)
|
[✔️](typescript%2F0875-koko-eating-bananas.ts)
-[2616 - Minimize the Maximum Difference of Pairs](https://leetcode.com/problems/minimize-the-maximum-difference-of-pairs/) |
|
|
|
|
|
|
|
[✔️](java%2F2616-minimize-the-maximum-difference-of-pairs.java)
|
|
[✔️](kotlin%2F2616-minimize-the-maximum-difference-of-pairs.kt)
|
[✔️](python%2F2616-minimize-the-maximum-difference-of-pairs.py)
|
|
|
|
|
-[0153 - Find Minimum In Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/) |
|
[✔️](c%2F0153-find-minimum-in-rotated-sorted-array.c)
|
[✔️](cpp%2F0153-find-minimum-in-rotated-sorted-array.cpp)
|
[✔️](csharp%2F0153-find-minimum-in-rotated-sorted-array.cs)
|
|
[✔️](go%2F0153-find-minimum-in-rotated-sorted-array.go)
|
|
[✔️](java%2F0153-find-minimum-in-rotated-sorted-array.java)
|
[✔️](javascript%2F0153-find-minimum-in-rotated-sorted-array.js)
|
[✔️](kotlin%2F0153-find-minimum-in-rotated-sorted-array.kt)
|
[✔️](python%2F0153-find-minimum-in-rotated-sorted-array.py)
|
[✔️](ruby%2F0153-find-minimum-in-rotated-sorted-array.rb)
|
[✔️](rust%2F0153-find-minimum-in-rotated-sorted-array.rs)
|
[✔️](scala%2F0153-find-minimum-in-rotated-sorted-array.scala)
|
[✔️](swift%2F0153-find-minimum-in-rotated-sorted-array.swift)
|
[✔️](typescript%2F0153-find-minimum-in-rotated-sorted-array.ts)
-[0033 - Search In Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/) |
|
[✔️](c%2F0033-search-in-rotated-sorted-array.c)
|
[✔️](cpp%2F0033-search-in-rotated-sorted-array.cpp)
|
[✔️](csharp%2F0033-search-in-rotated-sorted-array.cs)
|
|
[✔️](go%2F0033-search-in-rotated-sorted-array.go)
|
|
[✔️](java%2F0033-search-in-rotated-sorted-array.java)
|
[✔️](javascript%2F0033-search-in-rotated-sorted-array.js)
|
[✔️](kotlin%2F0033-search-in-rotated-sorted-array.kt)
|
[✔️](python%2F0033-search-in-rotated-sorted-array.py)
|
|
[✔️](rust%2F0033-search-in-rotated-sorted-array.rs)
|
[✔️](scala%2F0033-search-in-rotated-sorted-array.scala)
|
[✔️](swift%2F0033-search-in-rotated-sorted-array.swift)
|
[✔️](typescript%2F0033-search-in-rotated-sorted-array.ts)
-[0081 - Search In Rotated Sorted Array II](https://leetcode.com/problems/search-in-rotated-sorted-array-ii/) |
|
|
|
|
|
|
|
[✔️](java%2F0081-search-in-rotated-sorted-array-ii.java)
|
|
[✔️](kotlin%2F0081-search-in-rotated-sorted-array-ii.kt)
|
[✔️](python%2F0081-search-in-rotated-sorted-array-ii.py)
|
|
|
|
|
-[0981 - Time Based Key Value Store](https://leetcode.com/problems/time-based-key-value-store/) |
|
[✔️](c%2F0981-time-based-key-value-store.c)
|
[✔️](cpp%2F0981-time-based-key-value-store.cpp)
|
[✔️](csharp%2F0981-time-based-key-value-store.cs)
|
|
[✔️](go%2F0981-time-based-key-value-store.go)
|
|
[✔️](java%2F0981-time-based-key-value-store.java)
|
[✔️](javascript%2F0981-time-based-key-value-store.js)
|
[✔️](kotlin%2F0981-time-based-key-value-store.kt)
|
[✔️](python%2F0981-time-based-key-value-store.py)
|
[✔️](ruby%2F0981-Time-Based-Key-Value-Store.rb)
|
[✔️](rust%2F0981-time-based-key-value-store.rs)
|
|
[✔️](swift%2F0981-time-based-key-value-store.swift)
|
[✔️](typescript%2F0981-time-based-key-value-store.ts)
-[0034 - Find First And Last Position of Element In Sorted Array](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/) |
|
|
[✔️](cpp%2F0034-find-first-and-last-position-of-element-in-sorted-array.cpp)
|
[✔️](csharp%2F0034-find-first-and-last-position-of-element-in-sorted-array.cs)
|
|
[✔️](go%2F0034-find-first-and-last-position-of-element-in-sorted-array.go)
|
|
[✔️](java%2F0034-find-first-and-last-position-of-element-in-sorted-array.java)
|
[✔️](javascript%2F0034-find-first-and-last-position-of-element-in-sorted-array.js)
|
[✔️](kotlin%2F0034-find-first-and-last-position-of-element-in-sorted-array.kt)
|
[✔️](python%2F0034-find-first-and-last-position-of-element-in-sorted-array.py)
|
|
|
|
[✔️](swift%2F0034-find-first-and-last-position-of-element-in-sorted-array.swift)
|
-[1898 - Maximum Number of Removable Characters](https://leetcode.com/problems/maximum-number-of-removable-characters/) |
|
|
|
|
|
[✔️](go%2F1898-maximum-number-of-removable-characters.go)
|
|
[✔️](java%2F1898-maximum-number-of-removable-characters.java)
|
[✔️](javascript%2F1898-maximum-number-of-removable-characters.js)
|
[✔️](kotlin%2F1898-maximum-number-of-removable-characters.kt)
|
|
|
|
|
|
-[0116 - Populating Next Right Pointers In Each Node](https://leetcode.com/problems/populating-next-right-pointers-in-each-node/) |
|
|
[✔️](cpp%2F0116-populating-next-right-pointers-in-each-node.cpp)
|
|
|
[✔️](go%2F0116-populating-next-right-pointers-in-each-node.go)
|
|
[✔️](java%2F0116-populating-next-right-pointers-in-each-node.java)
|
[✔️](javascript%2F0116-populating-next-right-pointers-in-each-node.js)
|
[✔️](kotlin%2F0116-populating-next-right-pointers-in-each-node.kt)
|
|
|
|
|
|
-[1268 - Search Suggestions System](https://leetcode.com/problems/search-suggestions-system/) |
|
|
|
|
|
|
|
[✔️](java%2F1268-search-suggestions-system.java)
|
[✔️](javascript%2F1268-search-suggestions-system.js)
|
[✔️](kotlin%2F1268-search-suggestions-system.kt)
|
|
|
|
|
|
-[0410 - Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum/) |
|
|
|
|
|
|
|
[✔️](java%2F0410-split-array-largest-sum.java)
|
[✔️](javascript%2F0410-split-array-largest-sum.js)
|
[✔️](kotlin%2F0410-split-array-largest-sum.kt)
|
[✔️](python%2F0410-split-array-largest-sum.py)
|
|
|
|
|
-[0004 - Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) |
|
[✔️](c%2F0004-median-of-two-sorted-arrays.c)
|
[✔️](cpp%2F0004-median-of-two-sorted-arrays.cpp)
|
[✔️](csharp%2F0004-median-of-two-sorted-arrays.cs)
|
[✔️](dart%2F0004-median-of-two-sorted-arrays.dart)
|
[✔️](go%2F0004-median-of-two-sorted-arrays.go)
|
|
[✔️](java%2F0004-median-of-two-sorted-arrays.java)
|
[✔️](javascript%2F0004-median-of-two-sorted-arrays.js)
|
[✔️](kotlin%2F0004-median-of-two-sorted-arrays.kt)
|
[✔️](python%2F0004-median-of-two-sorted-arrays.py)
|
|
[✔️](rust%2F0004-median-of-two-sorted-arrays.rs)
|
|
[✔️](swift%2F0004-median-of-two-sorted-arrays.swift)
|
[✔️](typescript%2F0004-median-of-two-sorted-arrays.ts)
+| Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| [0704 - Binary Search](https://leetcode.com/problems/binary-search/) |
|
[✔️](c%2F0704-binary-search.c)
|
[✔️](cpp%2F0704-binary-search.cpp)
|
[✔️](csharp%2F0704-binary-search.cs)
|
[✔️](dart%2F0704-binary-search.dart)
|
[✔️](go%2F0704-binary-search.go)
|
|
[✔️](java%2F0704-binary-search.java)
|
[✔️](javascript%2F0704-binary-search.js)
|
[✔️](kotlin%2F0704-binary-search.kt)
|
[✔️](python%2F0704-binary-search.py)
|
[✔️](ruby%2F0704-binary-search.rb)
|
[✔️](rust%2F0704-binary-search.rs)
|
[✔️](scala%2F0704-binary-search.scala)
|
[✔️](swift%2F0704-binary-search.swift)
|
[✔️](typescript%2F0704-binary-search.ts)
| +| [0035 - Search Insert Position](https://leetcode.com/problems/search-insert-position/) |
|
[✔️](c%2F0035-search-insert-position.c)
|
[✔️](cpp%2F0035-search-insert-position.cpp)
|
[✔️](csharp%2F0035-search-insert-position.cs)
|
|
[✔️](go%2F0035-search-insert-position.go)
|
|
[✔️](java%2F0035-search-insert-position.java)
|
[✔️](javascript%2F0035-search-insert-position.js)
|
[✔️](kotlin%2F0035-search-insert-position.kt)
|
[✔️](python%2F0035-search-insert-position.py)
|
[✔️](ruby%2F0035-search-insert-position.rb)
|
[✔️](rust%2F0035-search-insert-position.rs)
|
|
[✔️](swift%2F0035-search-insert-position.swift)
|
[✔️](typescript%2F0035-search-insert-position.ts)
| +| [0374 - Guess Number Higher Or Lower](https://leetcode.com/problems/guess-number-higher-or-lower/) |
|
[✔️](c%2F0374-guess-number-higher-or-lower.c)
|
[✔️](cpp%2F0374-guess-number-higher-or-lower.cpp)
|
[✔️](csharp%2F0374-guess-number-higher-or-lower.cs)
|
|
[✔️](go%2F0374-guess-number-higher-or-lower.go)
|
|
[✔️](java%2F0374-guess-number-higher-or-lower.java)
|
[✔️](javascript%2F0374-guess-number-higher-or-lower.js)
|
[✔️](kotlin%2F0374-guess-number-higher-or-lower.kt)
|
[✔️](python%2F0374-guess-number-higher-or-lower.py)
|
|
[✔️](rust%2F0374-guess-number-higher-or-lower.rs)
|
|
[✔️](swift%2F0374-guess-number-higher-or-lower.swift)
|
| +| [0441 - Arranging Coins](https://leetcode.com/problems/arranging-coins/) |
|
|
[✔️](cpp%2F0441-arranging-coins.cpp)
|
|
|
|
|
[✔️](java%2F0441-arranging-coins.java)
|
[✔️](javascript%2F0441-arranging-coins.js)
|
[✔️](kotlin%2F0441-arranging-coins.kt)
|
[✔️](python%2F0441-arranging-coins.py)
|
|
[✔️](rust%2F0441-arranging-coins.rs)
|
|
|
| +| [0977 - Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/) |
|
|
[✔️](cpp%2F0977-squares-of-a-sorted-array.cpp)
|
|
|
[✔️](go%2F0977-squares-of-a-sorted-array.go)
|
|
[✔️](java%2F0977-squares-of-a-sorted-array.java)
|
[✔️](javascript%2F0977-squares-of-a-sorted-array.js)
|
[✔️](kotlin%2F0977-squares-of-a-sorted-array.kt)
|
[✔️](python%2F0977-squares-of-a-sorted-array.py)
|
|
[✔️](rust%2F0977-squares-of-a-sorted-array.rs)
|
|
[✔️](swift%2F0977-squares-of-a-sorted-array.swift)
|
[✔️](typescript%2F0977-squares-of-a-sorted-array.ts)
| +| [0367 - Valid Perfect Square](https://leetcode.com/problems/valid-perfect-square/) |
|
[✔️](c%2F0367-valid-perfect-square.c)
|
[✔️](cpp%2F0367-valid-perfect-square.cpp)
|
|
|
[✔️](go%2F0367-valid-perfect-square.go)
|
|
[✔️](java%2F0367-valid-perfect-square.java)
|
[✔️](javascript%2F0367-valid-perfect-square.js)
|
[✔️](kotlin%2F0367-valid-perfect-square.kt)
|
[✔️](python%2F0367-valid-perfect-square.py)
|
|
|
|
[✔️](swift%2F0367-valid-perfect-square.swift)
|
| +| [0069 - Sqrt(x) ](https://leetcode.com/problems/sqrtx/) |
|
[✔️](c%2F0069-sqrtx.c)
|
[✔️](cpp%2F0069-sqrtx.cpp)
|
[✔️](csharp%2F0069-sqrtx.cs)
|
|
|
|
[✔️](java%2F0069-sqrtx.java)
|
[✔️](javascript%2F0069-sqrtx.js)
|
[✔️](kotlin%2F0069-sqrtx.kt)
|
[✔️](python%2F0069-sqrtx.py)
|
|
|
|
|
| +| [0540 - Single Element in a Sorted Array](https://leetcode.com/problems/single-element-in-a-sorted-array/) |
|
[✔️](c%2F0540-single-element-in-a-sorted-array.c)
|
[✔️](cpp%2F0540-single-element-in-a-sorted-array.cpp)
|
|
|
|
|
[✔️](java%2F0540-single-element-in-a-sorted-array.java)
|
[✔️](javascript%2F0540-single-element-in-a-sorted-array.js)
|
[✔️](kotlin%2F0540-single-element-in-a-sorted-array.kt)
|
[✔️](python%2F0540-single-element-in-a-sorted-array.py)
|
|
|
|
|
[✔️](typescript%2F0540-single-element-in-a-sorted-array.ts)
| +| [1011 - Capacity to Ship Packages](https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/) |
|
|
[✔️](cpp%2F1011-capacity-to-ship-packages-within-d-days.cpp)
|
|
|
|
|
[✔️](java%2F1011-capacity-to-ship-packages-within-d-days.java)
|
|
[✔️](kotlin%2F1011-capacity-to-ship-packages-within-d-days.kt)
|
[✔️](python%2F1011-capacity-to-ship-packages-within-d-days.py)
|
|
|
|
|
| +| [0162 - Find Peak Element](https://leetcode.com/problems/find-peak-element/) |
|
[✔️](c%2F0162-find-peak-element.c)
|
[✔️](cpp%2F0162-find-peak-element.cpp)
|
|
|
|
|
[✔️](java%2F0162-find-peak-element.java)
|
[✔️](javascript%2F0162-find-peak-element.js)
|
[✔️](kotlin%2F0162-find-peak-element.kt)
|
[✔️](python%2F0162-find-peak-element.py)
|
|
|
|
|
| +| [2300 - Successful Pairs of Spells and Potions](https://leetcode.com/problems/successful-pairs-of-spells-and-potions/) |
|
|
[✔️](cpp%2F2300-successful-pairs-of-spells-and-potions.cpp)
|
|
|
|
|
[✔️](java%2F2300-successful-pairs-of-spells-and-potions.java)
|
|
[✔️](kotlin%2F2300-successful-pairs-of-spells-and-potions.kt)
|
[✔️](python%2F2300-successful-pairs-of-spells-and-potions.py)
|
|
|
|
|
| +| [0074 - Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/) |
|
[✔️](c%2F0074-search-a-2d-matrix.c)
|
[✔️](cpp%2F0074-search-a-2d-matrix.cpp)
|
[✔️](csharp%2F0074-search-a-2d-matrix.cs)
|
|
[✔️](go%2F0074-search-a-2d-matrix.go)
|
|
[✔️](java%2F0074-search-a-2d-matrix.java)
|
[✔️](javascript%2F0074-search-a-2d-matrix.js)
|
[✔️](kotlin%2F0074-search-a-2d-matrix.kt)
|
[✔️](python%2F0074-search-a-2d-matrix.py)
|
[✔️](ruby%2F0074-search-a-2d-matrix.rb)
|
[✔️](rust%2F0074-search-a-2d-matrix.rs)
|
|
[✔️](swift%2F0074-search-a-2d-matrix.swift)
|
[✔️](typescript%2F0074-search-a-2d-matrix.ts)
| +| [0875 - Koko Eating Bananas](https://leetcode.com/problems/koko-eating-bananas/) |
|
[✔️](c%2F0875-koko-eating-bananas.c)
|
[✔️](cpp%2F0875-koko-eating-bananas.cpp)
|
[✔️](csharp%2F0875-koko-eating-bananas.cs)
|
|
[✔️](go%2F0875-koko-eating-bananas.go)
|
|
[✔️](java%2F0875-koko-eating-bananas.java)
|
[✔️](javascript%2F0875-koko-eating-bananas.js)
|
[✔️](kotlin%2F0875-koko-eating-bananas.kt)
|
[✔️](python%2F0875-koko-eating-bananas.py)
|
[✔️](ruby%2F0875-koko-eating-bananas.rb)
|
[✔️](rust%2F0875-koko-eating-bananas.rs)
|
|
[✔️](swift%2F0875-koko-eating-bananas.swift)
|
[✔️](typescript%2F0875-koko-eating-bananas.ts)
| +| [2616 - Minimize the Maximum Difference of Pairs](https://leetcode.com/problems/minimize-the-maximum-difference-of-pairs/) |
|
|
|
|
|
|
|
[✔️](java%2F2616-minimize-the-maximum-difference-of-pairs.java)
|
|
[✔️](kotlin%2F2616-minimize-the-maximum-difference-of-pairs.kt)
|
[✔️](python%2F2616-minimize-the-maximum-difference-of-pairs.py)
|
|
|
|
|
| +| [0153 - Find Minimum In Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/) |
|
[✔️](c%2F0153-find-minimum-in-rotated-sorted-array.c)
|
[✔️](cpp%2F0153-find-minimum-in-rotated-sorted-array.cpp)
|
[✔️](csharp%2F0153-find-minimum-in-rotated-sorted-array.cs)
|
|
[✔️](go%2F0153-find-minimum-in-rotated-sorted-array.go)
|
|
[✔️](java%2F0153-find-minimum-in-rotated-sorted-array.java)
|
[✔️](javascript%2F0153-find-minimum-in-rotated-sorted-array.js)
|
[✔️](kotlin%2F0153-find-minimum-in-rotated-sorted-array.kt)
|
[✔️](python%2F0153-find-minimum-in-rotated-sorted-array.py)
|
[✔️](ruby%2F0153-find-minimum-in-rotated-sorted-array.rb)
|
[✔️](rust%2F0153-find-minimum-in-rotated-sorted-array.rs)
|
[✔️](scala%2F0153-find-minimum-in-rotated-sorted-array.scala)
|
[✔️](swift%2F0153-find-minimum-in-rotated-sorted-array.swift)
|
[✔️](typescript%2F0153-find-minimum-in-rotated-sorted-array.ts)
| +| [0033 - Search In Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/) |
|
[✔️](c%2F0033-search-in-rotated-sorted-array.c)
|
[✔️](cpp%2F0033-search-in-rotated-sorted-array.cpp)
|
[✔️](csharp%2F0033-search-in-rotated-sorted-array.cs)
|
|
[✔️](go%2F0033-search-in-rotated-sorted-array.go)
|
|
[✔️](java%2F0033-search-in-rotated-sorted-array.java)
|
[✔️](javascript%2F0033-search-in-rotated-sorted-array.js)
|
[✔️](kotlin%2F0033-search-in-rotated-sorted-array.kt)
|
[✔️](python%2F0033-search-in-rotated-sorted-array.py)
|
|
[✔️](rust%2F0033-search-in-rotated-sorted-array.rs)
|
[✔️](scala%2F0033-search-in-rotated-sorted-array.scala)
|
[✔️](swift%2F0033-search-in-rotated-sorted-array.swift)
|
[✔️](typescript%2F0033-search-in-rotated-sorted-array.ts)
| +| [0081 - Search In Rotated Sorted Array II](https://leetcode.com/problems/search-in-rotated-sorted-array-ii/) |
|
|
|
|
|
|
|
[✔️](java%2F0081-search-in-rotated-sorted-array-ii.java)
|
|
[✔️](kotlin%2F0081-search-in-rotated-sorted-array-ii.kt)
|
[✔️](python%2F0081-search-in-rotated-sorted-array-ii.py)
|
|
|
|
|
| +| [0981 - Time Based Key Value Store](https://leetcode.com/problems/time-based-key-value-store/) |
|
[✔️](c%2F0981-time-based-key-value-store.c)
|
[✔️](cpp%2F0981-time-based-key-value-store.cpp)
|
[✔️](csharp%2F0981-time-based-key-value-store.cs)
|
|
[✔️](go%2F0981-time-based-key-value-store.go)
|
|
[✔️](java%2F0981-time-based-key-value-store.java)
|
[✔️](javascript%2F0981-time-based-key-value-store.js)
|
[✔️](kotlin%2F0981-time-based-key-value-store.kt)
|
[✔️](python%2F0981-time-based-key-value-store.py)
|
[✔️](ruby%2F0981-Time-Based-Key-Value-Store.rb)
|
[✔️](rust%2F0981-time-based-key-value-store.rs)
|
|
[✔️](swift%2F0981-time-based-key-value-store.swift)
|
[✔️](typescript%2F0981-time-based-key-value-store.ts)
| +| [0034 - Find First And Last Position of Element In Sorted Array](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/) |
|
|
[✔️](cpp%2F0034-find-first-and-last-position-of-element-in-sorted-array.cpp)
|
[✔️](csharp%2F0034-find-first-and-last-position-of-element-in-sorted-array.cs)
|
|
[✔️](go%2F0034-find-first-and-last-position-of-element-in-sorted-array.go)
|
|
[✔️](java%2F0034-find-first-and-last-position-of-element-in-sorted-array.java)
|
[✔️](javascript%2F0034-find-first-and-last-position-of-element-in-sorted-array.js)
|
[✔️](kotlin%2F0034-find-first-and-last-position-of-element-in-sorted-array.kt)
|
[✔️](python%2F0034-find-first-and-last-position-of-element-in-sorted-array.py)
|
|
|
|
[✔️](swift%2F0034-find-first-and-last-position-of-element-in-sorted-array.swift)
|
| +| [1898 - Maximum Number of Removable Characters](https://leetcode.com/problems/maximum-number-of-removable-characters/) |
|
|
|
|
|
[✔️](go%2F1898-maximum-number-of-removable-characters.go)
|
|
[✔️](java%2F1898-maximum-number-of-removable-characters.java)
|
[✔️](javascript%2F1898-maximum-number-of-removable-characters.js)
|
[✔️](kotlin%2F1898-maximum-number-of-removable-characters.kt)
|
|
|
|
|
|
| +| [0116 - Populating Next Right Pointers In Each Node](https://leetcode.com/problems/populating-next-right-pointers-in-each-node/) |
|
|
[✔️](cpp%2F0116-populating-next-right-pointers-in-each-node.cpp)
|
|
|
[✔️](go%2F0116-populating-next-right-pointers-in-each-node.go)
|
|
[✔️](java%2F0116-populating-next-right-pointers-in-each-node.java)
|
[✔️](javascript%2F0116-populating-next-right-pointers-in-each-node.js)
|
[✔️](kotlin%2F0116-populating-next-right-pointers-in-each-node.kt)
|
|
|
|
|
|
| +| [1268 - Search Suggestions System](https://leetcode.com/problems/search-suggestions-system/) |
|
|
|
|
|
|
|
[✔️](java%2F1268-search-suggestions-system.java)
|
[✔️](javascript%2F1268-search-suggestions-system.js)
|
[✔️](kotlin%2F1268-search-suggestions-system.kt)
|
|
|
|
|
|
| +| [0410 - Split Array Largest Sum](https://leetcode.com/problems/split-array-largest-sum/) |
|
|
|
|
|
|
|
[✔️](java%2F0410-split-array-largest-sum.java)
|
[✔️](javascript%2F0410-split-array-largest-sum.js)
|
[✔️](kotlin%2F0410-split-array-largest-sum.kt)
|
[✔️](python%2F0410-split-array-largest-sum.py)
|
|
|
|
|
| +| [0004 - Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) |
|
[✔️](c%2F0004-median-of-two-sorted-arrays.c)
|
[✔️](cpp%2F0004-median-of-two-sorted-arrays.cpp)
|
[✔️](csharp%2F0004-median-of-two-sorted-arrays.cs)
|
[✔️](dart%2F0004-median-of-two-sorted-arrays.dart)
|
[✔️](go%2F0004-median-of-two-sorted-arrays.go)
|
|
[✔️](java%2F0004-median-of-two-sorted-arrays.java)
|
[✔️](javascript%2F0004-median-of-two-sorted-arrays.js)
|
[✔️](kotlin%2F0004-median-of-two-sorted-arrays.kt)
|
[✔️](python%2F0004-median-of-two-sorted-arrays.py)
|
|
[✔️](rust%2F0004-median-of-two-sorted-arrays.rs)
|
|
[✔️](swift%2F0004-median-of-two-sorted-arrays.swift)
|
[✔️](typescript%2F0004-median-of-two-sorted-arrays.ts)
| ### Linked List -Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS ----- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- -[0206 - Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) |
|
[✔️](c%2F0206-reverse-linked-list.c)
|
[✔️](cpp%2F0206-reverse-linked-list.cpp)
|
[✔️](csharp%2F0206-reverse-linked-list.cs)
|
[✔️](dart%2F0206-reverse-linked-list.dart)
|
[✔️](go%2F0206-reverse-linked-list.go)
|
|
[✔️](java%2F0206-reverse-linked-list.java)
|
[✔️](javascript%2F0206-reverse-linked-list.js)
|
[✔️](kotlin%2F0206-reverse-linked-list.kt)
|
[✔️](python%2F0206-reverse-linked-list.py)
|
[✔️](ruby%2F0206-reverse-linked-list.rb)
|
[✔️](rust%2F0206-reverse-linked-list.rs)
|
[✔️](scala%2F0206-reverse-linked-list.scala)
|
[✔️](swift%2F0206-reverse-linked-list.swift)
|
[✔️](typescript%2F0206-reverse-linked-list.ts)
-[0021 - Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/) |
|
[✔️](c%2F0021-merge-two-sorted-lists.c)
|
[✔️](cpp%2F0021-merge-two-sorted-lists.cpp)
|
[✔️](csharp%2F0021-merge-two-sorted-lists.cs)
|
[✔️](dart%2F0021-merge-two-sorted-lists.dart)
|
[✔️](go%2F0021-merge-two-sorted-lists.go)
|
|
[✔️](java%2F0021-merge-two-sorted-lists.java)
|
[✔️](javascript%2F0021-merge-two-sorted-lists.js)
|
[✔️](kotlin%2F0021-merge-two-sorted-lists.kt)
|
[✔️](python%2F0021-merge-two-sorted-lists.py)
|
[✔️](ruby%2F0021-merge-two-sorted-lists.rb)
|
[✔️](rust%2F0021-merge-two-sorted-lists.rs)
|
[✔️](scala%2F0021-merge-two-sorted-lists.scala)
|
[✔️](swift%2F0021-merge-two-sorted-lists.swift)
|
[✔️](typescript%2F0021-merge-two-sorted-lists.ts)
-[0234 - Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/) |
|
[✔️](c%2F0234-palindrome-linked-list.c)
|
[✔️](cpp%2F0234-palindrome-linked-list.cpp)
|
|
|
[✔️](go%2F0234-palindrome-linked-list.go)
|
|
[✔️](java%2F0234-palindrome-linked-list.java)
|
[✔️](javascript%2F0234-palindrome-linked-list.js)
|
[✔️](kotlin%2F0234-palindrome-linked-list.kt)
|
[✔️](python%2F0234-palindrome-linked-list.py)
|
|
|
|
|
-[0203 - Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/) |
|
|
[✔️](cpp%2F0203-remove-linked-list-elements.cpp)
|
[✔️](csharp%2F0203-remove-linked-list-elements.cs)
|
|
[✔️](go%2F0203-remove-linked-list-elements.go)
|
|
[✔️](java%2F0203-remove-linked-list-elements.java)
|
[✔️](javascript%2F0203-remove-linked-list-elements.js)
|
[✔️](kotlin%2F0203-remove-linked-list-elements.kt)
|
[✔️](python%2F0203-remove-linked-list-elements.py)
|
|
|
|
|
[✔️](typescript%2F0203-remove-linked-list-elements.ts)
-[0083 - Remove Duplicates From Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/) |
|
[✔️](c%2F0083-remove-duplicates-from-sorted-list.c)
|
[✔️](cpp%2F0083-remove-duplicates-from-sorted-list.cpp)
|
|
|
[✔️](go%2F0083-remove-duplicates-from-sorted-list.go)
|
|
[✔️](java%2F0083-remove-duplicates-from-sorted-list.java)
|
[✔️](javascript%2F0083-remove-duplicates-from-sorted-list.js)
|
[✔️](kotlin%2F0083-remove-duplicates-from-sorted-list.kt)
|
[✔️](python%2F0083-remove-duplicates-from-sorted-list.py)
|
|
|
|
[✔️](swift%2F0083-remove-duplicates-from-sorted-list.swift)
|
-[0876 - Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/) |
|
[✔️](c%2F0876-middle-of-the-linked-list.c)
|
[✔️](cpp%2F0876-middle-of-the-linked-list.cpp)
|
[✔️](csharp%2F0876-middle-of-the-linked-list.cs)
|
|
[✔️](go%2F0876-middle-of-the-linked-list.go)
|
|
[✔️](java%2F0876-middle-of-the-linked-list.java)
|
[✔️](javascript%2F0876-middle-of-the-linked-list.js)
|
[✔️](kotlin%2F0876-middle-of-the-linked-list.kt)
|
[✔️](python%2F0876-middle-of-the-linked-list.py)
|
|
[✔️](rust%2F0876-middle-of-the-linked-list.rs)
|
|
[✔️](swift%2F0876-middle-of-the-linked-list.swift)
|
[✔️](typescript%2F0876-middle-of-the-linked-list.ts)
-[0160 - Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/) |
|
[✔️](c%2F0160-intersection-of-two-linked-lists.c)
|
[✔️](cpp%2F0160-intersection-of-two-linked-lists.cpp)
|
|
|
[✔️](go%2F0160-intersection-of-two-linked-lists.go)
|
|
[✔️](java%2F0160-intersection-of-two-linked-lists.java)
|
[✔️](javascript%2F0160-intersection-of-two-linked-lists.js)
|
[✔️](kotlin%2F0160-intersection-of-two-linked-lists.kt)
|
[✔️](python%2F0160-intersection-of-two-linked-lists.py)
|
|
|
|
|
-[0143 - Reorder List](https://leetcode.com/problems/reorder-list/) |
|
[✔️](c%2F0143-reorder-list.c)
|
[✔️](cpp%2F0143-reorder-list.cpp)
|
[✔️](csharp%2F0143-reorder-list.cs)
|
|
[✔️](go%2F0143-reorder-list.go)
|
|
[✔️](java%2F0143-reorder-list.java)
|
[✔️](javascript%2F0143-reorder-list.js)
|
[✔️](kotlin%2F0143-reorder-list.kt)
|
[✔️](python%2F0143-reorder-list.py)
|
|
[✔️](rust%2F0143-reorder-list.rs)
|
|
[✔️](swift%2F0143-reorder-list.swift)
|
[✔️](typescript%2F0143-reorder-list.ts)
-[2130 - Maximum Twin Sum Of A Linked List](https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/) |
|
|
[✔️](cpp%2F2130-maximum-twin-sum-of-a-linked-list.cpp)
|
|
|
[✔️](go%2F2130-maximum-twin-sum-of-a-linked-list.go)
|
|
[✔️](java%2F2130-maximum-twin-sum-of-a-linked-list.java)
|
[✔️](javascript%2F2130-maximum-twin-sum-of-a-linked-list.js)
|
[✔️](kotlin%2F2130-maximum-twin-sum-of-a-linked-list.kt)
|
[✔️](python%2F2130-maximum-twin-sum-of-a-linked-list.py)
|
|
|
|
[✔️](swift%2F2130-maximum-twin-sum-of-a-linked-list.swift)
|
-[0019 - Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/) |
|
[✔️](c%2F0019-remove-nth-node-from-end-of-list.c)
|
[✔️](cpp%2F0019-remove-nth-node-from-end-of-list.cpp)
|
[✔️](csharp%2F0019-remove-nth-node-from-end-of-list.cs)
|
|
[✔️](go%2F0019-remove-nth-node-from-end-of-list.go)
|
|
[✔️](java%2F0019-remove-nth-node-from-end-of-list.java)
|
[✔️](javascript%2F0019-remove-nth-node-from-end-of-list.js)
|
[✔️](kotlin%2F0019-remove-nth-node-from-end-of-list.kt)
|
[✔️](python%2F0019-remove-nth-node-from-end-of-list.py)
|
|
[✔️](rust%2F0019-remove-nth-node-from-end-of-list.rs)
|
|
[✔️](swift%2F0019-remove-nth-node-from-end-of-list.swift)
|
[✔️](typescript%2F0019-remove-nth-node-from-end-of-list.ts)
-[1721 - Swapping Nodes in a Linked List](https://leetcode.com/problems/swapping-nodes-in-a-linked-list/) |
|
|
[✔️](cpp%2F1721-swapping-nodes-in-a-linked-list.cpp)
|
|
|
[✔️](go%2F1721-swapping-nodes-in-a-linked-list.go)
|
|
[✔️](java%2F1721-swapping-nodes-in-a-linked-list.java)
|
|
[✔️](kotlin%2F1721-swapping-nodes-in-a-linked-list.kt)
|
[✔️](python%2F1721-swapping-nodes-in-a-linked-list.py)
|
|
|
|
|
-[0460 - LFU Cache](https://leetcode.com/problems/lfu-cache/) |
|
|
|
|
|
|
|
[✔️](java%2F0460-lfu-cache.java)
|
[✔️](javascript%2F0460-lfu-cache.js)
|
[✔️](kotlin%2F0460-lfu-cache.kt)
|
|
|
|
|
|
-[0138 - Copy List With Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/) |
|
[✔️](c%2F0138-copy-list-with-random-pointer.c)
|
[✔️](cpp%2F0138-copy-list-with-random-pointer.cpp)
|
[✔️](csharp%2F0138-copy-list-with-random-pointer.cs)
|
|
[✔️](go%2F0138-copy-list-with-random-pointer.go)
|
|
[✔️](java%2F0138-copy-list-with-random-pointer.java)
|
[✔️](javascript%2F0138-copy-list-with-random-pointer.js)
|
[✔️](kotlin%2F0138-copy-list-with-random-pointer.kt)
|
[✔️](python%2F0138-copy-list-with-random-pointer.py)
|
[✔️](ruby%2F0138-copy-list-with-random-pointer.rb)
|
|
|
[✔️](swift%2F0138-copy-list-with-random-pointer.swift)
|
[✔️](typescript%2F0138-copy-list-with-random-pointer.ts)
-[0707 - Design Linked List](https://leetcode.com/problems/design-linked-list/) |
|
[✔️](c%2F0707-design-linked-list.c)
|
|
|
|
[✔️](go%2F0707-design-linked-list.go)
|
|
[✔️](java%2F0707-design-linked-list.java)
|
[✔️](javascript%2F0707-design-linked-list.js)
|
[✔️](kotlin%2F0707-design-linked-list.kt)
|
[✔️](python%2F0707-design-linked-list.py)
|
|
|
|
[✔️](swift%2F0707-design-linked-list.swift)
|
-[1472 - Design Browser History](https://leetcode.com/problems/design-browser-history/) |
|
|
|
|
|
[✔️](go%2F1472-design-browser-history.go)
|
|
[✔️](java%2F1472-design-browser-history.java)
|
[✔️](javascript%2F1472-design-browser-history.js)
|
[✔️](kotlin%2F1472-design-browser-history.kt)
|
[✔️](python%2F1472-design-browser-history.py)
|
|
[✔️](rust%2F1472-design-browser-history.rs)
|
|
[✔️](swift%2F1472-design-browser-history.swift)
|
[✔️](typescript%2F1472-design-browser-history.ts)
-[0002 - Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) |
|
[✔️](c%2F0002-add-two-numbers.c)
|
[✔️](cpp%2F0002-add-two-numbers.cpp)
|
[✔️](csharp%2F0002-add-two-numbers.cs)
|
[✔️](dart%2F0002-add-two-numbers.dart)
|
[✔️](go%2F0002-add-two-numbers.go)
|
|
[✔️](java%2F0002-add-two-numbers.java)
|
[✔️](javascript%2F0002-add-two-numbers.js)
|
[✔️](kotlin%2F0002-add-two-numbers.kt)
|
[✔️](python%2F0002-add-two-numbers.py)
|
[✔️](ruby%2F0002-add-two-numbers.rb)
|
[✔️](rust%2F0002-add-two-numbers.rs)
|
[✔️](scala%2F0002-add-two-numbers.scala)
|
[✔️](swift%2F0002-add-two-numbers.swift)
|
[✔️](typescript%2F0002-add-two-numbers.ts)
-[0141 - Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/) |
|
[✔️](c%2F0141-linked-list-cycle.c)
|
[✔️](cpp%2F0141-linked-list-cycle.cpp)
|
[✔️](csharp%2F0141-linked-list-cycle.cs)
|
|
[✔️](go%2F0141-linked-list-cycle.go)
|
|
[✔️](java%2F0141-linked-list-cycle.java)
|
[✔️](javascript%2F0141-linked-list-cycle.js)
|
[✔️](kotlin%2F0141-linked-list-cycle.kt)
|
[✔️](python%2F0141-linked-list-cycle.py)
|
[✔️](ruby%2F0141-linked-list-cycle.rb)
|
|
[✔️](scala%2F0141-linked-list-cycle.scala)
|
[✔️](swift%2F0141-linked-list-cycle.swift)
|
[✔️](typescript%2F0141-linked-list-cycle.ts)
-[0287 - Find The Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/) |
|
[✔️](c%2F0287-find-the-duplicate-number.c)
|
[✔️](cpp%2F0287-find-the-duplicate-number.cpp)
|
[✔️](csharp%2F0287-find-the-duplicate-number.cs)
|
|
[✔️](go%2F0287-find-the-duplicate-number.go)
|
|
[✔️](java%2F0287-find-the-duplicate-number.java)
|
[✔️](javascript%2F0287-find-the-duplicate-number.js)
|
[✔️](kotlin%2F0287-find-the-duplicate-number.kt)
|
[✔️](python%2F0287-find-the-duplicate-number.py)
|
[✔️](ruby%2F0287-find-the-duplicate-number.rb)
|
[✔️](rust%2F0287-find-the-duplicate-number.rs)
|
|
[✔️](swift%2F0287-find-the-duplicate-number.swift)
|
[✔️](typescript%2F0287-find-the-duplicate-number.ts)
-[0024 - Swap Nodes In Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/) |
|
[✔️](c%2F0024-swap-nodes-in-pairs.c)
|
[✔️](cpp%2F0024-swap-nodes-in-pairs.cpp)
|
|
|
[✔️](go%2F0024-swap-nodes-in-pairs.go)
|
|
[✔️](java%2F0024-swap-nodes-in-pairs.java)
|
|
[✔️](kotlin%2F0024-swap-nodes-in-pairs.kt)
|
[✔️](python%2F0024-swap-nodes-in-pairs.py)
|
|
|
|
|
-[0148 - Sort List](https://leetcode.com/problems/sort-list/) |
|
[✔️](c%2F0148-sort-list.c)
|
[✔️](cpp%2F0148-sort-list.cpp)
|
[✔️](csharp%2F0148-sort-list.cs)
|
|
|
|
[✔️](java%2F0148-sort-list.java)
|
|
[✔️](kotlin%2F0148-sort-list.kt)
|
[✔️](python%2F0148-sort-list.py)
|
|
|
|
|
-[0086 - Partition List](https://leetcode.com/problems/partition-list/) |
|
|
|
|
|
|
|
[✔️](java%2F0086-partition-list.java)
|
|
[✔️](kotlin%2F0086-partition-list.kt)
|
[✔️](python%2F0086-partition-list.py)
|
|
|
|
|
-[0061 - Rotate List](https://leetcode.com/problems/rotate-list/) |
|
|
[✔️](cpp%2F0061-rotate-list.cpp)
|
|
|
|
|
[✔️](java%2F0061-rotate-list.java)
|
|
[✔️](kotlin%2F0061-rotate-list.kt)
|
[✔️](python%2F0061-rotate-list.py)
|
|
|
|
|
-[0092 - Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/) |
|
|
[✔️](cpp%2F0092-reverse-linked-list-ii.cpp)
|
|
|
|
|
[✔️](java%2F0092-reverse-linked-list-ii.java)
|
[✔️](javascript%2F0092-reverse-linked-list-ii.js)
|
[✔️](kotlin%2F0092-reverse-linked-list-ii.kt)
|
[✔️](python%2F0092-reverse-linked-list-ii.py)
|
|
|
|
|
-[0622 - Design Circular Queue](https://leetcode.com/problems/design-circular-queue/) |
|
|
|
|
|
[✔️](go%2F0622-design-circular-queue.go)
|
|
[✔️](java%2F0622-design-circular-queue.java)
|
|
[✔️](kotlin%2F0622-design-circular-queue.kt)
|
[✔️](python%2F0622-design-circular-queue.py)
|
|
|
|
|
-[0147 - Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/) |
|
|
[✔️](cpp%2F0147-insertion-sort-list.cpp)
|
|
|
[✔️](go%2F0147-insertion-sort-list.go)
|
|
[✔️](java%2F0147-insertion-sort-list.java)
|
|
[✔️](kotlin%2F0147-insertion-sort-list.kt)
|
[✔️](python%2F0147-insertion-sort-list.py)
|
|
|
|
|
-[0725 - Split Linked List in Parts](https://leetcode.com/problems/split-linked-list-in-parts/) |
|
|
|
|
|
|
|
[✔️](java%2F0725-split-linked-list-in-parts.java)
|
|
[✔️](kotlin%2F0725-split-linked-list-in-parts.kt)
|
|
|
|
|
|
-[0146 - LRU Cache](https://leetcode.com/problems/lru-cache/) |
|
[✔️](c%2F0146-lru-cache.c)
|
[✔️](cpp%2F0146-lru-cache.cpp)
|
[✔️](csharp%2F0146-lru-cache.cs)
|
|
[✔️](go%2F0146-lru-cache.go)
|
|
[✔️](java%2F0146-lru-cache.java)
|
[✔️](javascript%2F0146-lru-cache.js)
|
[✔️](kotlin%2F0146-lru-cache.kt)
|
[✔️](python%2F0146-lru-cache.py)
|
[✔️](ruby%2F0146-lru-cache.rb)
|
|
|
[✔️](swift%2F0146-lru-cache.swift)
|
[✔️](typescript%2F0146-lru-cache.ts)
-[0023 - Merge K Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) |
|
[✔️](c%2F0023-merge-k-sorted-lists.c)
|
[✔️](cpp%2F0023-merge-k-sorted-lists.cpp)
|
[✔️](csharp%2F0023-merge-k-sorted-lists.cs)
|
|
[✔️](go%2F0023-merge-k-sorted-lists.go)
|
|
[✔️](java%2F0023-merge-k-sorted-lists.java)
|
[✔️](javascript%2F0023-merge-k-sorted-lists.js)
|
[✔️](kotlin%2F0023-merge-k-sorted-lists.kt)
|
[✔️](python%2F0023-merge-k-sorted-lists.py)
|
|
[✔️](rust%2F0023-merge-k-sorted-lists.rs)
|
|
[✔️](swift%2F0023-merge-k-sorted-lists.swift)
|
[✔️](typescript%2F0023-merge-k-sorted-lists.ts)
-[0025 - Reverse Nodes In K Group](https://leetcode.com/problems/reverse-nodes-in-k-group/) |
|
[✔️](c%2F0025-reverse-nodes-in-k-group.c)
|
[✔️](cpp%2F0025-reverse-nodes-in-k-group.cpp)
|
[✔️](csharp%2F0025-reverse-nodes-in-k-group.cs)
|
|
[✔️](go%2F0025-reverse-nodes-in-k-group.go)
|
|
[✔️](java%2F0025-reverse-nodes-in-k-group.java)
|
[✔️](javascript%2F0025-reverse-nodes-in-k-group.js)
|
[✔️](kotlin%2F0025-reverse-nodes-in-k-group.kt)
|
[✔️](python%2F0025-reverse-nodes-in-k-group.py)
|
|
[✔️](rust%2F0025-reverse-nodes-in-k-group.rs)
|
|
[✔️](swift%2F0025-reverse-nodes-in-k-group.swift)
|
[✔️](typescript%2F0025-reverse-nodes-in-k-group.ts)
+| Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS | +| ------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ---------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | --------------------------------------- | ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | +| [0206 - Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) |
|
[✔️](c%2F0206-reverse-linked-list.c)
|
[✔️](cpp%2F0206-reverse-linked-list.cpp)
|
[✔️](csharp%2F0206-reverse-linked-list.cs)
|
[✔️](dart%2F0206-reverse-linked-list.dart)
|
[✔️](go%2F0206-reverse-linked-list.go)
|
|
[✔️](java%2F0206-reverse-linked-list.java)
|
[✔️](javascript%2F0206-reverse-linked-list.js)
|
[✔️](kotlin%2F0206-reverse-linked-list.kt)
|
[✔️](python%2F0206-reverse-linked-list.py)
|
[✔️](ruby%2F0206-reverse-linked-list.rb)
|
[✔️](rust%2F0206-reverse-linked-list.rs)
|
[✔️](scala%2F0206-reverse-linked-list.scala)
|
[✔️](swift%2F0206-reverse-linked-list.swift)
|
[✔️](typescript%2F0206-reverse-linked-list.ts)
| +| [0021 - Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/) |
|
[✔️](c%2F0021-merge-two-sorted-lists.c)
|
[✔️](cpp%2F0021-merge-two-sorted-lists.cpp)
|
[✔️](csharp%2F0021-merge-two-sorted-lists.cs)
|
[✔️](dart%2F0021-merge-two-sorted-lists.dart)
|
[✔️](go%2F0021-merge-two-sorted-lists.go)
|
|
[✔️](java%2F0021-merge-two-sorted-lists.java)
|
[✔️](javascript%2F0021-merge-two-sorted-lists.js)
|
[✔️](kotlin%2F0021-merge-two-sorted-lists.kt)
|
[✔️](python%2F0021-merge-two-sorted-lists.py)
|
[✔️](ruby%2F0021-merge-two-sorted-lists.rb)
|
[✔️](rust%2F0021-merge-two-sorted-lists.rs)
|
[✔️](scala%2F0021-merge-two-sorted-lists.scala)
|
[✔️](swift%2F0021-merge-two-sorted-lists.swift)
|
[✔️](typescript%2F0021-merge-two-sorted-lists.ts)
| +| [0234 - Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/) |
|
[✔️](c%2F0234-palindrome-linked-list.c)
|
[✔️](cpp%2F0234-palindrome-linked-list.cpp)
|
|
|
[✔️](go%2F0234-palindrome-linked-list.go)
|
|
[✔️](java%2F0234-palindrome-linked-list.java)
|
[✔️](javascript%2F0234-palindrome-linked-list.js)
|
[✔️](kotlin%2F0234-palindrome-linked-list.kt)
|
[✔️](python%2F0234-palindrome-linked-list.py)
|
|
|
|
|
| +| [0203 - Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/) |
|
|
[✔️](cpp%2F0203-remove-linked-list-elements.cpp)
|
[✔️](csharp%2F0203-remove-linked-list-elements.cs)
|
|
[✔️](go%2F0203-remove-linked-list-elements.go)
|
|
[✔️](java%2F0203-remove-linked-list-elements.java)
|
[✔️](javascript%2F0203-remove-linked-list-elements.js)
|
[✔️](kotlin%2F0203-remove-linked-list-elements.kt)
|
[✔️](python%2F0203-remove-linked-list-elements.py)
|
|
|
|
|
[✔️](typescript%2F0203-remove-linked-list-elements.ts)
| +| [0083 - Remove Duplicates From Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/) |
|
[✔️](c%2F0083-remove-duplicates-from-sorted-list.c)
|
[✔️](cpp%2F0083-remove-duplicates-from-sorted-list.cpp)
|
|
|
[✔️](go%2F0083-remove-duplicates-from-sorted-list.go)
|
|
[✔️](java%2F0083-remove-duplicates-from-sorted-list.java)
|
[✔️](javascript%2F0083-remove-duplicates-from-sorted-list.js)
|
[✔️](kotlin%2F0083-remove-duplicates-from-sorted-list.kt)
|
[✔️](python%2F0083-remove-duplicates-from-sorted-list.py)
|
|
|
|
[✔️](swift%2F0083-remove-duplicates-from-sorted-list.swift)
|
| +| [0876 - Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/) |
|
[✔️](c%2F0876-middle-of-the-linked-list.c)
|
[✔️](cpp%2F0876-middle-of-the-linked-list.cpp)
|
[✔️](csharp%2F0876-middle-of-the-linked-list.cs)
|
|
[✔️](go%2F0876-middle-of-the-linked-list.go)
|
|
[✔️](java%2F0876-middle-of-the-linked-list.java)
|
[✔️](javascript%2F0876-middle-of-the-linked-list.js)
|
[✔️](kotlin%2F0876-middle-of-the-linked-list.kt)
|
[✔️](python%2F0876-middle-of-the-linked-list.py)
|
|
[✔️](rust%2F0876-middle-of-the-linked-list.rs)
|
|
[✔️](swift%2F0876-middle-of-the-linked-list.swift)
|
[✔️](typescript%2F0876-middle-of-the-linked-list.ts)
| +| [0160 - Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/) |
|
[✔️](c%2F0160-intersection-of-two-linked-lists.c)
|
[✔️](cpp%2F0160-intersection-of-two-linked-lists.cpp)
|
|
|
[✔️](go%2F0160-intersection-of-two-linked-lists.go)
|
|
[✔️](java%2F0160-intersection-of-two-linked-lists.java)
|
[✔️](javascript%2F0160-intersection-of-two-linked-lists.js)
|
[✔️](kotlin%2F0160-intersection-of-two-linked-lists.kt)
|
[✔️](python%2F0160-intersection-of-two-linked-lists.py)
|
|
|
|
|
| +| [0143 - Reorder List](https://leetcode.com/problems/reorder-list/) |
|
[✔️](c%2F0143-reorder-list.c)
|
[✔️](cpp%2F0143-reorder-list.cpp)
|
[✔️](csharp%2F0143-reorder-list.cs)
|
|
[✔️](go%2F0143-reorder-list.go)
|
|
[✔️](java%2F0143-reorder-list.java)
|
[✔️](javascript%2F0143-reorder-list.js)
|
[✔️](kotlin%2F0143-reorder-list.kt)
|
[✔️](python%2F0143-reorder-list.py)
|
|
[✔️](rust%2F0143-reorder-list.rs)
|
|
[✔️](swift%2F0143-reorder-list.swift)
|
[✔️](typescript%2F0143-reorder-list.ts)
| +| [2130 - Maximum Twin Sum Of A Linked List](https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/) |
|
|
[✔️](cpp%2F2130-maximum-twin-sum-of-a-linked-list.cpp)
|
|
|
[✔️](go%2F2130-maximum-twin-sum-of-a-linked-list.go)
|
|
[✔️](java%2F2130-maximum-twin-sum-of-a-linked-list.java)
|
[✔️](javascript%2F2130-maximum-twin-sum-of-a-linked-list.js)
|
[✔️](kotlin%2F2130-maximum-twin-sum-of-a-linked-list.kt)
|
[✔️](python%2F2130-maximum-twin-sum-of-a-linked-list.py)
|
|
|
|
[✔️](swift%2F2130-maximum-twin-sum-of-a-linked-list.swift)
|
| +| [0019 - Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/) |
|
[✔️](c%2F0019-remove-nth-node-from-end-of-list.c)
|
[✔️](cpp%2F0019-remove-nth-node-from-end-of-list.cpp)
|
[✔️](csharp%2F0019-remove-nth-node-from-end-of-list.cs)
|
|
[✔️](go%2F0019-remove-nth-node-from-end-of-list.go)
|
|
[✔️](java%2F0019-remove-nth-node-from-end-of-list.java)
|
[✔️](javascript%2F0019-remove-nth-node-from-end-of-list.js)
|
[✔️](kotlin%2F0019-remove-nth-node-from-end-of-list.kt)
|
[✔️](python%2F0019-remove-nth-node-from-end-of-list.py)
|
|
[✔️](rust%2F0019-remove-nth-node-from-end-of-list.rs)
|
|
[✔️](swift%2F0019-remove-nth-node-from-end-of-list.swift)
|
[✔️](typescript%2F0019-remove-nth-node-from-end-of-list.ts)
| +| [1721 - Swapping Nodes in a Linked List](https://leetcode.com/problems/swapping-nodes-in-a-linked-list/) |
|
|
[✔️](cpp%2F1721-swapping-nodes-in-a-linked-list.cpp)
|
|
|
[✔️](go%2F1721-swapping-nodes-in-a-linked-list.go)
|
|
[✔️](java%2F1721-swapping-nodes-in-a-linked-list.java)
|
|
[✔️](kotlin%2F1721-swapping-nodes-in-a-linked-list.kt)
|
[✔️](python%2F1721-swapping-nodes-in-a-linked-list.py)
|
|
|
|
|
| +| [0460 - LFU Cache](https://leetcode.com/problems/lfu-cache/) |
|
|
|
|
|
|
|
[✔️](java%2F0460-lfu-cache.java)
|
[✔️](javascript%2F0460-lfu-cache.js)
|
[✔️](kotlin%2F0460-lfu-cache.kt)
|
|
|
|
|
|
| +| [0138 - Copy List With Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/) |
|
[✔️](c%2F0138-copy-list-with-random-pointer.c)
|
[✔️](cpp%2F0138-copy-list-with-random-pointer.cpp)
|
[✔️](csharp%2F0138-copy-list-with-random-pointer.cs)
|
|
[✔️](go%2F0138-copy-list-with-random-pointer.go)
|
|
[✔️](java%2F0138-copy-list-with-random-pointer.java)
|
[✔️](javascript%2F0138-copy-list-with-random-pointer.js)
|
[✔️](kotlin%2F0138-copy-list-with-random-pointer.kt)
|
[✔️](python%2F0138-copy-list-with-random-pointer.py)
|
[✔️](ruby%2F0138-copy-list-with-random-pointer.rb)
|
|
|
[✔️](swift%2F0138-copy-list-with-random-pointer.swift)
|
[✔️](typescript%2F0138-copy-list-with-random-pointer.ts)
| +| [0707 - Design Linked List](https://leetcode.com/problems/design-linked-list/) |
|
[✔️](c%2F0707-design-linked-list.c)
|
|
|
|
[✔️](go%2F0707-design-linked-list.go)
|
|
[✔️](java%2F0707-design-linked-list.java)
|
[✔️](javascript%2F0707-design-linked-list.js)
|
[✔️](kotlin%2F0707-design-linked-list.kt)
|
[✔️](python%2F0707-design-linked-list.py)
|
|
|
|
[✔️](swift%2F0707-design-linked-list.swift)
|
| +| [1472 - Design Browser History](https://leetcode.com/problems/design-browser-history/) |
|
|
|
|
|
[✔️](go%2F1472-design-browser-history.go)
|
|
[✔️](java%2F1472-design-browser-history.java)
|
[✔️](javascript%2F1472-design-browser-history.js)
|
[✔️](kotlin%2F1472-design-browser-history.kt)
|
[✔️](python%2F1472-design-browser-history.py)
|
|
[✔️](rust%2F1472-design-browser-history.rs)
|
|
[✔️](swift%2F1472-design-browser-history.swift)
|
[✔️](typescript%2F1472-design-browser-history.ts)
| +| [0002 - Add Two Numbers](https://leetcode.com/problems/add-two-numbers/) |
|
[✔️](c%2F0002-add-two-numbers.c)
|
[✔️](cpp%2F0002-add-two-numbers.cpp)
|
[✔️](csharp%2F0002-add-two-numbers.cs)
|
[✔️](dart%2F0002-add-two-numbers.dart)
|
[✔️](go%2F0002-add-two-numbers.go)
|
|
[✔️](java%2F0002-add-two-numbers.java)
|
[✔️](javascript%2F0002-add-two-numbers.js)
|
[✔️](kotlin%2F0002-add-two-numbers.kt)
|
[✔️](python%2F0002-add-two-numbers.py)
|
[✔️](ruby%2F0002-add-two-numbers.rb)
|
[✔️](rust%2F0002-add-two-numbers.rs)
|
[✔️](scala%2F0002-add-two-numbers.scala)
|
[✔️](swift%2F0002-add-two-numbers.swift)
|
[✔️](typescript%2F0002-add-two-numbers.ts)
| +| [0141 - Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/) |
|
[✔️](c%2F0141-linked-list-cycle.c)
|
[✔️](cpp%2F0141-linked-list-cycle.cpp)
|
[✔️](csharp%2F0141-linked-list-cycle.cs)
|
|
[✔️](go%2F0141-linked-list-cycle.go)
|
|
[✔️](java%2F0141-linked-list-cycle.java)
|
[✔️](javascript%2F0141-linked-list-cycle.js)
|
[✔️](kotlin%2F0141-linked-list-cycle.kt)
|
[✔️](python%2F0141-linked-list-cycle.py)
|
[✔️](ruby%2F0141-linked-list-cycle.rb)
|
|
[✔️](scala%2F0141-linked-list-cycle.scala)
|
[✔️](swift%2F0141-linked-list-cycle.swift)
|
[✔️](typescript%2F0141-linked-list-cycle.ts)
| +| [0287 - Find The Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/) |
|
[✔️](c%2F0287-find-the-duplicate-number.c)
|
[✔️](cpp%2F0287-find-the-duplicate-number.cpp)
|
[✔️](csharp%2F0287-find-the-duplicate-number.cs)
|
|
[✔️](go%2F0287-find-the-duplicate-number.go)
|
|
[✔️](java%2F0287-find-the-duplicate-number.java)
|
[✔️](javascript%2F0287-find-the-duplicate-number.js)
|
[✔️](kotlin%2F0287-find-the-duplicate-number.kt)
|
[✔️](python%2F0287-find-the-duplicate-number.py)
|
[✔️](ruby%2F0287-find-the-duplicate-number.rb)
|
[✔️](rust%2F0287-find-the-duplicate-number.rs)
|
|
[✔️](swift%2F0287-find-the-duplicate-number.swift)
|
[✔️](typescript%2F0287-find-the-duplicate-number.ts)
| +| [0024 - Swap Nodes In Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/) |
|
[✔️](c%2F0024-swap-nodes-in-pairs.c)
|
[✔️](cpp%2F0024-swap-nodes-in-pairs.cpp)
|
|
|
[✔️](go%2F0024-swap-nodes-in-pairs.go)
|
|
[✔️](java%2F0024-swap-nodes-in-pairs.java)
|
|
[✔️](kotlin%2F0024-swap-nodes-in-pairs.kt)
|
[✔️](python%2F0024-swap-nodes-in-pairs.py)
|
|
|
|
|
| +| [0148 - Sort List](https://leetcode.com/problems/sort-list/) |
|
[✔️](c%2F0148-sort-list.c)
|
[✔️](cpp%2F0148-sort-list.cpp)
|
[✔️](csharp%2F0148-sort-list.cs)
|
|
|
|
[✔️](java%2F0148-sort-list.java)
|
|
[✔️](kotlin%2F0148-sort-list.kt)
|
[✔️](python%2F0148-sort-list.py)
|
|
|
|
|
| +| [0086 - Partition List](https://leetcode.com/problems/partition-list/) |
|
|
|
|
|
|
|
[✔️](java%2F0086-partition-list.java)
|
|
[✔️](kotlin%2F0086-partition-list.kt)
|
[✔️](python%2F0086-partition-list.py)
|
|
|
|
|
| +| [0061 - Rotate List](https://leetcode.com/problems/rotate-list/) |
|
|
[✔️](cpp%2F0061-rotate-list.cpp)
|
|
|
|
|
[✔️](java%2F0061-rotate-list.java)
|
|
[✔️](kotlin%2F0061-rotate-list.kt)
|
[✔️](python%2F0061-rotate-list.py)
|
|
|
|
|
| +| [0092 - Reverse Linked List II](https://leetcode.com/problems/reverse-linked-list-ii/) |
|
|
[✔️](cpp%2F0092-reverse-linked-list-ii.cpp)
|
|
|
|
|
[✔️](java%2F0092-reverse-linked-list-ii.java)
|
[✔️](javascript%2F0092-reverse-linked-list-ii.js)
|
[✔️](kotlin%2F0092-reverse-linked-list-ii.kt)
|
[✔️](python%2F0092-reverse-linked-list-ii.py)
|
|
|
|
|
| +| [0622 - Design Circular Queue](https://leetcode.com/problems/design-circular-queue/) |
|
|
|
|
|
[✔️](go%2F0622-design-circular-queue.go)
|
|
[✔️](java%2F0622-design-circular-queue.java)
|
|
[✔️](kotlin%2F0622-design-circular-queue.kt)
|
[✔️](python%2F0622-design-circular-queue.py)
|
|
|
|
|
| +| [0147 - Insertion Sort List](https://leetcode.com/problems/insertion-sort-list/) |
|
|
[✔️](cpp%2F0147-insertion-sort-list.cpp)
|
|
|
[✔️](go%2F0147-insertion-sort-list.go)
|
|
[✔️](java%2F0147-insertion-sort-list.java)
|
|
[✔️](kotlin%2F0147-insertion-sort-list.kt)
|
[✔️](python%2F0147-insertion-sort-list.py)
|
|
|
|
|
| +| [0725 - Split Linked List in Parts](https://leetcode.com/problems/split-linked-list-in-parts/) |
|
|
|
|
|
|
|
[✔️](java%2F0725-split-linked-list-in-parts.java)
|
|
[✔️](kotlin%2F0725-split-linked-list-in-parts.kt)
|
|
|
|
|
|
| +| [0146 - LRU Cache](https://leetcode.com/problems/lru-cache/) |
|
[✔️](c%2F0146-lru-cache.c)
|
[✔️](cpp%2F0146-lru-cache.cpp)
|
[✔️](csharp%2F0146-lru-cache.cs)
|
|
[✔️](go%2F0146-lru-cache.go)
|
|
[✔️](java%2F0146-lru-cache.java)
|
[✔️](javascript%2F0146-lru-cache.js)
|
[✔️](kotlin%2F0146-lru-cache.kt)
|
[✔️](python%2F0146-lru-cache.py)
|
[✔️](ruby%2F0146-lru-cache.rb)
|
|
|
[✔️](swift%2F0146-lru-cache.swift)
|
[✔️](typescript%2F0146-lru-cache.ts)
| +| [0023 - Merge K Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) |
|
[✔️](c%2F0023-merge-k-sorted-lists.c)
|
[✔️](cpp%2F0023-merge-k-sorted-lists.cpp)
|
[✔️](csharp%2F0023-merge-k-sorted-lists.cs)
|
|
[✔️](go%2F0023-merge-k-sorted-lists.go)
|
|
[✔️](java%2F0023-merge-k-sorted-lists.java)
|
[✔️](javascript%2F0023-merge-k-sorted-lists.js)
|
[✔️](kotlin%2F0023-merge-k-sorted-lists.kt)
|
[✔️](python%2F0023-merge-k-sorted-lists.py)
|
|
[✔️](rust%2F0023-merge-k-sorted-lists.rs)
|
|
[✔️](swift%2F0023-merge-k-sorted-lists.swift)
|
[✔️](typescript%2F0023-merge-k-sorted-lists.ts)
| +| [0025 - Reverse Nodes In K Group](https://leetcode.com/problems/reverse-nodes-in-k-group/) |
|
[✔️](c%2F0025-reverse-nodes-in-k-group.c)
|
[✔️](cpp%2F0025-reverse-nodes-in-k-group.cpp)
|
[✔️](csharp%2F0025-reverse-nodes-in-k-group.cs)
|
|
[✔️](go%2F0025-reverse-nodes-in-k-group.go)
|
|
[✔️](java%2F0025-reverse-nodes-in-k-group.java)
|
[✔️](javascript%2F0025-reverse-nodes-in-k-group.js)
|
[✔️](kotlin%2F0025-reverse-nodes-in-k-group.kt)
|
[✔️](python%2F0025-reverse-nodes-in-k-group.py)
|
|
[✔️](rust%2F0025-reverse-nodes-in-k-group.rs)
|
|
[✔️](swift%2F0025-reverse-nodes-in-k-group.swift)
|
[✔️](typescript%2F0025-reverse-nodes-in-k-group.ts)
| ### Trees -Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS ----- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- -[0094 - Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) |
|
[✔️](c%2F0094-binary-tree-inorder-traversal.c)
|
[✔️](cpp%2F0094-binary-tree-inorder-traversal.cpp)
|
[✔️](csharp%2F0094-binary-tree-inorder-traversal.cs)
|
|
[✔️](go%2F0094-binary-tree-inorder-traversal.go)
|
|
[✔️](java%2F0094-binary-tree-inorder-traversal.java)
|
[✔️](javascript%2F0094-binary-tree-inorder-traversal.js)
|
[✔️](kotlin%2F0094-binary-tree-inorder-traversal.kt)
|
[✔️](python%2F0094-binary-tree-inorder-traversal.py)
|
[✔️](ruby%2F0094-binary-tree-inorder-traversal.rb)
|
[✔️](rust%2F0094-binary-tree-inorder-traversal.rs)
|
|
[✔️](swift%2F0094-binary-tree-inorder-traversal.swift)
|
[✔️](typescript%2F0094-binary-tree-inorder-traversal.ts)
-[0144 - Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/) |
|
|
[✔️](cpp%2F0144-binary-tree-preorder-traversal.cpp)
|
[✔️](csharp%2F0144-binary-tree-preorder-traversal.cs)
|
|
|
|
[✔️](java%2F0144-binary-tree-preorder-traversal.java)
|
[✔️](javascript%2F0144-binary-tree-preorder-traversal.js)
|
[✔️](kotlin%2F0144-binary-tree-preorder-traversal.kt)
|
[✔️](python%2F0144-binary-tree-preorder-traversal.py)
|
|
|
|
[✔️](swift%2F0144-binary-tree-preorder-traversal.swift)
|
[✔️](typescript%2F0144-binary-tree-preorder-traversal.ts)
-[0145 - Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/) |
|
|
[✔️](cpp%2F0145-binary-tree-postorder-traversal.cpp)
|
[✔️](csharp%2F0145-binary-tree-postorder-traversal.cs)
|
|
|
|
[✔️](java%2F0145-binary-tree-postorder-traversal.java)
|
[✔️](javascript%2F0145-binary-tree-postorder-traversal.js)
|
[✔️](kotlin%2F0145-binary-tree-postorder-traversal.kt)
|
[✔️](python%2F0145-binary-tree-postorder-traversal.py)
|
|
|
|
[✔️](swift%2F0145-binary-tree-postorder-traversal.swift)
|
[✔️](typescript%2F0145-binary-tree-postorder-traversal.ts)
-[0226 - Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) |
|
[✔️](c%2F0226-invert-binary-tree.c)
|
[✔️](cpp%2F0226-invert-binary-tree.cpp)
|
[✔️](csharp%2F0226-invert-binary-tree.cs)
|
[✔️](dart%2F0226-invert-binary-tree.dart)
|
[✔️](go%2F0226-invert-binary-tree.go)
|
|
[✔️](java%2F0226-invert-binary-tree.java)
|
[✔️](javascript%2F0226-invert-binary-tree.js)
|
[✔️](kotlin%2F0226-invert-binary-tree.kt)
|
[✔️](python%2F0226-invert-binary-tree.py)
|
[✔️](ruby%2F0226-invert-binary-tree.rb)
|
[✔️](rust%2F0226-invert-binary-tree.rs)
|
|
[✔️](swift%2F0226-invert-binary-tree.swift)
|
[✔️](typescript%2F0226-invert-binary-tree.ts)
-[0104 - Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/) |
|
[✔️](c%2F0104-maximum-depth-of-binary-tree.c)
|
[✔️](cpp%2F0104-maximum-depth-of-binary-tree.cpp)
|
[✔️](csharp%2F0104-maximum-depth-of-binary-tree.cs)
|
|
[✔️](go%2F0104-maximum-depth-of-binary-tree.go)
|
|
[✔️](java%2F0104-maximum-depth-of-binary-tree.java)
|
[✔️](javascript%2F0104-maximum-depth-of-binary-tree.js)
|
[✔️](kotlin%2F0104-maximum-depth-of-binary-tree.kt)
|
[✔️](python%2F0104-maximum-depth-of-binary-tree.py)
|
[✔️](ruby%2F0104-maximum-depth-of-binary-tree.rb)
|
[✔️](rust%2F0104-maximum-depth-of-binary-tree.rs)
|
|
[✔️](swift%2F0104-maximum-depth-of-binary-tree.swift)
|
[✔️](typescript%2F0104-maximum-depth-of-binary-tree.ts)
-[0543 - Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/) |
|
[✔️](c%2F0543-diameter-of-binary-tree.c)
|
[✔️](cpp%2F0543-diameter-of-binary-tree.cpp)
|
[✔️](csharp%2F0543-diameter-of-binary-tree.cs)
|
|
[✔️](go%2F0543-diameter-of-binary-tree.go)
|
|
[✔️](java%2F0543-diameter-of-binary-tree.java)
|
[✔️](javascript%2F0543-diameter-of-binary-tree.js)
|
[✔️](kotlin%2F0543-diameter-of-binary-tree.kt)
|
[✔️](python%2F0543-diameter-of-binary-tree.py)
|
[✔️](ruby%2F0543-diameter-of-binary-tree.rb)
|
[✔️](rust%2F0543-diameter-of-binary-tree.rs)
|
|
[✔️](swift%2F0543-diameter-of-binary-tree.swift)
|
[✔️](typescript%2F0543-diameter-of-binary-tree.ts)
-[0110 - Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/) |
|
[✔️](c%2F0110-balanced-binary-tree.c)
|
[✔️](cpp%2F0110-balanced-binary-tree.cpp)
|
[✔️](csharp%2F0110-balanced-binary-tree.cs)
|
|
[✔️](go%2F0110-balanced-binary-tree.go)
|
|
[✔️](java%2F0110-balanced-binary-tree.java)
|
[✔️](javascript%2F0110-balanced-binary-tree.js)
|
[✔️](kotlin%2F0110-balanced-binary-tree.kt)
|
[✔️](python%2F0110-balanced-binary-tree.py)
|
[✔️](ruby%2F0110-balanced-binary-tree.rb)
|
[✔️](rust%2F0110-balanced-binary-tree.rs)
|
|
[✔️](swift%2F0110-balanced-binary-tree.swift)
|
[✔️](typescript%2F0110-balanced-binary-tree.ts)
-[0100 - Same Tree](https://leetcode.com/problems/same-tree/) |
|
[✔️](c%2F0100-same-tree.c)
|
[✔️](cpp%2F0100-same-tree.cpp)
|
[✔️](csharp%2F0100-same-tree.cs)
|
|
[✔️](go%2F0100-same-tree.go)
|
|
[✔️](java%2F0100-same-tree.java)
|
[✔️](javascript%2F0100-same-tree.js)
|
[✔️](kotlin%2F0100-same-tree.kt)
|
[✔️](python%2F0100-same-tree.py)
|
[✔️](ruby%2F0100-same-tree.rb)
|
[✔️](rust%2F0100-same-tree.rs)
|
|
[✔️](swift%2F0100-same-tree.swift)
|
[✔️](typescript%2F0100-same-tree.ts)
-[0572 - Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/) |
|
[✔️](c%2F0572-subtree-of-another-tree.c)
|
[✔️](cpp%2F0572-subtree-of-another-tree.cpp)
|
[✔️](csharp%2F0572-subtree-of-another-tree.cs)
|
|
[✔️](go%2F0572-subtree-of-another-tree.go)
|
|
[✔️](java%2F0572-subtree-of-another-tree.java)
|
[✔️](javascript%2F0572-subtree-of-another-tree.js)
|
[✔️](kotlin%2F0572-subtree-of-another-tree.kt)
|
[✔️](python%2F0572-subtree-of-another-tree.py)
|
[✔️](ruby%2F0572-subtree-of-another-tree.rb)
|
[✔️](rust%2F0572-subtree-of-another-tree.rs)
|
[✔️](scala%2F0572-subtree-of-another-tree.scala)
|
[✔️](swift%2F0572-subtree-of-another-tree.swift)
|
[✔️](typescript%2F0572-subtree-of-another-tree.ts)
-[0108 - Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) |
|
[✔️](c%2F0108-convert-sorted-array-to-binary-search-tree.c)
|
|
|
|
[✔️](go%2F0108-convert-sorted-array-to-binary-search-tree.go)
|
|
[✔️](java%2F0108-convert-sorted-array-to-binary-search-tree.java)
|
[✔️](javascript%2F0108-convert-sorted-array-to-binary-search-tree.js)
|
[✔️](kotlin%2F0108-convert-sorted-array-to-binary-search-tree.kt)
|
[✔️](python%2F0108-convert-sorted-array-to-binary-search-tree.py)
|
|
|
|
|
-[0617 - Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/) |
|
[✔️](c%2F0617-merge-two-binary-trees.c)
|
[✔️](cpp%2F0617-merge-two-binary-trees.cpp)
|
[✔️](csharp%2F0617-merge-two-binary-trees.cs)
|
[✔️](dart%2F0617-merge-two-binary-trees.dart)
|
[✔️](go%2F0617-merge-two-binary-trees.go)
|
|
[✔️](java%2F0617-merge-two-binary-trees.java)
|
[✔️](javascript%2F0617-merge-two-binary-trees.js)
|
[✔️](kotlin%2F0617-merge-two-binary-trees.kt)
|
[✔️](python%2F0617-merge-two-binary-trees.py)
|
|
|
|
|
-[0112 - Path Sum](https://leetcode.com/problems/path-sum/) |
|
[✔️](c%2F0112-path-sum.c)
|
[✔️](cpp%2F0112-path-sum.cpp)
|
[✔️](csharp%2F0112-path-sum.cs)
|
|
[✔️](go%2F0112-path-sum.go)
|
|
[✔️](java%2F0112-path-sum.java)
|
[✔️](javascript%2F0112-path-sum.js)
|
[✔️](kotlin%2F0112-path-sum.kt)
|
[✔️](python%2F0112-path-sum.py)
|
|
|
|
[✔️](swift%2F0112-path-sum.swift)
|
-[0606 - Construct String From Binary Tree](https://leetcode.com/problems/construct-string-from-binary-tree/) |
|
|
[✔️](cpp%2F0606-construct-string-from-binary-tree.cpp)
|
|
|
|
|
[✔️](java%2F0606-construct-string-from-binary-tree.java)
|
[✔️](javascript%2F0606-construct-string-from-binary-tree.js)
|
[✔️](kotlin%2F0606-construct-string-from-binary-tree.kt)
|
[✔️](python%2F0606-construct-string-from-binary-tree.py)
|
|
|
|
|
-[0235 - Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/) |
|
[✔️](c%2F0235-lowest-common-ancestor-of-a-binary-search-tree.c)
|
[✔️](cpp%2F0235-lowest-common-ancestor-of-a-binary-search-tree.cpp)
|
[✔️](csharp%2F0235-lowest-common-ancestor-of-a-binary-search-tree.cs)
|
|
[✔️](go%2F0235-lowest-common-ancestor-of-a-binary-search-tree.go)
|
|
[✔️](java%2F0235-lowest-common-ancestor-of-a-binary-search-tree.java)
|
[✔️](javascript%2F0235-lowest-common-ancestor-of-a-binary-search-tree.js)
|
[✔️](kotlin%2F0235-lowest-common-ancestor-of-a-binary-search-tree.kt)
|
[✔️](python%2F0235-lowest-common-ancestor-of-a-binary-search-tree.py)
|
[✔️](ruby%2F0235-lowest-common-ancestor-of-a-binary-search-tree.rb)
|
[✔️](rust%2F0235-lowest-common-ancestor-of-a-binary-search-tree.rs)
|
[✔️](scala%2F0235-lowest-common-ancestor-of-a-binary-search-tree.scala)
|
[✔️](swift%2F0235-lowest-common-ancestor-of-a-binary-search-tree.swift)
|
[✔️](typescript%2F0235-lowest-common-ancestor-of-a-binary-search-tree.ts)
-[0701 - Insert into a Binary Search Tree](https://leetcode.com/problems/insert-into-a-binary-search-tree/) |
|
|
[✔️](cpp%2F0701-insert-into-a-binary-search-tree.cpp)
|
[✔️](csharp%2F0701-insert-into-a-binary-search-tree.cs)
|
|
|
|
[✔️](java%2F0701-insert-into-a-binary-search-tree.java)
|
[✔️](javascript%2F0701-insert-into-a-binary-search-tree.js)
|
[✔️](kotlin%2F0701-insert-into-a-binary-search-tree.kt)
|
[✔️](python%2F0701-insert-into-a-binary-search-tree.py)
|
|
|
|
[✔️](swift%2F0701-insert-into-a-binary-search-tree.swift)
|
[✔️](typescript%2F0701-insert-into-a-binary-search-tree.ts)
-[0450 - Delete Node in a BST](https://leetcode.com/problems/delete-node-in-a-bst/) |
|
|
[✔️](cpp%2F0450-delete-node-in-a-bst.cpp)
|
|
|
|
|
[✔️](java%2F0450-delete-node-in-a-bst.java)
|
[✔️](javascript%2F0450-delete-node-in-a-bst.js)
|
[✔️](kotlin%2F0450-delete-node-in-a-bst.kt)
|
[✔️](python%2F0450-delete-node-in-a-bst.py)
|
|
[✔️](rust%2F0450-delete-node-in-a-bst.rs)
|
|
[✔️](swift%2F0450-delete-node-in-a-bst.swift)
|
[✔️](typescript%2F0450-delete-node-in-a-bst.ts)
-[0102 - Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/) |
|
[✔️](c%2F0102-binary-tree-level-order-traversal.c)
|
[✔️](cpp%2F0102-binary-tree-level-order-traversal.cpp)
|
[✔️](csharp%2F0102-binary-tree-level-order-traversal.cs)
|
|
[✔️](go%2F0102-binary-tree-level-order-traversal.go)
|
|
[✔️](java%2F0102-binary-tree-level-order-traversal.java)
|
[✔️](javascript%2F0102-binary-tree-level-order-traversal.js)
|
[✔️](kotlin%2F0102-binary-tree-level-order-traversal.kt)
|
[✔️](python%2F0102-binary-tree-level-order-traversal.py)
|
[✔️](ruby%2F0102-binary-tree-level-order-traversal.rb)
|
[✔️](rust%2F0102-binary-tree-level-order-traversal.rs)
|
|
[✔️](swift%2F0102-binary-tree-level-order-traversal.swift)
|
[✔️](typescript%2F0102-binary-tree-level-order-traversal.ts)
-[0199 - Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view/) |
|
[✔️](c%2F0199-binary-tree-right-side-view.c)
|
[✔️](cpp%2F0199-binary-tree-right-side-view.cpp)
|
[✔️](csharp%2F0199-binary-tree-right-side-view.cs)
|
|
[✔️](go%2F0199-binary-tree-right-side-view.go)
|
|
[✔️](java%2F0199-binary-tree-right-side-view.java)
|
[✔️](javascript%2F0199-binary-tree-right-side-view.js)
|
[✔️](kotlin%2F0199-binary-tree-right-side-view.kt)
|
[✔️](python%2F0199-binary-tree-right-side-view.py)
|
|
[✔️](rust%2F0199-binary-tree-right-side-view.rs)
|
|
[✔️](swift%2F0199-binary-tree-right-side-view.swift)
|
[✔️](typescript%2F0199-binary-tree-right-side-view.ts)
-[0783 - Minimum Distance between BST Nodes](https://leetcode.com/problems/minimum-distance-between-bst-nodes/) |
|
|
|
|
|
|
|
[✔️](java%2F0783-minimum-distance-between-bst-nodes.java)
|
[✔️](javascript%2F0783-minimum-distance-between-bst-nodes.js)
|
[✔️](kotlin%2F0783-minimum-distance-between-bst-nodes.kt)
|
[✔️](python%2F0783-minimum-distance-between-bst-nodes.py)
|
|
|
|
|
-[0101 - Symmetric Tree ](https://leetcode.com/problems/symmetric-tree/) |
|
|
[✔️](cpp%2F0101-symmetric-tree.cpp)
|
|
|
|
|
[✔️](java%2F0101-symmetric-tree.java)
|
[✔️](javascript%2F0101-symmetric-tree.js)
|
[✔️](kotlin%2F0101-symmetric-tree.kt)
|
[✔️](python%2F0101-symmetric-tree.py)
|
|
[✔️](rust%2F0101-symmetric-tree.rs)
|
|
|
-[1443 - Minimum Time to Collect All Apples in a Tree](https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F1443-minimum-time-to-collect-all-apples-in-a-tree.js)
|
[✔️](kotlin%2F1443-minimum-time-to-collect-all-apples-in-a-tree.kt)
|
|
|
[✔️](rust%2F1443-minimum-time-to-collect-all-apples-in-a-tree.rs)
|
|
|
-[0103 - Binary Tree Zigzag Level Order Traversal](https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/) |
|
|
[✔️](cpp%2F0103-binary-tree-zigzag-level-order-traversal.cpp)
|
|
|
|
|
[✔️](java%2F0103-binary-tree-zigzag-level-order-traversal.java)
|
[✔️](javascript%2F0103-binary-tree-zigzag-level-order-traversal.js)
|
[✔️](kotlin%2F0103-binary-tree-zigzag-level-order-traversal.kt)
|
[✔️](python%2F0103-binary-tree-zigzag-level-order-traversal.py)
|
|
|
|
|
-[0427 - Construct Quad Tree](https://leetcode.com/problems/construct-quad-tree/) |
|
|
|
|
|
|
|
[✔️](java%2F0427-construct-quad-tree.java)
|
|
[✔️](kotlin%2F0427-construct-quad-tree.kt)
|
|
|
|
|
|
-[0652 - Find Duplicate Subtrees](https://leetcode.com/problems/find-duplicate-subtrees/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F0652-find-duplicate-subtrees.js)
|
[✔️](kotlin%2F0652-find-duplicate-subtrees.kt)
|
|
|
|
|
|
-[0958 - Check Completeness of a Binary Tree](https://leetcode.com/problems/check-completeness-of-a-binary-tree/) |
|
|
[✔️](cpp%2F0958-check-completeness-of-a-binary-tree.cpp)
|
[✔️](csharp%2F0958-check-completeness-of-a-binary-tree.cs)
|
|
[✔️](go%2F0958-check-completeness-of-a-binary-tree.go)
|
|
|
[✔️](javascript%2F0958-check-completeness-of-a-binary-tree.js)
|
[✔️](kotlin%2F0958-check-completeness-of-a-binary-tree.kt)
|
|
|
|
|
|
-[0106 - Construct Binary Tree from Inorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/) |
|
|
|
|
|
|
|
[✔️](java%2F0106-construct-binary-tree-from-inorder-and-postorder-traversal.java)
|
[✔️](javascript%2F0106-construct-binary-tree-from-inorder-and-postorder-traversal.js)
|
[✔️](kotlin%2F0106-construct-binary-tree-from-inorder-and-postorder-traversal.kt)
|
[✔️](python%2F0106-construct-binary-tree-from-inorder-and-postorder-traversal.py)
|
|
|
|
|
-[0662 - Maximum Width of Binary Tree ](https://leetcode.com/problems/maximum-width-of-binary-tree/) |
|
|
|
|
|
|
|
[✔️](java%2F0662-maximum-width-of-binary-tree.java)
|
|
[✔️](kotlin%2F0662-maximum-width-of-binary-tree.kt)
|
[✔️](python%2F0662-maximum-width-of-binary-tree.py)
|
|
|
|
|
-[1376 - Time Needed to Inform All Employees ](https://leetcode.com/problems/time-needed-to-inform-all-employees/) |
|
|
|
|
|
|
|
[✔️](java%2F1376-time-needed-to-inform-all-employees.java)
|
[✔️](javascript%2F1376-time-needed-to-inform-all-employees.js)
|
[✔️](kotlin%2F1376-time-needed-to-inform-all-employees.kt)
|
|
|
|
|
|
-[1448 - Count Good Nodes In Binary Tree](https://leetcode.com/problems/count-good-nodes-in-binary-tree/) |
|
[✔️](c%2F1448-Count-Good-Nodes-in-Binary-Tree.c)
|
[✔️](cpp%2F1448-Count-Good-Nodes-In-Binary-Tree.cpp)
|
[✔️](csharp%2F1448-Count-Good-Nodes-in-Binary-Tree.cs)
|
|
[✔️](go%2F1448-count-good-nodes-in-binary-tree.go)
|
|
[✔️](java%2F1448-Count-Good-Nodes-in-Binary-Tree.java)
|
[✔️](javascript%2F1448-Count-Good-Nodes-in-Binary-Tree.js)
|
[✔️](kotlin%2F1448-Count-Good-Nodes-In-Binary-Tree.kt)
|
[✔️](python%2F1448-count-good-nodes-in-binary-tree.py)
|
|
[✔️](rust%2F1448-count-good-nodes-in-binary-tree.rs)
|
|
[✔️](swift%2F1448-count-good-nodes-in-binary-tree.swift)
|
[✔️](typescript%2F1448-Count-Good-Nodes-in-Binary-Tree.ts)
-[0098 - Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/) |
|
[✔️](c%2F0098-validate-binary-search-tree.c)
|
[✔️](cpp%2F0098-validate-binary-search-tree.cpp)
|
[✔️](csharp%2F0098-validate-binary-search-tree.cs)
|
|
[✔️](go%2F0098-validate-binary-search-tree.go)
|
|
[✔️](java%2F0098-validate-binary-search-tree.java)
|
[✔️](javascript%2F0098-validate-binary-search-tree.js)
|
[✔️](kotlin%2F0098-validate-binary-search-tree.kt)
|
[✔️](python%2F0098-validate-binary-search-tree.py)
|
|
[✔️](rust%2F0098-validate-binary-search-tree.rs)
|
|
[✔️](swift%2F0098-validate-binary-search-tree.swift)
|
[✔️](typescript%2F0098-validate-binary-search-tree.ts)
-[0230 - Kth Smallest Element In a Bst](https://leetcode.com/problems/kth-smallest-element-in-a-bst/) |
|
[✔️](c%2F0230-kth-smallest-element-in-a-bst.c)
|
[✔️](cpp%2F0230-kth-smallest-element-in-a-bst.cpp)
|
[✔️](csharp%2F0230-kth-smallest-element-in-a-bst.cs)
|
|
[✔️](go%2F0230-kth-smallest-element-in-a-bst.go)
|
|
[✔️](java%2F0230-kth-smallest-element-in-a-bst.java)
|
[✔️](javascript%2F0230-kth-smallest-element-in-a-bst.js)
|
[✔️](kotlin%2F0230-kth-smallest-element-in-a-bst.kt)
|
[✔️](python%2F0230-kth-smallest-element-in-a-bst.py)
|
|
[✔️](rust%2F0230-kth-smallest-element-in-a-bst.rs)
|
[✔️](scala%2F0230-kth-smallest-element-in-a-bst.scala)
|
[✔️](swift%2F0230-kth-smallest-element-in-a-bst.swift)
|
[✔️](typescript%2F0230-kth-smallest-element-in-a-bst.ts)
-[0105 - Construct Binary Tree From Preorder And Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/) |
|
[✔️](c%2F0105-construct-binary-tree-from-preorder-and-inorder-traversal.c)
|
[✔️](cpp%2F0105-construct-binary-tree-from-preorder-and-inorder-traversal.cpp)
|
[✔️](csharp%2F0105-construct-binary-tree-from-preorder-and-inorder-traversal.cs)
|
|
[✔️](go%2F0105-construct-binary-tree-from-preorder-and-inorder-traversal.go)
|
|
[✔️](java%2F0105-construct-binary-tree-from-preorder-and-inorder-traversal.java)
|
[✔️](javascript%2F0105-construct-binary-tree-from-preorder-and-inorder-traversal.js)
|
[✔️](kotlin%2F0105-construct-binary-tree-from-preorder-and-inorder-traversal.kt)
|
[✔️](python%2F0105-construct-binary-tree-from-preorder-and-inorder-traversal.py)
|
|
|
|
[✔️](swift%2F0105-construct-binary-tree-from-preorder-and-inorder-traversal.swift)
|
[✔️](typescript%2F0105-construct-binary-tree-from-preorder-and-inorder-traversal.ts)
-[0096 - Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/) |
|
[✔️](c%2F0096-unique-binary-search-trees.c)
|
|
|
|
|
|
[✔️](java%2F0096-unique-binary-search-trees.java)
|
[✔️](javascript%2F0096-unique-binary-search-trees.js)
|
[✔️](kotlin%2F0096-unique-binary-search-trees.kt)
|
|
|
|
|
|
-[0095 - Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/) |
|
|
|
|
|
|
|
[✔️](java%2F0095-unique-binary-search-trees-ii.java)
|
[✔️](javascript%2F0095-unique-binary-search-trees-ii.js)
|
[✔️](kotlin%2F0095-unique-binary-search-trees-ii.kt)
|
|
|
|
|
|
-[0129 - Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/) |
|
[✔️](c%2F0129-sum-root-to-leaf-numbers.c)
|
[✔️](cpp%2F0129-sum-root-to-leaf-numbers.cpp)
|
|
|
[✔️](go%2F0129-sum-root-to-leaf-numbers.go)
|
|
[✔️](java%2F0129-sum-root-to-leaf-numbers.java)
|
[✔️](javascript%2F0129-sum-root-to-leaf-numbers.js)
|
[✔️](kotlin%2F0129-sum-root-to-leaf-numbers.kt)
|
|
|
|
|
|
-[0337 - House Robber III](https://leetcode.com/problems/house-robber-iii/) |
|
|
|
|
|
|
|
[✔️](java%2F0337-house-robber-iii.java)
|
[✔️](javascript%2F0337-house-robber-iii.js)
|
[✔️](kotlin%2F0337-house-robber-iii.kt)
|
|
|
|
|
|
-[0951 - Flip Equivalent Binary Trees](https://leetcode.com/problems/flip-equivalent-binary-trees/) |
|
|
|
|
|
|
|
[✔️](java%2F0951-flip-equivalent-binary-trees.java)
|
[✔️](javascript%2F0951-flip-equivalent-binary-trees.js)
|
[✔️](kotlin%2F0951-flip-equivalent-binary-trees.kt)
|
|
|
|
|
|
-[1993 - Operations On Tree](https://leetcode.com/problems/operations-on-tree/) |
|
|
|
|
|
|
|
[✔️](java%2F1993-operations-on-tree.java)
|
[✔️](javascript%2F1993-operations-on-tree.js)
|
[✔️](kotlin%2F1993-operations-on-tree.kt)
|
|
|
|
|
|
-[0894 - All Possible Full Binary Trees](https://leetcode.com/problems/all-possible-full-binary-trees/) |
|
|
|
|
|
|
|
[✔️](java%2F0894-all-possible-full-binary-trees.java)
|
[✔️](javascript%2F0894-all-possible-full-binary-trees.js)
|
[✔️](kotlin%2F0894-all-possible-full-binary-trees.kt)
|
[✔️](python%2F0894-all-possible-full-binary-trees.py)
|
|
|
|
|
-[0513 - Find Bottom Left Tree Value](https://leetcode.com/problems/find-bottom-left-tree-value/) |
|
|
|
|
|
|
|
[✔️](java%2F0513-find-bottom-left-tree-value.java)
|
[✔️](javascript%2F0513-find-bottom-left-tree-value.js)
|
[✔️](kotlin%2F0513-find-bottom-left-tree-value.kt)
|
[✔️](python%2F0513-find-bottom-left-tree-value.py)
|
|
|
|
|
-[0669 - Trim a Binary Search Tree](https://leetcode.com/problems/trim-a-binary-search-tree/) |
|
|
|
|
|
[✔️](go%2F0669-trim-a-binary-search-tree.go)
|
|
[✔️](java%2F0669-trim-a-binary-search-tree.java)
|
[✔️](javascript%2F0669-trim-a-binary-search-tree.js)
|
[✔️](kotlin%2F0669-trim-a-binary-search-tree.kt)
|
[✔️](python%2F0669-trim-a-binary-search-tree.py)
|
|
|
|
|
[✔️](typescript%2F0669-trim-a-binary-search-tree.ts)
-[0173 - Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/) |
|
|
|
|
|
|
|
[✔️](java%2F0173-binary-search-tree-iterator.java)
|
[✔️](javascript%2F0173-binary-search-tree-iterator.js)
|
[✔️](kotlin%2F0173-binary-search-tree-iterator.kt)
|
|
|
|
|
[✔️](swift%2F0173-binary-search-tree-iterator.swift)
|
-[0538 - Convert Bst to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/) |
|
|
[✔️](cpp%2F0538-convert-bst-to-greater-tree.cpp)
|
|
|
|
|
[✔️](java%2F0538-convert-bst-to-greater-tree.java)
|
[✔️](javascript%2F0538-convert-bst-to-greater-tree.js)
|
[✔️](kotlin%2F0538-convert-bst-to-greater-tree.kt)
|
|
|
|
|
|
-[0124 - Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/) |
|
[✔️](c%2F0124-binary-tree-maximum-path-sum.c)
|
[✔️](cpp%2F0124-binary-tree-maximum-path-sum.cpp)
|
[✔️](csharp%2F0124-binary-tree-maximum-path-sum.cs)
|
|
[✔️](go%2F0124-binary-tree-maximum-path-sum.go)
|
|
[✔️](java%2F0124-binary-tree-maximum-path-sum.java)
|
[✔️](javascript%2F0124-binary-tree-maximum-path-sum.js)
|
[✔️](kotlin%2F0124-binary-tree-maximum-path-sum.kt)
|
[✔️](python%2F0124-binary-tree-maximum-path-sum.py)
|
|
[✔️](rust%2F0124-binary-tree-maximum-path-sum.rs)
|
|
[✔️](swift%2F0124-binary-tree-maximum-path-sum.swift)
|
[✔️](typescript%2F0124-binary-tree-maximum-path-sum.ts)
-[0297 - Serialize And Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) |
|
[✔️](c%2F0297-serialize-and-deserialize-binary-tree.c)
|
[✔️](cpp%2F0297-serialize-and-deserialize-binary-tree.cpp)
|
[✔️](csharp%2F0297-serialize-and-deserialize-binary-tree.cs)
|
|
[✔️](go%2F0297-serialize-and-deserialize-binary-tree.go)
|
|
[✔️](java%2F0297-serialize-and-deserialize-binary-tree.java)
|
[✔️](javascript%2F0297-serialize-and-deserialize-binary-tree.js)
|
[✔️](kotlin%2F0297-serialize-and-deserialize-binary-tree.kt)
|
[✔️](python%2F0297-serialize-and-deserialize-binary-tree.py)
|
|
|
|
[✔️](swift%2F0297-serialize-and-deserialize-binary-tree.swift)
|
[✔️](typescript%2F0297-serialize-and-deserialize-binary-tree.ts)
+| Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | +| [0094 - Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/) |
|
[✔️](c%2F0094-binary-tree-inorder-traversal.c)
|
[✔️](cpp%2F0094-binary-tree-inorder-traversal.cpp)
|
[✔️](csharp%2F0094-binary-tree-inorder-traversal.cs)
|
|
[✔️](go%2F0094-binary-tree-inorder-traversal.go)
|
|
[✔️](java%2F0094-binary-tree-inorder-traversal.java)
|
[✔️](javascript%2F0094-binary-tree-inorder-traversal.js)
|
[✔️](kotlin%2F0094-binary-tree-inorder-traversal.kt)
|
[✔️](python%2F0094-binary-tree-inorder-traversal.py)
|
[✔️](ruby%2F0094-binary-tree-inorder-traversal.rb)
|
[✔️](rust%2F0094-binary-tree-inorder-traversal.rs)
|
|
[✔️](swift%2F0094-binary-tree-inorder-traversal.swift)
|
[✔️](typescript%2F0094-binary-tree-inorder-traversal.ts)
| +| [0144 - Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/) |
|
|
[✔️](cpp%2F0144-binary-tree-preorder-traversal.cpp)
|
[✔️](csharp%2F0144-binary-tree-preorder-traversal.cs)
|
|
|
|
[✔️](java%2F0144-binary-tree-preorder-traversal.java)
|
[✔️](javascript%2F0144-binary-tree-preorder-traversal.js)
|
[✔️](kotlin%2F0144-binary-tree-preorder-traversal.kt)
|
[✔️](python%2F0144-binary-tree-preorder-traversal.py)
|
|
|
|
[✔️](swift%2F0144-binary-tree-preorder-traversal.swift)
|
[✔️](typescript%2F0144-binary-tree-preorder-traversal.ts)
| +| [0145 - Binary Tree Postorder Traversal](https://leetcode.com/problems/binary-tree-postorder-traversal/) |
|
|
[✔️](cpp%2F0145-binary-tree-postorder-traversal.cpp)
|
[✔️](csharp%2F0145-binary-tree-postorder-traversal.cs)
|
|
|
|
[✔️](java%2F0145-binary-tree-postorder-traversal.java)
|
[✔️](javascript%2F0145-binary-tree-postorder-traversal.js)
|
[✔️](kotlin%2F0145-binary-tree-postorder-traversal.kt)
|
[✔️](python%2F0145-binary-tree-postorder-traversal.py)
|
|
|
|
[✔️](swift%2F0145-binary-tree-postorder-traversal.swift)
|
[✔️](typescript%2F0145-binary-tree-postorder-traversal.ts)
| +| [0226 - Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) |
|
[✔️](c%2F0226-invert-binary-tree.c)
|
[✔️](cpp%2F0226-invert-binary-tree.cpp)
|
[✔️](csharp%2F0226-invert-binary-tree.cs)
|
[✔️](dart%2F0226-invert-binary-tree.dart)
|
[✔️](go%2F0226-invert-binary-tree.go)
|
|
[✔️](java%2F0226-invert-binary-tree.java)
|
[✔️](javascript%2F0226-invert-binary-tree.js)
|
[✔️](kotlin%2F0226-invert-binary-tree.kt)
|
[✔️](python%2F0226-invert-binary-tree.py)
|
[✔️](ruby%2F0226-invert-binary-tree.rb)
|
[✔️](rust%2F0226-invert-binary-tree.rs)
|
|
[✔️](swift%2F0226-invert-binary-tree.swift)
|
[✔️](typescript%2F0226-invert-binary-tree.ts)
| +| [0104 - Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/) |
|
[✔️](c%2F0104-maximum-depth-of-binary-tree.c)
|
[✔️](cpp%2F0104-maximum-depth-of-binary-tree.cpp)
|
[✔️](csharp%2F0104-maximum-depth-of-binary-tree.cs)
|
|
[✔️](go%2F0104-maximum-depth-of-binary-tree.go)
|
|
[✔️](java%2F0104-maximum-depth-of-binary-tree.java)
|
[✔️](javascript%2F0104-maximum-depth-of-binary-tree.js)
|
[✔️](kotlin%2F0104-maximum-depth-of-binary-tree.kt)
|
[✔️](python%2F0104-maximum-depth-of-binary-tree.py)
|
[✔️](ruby%2F0104-maximum-depth-of-binary-tree.rb)
|
[✔️](rust%2F0104-maximum-depth-of-binary-tree.rs)
|
|
[✔️](swift%2F0104-maximum-depth-of-binary-tree.swift)
|
[✔️](typescript%2F0104-maximum-depth-of-binary-tree.ts)
| +| [0543 - Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/) |
|
[✔️](c%2F0543-diameter-of-binary-tree.c)
|
[✔️](cpp%2F0543-diameter-of-binary-tree.cpp)
|
[✔️](csharp%2F0543-diameter-of-binary-tree.cs)
|
|
[✔️](go%2F0543-diameter-of-binary-tree.go)
|
|
[✔️](java%2F0543-diameter-of-binary-tree.java)
|
[✔️](javascript%2F0543-diameter-of-binary-tree.js)
|
[✔️](kotlin%2F0543-diameter-of-binary-tree.kt)
|
[✔️](python%2F0543-diameter-of-binary-tree.py)
|
[✔️](ruby%2F0543-diameter-of-binary-tree.rb)
|
[✔️](rust%2F0543-diameter-of-binary-tree.rs)
|
|
[✔️](swift%2F0543-diameter-of-binary-tree.swift)
|
[✔️](typescript%2F0543-diameter-of-binary-tree.ts)
| +| [0110 - Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/) |
|
[✔️](c%2F0110-balanced-binary-tree.c)
|
[✔️](cpp%2F0110-balanced-binary-tree.cpp)
|
[✔️](csharp%2F0110-balanced-binary-tree.cs)
|
|
[✔️](go%2F0110-balanced-binary-tree.go)
|
|
[✔️](java%2F0110-balanced-binary-tree.java)
|
[✔️](javascript%2F0110-balanced-binary-tree.js)
|
[✔️](kotlin%2F0110-balanced-binary-tree.kt)
|
[✔️](python%2F0110-balanced-binary-tree.py)
|
[✔️](ruby%2F0110-balanced-binary-tree.rb)
|
[✔️](rust%2F0110-balanced-binary-tree.rs)
|
|
[✔️](swift%2F0110-balanced-binary-tree.swift)
|
[✔️](typescript%2F0110-balanced-binary-tree.ts)
| +| [0100 - Same Tree](https://leetcode.com/problems/same-tree/) |
|
[✔️](c%2F0100-same-tree.c)
|
[✔️](cpp%2F0100-same-tree.cpp)
|
[✔️](csharp%2F0100-same-tree.cs)
|
|
[✔️](go%2F0100-same-tree.go)
|
|
[✔️](java%2F0100-same-tree.java)
|
[✔️](javascript%2F0100-same-tree.js)
|
[✔️](kotlin%2F0100-same-tree.kt)
|
[✔️](python%2F0100-same-tree.py)
|
[✔️](ruby%2F0100-same-tree.rb)
|
[✔️](rust%2F0100-same-tree.rs)
|
|
[✔️](swift%2F0100-same-tree.swift)
|
[✔️](typescript%2F0100-same-tree.ts)
| +| [0572 - Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/) |
|
[✔️](c%2F0572-subtree-of-another-tree.c)
|
[✔️](cpp%2F0572-subtree-of-another-tree.cpp)
|
[✔️](csharp%2F0572-subtree-of-another-tree.cs)
|
|
[✔️](go%2F0572-subtree-of-another-tree.go)
|
|
[✔️](java%2F0572-subtree-of-another-tree.java)
|
[✔️](javascript%2F0572-subtree-of-another-tree.js)
|
[✔️](kotlin%2F0572-subtree-of-another-tree.kt)
|
[✔️](python%2F0572-subtree-of-another-tree.py)
|
[✔️](ruby%2F0572-subtree-of-another-tree.rb)
|
[✔️](rust%2F0572-subtree-of-another-tree.rs)
|
[✔️](scala%2F0572-subtree-of-another-tree.scala)
|
[✔️](swift%2F0572-subtree-of-another-tree.swift)
|
[✔️](typescript%2F0572-subtree-of-another-tree.ts)
| +| [0108 - Convert Sorted Array to Binary Search Tree](https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/) |
|
[✔️](c%2F0108-convert-sorted-array-to-binary-search-tree.c)
|
|
|
|
[✔️](go%2F0108-convert-sorted-array-to-binary-search-tree.go)
|
|
[✔️](java%2F0108-convert-sorted-array-to-binary-search-tree.java)
|
[✔️](javascript%2F0108-convert-sorted-array-to-binary-search-tree.js)
|
[✔️](kotlin%2F0108-convert-sorted-array-to-binary-search-tree.kt)
|
[✔️](python%2F0108-convert-sorted-array-to-binary-search-tree.py)
|
|
|
|
|
| +| [0617 - Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/) |
|
[✔️](c%2F0617-merge-two-binary-trees.c)
|
[✔️](cpp%2F0617-merge-two-binary-trees.cpp)
|
[✔️](csharp%2F0617-merge-two-binary-trees.cs)
|
[✔️](dart%2F0617-merge-two-binary-trees.dart)
|
[✔️](go%2F0617-merge-two-binary-trees.go)
|
|
[✔️](java%2F0617-merge-two-binary-trees.java)
|
[✔️](javascript%2F0617-merge-two-binary-trees.js)
|
[✔️](kotlin%2F0617-merge-two-binary-trees.kt)
|
[✔️](python%2F0617-merge-two-binary-trees.py)
|
|
|
|
|
| +| [0112 - Path Sum](https://leetcode.com/problems/path-sum/) |
|
[✔️](c%2F0112-path-sum.c)
|
[✔️](cpp%2F0112-path-sum.cpp)
|
[✔️](csharp%2F0112-path-sum.cs)
|
|
[✔️](go%2F0112-path-sum.go)
|
|
[✔️](java%2F0112-path-sum.java)
|
[✔️](javascript%2F0112-path-sum.js)
|
[✔️](kotlin%2F0112-path-sum.kt)
|
[✔️](python%2F0112-path-sum.py)
|
|
|
|
[✔️](swift%2F0112-path-sum.swift)
|
| +| [0606 - Construct String From Binary Tree](https://leetcode.com/problems/construct-string-from-binary-tree/) |
|
|
[✔️](cpp%2F0606-construct-string-from-binary-tree.cpp)
|
|
|
|
|
[✔️](java%2F0606-construct-string-from-binary-tree.java)
|
[✔️](javascript%2F0606-construct-string-from-binary-tree.js)
|
[✔️](kotlin%2F0606-construct-string-from-binary-tree.kt)
|
[✔️](python%2F0606-construct-string-from-binary-tree.py)
|
|
|
|
|
| +| [0235 - Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/) |
|
[✔️](c%2F0235-lowest-common-ancestor-of-a-binary-search-tree.c)
|
[✔️](cpp%2F0235-lowest-common-ancestor-of-a-binary-search-tree.cpp)
|
[✔️](csharp%2F0235-lowest-common-ancestor-of-a-binary-search-tree.cs)
|
|
[✔️](go%2F0235-lowest-common-ancestor-of-a-binary-search-tree.go)
|
|
[✔️](java%2F0235-lowest-common-ancestor-of-a-binary-search-tree.java)
|
[✔️](javascript%2F0235-lowest-common-ancestor-of-a-binary-search-tree.js)
|
[✔️](kotlin%2F0235-lowest-common-ancestor-of-a-binary-search-tree.kt)
|
[✔️](python%2F0235-lowest-common-ancestor-of-a-binary-search-tree.py)
|
[✔️](ruby%2F0235-lowest-common-ancestor-of-a-binary-search-tree.rb)
|
[✔️](rust%2F0235-lowest-common-ancestor-of-a-binary-search-tree.rs)
|
[✔️](scala%2F0235-lowest-common-ancestor-of-a-binary-search-tree.scala)
|
[✔️](swift%2F0235-lowest-common-ancestor-of-a-binary-search-tree.swift)
|
[✔️](typescript%2F0235-lowest-common-ancestor-of-a-binary-search-tree.ts)
| +| [0701 - Insert into a Binary Search Tree](https://leetcode.com/problems/insert-into-a-binary-search-tree/) |
|
|
[✔️](cpp%2F0701-insert-into-a-binary-search-tree.cpp)
|
[✔️](csharp%2F0701-insert-into-a-binary-search-tree.cs)
|
|
|
|
[✔️](java%2F0701-insert-into-a-binary-search-tree.java)
|
[✔️](javascript%2F0701-insert-into-a-binary-search-tree.js)
|
[✔️](kotlin%2F0701-insert-into-a-binary-search-tree.kt)
|
[✔️](python%2F0701-insert-into-a-binary-search-tree.py)
|
|
|
|
[✔️](swift%2F0701-insert-into-a-binary-search-tree.swift)
|
[✔️](typescript%2F0701-insert-into-a-binary-search-tree.ts)
| +| [0450 - Delete Node in a BST](https://leetcode.com/problems/delete-node-in-a-bst/) |
|
|
[✔️](cpp%2F0450-delete-node-in-a-bst.cpp)
|
|
|
|
|
[✔️](java%2F0450-delete-node-in-a-bst.java)
|
[✔️](javascript%2F0450-delete-node-in-a-bst.js)
|
[✔️](kotlin%2F0450-delete-node-in-a-bst.kt)
|
[✔️](python%2F0450-delete-node-in-a-bst.py)
|
|
[✔️](rust%2F0450-delete-node-in-a-bst.rs)
|
|
[✔️](swift%2F0450-delete-node-in-a-bst.swift)
|
[✔️](typescript%2F0450-delete-node-in-a-bst.ts)
| +| [0102 - Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/) |
|
[✔️](c%2F0102-binary-tree-level-order-traversal.c)
|
[✔️](cpp%2F0102-binary-tree-level-order-traversal.cpp)
|
[✔️](csharp%2F0102-binary-tree-level-order-traversal.cs)
|
|
[✔️](go%2F0102-binary-tree-level-order-traversal.go)
|
|
[✔️](java%2F0102-binary-tree-level-order-traversal.java)
|
[✔️](javascript%2F0102-binary-tree-level-order-traversal.js)
|
[✔️](kotlin%2F0102-binary-tree-level-order-traversal.kt)
|
[✔️](python%2F0102-binary-tree-level-order-traversal.py)
|
[✔️](ruby%2F0102-binary-tree-level-order-traversal.rb)
|
[✔️](rust%2F0102-binary-tree-level-order-traversal.rs)
|
|
[✔️](swift%2F0102-binary-tree-level-order-traversal.swift)
|
[✔️](typescript%2F0102-binary-tree-level-order-traversal.ts)
| +| [0199 - Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view/) |
|
[✔️](c%2F0199-binary-tree-right-side-view.c)
|
[✔️](cpp%2F0199-binary-tree-right-side-view.cpp)
|
[✔️](csharp%2F0199-binary-tree-right-side-view.cs)
|
|
[✔️](go%2F0199-binary-tree-right-side-view.go)
|
|
[✔️](java%2F0199-binary-tree-right-side-view.java)
|
[✔️](javascript%2F0199-binary-tree-right-side-view.js)
|
[✔️](kotlin%2F0199-binary-tree-right-side-view.kt)
|
[✔️](python%2F0199-binary-tree-right-side-view.py)
|
|
[✔️](rust%2F0199-binary-tree-right-side-view.rs)
|
|
[✔️](swift%2F0199-binary-tree-right-side-view.swift)
|
[✔️](typescript%2F0199-binary-tree-right-side-view.ts)
| +| [0783 - Minimum Distance between BST Nodes](https://leetcode.com/problems/minimum-distance-between-bst-nodes/) |
|
|
|
|
|
|
|
[✔️](java%2F0783-minimum-distance-between-bst-nodes.java)
|
[✔️](javascript%2F0783-minimum-distance-between-bst-nodes.js)
|
[✔️](kotlin%2F0783-minimum-distance-between-bst-nodes.kt)
|
[✔️](python%2F0783-minimum-distance-between-bst-nodes.py)
|
|
|
|
|
| +| [0101 - Symmetric Tree ](https://leetcode.com/problems/symmetric-tree/) |
|
|
[✔️](cpp%2F0101-symmetric-tree.cpp)
|
|
|
|
|
[✔️](java%2F0101-symmetric-tree.java)
|
[✔️](javascript%2F0101-symmetric-tree.js)
|
[✔️](kotlin%2F0101-symmetric-tree.kt)
|
[✔️](python%2F0101-symmetric-tree.py)
|
|
[✔️](rust%2F0101-symmetric-tree.rs)
|
|
|
| +| [1443 - Minimum Time to Collect All Apples in a Tree](https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F1443-minimum-time-to-collect-all-apples-in-a-tree.js)
|
[✔️](kotlin%2F1443-minimum-time-to-collect-all-apples-in-a-tree.kt)
|
|
|
[✔️](rust%2F1443-minimum-time-to-collect-all-apples-in-a-tree.rs)
|
|
|
| +| [0103 - Binary Tree Zigzag Level Order Traversal](https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/) |
|
|
[✔️](cpp%2F0103-binary-tree-zigzag-level-order-traversal.cpp)
|
|
|
|
|
[✔️](java%2F0103-binary-tree-zigzag-level-order-traversal.java)
|
[✔️](javascript%2F0103-binary-tree-zigzag-level-order-traversal.js)
|
[✔️](kotlin%2F0103-binary-tree-zigzag-level-order-traversal.kt)
|
[✔️](python%2F0103-binary-tree-zigzag-level-order-traversal.py)
|
|
|
|
|
| +| [0427 - Construct Quad Tree](https://leetcode.com/problems/construct-quad-tree/) |
|
|
|
|
|
|
|
[✔️](java%2F0427-construct-quad-tree.java)
|
|
[✔️](kotlin%2F0427-construct-quad-tree.kt)
|
|
|
|
|
|
| +| [0652 - Find Duplicate Subtrees](https://leetcode.com/problems/find-duplicate-subtrees/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F0652-find-duplicate-subtrees.js)
|
[✔️](kotlin%2F0652-find-duplicate-subtrees.kt)
|
|
|
|
|
|
| +| [0958 - Check Completeness of a Binary Tree](https://leetcode.com/problems/check-completeness-of-a-binary-tree/) |
|
|
[✔️](cpp%2F0958-check-completeness-of-a-binary-tree.cpp)
|
[✔️](csharp%2F0958-check-completeness-of-a-binary-tree.cs)
|
|
[✔️](go%2F0958-check-completeness-of-a-binary-tree.go)
|
|
|
[✔️](javascript%2F0958-check-completeness-of-a-binary-tree.js)
|
[✔️](kotlin%2F0958-check-completeness-of-a-binary-tree.kt)
|
|
|
|
|
|
| +| [0106 - Construct Binary Tree from Inorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/) |
|
|
|
|
|
|
|
[✔️](java%2F0106-construct-binary-tree-from-inorder-and-postorder-traversal.java)
|
[✔️](javascript%2F0106-construct-binary-tree-from-inorder-and-postorder-traversal.js)
|
[✔️](kotlin%2F0106-construct-binary-tree-from-inorder-and-postorder-traversal.kt)
|
[✔️](python%2F0106-construct-binary-tree-from-inorder-and-postorder-traversal.py)
|
|
|
|
|
| +| [0662 - Maximum Width of Binary Tree ](https://leetcode.com/problems/maximum-width-of-binary-tree/) |
|
|
|
|
|
|
|
[✔️](java%2F0662-maximum-width-of-binary-tree.java)
|
|
[✔️](kotlin%2F0662-maximum-width-of-binary-tree.kt)
|
[✔️](python%2F0662-maximum-width-of-binary-tree.py)
|
|
|
|
|
| +| [1376 - Time Needed to Inform All Employees ](https://leetcode.com/problems/time-needed-to-inform-all-employees/) |
|
|
|
|
|
|
|
[✔️](java%2F1376-time-needed-to-inform-all-employees.java)
|
[✔️](javascript%2F1376-time-needed-to-inform-all-employees.js)
|
[✔️](kotlin%2F1376-time-needed-to-inform-all-employees.kt)
|
|
|
|
|
|
| +| [1448 - Count Good Nodes In Binary Tree](https://leetcode.com/problems/count-good-nodes-in-binary-tree/) |
|
[✔️](c%2F1448-Count-Good-Nodes-in-Binary-Tree.c)
|
[✔️](cpp%2F1448-Count-Good-Nodes-In-Binary-Tree.cpp)
|
[✔️](csharp%2F1448-Count-Good-Nodes-in-Binary-Tree.cs)
|
|
[✔️](go%2F1448-count-good-nodes-in-binary-tree.go)
|
|
[✔️](java%2F1448-Count-Good-Nodes-in-Binary-Tree.java)
|
[✔️](javascript%2F1448-Count-Good-Nodes-in-Binary-Tree.js)
|
[✔️](kotlin%2F1448-Count-Good-Nodes-In-Binary-Tree.kt)
|
[✔️](python%2F1448-count-good-nodes-in-binary-tree.py)
|
|
[✔️](rust%2F1448-count-good-nodes-in-binary-tree.rs)
|
|
[✔️](swift%2F1448-count-good-nodes-in-binary-tree.swift)
|
[✔️](typescript%2F1448-Count-Good-Nodes-in-Binary-Tree.ts)
| +| [0098 - Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/) |
|
[✔️](c%2F0098-validate-binary-search-tree.c)
|
[✔️](cpp%2F0098-validate-binary-search-tree.cpp)
|
[✔️](csharp%2F0098-validate-binary-search-tree.cs)
|
|
[✔️](go%2F0098-validate-binary-search-tree.go)
|
|
[✔️](java%2F0098-validate-binary-search-tree.java)
|
[✔️](javascript%2F0098-validate-binary-search-tree.js)
|
[✔️](kotlin%2F0098-validate-binary-search-tree.kt)
|
[✔️](python%2F0098-validate-binary-search-tree.py)
|
|
[✔️](rust%2F0098-validate-binary-search-tree.rs)
|
|
[✔️](swift%2F0098-validate-binary-search-tree.swift)
|
[✔️](typescript%2F0098-validate-binary-search-tree.ts)
| +| [0230 - Kth Smallest Element In a Bst](https://leetcode.com/problems/kth-smallest-element-in-a-bst/) |
|
[✔️](c%2F0230-kth-smallest-element-in-a-bst.c)
|
[✔️](cpp%2F0230-kth-smallest-element-in-a-bst.cpp)
|
[✔️](csharp%2F0230-kth-smallest-element-in-a-bst.cs)
|
|
[✔️](go%2F0230-kth-smallest-element-in-a-bst.go)
|
|
[✔️](java%2F0230-kth-smallest-element-in-a-bst.java)
|
[✔️](javascript%2F0230-kth-smallest-element-in-a-bst.js)
|
[✔️](kotlin%2F0230-kth-smallest-element-in-a-bst.kt)
|
[✔️](python%2F0230-kth-smallest-element-in-a-bst.py)
|
|
[✔️](rust%2F0230-kth-smallest-element-in-a-bst.rs)
|
[✔️](scala%2F0230-kth-smallest-element-in-a-bst.scala)
|
[✔️](swift%2F0230-kth-smallest-element-in-a-bst.swift)
|
[✔️](typescript%2F0230-kth-smallest-element-in-a-bst.ts)
| +| [0105 - Construct Binary Tree From Preorder And Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/) |
|
[✔️](c%2F0105-construct-binary-tree-from-preorder-and-inorder-traversal.c)
|
[✔️](cpp%2F0105-construct-binary-tree-from-preorder-and-inorder-traversal.cpp)
|
[✔️](csharp%2F0105-construct-binary-tree-from-preorder-and-inorder-traversal.cs)
|
|
[✔️](go%2F0105-construct-binary-tree-from-preorder-and-inorder-traversal.go)
|
|
[✔️](java%2F0105-construct-binary-tree-from-preorder-and-inorder-traversal.java)
|
[✔️](javascript%2F0105-construct-binary-tree-from-preorder-and-inorder-traversal.js)
|
[✔️](kotlin%2F0105-construct-binary-tree-from-preorder-and-inorder-traversal.kt)
|
[✔️](python%2F0105-construct-binary-tree-from-preorder-and-inorder-traversal.py)
|
|
|
|
[✔️](swift%2F0105-construct-binary-tree-from-preorder-and-inorder-traversal.swift)
|
[✔️](typescript%2F0105-construct-binary-tree-from-preorder-and-inorder-traversal.ts)
| +| [0096 - Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/) |
|
[✔️](c%2F0096-unique-binary-search-trees.c)
|
|
|
|
|
|
[✔️](java%2F0096-unique-binary-search-trees.java)
|
[✔️](javascript%2F0096-unique-binary-search-trees.js)
|
[✔️](kotlin%2F0096-unique-binary-search-trees.kt)
|
|
|
|
|
|
| +| [0095 - Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/) |
|
|
|
|
|
|
|
[✔️](java%2F0095-unique-binary-search-trees-ii.java)
|
[✔️](javascript%2F0095-unique-binary-search-trees-ii.js)
|
[✔️](kotlin%2F0095-unique-binary-search-trees-ii.kt)
|
|
|
|
|
|
| +| [0129 - Sum Root to Leaf Numbers](https://leetcode.com/problems/sum-root-to-leaf-numbers/) |
|
[✔️](c%2F0129-sum-root-to-leaf-numbers.c)
|
[✔️](cpp%2F0129-sum-root-to-leaf-numbers.cpp)
|
|
|
[✔️](go%2F0129-sum-root-to-leaf-numbers.go)
|
|
[✔️](java%2F0129-sum-root-to-leaf-numbers.java)
|
[✔️](javascript%2F0129-sum-root-to-leaf-numbers.js)
|
[✔️](kotlin%2F0129-sum-root-to-leaf-numbers.kt)
|
|
|
|
|
|
| +| [0337 - House Robber III](https://leetcode.com/problems/house-robber-iii/) |
|
|
|
|
|
|
|
[✔️](java%2F0337-house-robber-iii.java)
|
[✔️](javascript%2F0337-house-robber-iii.js)
|
[✔️](kotlin%2F0337-house-robber-iii.kt)
|
|
|
|
|
|
| +| [0951 - Flip Equivalent Binary Trees](https://leetcode.com/problems/flip-equivalent-binary-trees/) |
|
|
|
|
|
|
|
[✔️](java%2F0951-flip-equivalent-binary-trees.java)
|
[✔️](javascript%2F0951-flip-equivalent-binary-trees.js)
|
[✔️](kotlin%2F0951-flip-equivalent-binary-trees.kt)
|
|
|
|
|
|
| +| [1993 - Operations On Tree](https://leetcode.com/problems/operations-on-tree/) |
|
|
|
|
|
|
|
[✔️](java%2F1993-operations-on-tree.java)
|
[✔️](javascript%2F1993-operations-on-tree.js)
|
[✔️](kotlin%2F1993-operations-on-tree.kt)
|
|
|
|
|
|
| +| [0894 - All Possible Full Binary Trees](https://leetcode.com/problems/all-possible-full-binary-trees/) |
|
|
|
|
|
|
|
[✔️](java%2F0894-all-possible-full-binary-trees.java)
|
[✔️](javascript%2F0894-all-possible-full-binary-trees.js)
|
[✔️](kotlin%2F0894-all-possible-full-binary-trees.kt)
|
[✔️](python%2F0894-all-possible-full-binary-trees.py)
|
|
|
|
|
| +| [0513 - Find Bottom Left Tree Value](https://leetcode.com/problems/find-bottom-left-tree-value/) |
|
|
|
|
|
|
|
[✔️](java%2F0513-find-bottom-left-tree-value.java)
|
[✔️](javascript%2F0513-find-bottom-left-tree-value.js)
|
[✔️](kotlin%2F0513-find-bottom-left-tree-value.kt)
|
[✔️](python%2F0513-find-bottom-left-tree-value.py)
|
|
|
|
|
| +| [0669 - Trim a Binary Search Tree](https://leetcode.com/problems/trim-a-binary-search-tree/) |
|
|
|
|
|
[✔️](go%2F0669-trim-a-binary-search-tree.go)
|
|
[✔️](java%2F0669-trim-a-binary-search-tree.java)
|
[✔️](javascript%2F0669-trim-a-binary-search-tree.js)
|
[✔️](kotlin%2F0669-trim-a-binary-search-tree.kt)
|
[✔️](python%2F0669-trim-a-binary-search-tree.py)
|
|
|
|
|
[✔️](typescript%2F0669-trim-a-binary-search-tree.ts)
| +| [0173 - Binary Search Tree Iterator](https://leetcode.com/problems/binary-search-tree-iterator/) |
|
|
|
|
|
|
|
[✔️](java%2F0173-binary-search-tree-iterator.java)
|
[✔️](javascript%2F0173-binary-search-tree-iterator.js)
|
[✔️](kotlin%2F0173-binary-search-tree-iterator.kt)
|
|
|
|
|
[✔️](swift%2F0173-binary-search-tree-iterator.swift)
|
| +| [0538 - Convert Bst to Greater Tree](https://leetcode.com/problems/convert-bst-to-greater-tree/) |
|
|
[✔️](cpp%2F0538-convert-bst-to-greater-tree.cpp)
|
|
|
|
|
[✔️](java%2F0538-convert-bst-to-greater-tree.java)
|
[✔️](javascript%2F0538-convert-bst-to-greater-tree.js)
|
[✔️](kotlin%2F0538-convert-bst-to-greater-tree.kt)
|
|
|
|
|
|
| +| [0124 - Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/) |
|
[✔️](c%2F0124-binary-tree-maximum-path-sum.c)
|
[✔️](cpp%2F0124-binary-tree-maximum-path-sum.cpp)
|
[✔️](csharp%2F0124-binary-tree-maximum-path-sum.cs)
|
|
[✔️](go%2F0124-binary-tree-maximum-path-sum.go)
|
|
[✔️](java%2F0124-binary-tree-maximum-path-sum.java)
|
[✔️](javascript%2F0124-binary-tree-maximum-path-sum.js)
|
[✔️](kotlin%2F0124-binary-tree-maximum-path-sum.kt)
|
[✔️](python%2F0124-binary-tree-maximum-path-sum.py)
|
|
[✔️](rust%2F0124-binary-tree-maximum-path-sum.rs)
|
|
[✔️](swift%2F0124-binary-tree-maximum-path-sum.swift)
|
[✔️](typescript%2F0124-binary-tree-maximum-path-sum.ts)
| +| [0297 - Serialize And Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/) |
|
[✔️](c%2F0297-serialize-and-deserialize-binary-tree.c)
|
[✔️](cpp%2F0297-serialize-and-deserialize-binary-tree.cpp)
|
[✔️](csharp%2F0297-serialize-and-deserialize-binary-tree.cs)
|
|
[✔️](go%2F0297-serialize-and-deserialize-binary-tree.go)
|
|
[✔️](java%2F0297-serialize-and-deserialize-binary-tree.java)
|
[✔️](javascript%2F0297-serialize-and-deserialize-binary-tree.js)
|
[✔️](kotlin%2F0297-serialize-and-deserialize-binary-tree.kt)
|
[✔️](python%2F0297-serialize-and-deserialize-binary-tree.py)
|
|
|
|
[✔️](swift%2F0297-serialize-and-deserialize-binary-tree.swift)
|
[✔️](typescript%2F0297-serialize-and-deserialize-binary-tree.ts)
| ### Tries -Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS ----- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- -[0208 - Implement Trie Prefix Tree](https://leetcode.com/problems/implement-trie-prefix-tree/) |
|
[✔️](c%2F0208-implement-trie-prefix-tree.c)
|
[✔️](cpp%2F0208-implement-trie-prefix-tree.cpp)
|
[✔️](csharp%2F0208-implement-trie-prefix-tree.cs)
|
|
[✔️](go%2F0208-implement-trie-prefix-tree.go)
|
|
[✔️](java%2F0208-implement-trie-prefix-tree.java)
|
[✔️](javascript%2F0208-implement-trie-prefix-tree.js)
|
[✔️](kotlin%2F0208-implement-trie-prefix-tree.kt)
|
[✔️](python%2F0208-implement-trie-prefix-tree.py)
|
[✔️](ruby%2F0208-implement-trie-prefix-tree.rb)
|
[✔️](rust%2F0208-implement-trie-prefix-tree.rs)
|
[✔️](scala%2F0208-implement-trie-prefix-tree.scala)
|
[✔️](swift%2F0208-implement-trie-prefix-tree.swift)
|
[✔️](typescript%2F0208-implement-trie-prefix-tree.ts)
-[0211 - Design Add And Search Words Data Structure](https://leetcode.com/problems/design-add-and-search-words-data-structure/) |
|
[✔️](c%2F0211-design-add-and-search-words-data-structure.c)
|
[✔️](cpp%2F0211-design-add-and-search-words-data-structure.cpp)
|
[✔️](csharp%2F0211-design-add-and-search-words-data-structure.cs)
|
|
[✔️](go%2F0211-design-add-and-search-words-data-structure.go)
|
|
[✔️](java%2F0211-design-add-and-search-words-data-structure.java)
|
[✔️](javascript%2F0211-design-add-and-search-words-data-structure.js)
|
[✔️](kotlin%2F0211-design-add-and-search-words-data-structure.kt)
|
[✔️](python%2F0211-design-add-and-search-words-data-structure.py)
|
[✔️](ruby%2F0211-design-add-and-search-words-data-structure.rb)
|
[✔️](rust%2F0211-design-add-and-search-words-data-structure.rs)
|
[✔️](scala%2F0211-design-add-and-search-words-data-structure.scala)
|
[✔️](swift%2F0211-design-add-and-search-words-data-structure.swift)
|
[✔️](typescript%2F0211-design-add-and-search-words-data-structure.ts)
-[2707 - Extra Characters in a String](https://leetcode.com/problems/extra-characters-in-a-string/) |
|
|
[✔️](cpp%2F2707-extra-characters-in-a-string.cpp)
|
|
|
|
|
[✔️](java%2F2707-extra-characters-in-a-string.java)
|
|
|
|
|
|
|
|
-[0212 - Word Search II](https://leetcode.com/problems/word-search-ii/) |
|
[✔️](c%2F0212-word-search-ii.c)
|
[✔️](cpp%2F0212-word-search-ii.cpp)
|
[✔️](csharp%2F0212-word-search-ii.cs)
|
|
[✔️](go%2F0212-word-search-ii.go)
|
|
[✔️](java%2F0212-word-search-ii.java)
|
[✔️](javascript%2F0212-word-search-ii.js)
|
[✔️](kotlin%2F0212-word-search-ii.kt)
|
[✔️](python%2F0212-word-search-ii.py)
|
|
[✔️](rust%2F0212-word-search-ii.rs)
|
|
[✔️](swift%2F0212-word-search-ii.swift)
|
[✔️](typescript%2F0212-word-search-ii.ts)
+| Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS | +| ----------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | --------------------------------------- | -------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | +| [0208 - Implement Trie Prefix Tree](https://leetcode.com/problems/implement-trie-prefix-tree/) |
|
[✔️](c%2F0208-implement-trie-prefix-tree.c)
|
[✔️](cpp%2F0208-implement-trie-prefix-tree.cpp)
|
[✔️](csharp%2F0208-implement-trie-prefix-tree.cs)
|
|
[✔️](go%2F0208-implement-trie-prefix-tree.go)
|
|
[✔️](java%2F0208-implement-trie-prefix-tree.java)
|
[✔️](javascript%2F0208-implement-trie-prefix-tree.js)
|
[✔️](kotlin%2F0208-implement-trie-prefix-tree.kt)
|
[✔️](python%2F0208-implement-trie-prefix-tree.py)
|
[✔️](ruby%2F0208-implement-trie-prefix-tree.rb)
|
[✔️](rust%2F0208-implement-trie-prefix-tree.rs)
|
[✔️](scala%2F0208-implement-trie-prefix-tree.scala)
|
[✔️](swift%2F0208-implement-trie-prefix-tree.swift)
|
[✔️](typescript%2F0208-implement-trie-prefix-tree.ts)
| +| [0211 - Design Add And Search Words Data Structure](https://leetcode.com/problems/design-add-and-search-words-data-structure/) |
|
[✔️](c%2F0211-design-add-and-search-words-data-structure.c)
|
[✔️](cpp%2F0211-design-add-and-search-words-data-structure.cpp)
|
[✔️](csharp%2F0211-design-add-and-search-words-data-structure.cs)
|
|
[✔️](go%2F0211-design-add-and-search-words-data-structure.go)
|
|
[✔️](java%2F0211-design-add-and-search-words-data-structure.java)
|
[✔️](javascript%2F0211-design-add-and-search-words-data-structure.js)
|
[✔️](kotlin%2F0211-design-add-and-search-words-data-structure.kt)
|
[✔️](python%2F0211-design-add-and-search-words-data-structure.py)
|
[✔️](ruby%2F0211-design-add-and-search-words-data-structure.rb)
|
[✔️](rust%2F0211-design-add-and-search-words-data-structure.rs)
|
[✔️](scala%2F0211-design-add-and-search-words-data-structure.scala)
|
[✔️](swift%2F0211-design-add-and-search-words-data-structure.swift)
|
[✔️](typescript%2F0211-design-add-and-search-words-data-structure.ts)
| +| [2707 - Extra Characters in a String](https://leetcode.com/problems/extra-characters-in-a-string/) |
|
|
[✔️](cpp%2F2707-extra-characters-in-a-string.cpp)
|
|
|
|
|
[✔️](java%2F2707-extra-characters-in-a-string.java)
|
|
|
|
|
|
|
|
| +| [0212 - Word Search II](https://leetcode.com/problems/word-search-ii/) |
|
[✔️](c%2F0212-word-search-ii.c)
|
[✔️](cpp%2F0212-word-search-ii.cpp)
|
[✔️](csharp%2F0212-word-search-ii.cs)
|
|
[✔️](go%2F0212-word-search-ii.go)
|
|
[✔️](java%2F0212-word-search-ii.java)
|
[✔️](javascript%2F0212-word-search-ii.js)
|
[✔️](kotlin%2F0212-word-search-ii.kt)
|
[✔️](python%2F0212-word-search-ii.py)
|
|
[✔️](rust%2F0212-word-search-ii.rs)
|
|
[✔️](swift%2F0212-word-search-ii.swift)
|
[✔️](typescript%2F0212-word-search-ii.ts)
| ### Heap / Priority Queue -Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS ----- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- -[0703 - Kth Largest Element In a Stream](https://leetcode.com/problems/kth-largest-element-in-a-stream/) |
|
[✔️](c%2F0703-kth-largest-element-in-a-stream.c)
|
[✔️](cpp%2F0703-kth-largest-element-in-a-stream.cpp)
|
[✔️](csharp%2F0703-kth-largest-element-in-a-stream.cs)
|
|
[✔️](go%2F0703-kth-largest-element-in-a-stream.go)
|
|
[✔️](java%2F0703-kth-largest-element-in-a-stream.java)
|
[✔️](javascript%2F0703-kth-largest-element-in-a-stream.js)
|
[✔️](kotlin%2F0703-kth-largest-element-in-a-stream.kt)
|
[✔️](python%2F0703-kth-largest-element-in-a-stream.py)
|
[✔️](ruby%2F0703-kth-largest-element-in-a-stream.rb)
|
[✔️](rust%2F0703-kth-largest-element-in-a-stream.rs)
|
|
[✔️](swift%2F0703-kth-largest-element-in-a-stream.swift)
|
[✔️](typescript%2F0703-kth-largest-element-in-a-stream.ts)
-[1046 - Last Stone Weight](https://leetcode.com/problems/last-stone-weight/) |
|
[✔️](c%2F1046-last-stone-weight.c)
|
[✔️](cpp%2F1046-Last-Stone-Weight.cpp)
|
[✔️](csharp%2F1046-Last-Stone-Weight.cs)
|
|
[✔️](go%2F1046-last-stone-weight.go)
|
|
[✔️](java%2F1046-Last-Stone-Weight.java)
|
[✔️](javascript%2F1046-Last-Stone-Weight.js)
|
[✔️](kotlin%2F1046-last-stone-weight.kt)
|
[✔️](python%2F1046-last-stone-weight.py)
|
[✔️](ruby%2F1046-Last-Stone-Weight.rb)
|
[✔️](rust%2F1046-last-stone-weight.rs)
|
|
[✔️](swift%2F1046-last-stone-weight.swift)
|
[✔️](typescript%2F1046-Last-Stone-Weight.ts)
-[0973 - K Closest Points to Origin](https://leetcode.com/problems/k-closest-points-to-origin/) |
|
[✔️](c%2F0973-k-closest-points-to-origin.c)
|
[✔️](cpp%2F0973-k-closest-points-to-origin.cpp)
|
[✔️](csharp%2F0973-k-closest-points-to-origin.cs)
|
|
[✔️](go%2F0973-k-closest-points-to-origin.go)
|
|
[✔️](java%2F0973-k-closest-points-to-origin.java)
|
[✔️](javascript%2F0973-k-closest-points-to-origin.js)
|
[✔️](kotlin%2F0973-k-closest-points-to-origin.kt)
|
[✔️](python%2F0973-k-closest-points-to-origin.py)
|
|
[✔️](rust%2F0973-k-closest-points-to-origin.rs)
|
|
[✔️](swift%2F0973-k-closest-points-to-origin.swift)
|
-[0215 - Kth Largest Element In An Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) |
|
[✔️](c%2F0215-kth-largest-element-in-an-array.c)
|
[✔️](cpp%2F0215-kth-largest-element-in-an-array.cpp)
|
[✔️](csharp%2F0215-kth-largest-element-in-an-array.cs)
|
|
[✔️](go%2F0215-kth-largest-element-in-an-array.go)
|
|
[✔️](java%2F0215-kth-largest-element-in-an-array.java)
|
[✔️](javascript%2F0215-kth-largest-element-in-an-array.js)
|
[✔️](kotlin%2F0215-kth-largest-element-in-an-array.kt)
|
[✔️](python%2F0215-kth-largest-element-in-an-array.py)
|
|
[✔️](rust%2F0215-kth-largest-element-in-an-array.rs)
|
[✔️](scala%2F0215-kth-largest-element-in-an-array.scala)
|
[✔️](swift%2F0215-kth-largest-element-in-an-array.swift)
|
[✔️](typescript%2F0215-kth-largest-element-in-an-array.ts)
-[0621 - Task Scheduler](https://leetcode.com/problems/task-scheduler/) |
|
[✔️](c%2F0621-task-scheduler.c)
|
[✔️](cpp%2F0621-task-scheduler.cpp)
|
[✔️](csharp%2F0621-task-scheduler.cs)
|
|
|
|
[✔️](java%2F0621-task-scheduler.java)
|
[✔️](javascript%2F0621-task-scheduler.js)
|
[✔️](kotlin%2F0621-task-scheduler.kt)
|
[✔️](python%2F0621-task-scheduler.py)
|
|
[✔️](rust%2F0621-task-scheduler.rs)
|
|
[✔️](swift%2F0621-task-scheduler.swift)
|
[✔️](typescript%2F0621-task-scheduler.ts)
-[0355 - Design Twitter](https://leetcode.com/problems/design-twitter/) |
|
|
[✔️](cpp%2F0355-design-twitter.cpp)
|
[✔️](csharp%2F0355-design-twitter.cs)
|
|
[✔️](go%2F0355-design-twitter.go)
|
|
[✔️](java%2F0355-design-twitter.java)
|
[✔️](javascript%2F0355-design-twitter.js)
|
[✔️](kotlin%2F0355-design-twitter.kt)
|
[✔️](python%2F0355-design-twitter.py)
|
|
|
|
[✔️](swift%2F0355-design-twitter.swift)
|
-[1675 - Minimize Deviation in Array](https://leetcode.com/problems/minimize-deviation-in-array/) |
|
|
[✔️](cpp%2F1675-minimize-deviation-in-array.cpp)
|
|
|
|
|
|
|
[✔️](kotlin%2F1675-minimize-deviation-in-array.kt)
|
|
|
|
|
|
-[2542 - Maximum Subsequence Score](https://leetcode.com/problems/maximum-subsequence-score/) |
|
|
[✔️](cpp%2F2542-maximum-subsequence-score.cpp)
|
|
|
|
|
|
[✔️](javascript%2F2542-maximum-subsequence-score.js)
|
[✔️](kotlin%2F2542-maximum-subsequence-score.kt)
|
|
|
|
|
|
-[1834 - Single Threaded Cpu](https://leetcode.com/problems/single-threaded-cpu/) |
|
|
|
|
|
|
|
[✔️](java%2F1834-single-threaded-cpu.java)
|
[✔️](javascript%2F1834-single-threaded-cpu.js)
|
[✔️](kotlin%2F1834-single-threaded-cpu.kt)
|
[✔️](python%2F1834-single-threaded-cpu.py)
|
|
[✔️](rust%2F1834-single-threaded-cpu.rs)
|
|
|
-[1845 - Seat Reservation Manager](https://leetcode.com/problems/seat-reservation-manager/) |
|
|
[✔️](cpp%2F1845-seat-reservation-manager.cpp)
|
|
|
|
|
|
[✔️](javascript%2F1845-seat-reservation-manager.js)
|
[✔️](kotlin%2F1845-seat-reservation-manager.kt)
|
[✔️](python%2F1845-seat-reservation-manager.py)
|
|
|
|
|
-[1882 - Process Tasks Using Servers](https://leetcode.com/problems/process-tasks-using-servers/) |
|
|
|
|
|
|
|
[✔️](java%2F1882-process-tasks-using-servers.java)
|
[✔️](javascript%2F1882-process-tasks-using-servers.js)
|
[✔️](kotlin%2F1882-process-tasks-using-servers.kt)
|
|
|
|
|
|
-[1985 - Find The Kth Largest Integer In The Array](https://leetcode.com/problems/find-the-kth-largest-integer-in-the-array/) |
|
|
[✔️](cpp%2F1985-Find-The-Kth-Largest-Integer-In-The-Array.cpp)
|
|
|
[✔️](go%2F1985-find-the-kth-largest-integer-in-the-array.go)
|
|
[✔️](java%2F1985-Find-The-Kth-Largest-Integer-In-The-Array.java)
|
[✔️](javascript%2F1985-find-the-kth-largest-integer-in-the-array.js)
|
[✔️](kotlin%2F1985-find-the-kth-largest-integer-in-the-array.kt)
|
[✔️](python%2F1985-find-the-kth-largest-integer-in-the-array.py)
|
|
|
|
[✔️](swift%2F1985-Find-The-Kth-Largest-Integer-In-The-Array.swift)
|
-[0767 - Reorganize String](https://leetcode.com/problems/reorganize-string/) |
|
|
[✔️](cpp%2F0767-reorganize-string.cpp)
|
|
|
|
|
[✔️](java%2F0767-reorganize-string.java)
|
[✔️](javascript%2F0767-reorganize-string.js)
|
[✔️](kotlin%2F0767-reorganize-string.kt)
|
[✔️](python%2F0767-reorganize-string.py)
|
|
|
|
|
-[1405 - Longest Happy String](https://leetcode.com/problems/longest-happy-string/) |
|
|
|
|
|
|
|
[✔️](java%2F1405-longest-happy-string.java)
|
[✔️](javascript%2F1405-longest-happy-string.js)
|
[✔️](kotlin%2F1405-longest-happy-string.kt)
|
|
|
|
|
|
-[1094 - Car Pooling](https://leetcode.com/problems/car-pooling/) |
|
|
[✔️](cpp%2F1094-car-pooling.cpp)
|
[✔️](csharp%2F1094-Car-Pooling.cs)
|
|
|
|
[✔️](java%2F1094-car-pooling.java)
|
[✔️](javascript%2F1094-car-pooling.js)
|
[✔️](kotlin%2F1094-car-pooling.kt)
|
|
|
|
|
|
-[0295 - Find Median From Data Stream](https://leetcode.com/problems/find-median-from-data-stream/) |
|
|
[✔️](cpp%2F0295-find-median-from-data-stream.cpp)
|
[✔️](csharp%2F0295-find-median-from-data-stream.cs)
|
|
[✔️](go%2F0295-find-median-from-data-stream.go)
|
|
[✔️](java%2F0295-find-median-from-data-stream.java)
|
[✔️](javascript%2F0295-find-median-from-data-stream.js)
|
[✔️](kotlin%2F0295-find-median-from-data-stream.kt)
|
[✔️](python%2F0295-find-median-from-data-stream.py)
|
|
|
|
[✔️](swift%2F0295-find-median-from-data-stream.swift)
|
[✔️](typescript%2F0295-find-median-from-data-stream.ts)
-[1383 - Maximum Performance of a Team](https://leetcode.com/problems/maximum-performance-of-a-team/) |
|
|
|
[✔️](csharp%2F1383-Maximum-Performance-Of-A-Team.cs)
|
|
|
|
|
[✔️](javascript%2F1383-maximum-performance-of-a-team.js)
|
[✔️](kotlin%2F1383-maximum-performance-of-a-team.kt)
|
[✔️](python%2F1383-maximum-performance-of-a-team.py)
|
|
|
|
|
-[0502 - IPO](https://leetcode.com/problems/ipo/) |
|
|
|
|
|
|
|
[✔️](java%2F0502-ipo.java)
|
[✔️](javascript%2F0502-ipo.js)
|
[✔️](kotlin%2F0502-ipo.kt)
|
[✔️](python%2F0502-ipo.py)
|
|
[✔️](rust%2F0502-ipo.rs)
|
|
[✔️](swift%2F0502-ipo.swift)
|
[✔️](typescript%2F0502-ipo.ts)
+| Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS | +| --------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------- | --------------------------------------- | ----------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | +| [0703 - Kth Largest Element In a Stream](https://leetcode.com/problems/kth-largest-element-in-a-stream/) |
|
[✔️](c%2F0703-kth-largest-element-in-a-stream.c)
|
[✔️](cpp%2F0703-kth-largest-element-in-a-stream.cpp)
|
[✔️](csharp%2F0703-kth-largest-element-in-a-stream.cs)
|
|
[✔️](go%2F0703-kth-largest-element-in-a-stream.go)
|
|
[✔️](java%2F0703-kth-largest-element-in-a-stream.java)
|
[✔️](javascript%2F0703-kth-largest-element-in-a-stream.js)
|
[✔️](kotlin%2F0703-kth-largest-element-in-a-stream.kt)
|
[✔️](python%2F0703-kth-largest-element-in-a-stream.py)
|
[✔️](ruby%2F0703-kth-largest-element-in-a-stream.rb)
|
[✔️](rust%2F0703-kth-largest-element-in-a-stream.rs)
|
|
[✔️](swift%2F0703-kth-largest-element-in-a-stream.swift)
|
[✔️](typescript%2F0703-kth-largest-element-in-a-stream.ts)
| +| [1046 - Last Stone Weight](https://leetcode.com/problems/last-stone-weight/) |
|
[✔️](c%2F1046-last-stone-weight.c)
|
[✔️](cpp%2F1046-Last-Stone-Weight.cpp)
|
[✔️](csharp%2F1046-Last-Stone-Weight.cs)
|
|
[✔️](go%2F1046-last-stone-weight.go)
|
|
[✔️](java%2F1046-Last-Stone-Weight.java)
|
[✔️](javascript%2F1046-Last-Stone-Weight.js)
|
[✔️](kotlin%2F1046-last-stone-weight.kt)
|
[✔️](python%2F1046-last-stone-weight.py)
|
[✔️](ruby%2F1046-Last-Stone-Weight.rb)
|
[✔️](rust%2F1046-last-stone-weight.rs)
|
|
[✔️](swift%2F1046-last-stone-weight.swift)
|
[✔️](typescript%2F1046-Last-Stone-Weight.ts)
| +| [0973 - K Closest Points to Origin](https://leetcode.com/problems/k-closest-points-to-origin/) |
|
[✔️](c%2F0973-k-closest-points-to-origin.c)
|
[✔️](cpp%2F0973-k-closest-points-to-origin.cpp)
|
[✔️](csharp%2F0973-k-closest-points-to-origin.cs)
|
|
[✔️](go%2F0973-k-closest-points-to-origin.go)
|
|
[✔️](java%2F0973-k-closest-points-to-origin.java)
|
[✔️](javascript%2F0973-k-closest-points-to-origin.js)
|
[✔️](kotlin%2F0973-k-closest-points-to-origin.kt)
|
[✔️](python%2F0973-k-closest-points-to-origin.py)
|
|
[✔️](rust%2F0973-k-closest-points-to-origin.rs)
|
|
[✔️](swift%2F0973-k-closest-points-to-origin.swift)
|
| +| [0215 - Kth Largest Element In An Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) |
|
[✔️](c%2F0215-kth-largest-element-in-an-array.c)
|
[✔️](cpp%2F0215-kth-largest-element-in-an-array.cpp)
|
[✔️](csharp%2F0215-kth-largest-element-in-an-array.cs)
|
|
[✔️](go%2F0215-kth-largest-element-in-an-array.go)
|
|
[✔️](java%2F0215-kth-largest-element-in-an-array.java)
|
[✔️](javascript%2F0215-kth-largest-element-in-an-array.js)
|
[✔️](kotlin%2F0215-kth-largest-element-in-an-array.kt)
|
[✔️](python%2F0215-kth-largest-element-in-an-array.py)
|
|
[✔️](rust%2F0215-kth-largest-element-in-an-array.rs)
|
[✔️](scala%2F0215-kth-largest-element-in-an-array.scala)
|
[✔️](swift%2F0215-kth-largest-element-in-an-array.swift)
|
[✔️](typescript%2F0215-kth-largest-element-in-an-array.ts)
| +| [0621 - Task Scheduler](https://leetcode.com/problems/task-scheduler/) |
|
[✔️](c%2F0621-task-scheduler.c)
|
[✔️](cpp%2F0621-task-scheduler.cpp)
|
[✔️](csharp%2F0621-task-scheduler.cs)
|
|
|
|
[✔️](java%2F0621-task-scheduler.java)
|
[✔️](javascript%2F0621-task-scheduler.js)
|
[✔️](kotlin%2F0621-task-scheduler.kt)
|
[✔️](python%2F0621-task-scheduler.py)
|
|
[✔️](rust%2F0621-task-scheduler.rs)
|
|
[✔️](swift%2F0621-task-scheduler.swift)
|
[✔️](typescript%2F0621-task-scheduler.ts)
| +| [0355 - Design Twitter](https://leetcode.com/problems/design-twitter/) |
|
|
[✔️](cpp%2F0355-design-twitter.cpp)
|
[✔️](csharp%2F0355-design-twitter.cs)
|
|
[✔️](go%2F0355-design-twitter.go)
|
|
[✔️](java%2F0355-design-twitter.java)
|
[✔️](javascript%2F0355-design-twitter.js)
|
[✔️](kotlin%2F0355-design-twitter.kt)
|
[✔️](python%2F0355-design-twitter.py)
|
|
|
|
[✔️](swift%2F0355-design-twitter.swift)
|
| +| [1675 - Minimize Deviation in Array](https://leetcode.com/problems/minimize-deviation-in-array/) |
|
|
[✔️](cpp%2F1675-minimize-deviation-in-array.cpp)
|
|
|
|
|
|
|
[✔️](kotlin%2F1675-minimize-deviation-in-array.kt)
|
|
|
|
|
|
| +| [2542 - Maximum Subsequence Score](https://leetcode.com/problems/maximum-subsequence-score/) |
|
|
[✔️](cpp%2F2542-maximum-subsequence-score.cpp)
|
|
|
|
|
|
[✔️](javascript%2F2542-maximum-subsequence-score.js)
|
[✔️](kotlin%2F2542-maximum-subsequence-score.kt)
|
|
|
|
|
|
| +| [1834 - Single Threaded Cpu](https://leetcode.com/problems/single-threaded-cpu/) |
|
|
|
|
|
|
|
[✔️](java%2F1834-single-threaded-cpu.java)
|
[✔️](javascript%2F1834-single-threaded-cpu.js)
|
[✔️](kotlin%2F1834-single-threaded-cpu.kt)
|
[✔️](python%2F1834-single-threaded-cpu.py)
|
|
[✔️](rust%2F1834-single-threaded-cpu.rs)
|
|
|
| +| [1845 - Seat Reservation Manager](https://leetcode.com/problems/seat-reservation-manager/) |
|
|
[✔️](cpp%2F1845-seat-reservation-manager.cpp)
|
|
|
|
|
|
[✔️](javascript%2F1845-seat-reservation-manager.js)
|
[✔️](kotlin%2F1845-seat-reservation-manager.kt)
|
[✔️](python%2F1845-seat-reservation-manager.py)
|
|
|
|
|
| +| [1882 - Process Tasks Using Servers](https://leetcode.com/problems/process-tasks-using-servers/) |
|
|
|
|
|
|
|
[✔️](java%2F1882-process-tasks-using-servers.java)
|
[✔️](javascript%2F1882-process-tasks-using-servers.js)
|
[✔️](kotlin%2F1882-process-tasks-using-servers.kt)
|
|
|
|
|
|
| +| [1985 - Find The Kth Largest Integer In The Array](https://leetcode.com/problems/find-the-kth-largest-integer-in-the-array/) |
|
|
[✔️](cpp%2F1985-Find-The-Kth-Largest-Integer-In-The-Array.cpp)
|
|
|
[✔️](go%2F1985-find-the-kth-largest-integer-in-the-array.go)
|
|
[✔️](java%2F1985-Find-The-Kth-Largest-Integer-In-The-Array.java)
|
[✔️](javascript%2F1985-find-the-kth-largest-integer-in-the-array.js)
|
[✔️](kotlin%2F1985-find-the-kth-largest-integer-in-the-array.kt)
|
[✔️](python%2F1985-find-the-kth-largest-integer-in-the-array.py)
|
|
|
|
[✔️](swift%2F1985-Find-The-Kth-Largest-Integer-In-The-Array.swift)
|
| +| [0767 - Reorganize String](https://leetcode.com/problems/reorganize-string/) |
|
|
[✔️](cpp%2F0767-reorganize-string.cpp)
|
|
|
|
|
[✔️](java%2F0767-reorganize-string.java)
|
[✔️](javascript%2F0767-reorganize-string.js)
|
[✔️](kotlin%2F0767-reorganize-string.kt)
|
[✔️](python%2F0767-reorganize-string.py)
|
|
|
|
|
| +| [1405 - Longest Happy String](https://leetcode.com/problems/longest-happy-string/) |
|
|
|
|
|
|
|
[✔️](java%2F1405-longest-happy-string.java)
|
[✔️](javascript%2F1405-longest-happy-string.js)
|
[✔️](kotlin%2F1405-longest-happy-string.kt)
|
|
|
|
|
|
| +| [1094 - Car Pooling](https://leetcode.com/problems/car-pooling/) |
|
|
[✔️](cpp%2F1094-car-pooling.cpp)
|
[✔️](csharp%2F1094-Car-Pooling.cs)
|
|
|
|
[✔️](java%2F1094-car-pooling.java)
|
[✔️](javascript%2F1094-car-pooling.js)
|
[✔️](kotlin%2F1094-car-pooling.kt)
|
|
|
|
|
|
| +| [0295 - Find Median From Data Stream](https://leetcode.com/problems/find-median-from-data-stream/) |
|
|
[✔️](cpp%2F0295-find-median-from-data-stream.cpp)
|
[✔️](csharp%2F0295-find-median-from-data-stream.cs)
|
|
[✔️](go%2F0295-find-median-from-data-stream.go)
|
|
[✔️](java%2F0295-find-median-from-data-stream.java)
|
[✔️](javascript%2F0295-find-median-from-data-stream.js)
|
[✔️](kotlin%2F0295-find-median-from-data-stream.kt)
|
[✔️](python%2F0295-find-median-from-data-stream.py)
|
|
|
|
[✔️](swift%2F0295-find-median-from-data-stream.swift)
|
[✔️](typescript%2F0295-find-median-from-data-stream.ts)
| +| [1383 - Maximum Performance of a Team](https://leetcode.com/problems/maximum-performance-of-a-team/) |
|
|
|
[✔️](csharp%2F1383-Maximum-Performance-Of-A-Team.cs)
|
|
|
|
|
[✔️](javascript%2F1383-maximum-performance-of-a-team.js)
|
[✔️](kotlin%2F1383-maximum-performance-of-a-team.kt)
|
[✔️](python%2F1383-maximum-performance-of-a-team.py)
|
|
|
|
|
| +| [0502 - IPO](https://leetcode.com/problems/ipo/) |
|
|
|
|
|
|
|
[✔️](java%2F0502-ipo.java)
|
[✔️](javascript%2F0502-ipo.js)
|
[✔️](kotlin%2F0502-ipo.kt)
|
[✔️](python%2F0502-ipo.py)
|
|
[✔️](rust%2F0502-ipo.rs)
|
|
[✔️](swift%2F0502-ipo.swift)
|
[✔️](typescript%2F0502-ipo.ts)
| ### Backtracking -Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS ----- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- -[0078 - Subsets](https://leetcode.com/problems/subsets/) |
|
[✔️](c%2F0078-subsets.c)
|
[✔️](cpp%2F0078-subsets.cpp)
|
[✔️](csharp%2F0078-subsets.cs)
|
|
[✔️](go%2F0078-subsets.go)
|
|
[✔️](java%2F0078-subsets.java)
|
[✔️](javascript%2F0078-subsets.js)
|
[✔️](kotlin%2F0078-subsets.kt)
|
[✔️](python%2F0078-subsets.py)
|
[✔️](ruby%2F0078-subsets.rb)
|
[✔️](rust%2F0078-subsets.rs)
|
|
[✔️](swift%2F0078-subsets.swift)
|
[✔️](typescript%2F0078-subsets.ts)
-[0039 - Combination Sum](https://leetcode.com/problems/combination-sum/) |
|
[✔️](c%2F0039-combination-sum.c)
|
[✔️](cpp%2F0039-combination-sum.cpp)
|
[✔️](csharp%2F0039-combination-sum.cs)
|
|
[✔️](go%2F0039-combination-sum.go)
|
|
[✔️](java%2F0039-combination-sum.java)
|
[✔️](javascript%2F0039-combination-sum.js)
|
[✔️](kotlin%2F0039-combination-sum.kt)
|
[✔️](python%2F0039-combination-sum.py)
|
[✔️](ruby%2F0039-combination-sum.rb)
|
[✔️](rust%2F0039-combination-sum.rs)
|
|
[✔️](swift%2F0039-combination-sum.swift)
|
[✔️](typescript%2F0039-combination-sum.ts)
-[0077 - Combinations](https://leetcode.com/problems/combinations/) |
|
|
[✔️](cpp%2F0077-combinations.cpp)
|
[✔️](csharp%2F0077-combinations.cs)
|
|
[✔️](go%2F0077-combinations.go)
|
|
[✔️](java%2F0077-combinations.java)
|
|
[✔️](kotlin%2F0077-combinations.kt)
|
[✔️](python%2F0077-combinations.py)
|
|
|
|
[✔️](swift%2F0077-combinations.swift)
|
-[0046 - Permutations](https://leetcode.com/problems/permutations/) |
|
[✔️](c%2F0046-permutations.c)
|
[✔️](cpp%2F0046-permutations.cpp)
|
[✔️](csharp%2F0046-permutations.cs)
|
|
[✔️](go%2F0046-permutations.go)
|
|
[✔️](java%2F0046-permutations.java)
|
[✔️](javascript%2F0046-permutations.js)
|
[✔️](kotlin%2F0046-permutations.kt)
|
[✔️](python%2F0046-permutations.py)
|
[✔️](ruby%2F0046-permutations.rb)
|
[✔️](rust%2F0046-permutations.rs)
|
|
[✔️](swift%2F0046-permutations.swift)
|
[✔️](typescript%2F0046-permutations.ts)
-[0090 - Subsets II](https://leetcode.com/problems/subsets-ii/) |
|
[✔️](c%2F0090-subsets-ii.c)
|
[✔️](cpp%2F0090-subsets-ii.cpp)
|
[✔️](csharp%2F0090-subsets-ii.cs)
|
|
[✔️](go%2F0090-subsets-ii.go)
|
|
[✔️](java%2F0090-subsets-ii.java)
|
[✔️](javascript%2F0090-subsets-ii.js)
|
[✔️](kotlin%2F0090-subsets-ii.kt)
|
[✔️](python%2F0090-subsets-ii.py)
|
[✔️](ruby%2F0090-subsets-ii.rb)
|
[✔️](rust%2F0090-subsets-ii.rs)
|
|
[✔️](swift%2F0090-subsets-ii.swift)
|
[✔️](typescript%2F0090-subsets-ii.ts)
-[0040 - Combination Sum II](https://leetcode.com/problems/combination-sum-ii/) |
|
[✔️](c%2F0040-combination-sum-ii.c)
|
[✔️](cpp%2F0040-combination-sum-ii.cpp)
|
[✔️](csharp%2F0040-combination-sum-ii.cs)
|
|
[✔️](go%2F0040-combination-sum-ii.go)
|
|
[✔️](java%2F0040-combination-sum-ii.java)
|
[✔️](javascript%2F0040-combination-sum-ii.js)
|
[✔️](kotlin%2F0040-combination-sum-ii.kt)
|
[✔️](python%2F0040-combination-sum-ii.py)
|
[✔️](ruby%2F0040-combination-sum-ii.rb)
|
|
|
[✔️](swift%2F0040-combination-sum-ii.swift)
|
[✔️](typescript%2F0040-combination-sum-ii.ts)
-[0047 - Permutations II](https://leetcode.com/problems/permutations-ii/) |
|
|
|
[✔️](csharp%2F0047-permutations-ii.cs)
|
|
[✔️](go%2F0047-permutations-ii.go)
|
|
[✔️](java%2F0047-permutations-ii.java)
|
|
[✔️](kotlin%2F0047-permutations-ii.kt)
|
[✔️](python%2F0047-permutations-ii.py)
|
|
|
|
[✔️](swift%2F0047-permutations-ii.swift)
|
[✔️](typescript%2F0047-permutations-ii.ts)
-[0079 - Word Search](https://leetcode.com/problems/word-search/) |
|
[✔️](c%2F0079-word-search.c)
|
[✔️](cpp%2F0079-word-search.cpp)
|
[✔️](csharp%2F0079-word-search.cs)
|
|
[✔️](go%2F0079-word-search.go)
|
|
[✔️](java%2F0079-word-search.java)
|
[✔️](javascript%2F0079-word-search.js)
|
[✔️](kotlin%2F0079-word-search.kt)
|
[✔️](python%2F0079-word-search.py)
|
[✔️](ruby%2F0079-word-search.rb)
|
[✔️](rust%2F0079-word-search.rs)
|
|
[✔️](swift%2F0079-word-search.swift)
|
[✔️](typescript%2F0079-word-search.ts)
-[0131 - Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/) |
|
|
[✔️](cpp%2F0131-palindrome-partitioning.cpp)
|
[✔️](csharp%2F0131-palindrome-partitioning.cs)
|
|
[✔️](go%2F0131-palindrome-partitioning.go)
|
|
[✔️](java%2F0131-palindrome-partitioning.java)
|
[✔️](javascript%2F0131-palindrome-partitioning.js)
|
[✔️](kotlin%2F0131-palindrome-partitioning.kt)
|
[✔️](python%2F0131-palindrome-partitioning.py)
|
[✔️](ruby%2F0131-palindrome-partitioning.rb)
|
[✔️](rust%2F0131-palindrome-partitioning.rs)
|
|
[✔️](swift%2F0131-palindrome-partitioning.swift)
|
[✔️](typescript%2F0131-palindrome-partitioning.ts)
-[0093 - Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses/) |
|
|
|
[✔️](csharp%2F0093-restore-ip-addresses.cs)
|
|
[✔️](go%2F0093-restore-ip-addresses.go)
|
|
|
[✔️](javascript%2F0093-restore-ip-addresses.js)
|
[✔️](kotlin%2F0093-restore-ip-addresses.kt)
|
|
|
[✔️](rust%2F0093-restore-ip-addresses.rs)
|
|
|
[✔️](typescript%2F0093-restore-ip-addresses.ts)
-[0017 - Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/) |
|
|
[✔️](cpp%2F0017-letter-combinations-of-a-phone-number.cpp)
|
[✔️](csharp%2F0017-letter-combinations-of-a-phone-number.cs)
|
|
[✔️](go%2F0017-letter-combinations-of-a-phone-number.go)
|
|
[✔️](java%2F0017-letter-combinations-of-a-phone-number.java)
|
[✔️](javascript%2F0017-letter-combinations-of-a-phone-number.js)
|
[✔️](kotlin%2F0017-letter-combinations-of-a-phone-number.kt)
|
[✔️](python%2F0017-letter-combinations-of-a-phone-number.py)
|
[✔️](ruby%2F0017-letter-combinations-of-a-phone-number.rb)
|
[✔️](rust%2F0017-letter-combinations-of-a-phone-number.rs)
|
|
[✔️](swift%2F0017-letter-combinations-of-a-phone-number.swift)
|
[✔️](typescript%2F0017-letter-combinations-of-a-phone-number.ts)
-[0473 - Matchsticks to Square](https://leetcode.com/problems/matchsticks-to-square/) |
|
|
[✔️](cpp%2F0473-matchsticks-to-square.cpp)
|
|
|
|
|
[✔️](java%2F0473-matchsticks-to-square.java)
|
[✔️](javascript%2F0473-matchsticks-to-square.js)
|
[✔️](kotlin%2F0473-matchsticks-to-square.kt)
|
[✔️](python%2F0473-matchsticks-to-square.py)
|
|
|
|
|
-[1849 - Splitting a String Into Descending Consecutive Values](https://leetcode.com/problems/splitting-a-string-into-descending-consecutive-values/) |
|
|
[✔️](cpp%2F1849-splitting-a-string-into-descending-consecutive-values.cpp)
|
|
|
|
|
[✔️](java%2F1849-splitting-a-string-into-descending-consecutive-values.java)
|
|
[✔️](kotlin%2F1849-splitting-a-string-into-descending-consecutive-values.kt)
|
[✔️](python%2F1849-splitting-a-string-into-descending-consecutive-values.py)
|
|
|
|
|
-[1980 - Find Unique Binary String](https://leetcode.com/problems/find-unique-binary-string/) |
|
|
[✔️](cpp%2F1980-find-unique-binary-string.cpp)
|
|
|
|
|
[✔️](java%2F1980-find-unique-binary-string.java)
|
|
[✔️](kotlin%2F1980-find-unique-binary-string.kt)
|
[✔️](python%2F1980-find-unique-binary-string.py)
|
|
|
|
|
-[1239 - Maximum Length of a Concatenated String With Unique Characters](https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/) |
|
|
|
[✔️](csharp%2F1239-maximum-length-of-a-concatenated-string-with-unique-characters.cs)
|
|
|
|
|
|
[✔️](kotlin%2F1239-maximum-length-of-a-concatenated-string-with-unique-characters.kt)
|
[✔️](python%2F1239-maximum-length-of-a-concatenated-string-with-unique-characters.py)
|
|
|
|
|
-[0698 - Partition to K Equal Sum Subsets](https://leetcode.com/problems/partition-to-k-equal-sum-subsets/) |
|
|
|
|
|
|
|
[✔️](java%2F0698-partition-to-k-equal-sum-subsets.java)
|
|
[✔️](kotlin%2F0698-partition-to-k-equal-sum-subsets.kt)
|
[✔️](python%2F0698-partition-to-k-equal-sum-subsets.py)
|
|
|
|
|
-[0051 - N Queens](https://leetcode.com/problems/n-queens/) |
|
[✔️](c%2F0051-n-queens.c)
|
[✔️](cpp%2F0051-n-queens.cpp)
|
[✔️](csharp%2F0051-n-queens.cs)
|
|
[✔️](go%2F0051-n-queens.go)
|
|
[✔️](java%2F0051-n-queens.java)
|
[✔️](javascript%2F0051-n-queens.js)
|
[✔️](kotlin%2F0051-n-queens.kt)
|
[✔️](python%2F0051-n-queens.py)
|
|
[✔️](rust%2F0051-n-queens.rs)
|
|
[✔️](swift%2F0051-n-queens.swift)
|
[✔️](typescript%2F0051-n-queens.ts)
-[0052 - N Queens II](https://leetcode.com/problems/n-queens-ii/) |
|
[✔️](c%2F0052-n-queens-ii.c)
|
[✔️](cpp%2F0052-n-queens-ii.cpp)
|
[✔️](csharp%2F0052-n-queens-ii.cs)
|
|
|
|
[✔️](java%2F0052-n-queens-ii.java)
|
[✔️](javascript%2F0052-n-queens-ii.js)
|
[✔️](kotlin%2F0052-n-queens-ii.kt)
|
[✔️](python%2F0052-n-queens-ii.py)
|
|
|
|
|
+| Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | +| [0078 - Subsets](https://leetcode.com/problems/subsets/) |
|
[✔️](c%2F0078-subsets.c)
|
[✔️](cpp%2F0078-subsets.cpp)
|
[✔️](csharp%2F0078-subsets.cs)
|
|
[✔️](go%2F0078-subsets.go)
|
|
[✔️](java%2F0078-subsets.java)
|
[✔️](javascript%2F0078-subsets.js)
|
[✔️](kotlin%2F0078-subsets.kt)
|
[✔️](python%2F0078-subsets.py)
|
[✔️](ruby%2F0078-subsets.rb)
|
[✔️](rust%2F0078-subsets.rs)
|
|
[✔️](swift%2F0078-subsets.swift)
|
[✔️](typescript%2F0078-subsets.ts)
| +| [0039 - Combination Sum](https://leetcode.com/problems/combination-sum/) |
|
[✔️](c%2F0039-combination-sum.c)
|
[✔️](cpp%2F0039-combination-sum.cpp)
|
[✔️](csharp%2F0039-combination-sum.cs)
|
|
[✔️](go%2F0039-combination-sum.go)
|
|
[✔️](java%2F0039-combination-sum.java)
|
[✔️](javascript%2F0039-combination-sum.js)
|
[✔️](kotlin%2F0039-combination-sum.kt)
|
[✔️](python%2F0039-combination-sum.py)
|
[✔️](ruby%2F0039-combination-sum.rb)
|
[✔️](rust%2F0039-combination-sum.rs)
|
|
[✔️](swift%2F0039-combination-sum.swift)
|
[✔️](typescript%2F0039-combination-sum.ts)
| +| [0077 - Combinations](https://leetcode.com/problems/combinations/) |
|
|
[✔️](cpp%2F0077-combinations.cpp)
|
[✔️](csharp%2F0077-combinations.cs)
|
|
[✔️](go%2F0077-combinations.go)
|
|
[✔️](java%2F0077-combinations.java)
|
|
[✔️](kotlin%2F0077-combinations.kt)
|
[✔️](python%2F0077-combinations.py)
|
|
|
|
[✔️](swift%2F0077-combinations.swift)
|
| +| [0046 - Permutations](https://leetcode.com/problems/permutations/) |
|
[✔️](c%2F0046-permutations.c)
|
[✔️](cpp%2F0046-permutations.cpp)
|
[✔️](csharp%2F0046-permutations.cs)
|
|
[✔️](go%2F0046-permutations.go)
|
|
[✔️](java%2F0046-permutations.java)
|
[✔️](javascript%2F0046-permutations.js)
|
[✔️](kotlin%2F0046-permutations.kt)
|
[✔️](python%2F0046-permutations.py)
|
[✔️](ruby%2F0046-permutations.rb)
|
[✔️](rust%2F0046-permutations.rs)
|
|
[✔️](swift%2F0046-permutations.swift)
|
[✔️](typescript%2F0046-permutations.ts)
| +| [0090 - Subsets II](https://leetcode.com/problems/subsets-ii/) |
|
[✔️](c%2F0090-subsets-ii.c)
|
[✔️](cpp%2F0090-subsets-ii.cpp)
|
[✔️](csharp%2F0090-subsets-ii.cs)
|
|
[✔️](go%2F0090-subsets-ii.go)
|
|
[✔️](java%2F0090-subsets-ii.java)
|
[✔️](javascript%2F0090-subsets-ii.js)
|
[✔️](kotlin%2F0090-subsets-ii.kt)
|
[✔️](python%2F0090-subsets-ii.py)
|
[✔️](ruby%2F0090-subsets-ii.rb)
|
[✔️](rust%2F0090-subsets-ii.rs)
|
|
[✔️](swift%2F0090-subsets-ii.swift)
|
[✔️](typescript%2F0090-subsets-ii.ts)
| +| [0040 - Combination Sum II](https://leetcode.com/problems/combination-sum-ii/) |
|
[✔️](c%2F0040-combination-sum-ii.c)
|
[✔️](cpp%2F0040-combination-sum-ii.cpp)
|
[✔️](csharp%2F0040-combination-sum-ii.cs)
|
|
[✔️](go%2F0040-combination-sum-ii.go)
|
|
[✔️](java%2F0040-combination-sum-ii.java)
|
[✔️](javascript%2F0040-combination-sum-ii.js)
|
[✔️](kotlin%2F0040-combination-sum-ii.kt)
|
[✔️](python%2F0040-combination-sum-ii.py)
|
[✔️](ruby%2F0040-combination-sum-ii.rb)
|
|
|
[✔️](swift%2F0040-combination-sum-ii.swift)
|
[✔️](typescript%2F0040-combination-sum-ii.ts)
| +| [0047 - Permutations II](https://leetcode.com/problems/permutations-ii/) |
|
|
|
[✔️](csharp%2F0047-permutations-ii.cs)
|
|
[✔️](go%2F0047-permutations-ii.go)
|
|
[✔️](java%2F0047-permutations-ii.java)
|
|
[✔️](kotlin%2F0047-permutations-ii.kt)
|
[✔️](python%2F0047-permutations-ii.py)
|
|
|
|
[✔️](swift%2F0047-permutations-ii.swift)
|
[✔️](typescript%2F0047-permutations-ii.ts)
| +| [0079 - Word Search](https://leetcode.com/problems/word-search/) |
|
[✔️](c%2F0079-word-search.c)
|
[✔️](cpp%2F0079-word-search.cpp)
|
[✔️](csharp%2F0079-word-search.cs)
|
|
[✔️](go%2F0079-word-search.go)
|
|
[✔️](java%2F0079-word-search.java)
|
[✔️](javascript%2F0079-word-search.js)
|
[✔️](kotlin%2F0079-word-search.kt)
|
[✔️](python%2F0079-word-search.py)
|
[✔️](ruby%2F0079-word-search.rb)
|
[✔️](rust%2F0079-word-search.rs)
|
|
[✔️](swift%2F0079-word-search.swift)
|
[✔️](typescript%2F0079-word-search.ts)
| +| [0131 - Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/) |
|
|
[✔️](cpp%2F0131-palindrome-partitioning.cpp)
|
[✔️](csharp%2F0131-palindrome-partitioning.cs)
|
|
[✔️](go%2F0131-palindrome-partitioning.go)
|
|
[✔️](java%2F0131-palindrome-partitioning.java)
|
[✔️](javascript%2F0131-palindrome-partitioning.js)
|
[✔️](kotlin%2F0131-palindrome-partitioning.kt)
|
[✔️](python%2F0131-palindrome-partitioning.py)
|
[✔️](ruby%2F0131-palindrome-partitioning.rb)
|
[✔️](rust%2F0131-palindrome-partitioning.rs)
|
|
[✔️](swift%2F0131-palindrome-partitioning.swift)
|
[✔️](typescript%2F0131-palindrome-partitioning.ts)
| +| [0093 - Restore IP Addresses](https://leetcode.com/problems/restore-ip-addresses/) |
|
|
|
[✔️](csharp%2F0093-restore-ip-addresses.cs)
|
|
[✔️](go%2F0093-restore-ip-addresses.go)
|
|
|
[✔️](javascript%2F0093-restore-ip-addresses.js)
|
[✔️](kotlin%2F0093-restore-ip-addresses.kt)
|
|
|
[✔️](rust%2F0093-restore-ip-addresses.rs)
|
|
|
[✔️](typescript%2F0093-restore-ip-addresses.ts)
| +| [0017 - Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/) |
|
|
[✔️](cpp%2F0017-letter-combinations-of-a-phone-number.cpp)
|
[✔️](csharp%2F0017-letter-combinations-of-a-phone-number.cs)
|
|
[✔️](go%2F0017-letter-combinations-of-a-phone-number.go)
|
|
[✔️](java%2F0017-letter-combinations-of-a-phone-number.java)
|
[✔️](javascript%2F0017-letter-combinations-of-a-phone-number.js)
|
[✔️](kotlin%2F0017-letter-combinations-of-a-phone-number.kt)
|
[✔️](python%2F0017-letter-combinations-of-a-phone-number.py)
|
[✔️](ruby%2F0017-letter-combinations-of-a-phone-number.rb)
|
[✔️](rust%2F0017-letter-combinations-of-a-phone-number.rs)
|
|
[✔️](swift%2F0017-letter-combinations-of-a-phone-number.swift)
|
[✔️](typescript%2F0017-letter-combinations-of-a-phone-number.ts)
| +| [0473 - Matchsticks to Square](https://leetcode.com/problems/matchsticks-to-square/) |
|
|
[✔️](cpp%2F0473-matchsticks-to-square.cpp)
|
|
|
|
|
[✔️](java%2F0473-matchsticks-to-square.java)
|
[✔️](javascript%2F0473-matchsticks-to-square.js)
|
[✔️](kotlin%2F0473-matchsticks-to-square.kt)
|
[✔️](python%2F0473-matchsticks-to-square.py)
|
|
|
|
|
| +| [1849 - Splitting a String Into Descending Consecutive Values](https://leetcode.com/problems/splitting-a-string-into-descending-consecutive-values/) |
|
|
[✔️](cpp%2F1849-splitting-a-string-into-descending-consecutive-values.cpp)
|
|
|
|
|
[✔️](java%2F1849-splitting-a-string-into-descending-consecutive-values.java)
|
|
[✔️](kotlin%2F1849-splitting-a-string-into-descending-consecutive-values.kt)
|
[✔️](python%2F1849-splitting-a-string-into-descending-consecutive-values.py)
|
|
|
|
|
| +| [1980 - Find Unique Binary String](https://leetcode.com/problems/find-unique-binary-string/) |
|
|
[✔️](cpp%2F1980-find-unique-binary-string.cpp)
|
|
|
|
|
[✔️](java%2F1980-find-unique-binary-string.java)
|
|
[✔️](kotlin%2F1980-find-unique-binary-string.kt)
|
[✔️](python%2F1980-find-unique-binary-string.py)
|
|
|
|
|
| +| [1239 - Maximum Length of a Concatenated String With Unique Characters](https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/) |
|
|
|
[✔️](csharp%2F1239-maximum-length-of-a-concatenated-string-with-unique-characters.cs)
|
|
|
|
|
|
[✔️](kotlin%2F1239-maximum-length-of-a-concatenated-string-with-unique-characters.kt)
|
[✔️](python%2F1239-maximum-length-of-a-concatenated-string-with-unique-characters.py)
|
|
|
|
|
| +| [0698 - Partition to K Equal Sum Subsets](https://leetcode.com/problems/partition-to-k-equal-sum-subsets/) |
|
|
|
|
|
|
|
[✔️](java%2F0698-partition-to-k-equal-sum-subsets.java)
|
|
[✔️](kotlin%2F0698-partition-to-k-equal-sum-subsets.kt)
|
[✔️](python%2F0698-partition-to-k-equal-sum-subsets.py)
|
|
|
|
|
| +| [0051 - N Queens](https://leetcode.com/problems/n-queens/) |
|
[✔️](c%2F0051-n-queens.c)
|
[✔️](cpp%2F0051-n-queens.cpp)
|
[✔️](csharp%2F0051-n-queens.cs)
|
|
[✔️](go%2F0051-n-queens.go)
|
|
[✔️](java%2F0051-n-queens.java)
|
[✔️](javascript%2F0051-n-queens.js)
|
[✔️](kotlin%2F0051-n-queens.kt)
|
[✔️](python%2F0051-n-queens.py)
|
|
[✔️](rust%2F0051-n-queens.rs)
|
|
[✔️](swift%2F0051-n-queens.swift)
|
[✔️](typescript%2F0051-n-queens.ts)
| +| [0052 - N Queens II](https://leetcode.com/problems/n-queens-ii/) |
|
[✔️](c%2F0052-n-queens-ii.c)
|
[✔️](cpp%2F0052-n-queens-ii.cpp)
|
[✔️](csharp%2F0052-n-queens-ii.cs)
|
|
|
|
[✔️](java%2F0052-n-queens-ii.java)
|
[✔️](javascript%2F0052-n-queens-ii.js)
|
[✔️](kotlin%2F0052-n-queens-ii.kt)
|
[✔️](python%2F0052-n-queens-ii.py)
|
|
|
|
|
| ### Graphs -Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS ----- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- -[0463 - Island Perimeter](https://leetcode.com/problems/island-perimeter/) |
|
[✔️](c%2F0463-island-perimeter.c)
|
[✔️](cpp%2F0463-island-perimeter.cpp)
|
[✔️](csharp%2F0463-island-perimeter.cs)
|
|
[✔️](go%2F0463-island-perimeter.go)
|
|
[✔️](java%2F0463-island-perimeter.java)
|
[✔️](javascript%2F0463-island-perimeter.js)
|
[✔️](kotlin%2F0463-island-perimeter.kt)
|
[✔️](python%2F0463-island-perimeter.py)
|
|
|
|
|
-[0953 - Verifying An Alien Dictionary](https://leetcode.com/problems/verifying-an-alien-dictionary/) |
|
[✔️](c%2F0953-verifying-an-alien-dictionary.c)
|
[✔️](cpp%2F0953-verifying-an-alien-dictionary.cpp)
|
|
|
[✔️](go%2F0953-verifying-an-alien-dictionary.go)
|
|
[✔️](java%2F0953-verifying-an-alien-dictionary.java)
|
[✔️](javascript%2F0953-verifying-an-alien-dictionary.js)
|
[✔️](kotlin%2F0953-verifying-an-alien-dictionary.kt)
|
[✔️](python%2F0953-verifying-an-alien-dictionary.py)
|
|
[✔️](rust%2F0953-verifying-an-alien-dictionary.rs)
|
|
|
-[0200 - Number of Islands](https://leetcode.com/problems/number-of-islands/) |
|
[✔️](c%2F0200-number-of-islands.c)
|
[✔️](cpp%2F0200-number-of-islands.cpp)
|
[✔️](csharp%2F0200-number-of-islands.cs)
|
|
[✔️](go%2F0200-number-of-islands.go)
|
|
[✔️](java%2F0200-number-of-islands.java)
|
[✔️](javascript%2F0200-number-of-islands.js)
|
[✔️](kotlin%2F0200-number-of-islands.kt)
|
[✔️](python%2F0200-number-of-islands.py)
|
[✔️](ruby%2F0200-number-of-islands.rb)
|
[✔️](rust%2F0200-number-of-islands.rs)
|
|
[✔️](swift%2F0200-number-of-islands.swift)
|
[✔️](typescript%2F0200-number-of-islands.ts)
-[0133 - Clone Graph](https://leetcode.com/problems/clone-graph/) |
|
[✔️](c%2F0133-clone-graph.c)
|
[✔️](cpp%2F0133-clone-graph.cpp)
|
[✔️](csharp%2F0133-clone-graph.cs)
|
|
[✔️](go%2F0133-clone-graph.go)
|
|
[✔️](java%2F0133-clone-graph.java)
|
[✔️](javascript%2F0133-clone-graph.js)
|
[✔️](kotlin%2F0133-clone-graph.kt)
|
[✔️](python%2F0133-clone-graph.py)
|
[✔️](ruby%2F0133-clone-graph.rb)
|
|
|
[✔️](swift%2F0133-clone-graph.swift)
|
[✔️](typescript%2F0133-clone-graph.ts)
-[0695 - Max Area of Island](https://leetcode.com/problems/max-area-of-island/) |
|
[✔️](c%2F0695-max-area-of-island.c)
|
[✔️](cpp%2F0695-max-area-of-island.cpp)
|
[✔️](csharp%2F0695-max-area-of-island.cs)
|
|
[✔️](go%2F0695-max-area-of-island.go)
|
|
[✔️](java%2F0695-max-area-of-island.java)
|
[✔️](javascript%2F0695-max-area-of-island.js)
|
[✔️](kotlin%2F0695-max-area-of-island.kt)
|
[✔️](python%2F0695-max-area-of-island.py)
|
|
[✔️](rust%2F0695-max-area-of-island.rs)
|
|
[✔️](swift%2F0695-max-area-of-island.swift)
|
[✔️](typescript%2F0695-max-area-of-island.ts)
-[1905 - Count Sub Islands](https://leetcode.com/problems/count-sub-islands/) |
|
[✔️](c%2F1905-Count-Sub-Islands.c)
|
[✔️](cpp%2F1905-count-sub-islands.cpp)
|
[✔️](csharp%2F1905-Count-Sub-Islands.cs)
|
|
[✔️](go%2F1905-count-sub-islands.go)
|
|
[✔️](java%2F1905-count-sub-islands.java)
|
[✔️](javascript%2F1905-count-sub-islands.js)
|
[✔️](kotlin%2F1905-count-sub-islands.kt)
|
[✔️](python%2F1905-count-sub-islands.py)
|
|
|
|
|
-[0417 - Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow/) |
|
[✔️](c%2F0417-pacific-atlantic-water-flow.c)
|
[✔️](cpp%2F0417-pacific-atlantic-water-flow.cpp)
|
[✔️](csharp%2F0417-pacific-atlantic-water-flow.cs)
|
|
[✔️](go%2F0417-pacific-atlantic-water-flow.go)
|
|
[✔️](java%2F0417-pacific-atlantic-water-flow.java)
|
[✔️](javascript%2F0417-pacific-atlantic-water-flow.js)
|
[✔️](kotlin%2F0417-pacific-atlantic-water-flow.kt)
|
[✔️](python%2F0417-pacific-atlantic-water-flow.py)
|
|
[✔️](rust%2F0417-pacific-atlantic-water-flow.rs)
|
|
[✔️](swift%2F0417-pacific-atlantic-water-flow.swift)
|
[✔️](typescript%2F0417-pacific-atlantic-water-flow.ts)
-[0130 - Surrounded Regions](https://leetcode.com/problems/surrounded-regions/) |
|
[✔️](c%2F0130-surrounded-regions.c)
|
[✔️](cpp%2F0130-surrounded-regions.cpp)
|
[✔️](csharp%2F0130-surrounded-regions.cs)
|
[✔️](dart%2F0130-surrounded-regions.dart)
|
[✔️](go%2F0130-surrounded-regions.go)
|
|
[✔️](java%2F0130-surrounded-regions.java)
|
[✔️](javascript%2F0130-surrounded-regions.js)
|
[✔️](kotlin%2F0130-surrounded-regions.kt)
|
[✔️](python%2F0130-surrounded-regions.py)
|
|
|
|
[✔️](swift%2F0130-surrounded-regions.swift)
|
[✔️](typescript%2F0130-surrounded-regions.ts)
-[1466 - Reorder Routes to Make All Paths Lead to The City Zero](https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/) |
|
|
[✔️](cpp%2F1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.cpp)
|
[✔️](csharp%2F1466-Reorder-Routes-to-Make-All-Paths-Lead-To-The-City-Zero.cs)
|
|
|
|
[✔️](java%2F1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.java)
|
|
[✔️](kotlin%2F1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.kt)
|
[✔️](python%2F1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.py)
|
|
|
|
|
-[0994 - Rotting Oranges](https://leetcode.com/problems/rotting-oranges/) |
|
[✔️](c%2F0994-rotting-oranges.c)
|
[✔️](cpp%2F0994-rotting-oranges.cpp)
|
[✔️](csharp%2F0994-rotting-oranges.cs)
|
|
[✔️](go%2F0994-rotting-oranges.go)
|
|
[✔️](java%2F0994-rotting-oranges.java)
|
[✔️](javascript%2F0994-rotting-oranges.js)
|
[✔️](kotlin%2F0994-rotting-oranges.kt)
|
[✔️](python%2F0994-rotting-oranges.py)
|
|
|
|
[✔️](swift%2F0994-rotting-oranges.swift)
|
[✔️](typescript%2F0994-rotting-oranges.ts)
-[0286 - Walls And Gates](https://leetcode.com/problems/walls-and-gates/) |
|
|
[✔️](cpp%2F0286-walls-and-gates.cpp)
|
[✔️](csharp%2F0286-walls-and-gates.cs)
|
|
|
|
[✔️](java%2F0286-walls-and-gates.java)
|
[✔️](javascript%2F0286-walls-and-gates.js)
|
[✔️](kotlin%2F0286-walls-and-gates.kt)
|
[✔️](python%2F0286-walls-and-gates.py)
|
|
|
|
[✔️](swift%2F0286-walls-and-gates.swift)
|
-[0909 - Snakes And Ladders](https://leetcode.com/problems/snakes-and-ladders/) |
|
|
|
[✔️](csharp%2F0909-snakes-and-ladders.cs)
|
|
|
|
[✔️](java%2F0909-snakes-and-ladders.java)
|
[✔️](javascript%2F0909-snakes-and-ladders.js)
|
[✔️](kotlin%2F0909-snakes-and-ladders.kt)
|
[✔️](python%2F0909-snakes-and-ladders.py)
|
|
|
|
|
-[0752 - Open The Lock](https://leetcode.com/problems/open-the-lock/) |
|
|
|
[✔️](csharp%2F0752-open-the-lock.cs)
|
|
|
|
[✔️](java%2F0752-open-the-lock.java)
|
[✔️](javascript%2F0752-open-the-lock.js)
|
[✔️](kotlin%2F0752-open-the-lock.kt)
|
[✔️](python%2F0752-open-the-lock.py)
|
|
|
|
|
-[0802 - Find Eventual Safe States](https://leetcode.com/problems/find-eventual-safe-states/) |
|
|
|
|
|
|
|
[✔️](java%2F0802-find-eventual-safe-states.java)
|
|
[✔️](kotlin%2F0802-find-eventual-safe-states.kt)
|
[✔️](python%2F0802-find-eventual-safe-states.py)
|
|
|
|
|
-[0207 - Course Schedule](https://leetcode.com/problems/course-schedule/) |
|
[✔️](c%2F0207-course-schedule.c)
|
[✔️](cpp%2F0207-course-schedule.cpp)
|
[✔️](csharp%2F0207-course-schedule.cs)
|
|
[✔️](go%2F0207-course-schedule.go)
|
|
[✔️](java%2F0207-course-schedule.java)
|
[✔️](javascript%2F0207-course-schedule.js)
|
[✔️](kotlin%2F0207-course-schedule.kt)
|
[✔️](python%2F0207-course-schedule.py)
|
|
[✔️](rust%2F0207-course-schedule.rs)
|
|
[✔️](swift%2F0207-course-schedule.swift)
|
[✔️](typescript%2F0207-course-schedule.ts)
-[0210 - Course Schedule II](https://leetcode.com/problems/course-schedule-ii/) |
|
|
[✔️](cpp%2F0210-course-schedule-ii.cpp)
|
[✔️](csharp%2F0210-course-schedule-ii.cs)
|
|
[✔️](go%2F0210-course-schedule-ii.go)
|
|
[✔️](java%2F0210-course-schedule-ii.java)
|
[✔️](javascript%2F0210-course-schedule-ii.js)
|
[✔️](kotlin%2F0210-course-schedule-ii.kt)
|
[✔️](python%2F0210-course-schedule-ii.py)
|
|
|
|
[✔️](swift%2F0210-course-schedule-ii.swift)
|
[✔️](typescript%2F0210-course-schedule-ii.ts)
-[1462 - Course Schedule IV](https://leetcode.com/problems/course-schedule-iv/) |
|
|
|
|
|
|
|
[✔️](java%2F1462-course-schedule-iv.java)
|
|
[✔️](kotlin%2F1462-course-schedule-iv.kt)
|
[✔️](python%2F1462-course-schedule-iv.py)
|
|
|
|
[✔️](swift%2F1462-course-schedule-iv.swift)
|
[✔️](typescript%2F1462-course-schedule-iv.ts)
-[1958 - Check if Move Is Legal](https://leetcode.com/problems/check-if-move-is-legal/) |
|
|
[✔️](cpp%2F1958-check-if-move-is-legal.cpp)
|
|
|
[✔️](go%2F1958-check-if-move-is-legal.go)
|
|
[✔️](java%2F1958-check-if-move-is-legal.java)
|
[✔️](javascript%2F1958-check-if-move-is-legal.js)
|
[✔️](kotlin%2F1958-check-if-move-is-legal.kt)
|
[✔️](python%2F1958-check-if-move-is-legal.py)
|
|
|
|
|
-[0934 - Shortest Bridge](https://leetcode.com/problems/shortest-bridge/) |
|
|
|
|
|
|
|
[✔️](java%2F0934-shortest-bridge.java)
|
[✔️](javascript%2F0934-shortest-bridge.js)
|
[✔️](kotlin%2F0934-shortest-bridge.kt)
|
|
|
|
|
|
-[1091 - Shortest Path in Binary Matrix](https://leetcode.com/problems/shortest-path-in-binary-matrix/) |
|
|
[✔️](cpp%2F1091-shortest-path-in-binary-matrix.cpp)
|
|
|
[✔️](go%2F1091-shortest-path-in-binary-matrix.go)
|
|
[✔️](java%2F1091-shortest-path-in-binary-matrix.java)
|
|
[✔️](kotlin%2F1091-shortest-path-in-binary-matrix.kt)
|
[✔️](python%2F1091-shortest-path-in-binary-matrix.py)
|
|
|
|
[✔️](swift%2F1091-shortest-path-in-binary-matrix.swift)
|
-[0684 - Redundant Connection](https://leetcode.com/problems/redundant-connection/) |
|
[✔️](c%2F0684-redundant-connection.c)
|
[✔️](cpp%2F0684-redundant-connection.cpp)
|
[✔️](csharp%2F0684-redundant-connection.cs)
|
|
[✔️](go%2F0684-redundant-connection.go)
|
|
[✔️](java%2F0684-redundant-connection.java)
|
[✔️](javascript%2F0684-redundant-connection.js)
|
[✔️](kotlin%2F0684-redundant-connection.kt)
|
[✔️](python%2F0684-redundant-connection.py)
|
|
[✔️](rust%2F0684-redundant-connection.rs)
|
|
[✔️](swift%2F0684-redundant-connection.swift)
|
[✔️](typescript%2F0684-redundant-connection.ts)
-[0323 - Number of Connected Components In An Undirected Graph](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/) |
|
|
[✔️](cpp%2F0323-number-of-connected-components-in-an-undirected-graph.cpp)
|
[✔️](csharp%2F0323-number-of-connected-components-in-an-undirected-graph.cs)
|
|
[✔️](go%2F0323-number-of-connected-components-in-an-undirected-graph.go)
|
|
[✔️](java%2F0323-number-of-connected-components-in-an-undirected-graph.java)
|
[✔️](javascript%2F0323-number-of-connected-components-in-an-undirected-graph.js)
|
[✔️](kotlin%2F0323-number-of-connected-components-in-an-undirected-graph.kt)
|
[✔️](python%2F0323-number-of-connected-components-in-an-undirected-graph.py)
|
|
|
|
[✔️](swift%2F0323-number-of-connected-components-in-an-undirected-graph.swift)
|
-[0261 - Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree/) |
|
|
[✔️](cpp%2F0261-graph-valid-tree.cpp)
|
[✔️](csharp%2F0261-graph-valid-tree.cs)
|
|
|
|
[✔️](java%2F0261-graph-valid-tree.java)
|
[✔️](javascript%2F0261-graph-valid-tree.js)
|
[✔️](kotlin%2F0261-graph-valid-tree.kt)
|
[✔️](python%2F0261-graph-valid-tree.py)
|
|
|
|
[✔️](swift%2F0261-graph-valid-tree.swift)
|
[✔️](typescript%2F0261-graph-valid-tree.ts)
-[0721 - Accounts Merge](https://leetcode.com/problems/accounts-merge/) |
|
|
|
|
|
|
|
[✔️](java%2F0721-accounts-merge.java)
|
|
[✔️](kotlin%2F0721-accounts-merge.kt)
|
[✔️](python%2F0721-accounts-merge.py)
|
|
|
|
[✔️](swift%2F0721-accounts-merge.swift)
|
-[2359 - Find Closest Node to Given Two Nodes](https://leetcode.com/problems/find-closest-node-to-given-two-nodes/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F2359-find-closest-node-to-given-two-nodes.kt)
|
|
|
|
|
|
-[1162 - As Far from Land as Possible](https://leetcode.com/problems/as-far-from-land-as-possible/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1162-as-far-from-land-as-possible.kt)
|
|
|
|
|
|
-[1129 - Shortest Path with Alternating Colors](https://leetcode.com/problems/shortest-path-with-alternating-colors/) |
|
|
|
|
|
|
|
[✔️](java%2F1129-shortest-path-with-alternating-colors.java)
|
|
[✔️](kotlin%2F1129-shortest-path-with-alternating-colors.kt)
|
|
|
|
|
|
-[2477 - Minimum Fuel Cost to Report to the Capital](https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/) |
|
|
|
|
|
|
|
[✔️](java%2F2477-minimum-fuel-cost-to-report-to-the-capital.java)
|
|
[✔️](kotlin%2F2477-minimum-fuel-cost-to-report-to-the-capital.kt)
|
|
|
|
|
|
-[2492 - Minimum Score of a Path Between Two Cities](https://leetcode.com/problems/minimum-score-of-a-path-between-two-cities/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F2492-minimum-score-of-a-path-between-two-cities.kt)
|
|
|
|
|
|
-[1254 - Number of Closed Islands](https://leetcode.com/problems/number-of-closed-islands/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1254-number-of-closed-islands.kt)
|
[✔️](python%2F1254-number-of-closed-islands.py)
|
|
|
|
|
-[1020 - Number of Enclaves](https://leetcode.com/problems/number-of-enclaves/) |
|
|
|
|
|
|
|
[✔️](java%2F1020-number-of-enclaves.java)
|
|
[✔️](kotlin%2F1020-number-of-enclaves.kt)
|
[✔️](python%2F1020-number-of-enclaves.py)
|
|
|
|
|
-[1557 - Minimum Number of Vertices to Reach all Nodes](https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/) |
|
|
|
|
|
|
|
[✔️](java%2F1557-minimum-number-of-vertices-to-reach-all-nodes.java)
|
|
[✔️](kotlin%2F1557-minimum-number-of-vertices-to-reach-all-nodes.kt)
|
|
|
|
|
|
-[0785 - Is Graph Bipartite?](https://leetcode.com/problems/is-graph-bipartite/) |
|
|
|
|
|
|
|
[✔️](java%2F0785-is-graph-bipartite.java)
|
|
[✔️](kotlin%2F0785-is-graph-bipartite.kt)
|
[✔️](python%2F0785-is-graph-bipartite.py)
|
|
|
|
|
-[0399 - Evaluate Division](https://leetcode.com/problems/evaluate-division/) |
|
|
[✔️](cpp%2F0399-evaluate-division.cpp)
|
|
|
|
|
[✔️](java%2F0399-evaluate-division.java)
|
|
[✔️](kotlin%2F0399-evaluate-division.kt)
|
|
|
|
|
|
-[2101 - Detonate the Maximum Bombs](https://leetcode.com/problems/detonate-the-maximum-bombs/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F2101-detonate-the-maximum-bombs.kt)
|
[✔️](python%2F2101-detonate-the-maximum-bombs.py)
|
|
|
|
|
-[1857 - Largest Color Value in a Directed Graph](https://leetcode.com/problems/largest-color-value-in-a-directed-graph/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1857-largest-color-value-in-a-directed-graph.kt)
|
|
|
[✔️](rust%2F1857-largest-color-value-in-a-directed-graph.rs)
|
|
|
-[1553 - Minimum Number of Days to Eat N Oranges](https://leetcode.com/problems/minimum-number-of-days-to-eat-n-oranges/) |
|
|
|
|
|
|
|
[✔️](java%2F1553-minimum-number-of-days-to-eat-n-oranges.java)
|
|
[✔️](kotlin%2F1553-minimum-number-of-days-to-eat-n-oranges.kt)
|
|
|
|
|
|
-[0127 - Word Ladder](https://leetcode.com/problems/word-ladder/) |
|
|
[✔️](cpp%2F0127-word-ladder.cpp)
|
[✔️](csharp%2F0127-word-ladder.cs)
|
|
[✔️](go%2F0127-word-ladder.go)
|
|
[✔️](java%2F0127-word-ladder.java)
|
[✔️](javascript%2F0127-word-ladder.js)
|
[✔️](kotlin%2F0127-word-ladder.kt)
|
[✔️](python%2F0127-word-ladder.py)
|
|
[✔️](rust%2F0127-word-ladder.rs)
|
|
[✔️](swift%2F0127-word-ladder.swift)
|
[✔️](typescript%2F0127-word-ladder.ts)
+| Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ----------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | +| [0463 - Island Perimeter](https://leetcode.com/problems/island-perimeter/) |
|
[✔️](c%2F0463-island-perimeter.c)
|
[✔️](cpp%2F0463-island-perimeter.cpp)
|
[✔️](csharp%2F0463-island-perimeter.cs)
|
|
[✔️](go%2F0463-island-perimeter.go)
|
|
[✔️](java%2F0463-island-perimeter.java)
|
[✔️](javascript%2F0463-island-perimeter.js)
|
[✔️](kotlin%2F0463-island-perimeter.kt)
|
[✔️](python%2F0463-island-perimeter.py)
|
|
|
|
|
| +| [0953 - Verifying An Alien Dictionary](https://leetcode.com/problems/verifying-an-alien-dictionary/) |
|
[✔️](c%2F0953-verifying-an-alien-dictionary.c)
|
[✔️](cpp%2F0953-verifying-an-alien-dictionary.cpp)
|
|
|
[✔️](go%2F0953-verifying-an-alien-dictionary.go)
|
|
[✔️](java%2F0953-verifying-an-alien-dictionary.java)
|
[✔️](javascript%2F0953-verifying-an-alien-dictionary.js)
|
[✔️](kotlin%2F0953-verifying-an-alien-dictionary.kt)
|
[✔️](python%2F0953-verifying-an-alien-dictionary.py)
|
|
[✔️](rust%2F0953-verifying-an-alien-dictionary.rs)
|
|
|
| +| [0200 - Number of Islands](https://leetcode.com/problems/number-of-islands/) |
|
[✔️](c%2F0200-number-of-islands.c)
|
[✔️](cpp%2F0200-number-of-islands.cpp)
|
[✔️](csharp%2F0200-number-of-islands.cs)
|
|
[✔️](go%2F0200-number-of-islands.go)
|
|
[✔️](java%2F0200-number-of-islands.java)
|
[✔️](javascript%2F0200-number-of-islands.js)
|
[✔️](kotlin%2F0200-number-of-islands.kt)
|
[✔️](python%2F0200-number-of-islands.py)
|
[✔️](ruby%2F0200-number-of-islands.rb)
|
[✔️](rust%2F0200-number-of-islands.rs)
|
|
[✔️](swift%2F0200-number-of-islands.swift)
|
[✔️](typescript%2F0200-number-of-islands.ts)
| +| [0133 - Clone Graph](https://leetcode.com/problems/clone-graph/) |
|
[✔️](c%2F0133-clone-graph.c)
|
[✔️](cpp%2F0133-clone-graph.cpp)
|
[✔️](csharp%2F0133-clone-graph.cs)
|
|
[✔️](go%2F0133-clone-graph.go)
|
|
[✔️](java%2F0133-clone-graph.java)
|
[✔️](javascript%2F0133-clone-graph.js)
|
[✔️](kotlin%2F0133-clone-graph.kt)
|
[✔️](python%2F0133-clone-graph.py)
|
[✔️](ruby%2F0133-clone-graph.rb)
|
|
|
[✔️](swift%2F0133-clone-graph.swift)
|
[✔️](typescript%2F0133-clone-graph.ts)
| +| [0695 - Max Area of Island](https://leetcode.com/problems/max-area-of-island/) |
|
[✔️](c%2F0695-max-area-of-island.c)
|
[✔️](cpp%2F0695-max-area-of-island.cpp)
|
[✔️](csharp%2F0695-max-area-of-island.cs)
|
|
[✔️](go%2F0695-max-area-of-island.go)
|
|
[✔️](java%2F0695-max-area-of-island.java)
|
[✔️](javascript%2F0695-max-area-of-island.js)
|
[✔️](kotlin%2F0695-max-area-of-island.kt)
|
[✔️](python%2F0695-max-area-of-island.py)
|
|
[✔️](rust%2F0695-max-area-of-island.rs)
|
|
[✔️](swift%2F0695-max-area-of-island.swift)
|
[✔️](typescript%2F0695-max-area-of-island.ts)
| +| [1905 - Count Sub Islands](https://leetcode.com/problems/count-sub-islands/) |
|
[✔️](c%2F1905-Count-Sub-Islands.c)
|
[✔️](cpp%2F1905-count-sub-islands.cpp)
|
[✔️](csharp%2F1905-Count-Sub-Islands.cs)
|
|
[✔️](go%2F1905-count-sub-islands.go)
|
|
[✔️](java%2F1905-count-sub-islands.java)
|
[✔️](javascript%2F1905-count-sub-islands.js)
|
[✔️](kotlin%2F1905-count-sub-islands.kt)
|
[✔️](python%2F1905-count-sub-islands.py)
|
|
|
|
|
| +| [0417 - Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow/) |
|
[✔️](c%2F0417-pacific-atlantic-water-flow.c)
|
[✔️](cpp%2F0417-pacific-atlantic-water-flow.cpp)
|
[✔️](csharp%2F0417-pacific-atlantic-water-flow.cs)
|
|
[✔️](go%2F0417-pacific-atlantic-water-flow.go)
|
|
[✔️](java%2F0417-pacific-atlantic-water-flow.java)
|
[✔️](javascript%2F0417-pacific-atlantic-water-flow.js)
|
[✔️](kotlin%2F0417-pacific-atlantic-water-flow.kt)
|
[✔️](python%2F0417-pacific-atlantic-water-flow.py)
|
|
[✔️](rust%2F0417-pacific-atlantic-water-flow.rs)
|
|
[✔️](swift%2F0417-pacific-atlantic-water-flow.swift)
|
[✔️](typescript%2F0417-pacific-atlantic-water-flow.ts)
| +| [0130 - Surrounded Regions](https://leetcode.com/problems/surrounded-regions/) |
|
[✔️](c%2F0130-surrounded-regions.c)
|
[✔️](cpp%2F0130-surrounded-regions.cpp)
|
[✔️](csharp%2F0130-surrounded-regions.cs)
|
[✔️](dart%2F0130-surrounded-regions.dart)
|
[✔️](go%2F0130-surrounded-regions.go)
|
|
[✔️](java%2F0130-surrounded-regions.java)
|
[✔️](javascript%2F0130-surrounded-regions.js)
|
[✔️](kotlin%2F0130-surrounded-regions.kt)
|
[✔️](python%2F0130-surrounded-regions.py)
|
|
|
|
[✔️](swift%2F0130-surrounded-regions.swift)
|
[✔️](typescript%2F0130-surrounded-regions.ts)
| +| [1466 - Reorder Routes to Make All Paths Lead to The City Zero](https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/) |
|
|
[✔️](cpp%2F1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.cpp)
|
[✔️](csharp%2F1466-Reorder-Routes-to-Make-All-Paths-Lead-To-The-City-Zero.cs)
|
|
|
|
[✔️](java%2F1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.java)
|
|
[✔️](kotlin%2F1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.kt)
|
[✔️](python%2F1466-reorder-routes-to-make-all-paths-lead-to-the-city-zero.py)
|
|
|
|
|
| +| [0994 - Rotting Oranges](https://leetcode.com/problems/rotting-oranges/) |
|
[✔️](c%2F0994-rotting-oranges.c)
|
[✔️](cpp%2F0994-rotting-oranges.cpp)
|
[✔️](csharp%2F0994-rotting-oranges.cs)
|
|
[✔️](go%2F0994-rotting-oranges.go)
|
|
[✔️](java%2F0994-rotting-oranges.java)
|
[✔️](javascript%2F0994-rotting-oranges.js)
|
[✔️](kotlin%2F0994-rotting-oranges.kt)
|
[✔️](python%2F0994-rotting-oranges.py)
|
|
|
|
[✔️](swift%2F0994-rotting-oranges.swift)
|
[✔️](typescript%2F0994-rotting-oranges.ts)
| +| [0286 - Walls And Gates](https://leetcode.com/problems/walls-and-gates/) |
|
|
[✔️](cpp%2F0286-walls-and-gates.cpp)
|
[✔️](csharp%2F0286-walls-and-gates.cs)
|
|
|
|
[✔️](java%2F0286-walls-and-gates.java)
|
[✔️](javascript%2F0286-walls-and-gates.js)
|
[✔️](kotlin%2F0286-walls-and-gates.kt)
|
[✔️](python%2F0286-walls-and-gates.py)
|
|
|
|
[✔️](swift%2F0286-walls-and-gates.swift)
|
| +| [0909 - Snakes And Ladders](https://leetcode.com/problems/snakes-and-ladders/) |
|
|
|
[✔️](csharp%2F0909-snakes-and-ladders.cs)
|
|
|
|
[✔️](java%2F0909-snakes-and-ladders.java)
|
[✔️](javascript%2F0909-snakes-and-ladders.js)
|
[✔️](kotlin%2F0909-snakes-and-ladders.kt)
|
[✔️](python%2F0909-snakes-and-ladders.py)
|
|
|
|
|
| +| [0752 - Open The Lock](https://leetcode.com/problems/open-the-lock/) |
|
|
|
[✔️](csharp%2F0752-open-the-lock.cs)
|
|
|
|
[✔️](java%2F0752-open-the-lock.java)
|
[✔️](javascript%2F0752-open-the-lock.js)
|
[✔️](kotlin%2F0752-open-the-lock.kt)
|
[✔️](python%2F0752-open-the-lock.py)
|
|
|
|
|
| +| [0802 - Find Eventual Safe States](https://leetcode.com/problems/find-eventual-safe-states/) |
|
|
|
|
|
|
|
[✔️](java%2F0802-find-eventual-safe-states.java)
|
|
[✔️](kotlin%2F0802-find-eventual-safe-states.kt)
|
[✔️](python%2F0802-find-eventual-safe-states.py)
|
|
|
|
|
| +| [0207 - Course Schedule](https://leetcode.com/problems/course-schedule/) |
|
[✔️](c%2F0207-course-schedule.c)
|
[✔️](cpp%2F0207-course-schedule.cpp)
|
[✔️](csharp%2F0207-course-schedule.cs)
|
|
[✔️](go%2F0207-course-schedule.go)
|
|
[✔️](java%2F0207-course-schedule.java)
|
[✔️](javascript%2F0207-course-schedule.js)
|
[✔️](kotlin%2F0207-course-schedule.kt)
|
[✔️](python%2F0207-course-schedule.py)
|
|
[✔️](rust%2F0207-course-schedule.rs)
|
|
[✔️](swift%2F0207-course-schedule.swift)
|
[✔️](typescript%2F0207-course-schedule.ts)
| +| [0210 - Course Schedule II](https://leetcode.com/problems/course-schedule-ii/) |
|
|
[✔️](cpp%2F0210-course-schedule-ii.cpp)
|
[✔️](csharp%2F0210-course-schedule-ii.cs)
|
|
[✔️](go%2F0210-course-schedule-ii.go)
|
|
[✔️](java%2F0210-course-schedule-ii.java)
|
[✔️](javascript%2F0210-course-schedule-ii.js)
|
[✔️](kotlin%2F0210-course-schedule-ii.kt)
|
[✔️](python%2F0210-course-schedule-ii.py)
|
|
|
|
[✔️](swift%2F0210-course-schedule-ii.swift)
|
[✔️](typescript%2F0210-course-schedule-ii.ts)
| +| [1462 - Course Schedule IV](https://leetcode.com/problems/course-schedule-iv/) |
|
|
|
|
|
|
|
[✔️](java%2F1462-course-schedule-iv.java)
|
|
[✔️](kotlin%2F1462-course-schedule-iv.kt)
|
[✔️](python%2F1462-course-schedule-iv.py)
|
|
|
|
[✔️](swift%2F1462-course-schedule-iv.swift)
|
[✔️](typescript%2F1462-course-schedule-iv.ts)
| +| [1958 - Check if Move Is Legal](https://leetcode.com/problems/check-if-move-is-legal/) |
|
|
[✔️](cpp%2F1958-check-if-move-is-legal.cpp)
|
|
|
[✔️](go%2F1958-check-if-move-is-legal.go)
|
|
[✔️](java%2F1958-check-if-move-is-legal.java)
|
[✔️](javascript%2F1958-check-if-move-is-legal.js)
|
[✔️](kotlin%2F1958-check-if-move-is-legal.kt)
|
[✔️](python%2F1958-check-if-move-is-legal.py)
|
|
|
|
|
| +| [0934 - Shortest Bridge](https://leetcode.com/problems/shortest-bridge/) |
|
|
|
|
|
|
|
[✔️](java%2F0934-shortest-bridge.java)
|
[✔️](javascript%2F0934-shortest-bridge.js)
|
[✔️](kotlin%2F0934-shortest-bridge.kt)
|
|
|
|
|
|
| +| [1091 - Shortest Path in Binary Matrix](https://leetcode.com/problems/shortest-path-in-binary-matrix/) |
|
|
[✔️](cpp%2F1091-shortest-path-in-binary-matrix.cpp)
|
|
|
[✔️](go%2F1091-shortest-path-in-binary-matrix.go)
|
|
[✔️](java%2F1091-shortest-path-in-binary-matrix.java)
|
|
[✔️](kotlin%2F1091-shortest-path-in-binary-matrix.kt)
|
[✔️](python%2F1091-shortest-path-in-binary-matrix.py)
|
|
|
|
[✔️](swift%2F1091-shortest-path-in-binary-matrix.swift)
|
| +| [0684 - Redundant Connection](https://leetcode.com/problems/redundant-connection/) |
|
[✔️](c%2F0684-redundant-connection.c)
|
[✔️](cpp%2F0684-redundant-connection.cpp)
|
[✔️](csharp%2F0684-redundant-connection.cs)
|
|
[✔️](go%2F0684-redundant-connection.go)
|
|
[✔️](java%2F0684-redundant-connection.java)
|
[✔️](javascript%2F0684-redundant-connection.js)
|
[✔️](kotlin%2F0684-redundant-connection.kt)
|
[✔️](python%2F0684-redundant-connection.py)
|
|
[✔️](rust%2F0684-redundant-connection.rs)
|
|
[✔️](swift%2F0684-redundant-connection.swift)
|
[✔️](typescript%2F0684-redundant-connection.ts)
| +| [0323 - Number of Connected Components In An Undirected Graph](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/) |
|
|
[✔️](cpp%2F0323-number-of-connected-components-in-an-undirected-graph.cpp)
|
[✔️](csharp%2F0323-number-of-connected-components-in-an-undirected-graph.cs)
|
|
[✔️](go%2F0323-number-of-connected-components-in-an-undirected-graph.go)
|
|
[✔️](java%2F0323-number-of-connected-components-in-an-undirected-graph.java)
|
[✔️](javascript%2F0323-number-of-connected-components-in-an-undirected-graph.js)
|
[✔️](kotlin%2F0323-number-of-connected-components-in-an-undirected-graph.kt)
|
[✔️](python%2F0323-number-of-connected-components-in-an-undirected-graph.py)
|
|
|
|
[✔️](swift%2F0323-number-of-connected-components-in-an-undirected-graph.swift)
|
| +| [0261 - Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree/) |
|
|
[✔️](cpp%2F0261-graph-valid-tree.cpp)
|
[✔️](csharp%2F0261-graph-valid-tree.cs)
|
|
|
|
[✔️](java%2F0261-graph-valid-tree.java)
|
[✔️](javascript%2F0261-graph-valid-tree.js)
|
[✔️](kotlin%2F0261-graph-valid-tree.kt)
|
[✔️](python%2F0261-graph-valid-tree.py)
|
|
|
|
[✔️](swift%2F0261-graph-valid-tree.swift)
|
[✔️](typescript%2F0261-graph-valid-tree.ts)
| +| [0721 - Accounts Merge](https://leetcode.com/problems/accounts-merge/) |
|
|
|
|
|
|
|
[✔️](java%2F0721-accounts-merge.java)
|
|
[✔️](kotlin%2F0721-accounts-merge.kt)
|
[✔️](python%2F0721-accounts-merge.py)
|
|
|
|
[✔️](swift%2F0721-accounts-merge.swift)
|
| +| [2359 - Find Closest Node to Given Two Nodes](https://leetcode.com/problems/find-closest-node-to-given-two-nodes/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F2359-find-closest-node-to-given-two-nodes.kt)
|
|
|
|
|
|
| +| [1162 - As Far from Land as Possible](https://leetcode.com/problems/as-far-from-land-as-possible/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1162-as-far-from-land-as-possible.kt)
|
|
|
|
|
|
| +| [1129 - Shortest Path with Alternating Colors](https://leetcode.com/problems/shortest-path-with-alternating-colors/) |
|
|
|
|
|
|
|
[✔️](java%2F1129-shortest-path-with-alternating-colors.java)
|
|
[✔️](kotlin%2F1129-shortest-path-with-alternating-colors.kt)
|
|
|
|
|
|
| +| [2477 - Minimum Fuel Cost to Report to the Capital](https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/) |
|
|
|
|
|
|
|
[✔️](java%2F2477-minimum-fuel-cost-to-report-to-the-capital.java)
|
|
[✔️](kotlin%2F2477-minimum-fuel-cost-to-report-to-the-capital.kt)
|
|
|
|
|
|
| +| [2492 - Minimum Score of a Path Between Two Cities](https://leetcode.com/problems/minimum-score-of-a-path-between-two-cities/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F2492-minimum-score-of-a-path-between-two-cities.kt)
|
|
|
|
|
|
| +| [1254 - Number of Closed Islands](https://leetcode.com/problems/number-of-closed-islands/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1254-number-of-closed-islands.kt)
|
[✔️](python%2F1254-number-of-closed-islands.py)
|
|
|
|
|
| +| [1020 - Number of Enclaves](https://leetcode.com/problems/number-of-enclaves/) |
|
|
|
|
|
|
|
[✔️](java%2F1020-number-of-enclaves.java)
|
|
[✔️](kotlin%2F1020-number-of-enclaves.kt)
|
[✔️](python%2F1020-number-of-enclaves.py)
|
|
|
|
|
| +| [1557 - Minimum Number of Vertices to Reach all Nodes](https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/) |
|
|
|
|
|
|
|
[✔️](java%2F1557-minimum-number-of-vertices-to-reach-all-nodes.java)
|
|
[✔️](kotlin%2F1557-minimum-number-of-vertices-to-reach-all-nodes.kt)
|
|
|
|
|
|
| +| [0785 - Is Graph Bipartite?](https://leetcode.com/problems/is-graph-bipartite/) |
|
|
|
|
|
|
|
[✔️](java%2F0785-is-graph-bipartite.java)
|
|
[✔️](kotlin%2F0785-is-graph-bipartite.kt)
|
[✔️](python%2F0785-is-graph-bipartite.py)
|
|
|
|
|
| +| [0399 - Evaluate Division](https://leetcode.com/problems/evaluate-division/) |
|
|
[✔️](cpp%2F0399-evaluate-division.cpp)
|
|
|
|
|
[✔️](java%2F0399-evaluate-division.java)
|
|
[✔️](kotlin%2F0399-evaluate-division.kt)
|
|
|
|
|
|
| +| [2101 - Detonate the Maximum Bombs](https://leetcode.com/problems/detonate-the-maximum-bombs/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F2101-detonate-the-maximum-bombs.kt)
|
[✔️](python%2F2101-detonate-the-maximum-bombs.py)
|
|
|
|
|
| +| [1857 - Largest Color Value in a Directed Graph](https://leetcode.com/problems/largest-color-value-in-a-directed-graph/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1857-largest-color-value-in-a-directed-graph.kt)
|
|
|
[✔️](rust%2F1857-largest-color-value-in-a-directed-graph.rs)
|
|
|
| +| [1553 - Minimum Number of Days to Eat N Oranges](https://leetcode.com/problems/minimum-number-of-days-to-eat-n-oranges/) |
|
|
|
|
|
|
|
[✔️](java%2F1553-minimum-number-of-days-to-eat-n-oranges.java)
|
|
[✔️](kotlin%2F1553-minimum-number-of-days-to-eat-n-oranges.kt)
|
|
|
|
|
|
| +| [0127 - Word Ladder](https://leetcode.com/problems/word-ladder/) |
|
|
[✔️](cpp%2F0127-word-ladder.cpp)
|
[✔️](csharp%2F0127-word-ladder.cs)
|
|
[✔️](go%2F0127-word-ladder.go)
|
|
[✔️](java%2F0127-word-ladder.java)
|
[✔️](javascript%2F0127-word-ladder.js)
|
[✔️](kotlin%2F0127-word-ladder.kt)
|
[✔️](python%2F0127-word-ladder.py)
|
|
[✔️](rust%2F0127-word-ladder.rs)
|
|
[✔️](swift%2F0127-word-ladder.swift)
|
[✔️](typescript%2F0127-word-ladder.ts)
| ### Advanced Graphs -Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS ----- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- -[1631 - Path with Minimum Effort](https://leetcode.com/problems/path-with-minimum-effort/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1631-path-with-minimum-effort.kt)
|
[✔️](python%2F1631-path-with-minimum-effort.py)
|
|
|
|
|
-[0332 - Reconstruct Itinerary](https://leetcode.com/problems/reconstruct-itinerary/) |
|
[✔️](c%2F0332-reconstruct-itinerary.c)
|
[✔️](cpp%2F0332-reconstruct-itinerary.cpp)
|
[✔️](csharp%2F0332-reconstruct-itinerary.cs)
|
|
[✔️](go%2F0332-reconstruct-itinerary.go)
|
|
[✔️](java%2F0332-reconstruct-itinerary.java)
|
[✔️](javascript%2F0332-reconstruct-itinerary.js)
|
[✔️](kotlin%2F0332-reconstruct-itinerary.kt)
|
[✔️](python%2F0332-reconstruct-itinerary.py)
|
|
[✔️](rust%2F0332-reconstruct-itinerary.rs)
|
|
[✔️](swift%2F0332-reconstruct-itinerary.swift)
|
-[1584 - Min Cost to Connect All Points](https://leetcode.com/problems/min-cost-to-connect-all-points/) |
|
|
[✔️](cpp%2F1584-Min-Cost-To-Connect-All-Points.cpp)
|
[✔️](csharp%2F1584-Min-Cost-to-Connect-All-Points.cs)
|
|
[✔️](go%2F1584-min-cost-to-connect-all-points.go)
|
|
[✔️](java%2F1584-Min-Cost-to-Connect-All-Points.java)
|
[✔️](javascript%2F1584-Min-Cost-to-Connect-all-Points.js)
|
[✔️](kotlin%2F1584-min-cost-to-connect-all-points.kt)
|
[✔️](python%2F1584-min-cost-to-connect-all-points.py)
|
[✔️](ruby%2F1584-Min-Cost-to-Connect-All-Points.rb)
|
|
|
[✔️](swift%2F1584-Min-Cost-to-Connect-All-Points.swift)
|
[✔️](typescript%2F1584-min-cost-to-connect-all-points.ts)
-[0743 - Network Delay Time](https://leetcode.com/problems/network-delay-time/) |
|
|
[✔️](cpp%2F0743-network-delay-time.cpp)
|
[✔️](csharp%2F0743-network-delay-time.cs)
|
|
[✔️](go%2F0743-network-delay-time.go)
|
|
[✔️](java%2F0743-network-delay-time.java)
|
[✔️](javascript%2F0743-network-delay-time.js)
|
[✔️](kotlin%2F0743-network-delay-time.kt)
|
[✔️](python%2F0743-network-delay-time.py)
|
|
|
|
[✔️](swift%2F0743-network-delay-time.swift)
|
[✔️](typescript%2F0743-network-delay-time.ts)
-[1514 - Path with Maximum Probability](https://leetcode.com/problems/path-with-maximum-probability/) |
|
|
[✔️](cpp%2F1514-path-with-maximum-probability.cpp)
|
|
|
|
|
[✔️](java%2F1514-path-with-maximum-probability.java)
|
[✔️](javascript%2F1514-path-with-maximum-probability.js)
|
[✔️](kotlin%2F1514-path-with-maximum-probability.kt)
|
[✔️](python%2F1514-path-with-maximum-probability.py)
|
|
|
|
[✔️](swift%2F1514-path-with-maximum-probability.swift)
|
[✔️](typescript%2F1514-path-with-maximum-probability.ts)
-[0778 - Swim In Rising Water](https://leetcode.com/problems/swim-in-rising-water/) |
|
|
[✔️](cpp%2F0778-swim-in-rising-water.cpp)
|
[✔️](csharp%2F0778-swim-in-rising-water.cs)
|
|
[✔️](go%2F0778-swim-in-rising-water.go)
|
|
[✔️](java%2F0778-swim-in-rising-water.java)
|
[✔️](javascript%2F0778-swim-in-rising-water.js)
|
[✔️](kotlin%2F0778-swim-in-rising-water.kt)
|
[✔️](python%2F0778-swim-in-rising-water.py)
|
|
[✔️](rust%2F0778-swim-in-rising-water.rs)
|
|
[✔️](swift%2F0778-swim-in-rising-water.swift)
|
[✔️](typescript%2F0778-swim-in-rising-water.ts)
-[0269 - Alien Dictionary](https://leetcode.com/problems/alien-dictionary/) |
|
|
[✔️](cpp%2F0269-alien-dictionary.cpp)
|
[✔️](csharp%2F0269-alien-dictionary.cs)
|
|
|
|
[✔️](java%2F0269-alien-dictionary.java)
|
[✔️](javascript%2F0269-alien-dictionary.js)
|
|
[✔️](python%2F0269-alien-dictionary.py)
|
|
|
|
[✔️](swift%2F0269-alien-dictionary.swift)
|
-[0787 - Cheapest Flights Within K Stops](https://leetcode.com/problems/cheapest-flights-within-k-stops/) |
|
|
[✔️](cpp%2F0787-cheapest-flights-within-k-stops.cpp)
|
[✔️](csharp%2F0787-cheapest-flights-within-k-stops.cs)
|
|
[✔️](go%2F0787-cheapest-flights-within-k-stops.go)
|
|
[✔️](java%2F0787-cheapest-flights-within-k-stops.java)
|
[✔️](javascript%2F0787-cheapest-flights-within-k-stops.js)
|
[✔️](kotlin%2F0787-cheapest-flights-within-k-stops.kt)
|
[✔️](python%2F0787-cheapest-flights-within-k-stops.py)
|
|
|
|
[✔️](swift%2F0787-cheapest-flights-within-k-stops.swift)
|
[✔️](typescript%2F0787-cheapest-flights-within-k-stops.ts)
-[2421 - Number of Good Paths](https://leetcode.com/problems/number-of-good-paths/) |
|
|
|
|
|
[✔️](go%2F2421-number-of-good-paths.go)
|
|
|
[✔️](javascript%2F2421-number-of-good-paths.js)
|
[✔️](kotlin%2F2421-number-of-good-paths.kt)
|
|
|
[✔️](rust%2F2421-number-of-good-paths.rs)
|
|
|
[✔️](typescript%2F2421-number-of-good-paths.ts)
-[1579 - Remove Max Number of Edges to Keep Graph Fully Traversable](https://leetcode.com/problems/remove-max-number-of-edges-to-keep-graph-fully-traversable/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1579-remove-max-number-of-edges-to-keep-graph-fully-traversable.kt)
|
|
|
|
|
|
-[1489 - Find Critical and Pseudo Critical Edges in Minimum Spanning Tree](https://leetcode.com/problems/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.kt)
|
[✔️](python%2F1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.py)
|
|
|
|
[✔️](swift%2F1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.swift)
|
[✔️](typescript%2F1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.ts)
+| Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | --------------------------------------- | --------------------------------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------- | +| [1631 - Path with Minimum Effort](https://leetcode.com/problems/path-with-minimum-effort/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1631-path-with-minimum-effort.kt)
|
[✔️](python%2F1631-path-with-minimum-effort.py)
|
|
|
|
|
| +| [0332 - Reconstruct Itinerary](https://leetcode.com/problems/reconstruct-itinerary/) |
|
[✔️](c%2F0332-reconstruct-itinerary.c)
|
[✔️](cpp%2F0332-reconstruct-itinerary.cpp)
|
[✔️](csharp%2F0332-reconstruct-itinerary.cs)
|
|
[✔️](go%2F0332-reconstruct-itinerary.go)
|
|
[✔️](java%2F0332-reconstruct-itinerary.java)
|
[✔️](javascript%2F0332-reconstruct-itinerary.js)
|
[✔️](kotlin%2F0332-reconstruct-itinerary.kt)
|
[✔️](python%2F0332-reconstruct-itinerary.py)
|
|
[✔️](rust%2F0332-reconstruct-itinerary.rs)
|
|
[✔️](swift%2F0332-reconstruct-itinerary.swift)
|
| +| [1584 - Min Cost to Connect All Points](https://leetcode.com/problems/min-cost-to-connect-all-points/) |
|
|
[✔️](cpp%2F1584-Min-Cost-To-Connect-All-Points.cpp)
|
[✔️](csharp%2F1584-Min-Cost-to-Connect-All-Points.cs)
|
|
[✔️](go%2F1584-min-cost-to-connect-all-points.go)
|
|
[✔️](java%2F1584-Min-Cost-to-Connect-All-Points.java)
|
[✔️](javascript%2F1584-Min-Cost-to-Connect-all-Points.js)
|
[✔️](kotlin%2F1584-min-cost-to-connect-all-points.kt)
|
[✔️](python%2F1584-min-cost-to-connect-all-points.py)
|
[✔️](ruby%2F1584-Min-Cost-to-Connect-All-Points.rb)
|
|
|
[✔️](swift%2F1584-Min-Cost-to-Connect-All-Points.swift)
|
[✔️](typescript%2F1584-min-cost-to-connect-all-points.ts)
| +| [0743 - Network Delay Time](https://leetcode.com/problems/network-delay-time/) |
|
|
[✔️](cpp%2F0743-network-delay-time.cpp)
|
[✔️](csharp%2F0743-network-delay-time.cs)
|
|
[✔️](go%2F0743-network-delay-time.go)
|
|
[✔️](java%2F0743-network-delay-time.java)
|
[✔️](javascript%2F0743-network-delay-time.js)
|
[✔️](kotlin%2F0743-network-delay-time.kt)
|
[✔️](python%2F0743-network-delay-time.py)
|
|
|
|
[✔️](swift%2F0743-network-delay-time.swift)
|
[✔️](typescript%2F0743-network-delay-time.ts)
| +| [1514 - Path with Maximum Probability](https://leetcode.com/problems/path-with-maximum-probability/) |
|
|
[✔️](cpp%2F1514-path-with-maximum-probability.cpp)
|
|
|
|
|
[✔️](java%2F1514-path-with-maximum-probability.java)
|
[✔️](javascript%2F1514-path-with-maximum-probability.js)
|
[✔️](kotlin%2F1514-path-with-maximum-probability.kt)
|
[✔️](python%2F1514-path-with-maximum-probability.py)
|
|
|
|
[✔️](swift%2F1514-path-with-maximum-probability.swift)
|
[✔️](typescript%2F1514-path-with-maximum-probability.ts)
| +| [0778 - Swim In Rising Water](https://leetcode.com/problems/swim-in-rising-water/) |
|
|
[✔️](cpp%2F0778-swim-in-rising-water.cpp)
|
[✔️](csharp%2F0778-swim-in-rising-water.cs)
|
|
[✔️](go%2F0778-swim-in-rising-water.go)
|
|
[✔️](java%2F0778-swim-in-rising-water.java)
|
[✔️](javascript%2F0778-swim-in-rising-water.js)
|
[✔️](kotlin%2F0778-swim-in-rising-water.kt)
|
[✔️](python%2F0778-swim-in-rising-water.py)
|
|
[✔️](rust%2F0778-swim-in-rising-water.rs)
|
|
[✔️](swift%2F0778-swim-in-rising-water.swift)
|
[✔️](typescript%2F0778-swim-in-rising-water.ts)
| +| [0269 - Alien Dictionary](https://leetcode.com/problems/alien-dictionary/) |
|
|
[✔️](cpp%2F0269-alien-dictionary.cpp)
|
[✔️](csharp%2F0269-alien-dictionary.cs)
|
|
|
|
[✔️](java%2F0269-alien-dictionary.java)
|
[✔️](javascript%2F0269-alien-dictionary.js)
|
|
[✔️](python%2F0269-alien-dictionary.py)
|
|
|
|
[✔️](swift%2F0269-alien-dictionary.swift)
|
| +| [0787 - Cheapest Flights Within K Stops](https://leetcode.com/problems/cheapest-flights-within-k-stops/) |
|
|
[✔️](cpp%2F0787-cheapest-flights-within-k-stops.cpp)
|
[✔️](csharp%2F0787-cheapest-flights-within-k-stops.cs)
|
|
[✔️](go%2F0787-cheapest-flights-within-k-stops.go)
|
|
[✔️](java%2F0787-cheapest-flights-within-k-stops.java)
|
[✔️](javascript%2F0787-cheapest-flights-within-k-stops.js)
|
[✔️](kotlin%2F0787-cheapest-flights-within-k-stops.kt)
|
[✔️](python%2F0787-cheapest-flights-within-k-stops.py)
|
|
|
|
[✔️](swift%2F0787-cheapest-flights-within-k-stops.swift)
|
[✔️](typescript%2F0787-cheapest-flights-within-k-stops.ts)
| +| [2421 - Number of Good Paths](https://leetcode.com/problems/number-of-good-paths/) |
|
|
|
|
|
[✔️](go%2F2421-number-of-good-paths.go)
|
|
|
[✔️](javascript%2F2421-number-of-good-paths.js)
|
[✔️](kotlin%2F2421-number-of-good-paths.kt)
|
|
|
[✔️](rust%2F2421-number-of-good-paths.rs)
|
|
|
[✔️](typescript%2F2421-number-of-good-paths.ts)
| +| [1579 - Remove Max Number of Edges to Keep Graph Fully Traversable](https://leetcode.com/problems/remove-max-number-of-edges-to-keep-graph-fully-traversable/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1579-remove-max-number-of-edges-to-keep-graph-fully-traversable.kt)
|
|
|
|
|
|
| +| [1489 - Find Critical and Pseudo Critical Edges in Minimum Spanning Tree](https://leetcode.com/problems/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.kt)
|
[✔️](python%2F1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.py)
|
|
|
|
[✔️](swift%2F1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.swift)
|
[✔️](typescript%2F1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.ts)
| ### 1-D Dynamic Programming -Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS ----- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- -[0070 - Climbing Stairs](https://leetcode.com/problems/climbing-stairs/) |
|
[✔️](c%2F0070-climbing-stairs.c)
|
[✔️](cpp%2F0070-climbing-stairs.cpp)
|
[✔️](csharp%2F0070-climbing-stairs.cs)
|
[✔️](dart%2F0070-climbing-stairs.dart)
|
[✔️](go%2F0070-climbing-stairs.go)
|
|
[✔️](java%2F0070-climbing-stairs.java)
|
[✔️](javascript%2F0070-climbing-stairs.js)
|
[✔️](kotlin%2F0070-climbing-stairs.kt)
|
[✔️](python%2F0070-climbing-stairs.py)
|
[✔️](ruby%2F0070-climbing-stairs.rb)
|
[✔️](rust%2F0070-climbing-stairs.rs)
|
[✔️](scala%2F0070-climbing-stairs.scala)
|
[✔️](swift%2F0070-climbing-stairs.swift)
|
[✔️](typescript%2F0070-climbing-stairs.ts)
-[0746 - Min Cost Climbing Stairs](https://leetcode.com/problems/min-cost-climbing-stairs/) |
|
[✔️](c%2F0746-min-cost-climbing-stairs.c)
|
[✔️](cpp%2F0746-min-cost-climbing-stairs.cpp)
|
[✔️](csharp%2F0746-min-cost-climbing-stairs.cs)
|
[✔️](dart%2F0746-min-cost-climbing-stairs.dart)
|
[✔️](go%2F0746-min-cost-climbing-stairs.go)
|
|
[✔️](java%2F0746-min-cost-climbing-stairs.java)
|
[✔️](javascript%2F0746-min-cost-climbing-stairs.js)
|
[✔️](kotlin%2F0746-min-cost-climbing-stairs.kt)
|
[✔️](python%2F0746-min-cost-climbing-stairs.py)
|
[✔️](ruby%2F0746-min-cost-climbing-stairs.rb)
|
[✔️](rust%2F0746-min-cost-climbing-stairs.rs)
|
[✔️](scala%2F0746-min-cost-climbing-stairs.scala)
|
[✔️](swift%2F0746-min-cost-climbing-stairs.swift)
|
[✔️](typescript%2F0746-min-cost-climbing-stairs.ts)
-[0198 - House Robber](https://leetcode.com/problems/house-robber/) |
|
[✔️](c%2F0198-house-robber.c)
|
[✔️](cpp%2F0198-house-robber.cpp)
|
[✔️](csharp%2F0198-house-robber.cs)
|
|
[✔️](go%2F0198-house-robber.go)
|
|
[✔️](java%2F0198-house-robber.java)
|
[✔️](javascript%2F0198-house-robber.js)
|
[✔️](kotlin%2F0198-house-robber.kt)
|
[✔️](python%2F0198-house-robber.py)
|
[✔️](ruby%2F0198-house-robber.rb)
|
[✔️](rust%2F0198-house-robber.rs)
|
[✔️](scala%2F0198-house-robber.scala)
|
[✔️](swift%2F0198-house-robber.swift)
|
[✔️](typescript%2F0198-house-robber.ts)
-[0213 - House Robber II](https://leetcode.com/problems/house-robber-ii/) |
|
[✔️](c%2F0213-house-robber-ii.c)
|
[✔️](cpp%2F0213-house-robber-ii.cpp)
|
[✔️](csharp%2F0213-house-robber-ii.cs)
|
|
[✔️](go%2F0213-house-robber-ii.go)
|
|
[✔️](java%2F0213-house-robber-ii.java)
|
[✔️](javascript%2F0213-house-robber-ii.js)
|
[✔️](kotlin%2F0213-house-robber-ii.kt)
|
[✔️](python%2F0213-house-robber-ii.py)
|
[✔️](ruby%2F0213-house-robber-ii.rb)
|
[✔️](rust%2F0213-house-robber-ii.rs)
|
[✔️](scala%2F0213-house-robber-ii.scala)
|
[✔️](swift%2F0213-house-robber-ii.swift)
|
[✔️](typescript%2F0213-house-robber-ii.ts)
-[0005 - Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) |
|
[✔️](c%2F0005-longest-palindromic-substring.c)
|
[✔️](cpp%2F0005-longest-palindromic-substring.cpp)
|
[✔️](csharp%2F0005-longest-palindromic-substring.cs)
|
|
[✔️](go%2F0005-Longest-Palindromic-Substring.go)
|
|
[✔️](java%2F0005-longest-palindromic-substring.java)
|
[✔️](javascript%2F0005-longest-palindromic-substring.js)
|
[✔️](kotlin%2F0005-longest-palindromic-substring.kt)
|
[✔️](python%2F0005-longest-palindromic-substring.py)
|
|
[✔️](rust%2F0005-longest-palindromic-substring.rs)
|
|
[✔️](swift%2F0005-longest-palindromic-substring.swift)
|
[✔️](typescript%2F0005-longest-palindromic-substring.ts)
-[0647 - Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/) |
|
[✔️](c%2F0647-palindromic-substrings.c)
|
[✔️](cpp%2F0647-palindromic-substrings.cpp)
|
[✔️](csharp%2F0647-palindromic-substrings.cs)
|
|
[✔️](go%2F0647-palindromic-substrings.go)
|
|
[✔️](java%2F0647-palindromic-substrings.java)
|
[✔️](javascript%2F0647-palindromic-substrings.js)
|
[✔️](kotlin%2F0647-palindromic-substrings.kt)
|
[✔️](python%2F0647-palindromic-substrings.py)
|
|
[✔️](rust%2F0647-palindromic-substrings.rs)
|
|
[✔️](swift%2F0647-palindromic-substrings.swift)
|
[✔️](typescript%2F0647-palindromic-substrings.ts)
-[0091 - Decode Ways](https://leetcode.com/problems/decode-ways/) |
|
[✔️](c%2F0091-decode-ways.c)
|
[✔️](cpp%2F0091-decode-ways.cpp)
|
[✔️](csharp%2F0091-decode-ways.cs)
|
|
[✔️](go%2F0091-decode-ways.go)
|
|
[✔️](java%2F0091-decode-ways.java)
|
[✔️](javascript%2F0091-decode-ways.js)
|
[✔️](kotlin%2F0091-decode-ways.kt)
|
[✔️](python%2F0091-decode-ways.py)
|
|
[✔️](rust%2F0091-decode-ways.rs)
|
[✔️](scala%2F0091-decode-ways.scala)
|
[✔️](swift%2F0091-decode-ways.swift)
|
[✔️](typescript%2F0091-decode-ways.ts)
-[0322 - Coin Change](https://leetcode.com/problems/coin-change/) |
|
[✔️](c%2F0322-coin-change.c)
|
[✔️](cpp%2F0322-coin-change.cpp)
|
[✔️](csharp%2F0322-coin-change.cs)
|
|
[✔️](go%2F0322-coin-change.go)
|
|
[✔️](java%2F0322-coin-change.java)
|
[✔️](javascript%2F0322-coin-change.js)
|
[✔️](kotlin%2F0322-coin-change.kt)
|
[✔️](python%2F0322-coin-change.py)
|
|
[✔️](rust%2F0322-coin-change.rs)
|
[✔️](scala%2F0322-coin-change.scala)
|
[✔️](swift%2F0322-coin-change.swift)
|
[✔️](typescript%2F0322-coin-change.ts)
-[0152 - Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/) |
|
[✔️](c%2F0152-maximum-product-subarray.c)
|
[✔️](cpp%2F0152-maximum-product-subarray.cpp)
|
[✔️](csharp%2F0152-maximum-product-subarray.cs)
|
|
[✔️](go%2F0152-maximum-product-subarray.go)
|
|
[✔️](java%2F0152-maximum-product-subarray.java)
|
[✔️](javascript%2F0152-maximum-product-subarray.js)
|
[✔️](kotlin%2F0152-maximum-product-subarray.kt)
|
[✔️](python%2F0152-maximum-product-subarray.py)
|
[✔️](ruby%2F0152-maximum-product-subarray.rb)
|
[✔️](rust%2F0152-maximum-product-subarray.rs)
|
|
[✔️](swift%2F0152-maximum-product-subarray.swift)
|
[✔️](typescript%2F0152-maximum-product-subarray.ts)
-[0139 - Word Break](https://leetcode.com/problems/word-break/) |
|
|
[✔️](cpp%2F0139-word-break.cpp)
|
[✔️](csharp%2F0139-word-break.cs)
|
|
[✔️](go%2F0139-word-break.go)
|
|
[✔️](java%2F0139-word-break.java)
|
[✔️](javascript%2F0139-word-break.js)
|
[✔️](kotlin%2F0139-word-break.kt)
|
[✔️](python%2F0139-word-break.py)
|
|
|
|
[✔️](swift%2F0139-word-break.swift)
|
[✔️](typescript%2F0139-word-break.ts)
-[0300 - Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/) |
|
[✔️](c%2F0300-longest-increasing-subsequence.c)
|
[✔️](cpp%2F0300-longest-increasing-subsequence.cpp)
|
[✔️](csharp%2F0300-longest-increasing-subsequence.cs)
|
|
[✔️](go%2F0300-longest-increasing-subsequence.go)
|
|
[✔️](java%2F0300-longest-increasing-subsequence.java)
|
[✔️](javascript%2F0300-longest-increasing-subsequence.js)
|
[✔️](kotlin%2F0300-longest-increasing-subsequence.kt)
|
[✔️](python%2F0300-longest-increasing-subsequence.py)
|
|
[✔️](rust%2F0300-longest-increasing-subsequence.rs)
|
|
[✔️](swift%2F0300-longest-increasing-subsequence.swift)
|
[✔️](typescript%2F0300-longest-increasing-subsequence.ts)
-[0416 - Partition Equal Subset Sum](https://leetcode.com/problems/partition-equal-subset-sum/) |
|
[✔️](c%2F0416-partition-equal-subset-sum.c)
|
[✔️](cpp%2F0416-partition-equal-subset-sum.cpp)
|
[✔️](csharp%2F0416-partition-equal-subset-sum.cs)
|
|
[✔️](go%2F0416-partition-equal-subset-sum.go)
|
|
[✔️](java%2F0416-partition-equal-subset-sum.java)
|
[✔️](javascript%2F0416-partition-equal-subset-sum.js)
|
[✔️](kotlin%2F0416-partition-equal-subset-sum.kt)
|
[✔️](python%2F0416-partition-equal-subset-sum.py)
|
|
|
|
[✔️](swift%2F0416-partition-equal-subset-sum.swift)
|
-[0120 - Triangle](https://leetcode.com/problems/triangle/) |
|
[✔️](c%2F0120-triangle.c)
|
[✔️](cpp%2F0120-triangle.cpp)
|
|
|
|
|
[✔️](java%2F0120-triangle.java)
|
|
[✔️](kotlin%2F0120-triangle.kt)
|
[✔️](python%2F0120-triangle.py)
|
|
|
|
|
-[0740 - Delete And Earn](https://leetcode.com/problems/delete-and-earn/) |
|
[✔️](c%2F0740-delete-and-earn.c)
|
[✔️](cpp%2F0740-delete-and-earn.cpp)
|
|
|
[✔️](go%2F0740-delete-and-earn.go)
|
|
[✔️](java%2F0740-delete-and-earn.java)
|
|
[✔️](kotlin%2F0740-delete-and-earn.kt)
|
[✔️](python%2F0740-delete-and-earn.py)
|
|
|
|
|
-[0256 - Paint House](https://leetcode.com/problems/paint-house/) |
|
|
|
[✔️](csharp%2F0256-paint-house.cs)
|
|
|
|
[✔️](java%2F0256-paint-house.java)
|
|
|
|
|
|
|
|
[✔️](typescript%2F0256-paint-house.ts)
-[0377 - Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/) |
|
[✔️](c%2F0377-combination-sum-iv.c)
|
[✔️](cpp%2F0377-combination-sum-iv.cpp)
|
|
|
|
|
[✔️](java%2F0377-combination-sum-iv.java)
|
|
[✔️](kotlin%2F0377-combination-sum-iv.kt)
|
[✔️](python%2F0377-combination-sum-iv.py)
|
|
|
|
|
-[0279 - Perfect Squares](https://leetcode.com/problems/perfect-squares/) |
|
[✔️](c%2F0279-perfect-squares.c)
|
[✔️](cpp%2F0279-perfect-squares.cpp)
|
|
|
[✔️](go%2F0279-perfect-squares.go)
|
|
[✔️](java%2F0279-perfect-squares.java)
|
|
[✔️](kotlin%2F0279-perfect-squares.kt)
|
|
|
|
|
|
-[2369 - Check if There is a Valid Partition For The Array](https://leetcode.com/problems/check-if-there-is-a-valid-partition-for-the-array/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F2369-check-if-there-is-a-valid-partition-for-the-array.kt)
|
|
|
|
|
|
-[1856 - Maximum Subarray Min Product](https://leetcode.com/problems/maximum-subarray-min-product/) |
|
[✔️](c%2F1856-maximum-subarray-min-product.c)
|
|
|
|
|
|
[✔️](java%2F1856-maximum-subarray-min-product.java)
|
|
[✔️](kotlin%2F1856-maximum-subarray-min-product.kt)
|
|
|
|
|
|
-[0983 - Minimum Cost For Tickets](https://leetcode.com/problems/minimum-cost-for-tickets/) |
|
[✔️](c%2F0983-minimum-cost-for-tickets.c)
|
[✔️](cpp%2F0983-minimum-cost-for-tickets.cpp)
|
|
|
|
|
|
|
[✔️](kotlin%2F0983-minimum-cost-for-tickets.kt)
|
|
|
|
|
[✔️](swift%2F0983-minimum-cost-for-tickets.swift)
|
[✔️](typescript%2F0983-minimum-cost-for-tickets.ts)
-[0343 - Integer Break](https://leetcode.com/problems/integer-break/) |
|
[✔️](c%2F0343-integer-break.c)
|
[✔️](cpp%2F0343-integer-break.cpp)
|
|
|
|
|
[✔️](java%2F0343-integer-break.java)
|
|
[✔️](kotlin%2F0343-integer-break.kt)
|
|
|
|
|
|
-[0673 - Number of Longest Increasing Subsequence](https://leetcode.com/problems/number-of-longest-increasing-subsequence/) |
|
[✔️](c%2F0673-number-of-longest-increasing-subsequence.c)
|
|
|
|
|
|
[✔️](java%2F0673-number-of-longest-increasing-subsequence.java)
|
|
[✔️](kotlin%2F0673-number-of-longest-increasing-subsequence.kt)
|
[✔️](python%2F0673-number-of-longest-increasing-subsequence.py)
|
|
|
|
|
-[0691 - Stickers to Spell Word](https://leetcode.com/problems/stickers-to-spell-word/) |
|
[✔️](c%2F0691-stickers-to-spell-word.c)
|
|
|
|
|
|
|
|
[✔️](kotlin%2F0691-stickers-to-spell-word.kt)
|
|
|
|
|
|
-[1137 - N-th Tribonacci Number](https://leetcode.com/problems/n-th-tribonacci-number/) |
|
[✔️](c%2F1137-n-th-tribonacci-number.c)
|
[✔️](cpp%2F1137-n-th-tribonacci-number.cpp)
|
[✔️](csharp%2F1137-n-th-tribonacci-number.cs)
|
|
[✔️](go%2F1137-n-th-tribonacci-number.go)
|
|
|
[✔️](javascript%2F1137-n-th-tribonacci-number.js)
|
[✔️](kotlin%2F1137-n-th-tribonacci-number.kt)
|
[✔️](python%2F1137-n-th-tribonacci-number.py)
|
|
[✔️](rust%2F1137-n-th-tribonacci-number.rs)
|
|
|
[✔️](typescript%2F1137-n-th-tribonacci-number.ts)
-[1035 - Uncrossed Lines](https://leetcode.com/problems/uncrossed-lines/) |
|
[✔️](c%2F1035-uncrossed-lines.c)
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1035-uncrossed-lines.kt)
|
|
|
|
|
|
-[2140 - Solving Questions With Brainpower](https://leetcode.com/problems/solving-questions-with-brainpower/) |
|
[✔️](c%2F2140-solving-questions-with-brainpower.c)
|
[✔️](cpp%2F2140-solving-questions-with-brainpower.cpp)
|
|
|
|
|
|
|
[✔️](kotlin%2F2140-solving-questions-with-brainpower.kt)
|
|
|
|
|
|
-[2466 - Count Ways to Build Good Strings](https://leetcode.com/problems/count-ways-to-build-good-strings/) |
|
[✔️](c%2F2466-count-ways-to-build-good-strings.c)
|
|
|
|
|
|
|
|
[✔️](kotlin%2F2466-count-ways-to-build-good-strings.kt)
|
|
|
|
|
|
-[0837 - New 21 Game](https://leetcode.com/problems/new-21-game/) |
|
[✔️](c%2F0837-new-21-game.c)
|
|
|
|
|
|
[✔️](java%2F0837-new-21-game.java)
|
[✔️](javascript%2F0837-new-21-game.js)
|
[✔️](kotlin%2F0837-new-21-game.kt)
|
|
|
|
|
|
-[1626 - Best Team with no Conflicts](https://leetcode.com/problems/best-team-with-no-conflicts/) |
|
[✔️](c%2F1626-best-team-with-no-conflicts.c)
|
|
|
|
|
|
[✔️](java%2F1626-best-team-with-no-conflicts.java)
|
|
[✔️](kotlin%2F1626-best-team-with-no-conflicts.kt)
|
|
|
|
|
|
-[1406 - Stone Game III](https://leetcode.com/problems/stone-game-iii/) |
|
[✔️](c%2F1406-stone-game-iii.c)
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1406-stone-game-iii.kt)
|
|
|
|
|
|
-[0472 - Concatenated Words](https://leetcode.com/problems/concatenated-words/) |
|
|
|
|
|
[✔️](go%2F0472-concatenated-words.go)
|
|
|
[✔️](javascript%2F0472-concatenated-words.js)
|
[✔️](kotlin%2F0472-concatenated-words.kt)
|
|
|
[✔️](rust%2F0472-concatenated-words.rs)
|
|
|
[✔️](typescript%2F0472-concatenated-words.ts)
-[1799 - Maximize Score after N Operations](https://leetcode.com/problems/maximize-score-after-n-operations/) |
|
[✔️](c%2F1799-maximize-score-after-n-operations.c)
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1799-maximize-score-after-n-operations.kt)
|
|
|
|
|
|
-[1964 - Find the Longest Valid Obstacle Course at Each Position](https://leetcode.com/problems/find-the-longest-valid-obstacle-course-at-each-position/) |
|
[✔️](c%2F1964-find-the-longest-valid-obstacle-course-at-each-position.c)
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1964-find-the-longest-valid-obstacle-course-at-each-position.kt)
|
|
|
|
|
|
-[1359 - Count all Valid Pickup and Delivery Options](https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/) |
|
|
|
|
|
|
|
[✔️](java%2F1359-count-all-valid-pickup-and-delivery-options.java)
|
|
[✔️](kotlin%2F1359-count-all-valid-pickup-and-delivery-options.kt)
|
|
|
|
|
|
+| Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | +| [0070 - Climbing Stairs](https://leetcode.com/problems/climbing-stairs/) |
|
[✔️](c%2F0070-climbing-stairs.c)
|
[✔️](cpp%2F0070-climbing-stairs.cpp)
|
[✔️](csharp%2F0070-climbing-stairs.cs)
|
[✔️](dart%2F0070-climbing-stairs.dart)
|
[✔️](go%2F0070-climbing-stairs.go)
|
|
[✔️](java%2F0070-climbing-stairs.java)
|
[✔️](javascript%2F0070-climbing-stairs.js)
|
[✔️](kotlin%2F0070-climbing-stairs.kt)
|
[✔️](python%2F0070-climbing-stairs.py)
|
[✔️](ruby%2F0070-climbing-stairs.rb)
|
[✔️](rust%2F0070-climbing-stairs.rs)
|
[✔️](scala%2F0070-climbing-stairs.scala)
|
[✔️](swift%2F0070-climbing-stairs.swift)
|
[✔️](typescript%2F0070-climbing-stairs.ts)
| +| [0746 - Min Cost Climbing Stairs](https://leetcode.com/problems/min-cost-climbing-stairs/) |
|
[✔️](c%2F0746-min-cost-climbing-stairs.c)
|
[✔️](cpp%2F0746-min-cost-climbing-stairs.cpp)
|
[✔️](csharp%2F0746-min-cost-climbing-stairs.cs)
|
[✔️](dart%2F0746-min-cost-climbing-stairs.dart)
|
[✔️](go%2F0746-min-cost-climbing-stairs.go)
|
|
[✔️](java%2F0746-min-cost-climbing-stairs.java)
|
[✔️](javascript%2F0746-min-cost-climbing-stairs.js)
|
[✔️](kotlin%2F0746-min-cost-climbing-stairs.kt)
|
[✔️](python%2F0746-min-cost-climbing-stairs.py)
|
[✔️](ruby%2F0746-min-cost-climbing-stairs.rb)
|
[✔️](rust%2F0746-min-cost-climbing-stairs.rs)
|
[✔️](scala%2F0746-min-cost-climbing-stairs.scala)
|
[✔️](swift%2F0746-min-cost-climbing-stairs.swift)
|
[✔️](typescript%2F0746-min-cost-climbing-stairs.ts)
| +| [0198 - House Robber](https://leetcode.com/problems/house-robber/) |
|
[✔️](c%2F0198-house-robber.c)
|
[✔️](cpp%2F0198-house-robber.cpp)
|
[✔️](csharp%2F0198-house-robber.cs)
|
|
[✔️](go%2F0198-house-robber.go)
|
|
[✔️](java%2F0198-house-robber.java)
|
[✔️](javascript%2F0198-house-robber.js)
|
[✔️](kotlin%2F0198-house-robber.kt)
|
[✔️](python%2F0198-house-robber.py)
|
[✔️](ruby%2F0198-house-robber.rb)
|
[✔️](rust%2F0198-house-robber.rs)
|
[✔️](scala%2F0198-house-robber.scala)
|
[✔️](swift%2F0198-house-robber.swift)
|
[✔️](typescript%2F0198-house-robber.ts)
| +| [0213 - House Robber II](https://leetcode.com/problems/house-robber-ii/) |
|
[✔️](c%2F0213-house-robber-ii.c)
|
[✔️](cpp%2F0213-house-robber-ii.cpp)
|
[✔️](csharp%2F0213-house-robber-ii.cs)
|
|
[✔️](go%2F0213-house-robber-ii.go)
|
|
[✔️](java%2F0213-house-robber-ii.java)
|
[✔️](javascript%2F0213-house-robber-ii.js)
|
[✔️](kotlin%2F0213-house-robber-ii.kt)
|
[✔️](python%2F0213-house-robber-ii.py)
|
[✔️](ruby%2F0213-house-robber-ii.rb)
|
[✔️](rust%2F0213-house-robber-ii.rs)
|
[✔️](scala%2F0213-house-robber-ii.scala)
|
[✔️](swift%2F0213-house-robber-ii.swift)
|
[✔️](typescript%2F0213-house-robber-ii.ts)
| +| [0005 - Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/) |
|
[✔️](c%2F0005-longest-palindromic-substring.c)
|
[✔️](cpp%2F0005-longest-palindromic-substring.cpp)
|
[✔️](csharp%2F0005-longest-palindromic-substring.cs)
|
|
[✔️](go%2F0005-Longest-Palindromic-Substring.go)
|
|
[✔️](java%2F0005-longest-palindromic-substring.java)
|
[✔️](javascript%2F0005-longest-palindromic-substring.js)
|
[✔️](kotlin%2F0005-longest-palindromic-substring.kt)
|
[✔️](python%2F0005-longest-palindromic-substring.py)
|
|
[✔️](rust%2F0005-longest-palindromic-substring.rs)
|
|
[✔️](swift%2F0005-longest-palindromic-substring.swift)
|
[✔️](typescript%2F0005-longest-palindromic-substring.ts)
| +| [0647 - Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/) |
|
[✔️](c%2F0647-palindromic-substrings.c)
|
[✔️](cpp%2F0647-palindromic-substrings.cpp)
|
[✔️](csharp%2F0647-palindromic-substrings.cs)
|
|
[✔️](go%2F0647-palindromic-substrings.go)
|
|
[✔️](java%2F0647-palindromic-substrings.java)
|
[✔️](javascript%2F0647-palindromic-substrings.js)
|
[✔️](kotlin%2F0647-palindromic-substrings.kt)
|
[✔️](python%2F0647-palindromic-substrings.py)
|
|
[✔️](rust%2F0647-palindromic-substrings.rs)
|
|
[✔️](swift%2F0647-palindromic-substrings.swift)
|
[✔️](typescript%2F0647-palindromic-substrings.ts)
| +| [0091 - Decode Ways](https://leetcode.com/problems/decode-ways/) |
|
[✔️](c%2F0091-decode-ways.c)
|
[✔️](cpp%2F0091-decode-ways.cpp)
|
[✔️](csharp%2F0091-decode-ways.cs)
|
|
[✔️](go%2F0091-decode-ways.go)
|
|
[✔️](java%2F0091-decode-ways.java)
|
[✔️](javascript%2F0091-decode-ways.js)
|
[✔️](kotlin%2F0091-decode-ways.kt)
|
[✔️](python%2F0091-decode-ways.py)
|
|
[✔️](rust%2F0091-decode-ways.rs)
|
[✔️](scala%2F0091-decode-ways.scala)
|
[✔️](swift%2F0091-decode-ways.swift)
|
[✔️](typescript%2F0091-decode-ways.ts)
| +| [0322 - Coin Change](https://leetcode.com/problems/coin-change/) |
|
[✔️](c%2F0322-coin-change.c)
|
[✔️](cpp%2F0322-coin-change.cpp)
|
[✔️](csharp%2F0322-coin-change.cs)
|
|
[✔️](go%2F0322-coin-change.go)
|
|
[✔️](java%2F0322-coin-change.java)
|
[✔️](javascript%2F0322-coin-change.js)
|
[✔️](kotlin%2F0322-coin-change.kt)
|
[✔️](python%2F0322-coin-change.py)
|
|
[✔️](rust%2F0322-coin-change.rs)
|
[✔️](scala%2F0322-coin-change.scala)
|
[✔️](swift%2F0322-coin-change.swift)
|
[✔️](typescript%2F0322-coin-change.ts)
| +| [0152 - Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/) |
|
[✔️](c%2F0152-maximum-product-subarray.c)
|
[✔️](cpp%2F0152-maximum-product-subarray.cpp)
|
[✔️](csharp%2F0152-maximum-product-subarray.cs)
|
|
[✔️](go%2F0152-maximum-product-subarray.go)
|
|
[✔️](java%2F0152-maximum-product-subarray.java)
|
[✔️](javascript%2F0152-maximum-product-subarray.js)
|
[✔️](kotlin%2F0152-maximum-product-subarray.kt)
|
[✔️](python%2F0152-maximum-product-subarray.py)
|
[✔️](ruby%2F0152-maximum-product-subarray.rb)
|
[✔️](rust%2F0152-maximum-product-subarray.rs)
|
|
[✔️](swift%2F0152-maximum-product-subarray.swift)
|
[✔️](typescript%2F0152-maximum-product-subarray.ts)
| +| [0139 - Word Break](https://leetcode.com/problems/word-break/) |
|
|
[✔️](cpp%2F0139-word-break.cpp)
|
[✔️](csharp%2F0139-word-break.cs)
|
|
[✔️](go%2F0139-word-break.go)
|
|
[✔️](java%2F0139-word-break.java)
|
[✔️](javascript%2F0139-word-break.js)
|
[✔️](kotlin%2F0139-word-break.kt)
|
[✔️](python%2F0139-word-break.py)
|
|
|
|
[✔️](swift%2F0139-word-break.swift)
|
[✔️](typescript%2F0139-word-break.ts)
| +| [0300 - Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/) |
|
[✔️](c%2F0300-longest-increasing-subsequence.c)
|
[✔️](cpp%2F0300-longest-increasing-subsequence.cpp)
|
[✔️](csharp%2F0300-longest-increasing-subsequence.cs)
|
|
[✔️](go%2F0300-longest-increasing-subsequence.go)
|
|
[✔️](java%2F0300-longest-increasing-subsequence.java)
|
[✔️](javascript%2F0300-longest-increasing-subsequence.js)
|
[✔️](kotlin%2F0300-longest-increasing-subsequence.kt)
|
[✔️](python%2F0300-longest-increasing-subsequence.py)
|
|
[✔️](rust%2F0300-longest-increasing-subsequence.rs)
|
|
[✔️](swift%2F0300-longest-increasing-subsequence.swift)
|
[✔️](typescript%2F0300-longest-increasing-subsequence.ts)
| +| [0416 - Partition Equal Subset Sum](https://leetcode.com/problems/partition-equal-subset-sum/) |
|
[✔️](c%2F0416-partition-equal-subset-sum.c)
|
[✔️](cpp%2F0416-partition-equal-subset-sum.cpp)
|
[✔️](csharp%2F0416-partition-equal-subset-sum.cs)
|
|
[✔️](go%2F0416-partition-equal-subset-sum.go)
|
|
[✔️](java%2F0416-partition-equal-subset-sum.java)
|
[✔️](javascript%2F0416-partition-equal-subset-sum.js)
|
[✔️](kotlin%2F0416-partition-equal-subset-sum.kt)
|
[✔️](python%2F0416-partition-equal-subset-sum.py)
|
|
|
|
[✔️](swift%2F0416-partition-equal-subset-sum.swift)
|
| +| [0120 - Triangle](https://leetcode.com/problems/triangle/) |
|
[✔️](c%2F0120-triangle.c)
|
[✔️](cpp%2F0120-triangle.cpp)
|
|
|
|
|
[✔️](java%2F0120-triangle.java)
|
|
[✔️](kotlin%2F0120-triangle.kt)
|
[✔️](python%2F0120-triangle.py)
|
|
|
|
|
| +| [0740 - Delete And Earn](https://leetcode.com/problems/delete-and-earn/) |
|
[✔️](c%2F0740-delete-and-earn.c)
|
[✔️](cpp%2F0740-delete-and-earn.cpp)
|
|
|
[✔️](go%2F0740-delete-and-earn.go)
|
|
[✔️](java%2F0740-delete-and-earn.java)
|
|
[✔️](kotlin%2F0740-delete-and-earn.kt)
|
[✔️](python%2F0740-delete-and-earn.py)
|
|
|
|
|
| +| [0256 - Paint House](https://leetcode.com/problems/paint-house/) |
|
|
|
[✔️](csharp%2F0256-paint-house.cs)
|
|
|
|
[✔️](java%2F0256-paint-house.java)
|
|
|
|
|
|
|
|
[✔️](typescript%2F0256-paint-house.ts)
| +| [0377 - Combination Sum IV](https://leetcode.com/problems/combination-sum-iv/) |
|
[✔️](c%2F0377-combination-sum-iv.c)
|
[✔️](cpp%2F0377-combination-sum-iv.cpp)
|
|
|
|
|
[✔️](java%2F0377-combination-sum-iv.java)
|
|
[✔️](kotlin%2F0377-combination-sum-iv.kt)
|
[✔️](python%2F0377-combination-sum-iv.py)
|
|
|
|
|
| +| [0279 - Perfect Squares](https://leetcode.com/problems/perfect-squares/) |
|
[✔️](c%2F0279-perfect-squares.c)
|
[✔️](cpp%2F0279-perfect-squares.cpp)
|
|
|
[✔️](go%2F0279-perfect-squares.go)
|
|
[✔️](java%2F0279-perfect-squares.java)
|
|
[✔️](kotlin%2F0279-perfect-squares.kt)
|
|
|
|
|
|
| +| [2369 - Check if There is a Valid Partition For The Array](https://leetcode.com/problems/check-if-there-is-a-valid-partition-for-the-array/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F2369-check-if-there-is-a-valid-partition-for-the-array.kt)
|
|
|
|
|
|
| +| [1856 - Maximum Subarray Min Product](https://leetcode.com/problems/maximum-subarray-min-product/) |
|
[✔️](c%2F1856-maximum-subarray-min-product.c)
|
|
|
|
|
|
[✔️](java%2F1856-maximum-subarray-min-product.java)
|
|
[✔️](kotlin%2F1856-maximum-subarray-min-product.kt)
|
|
|
|
|
|
| +| [0983 - Minimum Cost For Tickets](https://leetcode.com/problems/minimum-cost-for-tickets/) |
|
[✔️](c%2F0983-minimum-cost-for-tickets.c)
|
[✔️](cpp%2F0983-minimum-cost-for-tickets.cpp)
|
|
|
|
|
|
|
[✔️](kotlin%2F0983-minimum-cost-for-tickets.kt)
|
|
|
|
|
[✔️](swift%2F0983-minimum-cost-for-tickets.swift)
|
[✔️](typescript%2F0983-minimum-cost-for-tickets.ts)
| +| [0343 - Integer Break](https://leetcode.com/problems/integer-break/) |
|
[✔️](c%2F0343-integer-break.c)
|
[✔️](cpp%2F0343-integer-break.cpp)
|
|
|
|
|
[✔️](java%2F0343-integer-break.java)
|
|
[✔️](kotlin%2F0343-integer-break.kt)
|
|
|
|
|
|
| +| [0673 - Number of Longest Increasing Subsequence](https://leetcode.com/problems/number-of-longest-increasing-subsequence/) |
|
[✔️](c%2F0673-number-of-longest-increasing-subsequence.c)
|
|
|
|
|
|
[✔️](java%2F0673-number-of-longest-increasing-subsequence.java)
|
|
[✔️](kotlin%2F0673-number-of-longest-increasing-subsequence.kt)
|
[✔️](python%2F0673-number-of-longest-increasing-subsequence.py)
|
|
|
|
|
| +| [0691 - Stickers to Spell Word](https://leetcode.com/problems/stickers-to-spell-word/) |
|
[✔️](c%2F0691-stickers-to-spell-word.c)
|
|
|
|
|
|
|
|
[✔️](kotlin%2F0691-stickers-to-spell-word.kt)
|
|
|
|
|
|
| +| [1137 - N-th Tribonacci Number](https://leetcode.com/problems/n-th-tribonacci-number/) |
|
[✔️](c%2F1137-n-th-tribonacci-number.c)
|
[✔️](cpp%2F1137-n-th-tribonacci-number.cpp)
|
[✔️](csharp%2F1137-n-th-tribonacci-number.cs)
|
|
[✔️](go%2F1137-n-th-tribonacci-number.go)
|
|
|
[✔️](javascript%2F1137-n-th-tribonacci-number.js)
|
[✔️](kotlin%2F1137-n-th-tribonacci-number.kt)
|
[✔️](python%2F1137-n-th-tribonacci-number.py)
|
|
[✔️](rust%2F1137-n-th-tribonacci-number.rs)
|
|
|
[✔️](typescript%2F1137-n-th-tribonacci-number.ts)
| +| [1035 - Uncrossed Lines](https://leetcode.com/problems/uncrossed-lines/) |
|
[✔️](c%2F1035-uncrossed-lines.c)
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1035-uncrossed-lines.kt)
|
|
|
|
|
|
| +| [2140 - Solving Questions With Brainpower](https://leetcode.com/problems/solving-questions-with-brainpower/) |
|
[✔️](c%2F2140-solving-questions-with-brainpower.c)
|
[✔️](cpp%2F2140-solving-questions-with-brainpower.cpp)
|
|
|
|
|
|
|
[✔️](kotlin%2F2140-solving-questions-with-brainpower.kt)
|
|
|
|
|
|
| +| [2466 - Count Ways to Build Good Strings](https://leetcode.com/problems/count-ways-to-build-good-strings/) |
|
[✔️](c%2F2466-count-ways-to-build-good-strings.c)
|
|
|
|
|
|
|
|
[✔️](kotlin%2F2466-count-ways-to-build-good-strings.kt)
|
|
|
|
|
|
| +| [0837 - New 21 Game](https://leetcode.com/problems/new-21-game/) |
|
[✔️](c%2F0837-new-21-game.c)
|
|
|
|
|
|
[✔️](java%2F0837-new-21-game.java)
|
[✔️](javascript%2F0837-new-21-game.js)
|
[✔️](kotlin%2F0837-new-21-game.kt)
|
|
|
|
|
|
| +| [1626 - Best Team with no Conflicts](https://leetcode.com/problems/best-team-with-no-conflicts/) |
|
[✔️](c%2F1626-best-team-with-no-conflicts.c)
|
|
|
|
|
|
[✔️](java%2F1626-best-team-with-no-conflicts.java)
|
|
[✔️](kotlin%2F1626-best-team-with-no-conflicts.kt)
|
|
|
|
|
|
| +| [1406 - Stone Game III](https://leetcode.com/problems/stone-game-iii/) |
|
[✔️](c%2F1406-stone-game-iii.c)
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1406-stone-game-iii.kt)
|
|
|
|
|
|
| +| [0472 - Concatenated Words](https://leetcode.com/problems/concatenated-words/) |
|
|
|
|
|
[✔️](go%2F0472-concatenated-words.go)
|
|
|
[✔️](javascript%2F0472-concatenated-words.js)
|
[✔️](kotlin%2F0472-concatenated-words.kt)
|
|
|
[✔️](rust%2F0472-concatenated-words.rs)
|
|
|
[✔️](typescript%2F0472-concatenated-words.ts)
| +| [1799 - Maximize Score after N Operations](https://leetcode.com/problems/maximize-score-after-n-operations/) |
|
[✔️](c%2F1799-maximize-score-after-n-operations.c)
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1799-maximize-score-after-n-operations.kt)
|
|
|
|
|
|
| +| [1964 - Find the Longest Valid Obstacle Course at Each Position](https://leetcode.com/problems/find-the-longest-valid-obstacle-course-at-each-position/) |
|
[✔️](c%2F1964-find-the-longest-valid-obstacle-course-at-each-position.c)
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1964-find-the-longest-valid-obstacle-course-at-each-position.kt)
|
|
|
|
|
|
| +| [1359 - Count all Valid Pickup and Delivery Options](https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/) |
|
|
|
|
|
|
|
[✔️](java%2F1359-count-all-valid-pickup-and-delivery-options.java)
|
|
[✔️](kotlin%2F1359-count-all-valid-pickup-and-delivery-options.kt)
|
|
|
|
|
|
| ### 2-D Dynamic Programming -Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS ----- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- -[0062 - Unique Paths](https://leetcode.com/problems/unique-paths/) |
|
[✔️](c%2F0062-unique-paths.c)
|
[✔️](cpp%2F0062-unique-paths.cpp)
|
[✔️](csharp%2F0062-unique-paths.cs)
|
|
[✔️](go%2F0062-unique-paths.go)
|
|
[✔️](java%2F0062-unique-paths.java)
|
[✔️](javascript%2F0062-unique-paths.js)
|
[✔️](kotlin%2F0062-unique-paths.kt)
|
[✔️](python%2F0062-unique-paths.py)
|
|
[✔️](rust%2F0062-unique-paths.rs)
|
|
[✔️](swift%2F0062-unique-paths.swift)
|
[✔️](typescript%2F0062-unique-paths.ts)
-[0063 - Unique Paths II](https://leetcode.com/problems/unique-paths-ii/) |
|
|
[✔️](cpp%2F0063-unique-paths-ii.cpp)
|
[✔️](csharp%2F0063-unique-paths-ii.cs)
|
|
[✔️](go%2F0063-unique-paths-ii.go)
|
|
[✔️](java%2F0063-unique-paths-ii.java)
|
|
[✔️](kotlin%2F0063-unique-paths-ii.kt)
|
[✔️](python%2F0063-unique-paths-ii.py)
|
|
[✔️](rust%2F0063-unique-paths-ii.rs)
|
|
[✔️](swift%2F0063-unique-paths-ii.swift)
|
-[1143 - Longest Common Subsequence](https://leetcode.com/problems/longest-common-subsequence/) |
|
[✔️](c%2F1143-longest-common-subsequence.c)
|
[✔️](cpp%2F1143-Longest-Common-Subsequence.cpp)
|
[✔️](csharp%2F1143-Longest-Common-Subsequence.cs)
|
[✔️](dart%2F1143-longest-common-subsequence.dart)
|
[✔️](go%2F1143-Longest-Common-Subsequence.go)
|
|
[✔️](java%2F1143-longest-common-subsequence.java)
|
[✔️](javascript%2F1143-Longest-Common-Subsequence.js)
|
[✔️](kotlin%2F1143-Longest-Common-Subsequence.kt)
|
[✔️](python%2F1143-longest-common-subsequence.py)
|
|
[✔️](rust%2F1143-Longest-Common-Subsequence.rs)
|
|
[✔️](swift%2F1143-Longest-Common-Subsequence.swift)
|
[✔️](typescript%2F1143-Longest-Common-Subsequence.ts)
-[0516 - Longest Palindromic Subsequence](https://leetcode.com/problems/longest-palindromic-subsequence/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F0516-longest-palindromic-subsequence.kt)
|
[✔️](python%2F0516-longest-palindromic-subsequence.py)
|
|
|
|
[✔️](swift%2F0516-longest-palindromic-subsequence.swift)
|
-[1049 - Last Stone Weight II](https://leetcode.com/problems/last-stone-weight-ii/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1049-last-stone-weight-ii.kt)
|
[✔️](python%2F1049-last-stone-weight-ii.py)
|
|
|
|
[✔️](swift%2F1049-last-stone-weight-ii.swift)
|
[✔️](typescript%2F1049-last-stone-weight-ii.ts)
-[0309 - Best Time to Buy And Sell Stock With Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/) |
|
[✔️](c%2F0309-best-time-to-buy-and-sell-stock-with-cooldown.c)
|
[✔️](cpp%2F0309-best-time-to-buy-and-sell-stock-with-cooldown.cpp)
|
[✔️](csharp%2F0309-best-time-to-buy-and-sell-stock-with-cooldown.cs)
|
|
[✔️](go%2F0309-best-time-to-buy-and-sell-stock-with-cooldown.go)
|
|
[✔️](java%2F0309-best-time-to-buy-and-sell-stock-with-cooldown.java)
|
[✔️](javascript%2F0309-best-time-to-buy-and-sell-stock-with-cooldown.js)
|
[✔️](kotlin%2F0309-best-time-to-buy-and-sell-stock-with-cooldown.kt)
|
[✔️](python%2F0309-best-time-to-buy-and-sell-stock-with-cooldown.py)
|
|
[✔️](rust%2F0309-best-time-to-buy-and-sell-stock-with-cooldown.rs)
|
|
[✔️](swift%2F0309-best-time-to-buy-and-sell-stock-with-cooldown.swift)
|
[✔️](typescript%2F0309-best-time-to-buy-and-sell-stock-with-cooldown.ts)
-[0518 - Coin Change II](https://leetcode.com/problems/coin-change-ii/) |
|
[✔️](c%2F0518-coin-change-ii.c)
|
[✔️](cpp%2F0518-coin-change-ii.cpp)
|
[✔️](csharp%2F0518-coin-change-ii.cs)
|
|
[✔️](go%2F0518-coin-change-ii.go)
|
|
[✔️](java%2F0518-coin-change-ii.java)
|
[✔️](javascript%2F0518-coin-change-ii.js)
|
[✔️](kotlin%2F0518-coin-change-ii.kt)
|
[✔️](python%2F0518-coin-change-ii.py)
|
|
[✔️](rust%2F0518-coin-change-ii.rs)
|
|
[✔️](swift%2F0518-coin-change-ii.swift)
|
[✔️](typescript%2F0518-coin-change-ii.ts)
-[0494 - Target Sum](https://leetcode.com/problems/target-sum/) |
|
[✔️](c%2F0494-target-sum.c)
|
[✔️](cpp%2F0494-target-sum.cpp)
|
[✔️](csharp%2F0494-target-sum.cs)
|
|
[✔️](go%2F0494-target-sum.go)
|
|
[✔️](java%2F0494-target-sum.java)
|
[✔️](javascript%2F0494-target-sum.js)
|
[✔️](kotlin%2F0494-target-sum.kt)
|
[✔️](python%2F0494-target-sum.py)
|
|
|
|
[✔️](swift%2F0494-target-sum.swift)
|
[✔️](typescript%2F0494-target-sum.ts)
-[0097 - Interleaving String](https://leetcode.com/problems/interleaving-string/) |
|
[✔️](c%2F0097-interleaving-string.c)
|
[✔️](cpp%2F0097-interleaving-string.cpp)
|
[✔️](csharp%2F0097-interleaving-string.cs)
|
|
[✔️](go%2F0097-interleaving-string.go)
|
|
[✔️](java%2F0097-interleaving-string.java)
|
[✔️](javascript%2F0097-interleaving-string.js)
|
[✔️](kotlin%2F0097-interleaving-string.kt)
|
[✔️](python%2F0097-interleaving-string.py)
|
|
|
[✔️](scala%2F0097-interleaving-string.scala)
|
[✔️](swift%2F0097-interleaving-string.swift)
|
[✔️](typescript%2F0097-interleaving-string.ts)
-[0877 - Stone Game](https://leetcode.com/problems/stone-game/) |
|
|
[✔️](cpp%2F0877-stone-game.cpp)
|
|
|
|
|
|
|
[✔️](kotlin%2F0877-stone-game.kt)
|
|
|
|
|
|
-[0064 - Minimum Path Sum](https://leetcode.com/problems/minimum-path-sum/) |
|
|
[✔️](cpp%2F0064-minimum-path-sum.cpp)
|
|
|
|
|
[✔️](java%2F0064-minimum-path-sum.java)
|
|
[✔️](kotlin%2F0064-minimum-path-sum.kt)
|
[✔️](python%2F0064-minimum-path-sum.py)
|
|
|
|
|
-[0329 - Longest Increasing Path In a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/) |
|
[✔️](c%2F0329-longest-increasing-path-in-a-matrix.c)
|
[✔️](cpp%2F0329-longest-increasing-path-in-a-matrix.cpp)
|
[✔️](csharp%2F0329-longest-increasing-path-in-a-matrix.cs)
|
|
|
|
[✔️](java%2F0329-longest-increasing-path-in-a-matrix.java)
|
[✔️](javascript%2F0329-longest-increasing-path-in-a-matrix.js)
|
[✔️](kotlin%2F0329-longest-increasing-path-in-a-matrix.kt)
|
[✔️](python%2F0329-longest-increasing-path-in-a-matrix.py)
|
|
[✔️](rust%2F0329-longest-increasing-path-in-a-matrix.rs)
|
|
[✔️](swift%2F0329-longest-increasing-path-in-a-matrix.swift)
|
-[0221 - Maximal Square](https://leetcode.com/problems/maximal-square/) |
|
|
[✔️](cpp%2F0221-maximal-square.cpp)
|
|
|
|
|
[✔️](java%2F0221-maximal-square.java)
|
|
[✔️](kotlin%2F0221-maximal-square.kt)
|
[✔️](python%2F0221-maximal-square.py)
|
|
|
|
|
-[0474 - Ones and Zeroes](https://leetcode.com/problems/ones-and-zeroes/) |
|
|
[✔️](cpp%2F0474-ones-and-zeroes.cpp)
|
|
|
|
|
[✔️](java%2F0474-ones-and-zeroes.java)
|
|
[✔️](kotlin%2F0474-ones-and-zeroes.kt)
|
[✔️](python%2F0474-ones-and-zeroes.py)
|
|
|
|
[✔️](swift%2F0474-ones-and-zeroes.swift)
|
[✔️](typescript%2F0474-ones-and-zeroes.ts)
-[5782 - Maximum Alternating Subsequence Sum](https://leetcode.com/problems/maximum-alternating-subsequence-sum/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
-[0115 - Distinct Subsequences](https://leetcode.com/problems/distinct-subsequences/) |
|
[✔️](c%2F0115-distinct-subsequences.c)
|
[✔️](cpp%2F0115-distinct-subsequences.cpp)
|
[✔️](csharp%2F0115-distinct-subsequences.cs)
|
|
|
|
[✔️](java%2F0115-distinct-subsequences.java)
|
[✔️](javascript%2F0115-distinct-subsequences.js)
|
[✔️](kotlin%2F0115-distinct-subsequences.kt)
|
[✔️](python%2F0115-distinct-subsequences.py)
|
|
|
|
[✔️](swift%2F0115-distinct-subsequences.swift)
|
[✔️](typescript%2F0115-distinct-subsequences.ts)
-[0072 - Edit Distance](https://leetcode.com/problems/edit-distance/) |
|
[✔️](c%2F0072-edit-distance.c)
|
[✔️](cpp%2F0072-edit-distance.cpp)
|
[✔️](csharp%2F0072-edit-distance.cs)
|
|
|
|
[✔️](java%2F0072-edit-distance.java)
|
[✔️](javascript%2F0072-edit-distance.js)
|
[✔️](kotlin%2F0072-edit-distance.kt)
|
[✔️](python%2F0072-edit-distance.py)
|
|
[✔️](rust%2F0072-edit-distance.rs)
|
[✔️](scala%2F0072-edit-distance.scala)
|
[✔️](swift%2F0072-edit-distance.swift)
|
[✔️](typescript%2F0072-edit-distance.ts)
-[1220 - Count Vowels Permutation](https://leetcode.com/problems/count-vowels-permutation/) |
|
|
[✔️](cpp%2F1220-count-vowels-permutation.cpp)
|
|
|
[✔️](go%2F1220-count-vowels-permutation.go)
|
|
[✔️](java%2F1220-count-vowels-permutation.java)
|
|
[✔️](kotlin%2F1220-count-vowels-permutation.kt)
|
[✔️](python%2F1220-count-vowels-permutation.py)
|
|
|
|
|
-[0312 - Burst Balloons](https://leetcode.com/problems/burst-balloons/) |
|
[✔️](c%2F0312-burst-balloons.c)
|
[✔️](cpp%2F0312-burst-balloons.cpp)
|
[✔️](csharp%2F0312-burst-balloons.cs)
|
|
|
|
[✔️](java%2F0312-burst-balloons.java)
|
[✔️](javascript%2F0312-burst-balloons.js)
|
[✔️](kotlin%2F0312-burst-balloons.kt)
|
[✔️](python%2F0312-burst-balloons.py)
|
|
|
|
[✔️](swift%2F0312-burst-balloons.swift)
|
[✔️](typescript%2F0312-burst-balloons.ts)
-[1866 - Number of Ways to Rearrange Sticks With K Sticks Visible](https://leetcode.com/problems/number-of-ways-to-rearrange-sticks-with-k-sticks-visible/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1866-number-of-ways-to-rearrange-sticks-with-k-sticks-visible.kt)
|
|
|
|
|
|
-[0010 - Regular Expression Matching](https://leetcode.com/problems/regular-expression-matching/) |
|
[✔️](c%2F0010-regular-expression-matching.c)
|
[✔️](cpp%2F0010-regular-expression-matching.cpp)
|
[✔️](csharp%2F0010-regular-expression-matching.cs)
|
|
[✔️](go%2F0010-regular-expression-matching.go)
|
|
[✔️](java%2F0010-regular-expression-matching.java)
|
[✔️](javascript%2F0010-regular-expression-matching.js)
|
[✔️](kotlin%2F0010-regular-expression-matching.kt)
|
[✔️](python%2F0010-regular-expression-matching.py)
|
|
|
|
[✔️](swift%2F0010-regular-expression-matching.swift)
|
[✔️](typescript%2F0010-regular-expression-matching.ts)
-[1140 - Stone Game II](https://leetcode.com/problems/stone-game-ii/) |
|
|
|
|
|
|
|
[✔️](java%2F1140-stone-game-ii.java)
|
|
[✔️](kotlin%2F1140-stone-game-ii.kt)
|
|
|
|
|
|
-[0926 - Flip String to Monotone Increasing](https://leetcode.com/problems/flip-string-to-monotone-increasing/) |
|
|
|
|
|
[✔️](go%2F0926-flip-string-to-monotone-increasing.go)
|
|
|
[✔️](javascript%2F0926-flip-string-to-monotone-increasing.js)
|
[✔️](kotlin%2F0926-flip-string-to-monotone-increasing.kt)
|
|
|
[✔️](rust%2F0926-flip-string-to-monotone-increasing.rs)
|
|
|
[✔️](typescript%2F0926-flip-string-to-monotone-increasing.ts)
-[2218 - Maximum Value of K Coins from Piles](https://leetcode.com/problems/maximum-value-of-k-coins-from-piles/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F2218-maximum-value-of-k-coins-from-piles.kt)
|
|
|
|
|
|
-[0920 - Number of Music Playlists](https://leetcode.com/problems/number-of-music-playlists/) |
|
|
|
|
|
|
|
[✔️](java%2F0920-number-of-music-playlists.java)
|
|
[✔️](kotlin%2F0920-number-of-music-playlists.kt)
|
|
|
|
|
|
-[1639 - Number of Ways to Form a Target String Given a Dictionary](https://leetcode.com/problems/number-of-ways-to-form-a-target-string-given-a-dictionary/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1639-number-of-ways-to-form-a-target-string-given-a-dictionary.kt)
|
|
|
|
|
|
-[0879 - Profitable Schemes](https://leetcode.com/problems/profitable-schemes/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F0879-profitable-schemes.kt)
|
|
|
|
|
|
-[1547 - Minimum Cost to Cut a Stick](https://leetcode.com/problems/minimum-cost-to-cut-a-stick/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1547-minimum-cost-to-cut-a-stick.kt)
|
|
|
|
|
|
+| Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | +| [0062 - Unique Paths](https://leetcode.com/problems/unique-paths/) |
|
[✔️](c%2F0062-unique-paths.c)
|
[✔️](cpp%2F0062-unique-paths.cpp)
|
[✔️](csharp%2F0062-unique-paths.cs)
|
|
[✔️](go%2F0062-unique-paths.go)
|
|
[✔️](java%2F0062-unique-paths.java)
|
[✔️](javascript%2F0062-unique-paths.js)
|
[✔️](kotlin%2F0062-unique-paths.kt)
|
[✔️](python%2F0062-unique-paths.py)
|
|
[✔️](rust%2F0062-unique-paths.rs)
|
|
[✔️](swift%2F0062-unique-paths.swift)
|
[✔️](typescript%2F0062-unique-paths.ts)
| +| [0063 - Unique Paths II](https://leetcode.com/problems/unique-paths-ii/) |
|
|
[✔️](cpp%2F0063-unique-paths-ii.cpp)
|
[✔️](csharp%2F0063-unique-paths-ii.cs)
|
|
[✔️](go%2F0063-unique-paths-ii.go)
|
|
[✔️](java%2F0063-unique-paths-ii.java)
|
|
[✔️](kotlin%2F0063-unique-paths-ii.kt)
|
[✔️](python%2F0063-unique-paths-ii.py)
|
|
[✔️](rust%2F0063-unique-paths-ii.rs)
|
|
[✔️](swift%2F0063-unique-paths-ii.swift)
|
| +| [1143 - Longest Common Subsequence](https://leetcode.com/problems/longest-common-subsequence/) |
|
[✔️](c%2F1143-longest-common-subsequence.c)
|
[✔️](cpp%2F1143-Longest-Common-Subsequence.cpp)
|
[✔️](csharp%2F1143-Longest-Common-Subsequence.cs)
|
[✔️](dart%2F1143-longest-common-subsequence.dart)
|
[✔️](go%2F1143-Longest-Common-Subsequence.go)
|
|
[✔️](java%2F1143-longest-common-subsequence.java)
|
[✔️](javascript%2F1143-Longest-Common-Subsequence.js)
|
[✔️](kotlin%2F1143-Longest-Common-Subsequence.kt)
|
[✔️](python%2F1143-longest-common-subsequence.py)
|
|
[✔️](rust%2F1143-Longest-Common-Subsequence.rs)
|
|
[✔️](swift%2F1143-Longest-Common-Subsequence.swift)
|
[✔️](typescript%2F1143-Longest-Common-Subsequence.ts)
| +| [0516 - Longest Palindromic Subsequence](https://leetcode.com/problems/longest-palindromic-subsequence/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F0516-longest-palindromic-subsequence.kt)
|
[✔️](python%2F0516-longest-palindromic-subsequence.py)
|
|
|
|
[✔️](swift%2F0516-longest-palindromic-subsequence.swift)
|
| +| [1049 - Last Stone Weight II](https://leetcode.com/problems/last-stone-weight-ii/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1049-last-stone-weight-ii.kt)
|
[✔️](python%2F1049-last-stone-weight-ii.py)
|
|
|
|
[✔️](swift%2F1049-last-stone-weight-ii.swift)
|
[✔️](typescript%2F1049-last-stone-weight-ii.ts)
| +| [0309 - Best Time to Buy And Sell Stock With Cooldown](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/) |
|
[✔️](c%2F0309-best-time-to-buy-and-sell-stock-with-cooldown.c)
|
[✔️](cpp%2F0309-best-time-to-buy-and-sell-stock-with-cooldown.cpp)
|
[✔️](csharp%2F0309-best-time-to-buy-and-sell-stock-with-cooldown.cs)
|
|
[✔️](go%2F0309-best-time-to-buy-and-sell-stock-with-cooldown.go)
|
|
[✔️](java%2F0309-best-time-to-buy-and-sell-stock-with-cooldown.java)
|
[✔️](javascript%2F0309-best-time-to-buy-and-sell-stock-with-cooldown.js)
|
[✔️](kotlin%2F0309-best-time-to-buy-and-sell-stock-with-cooldown.kt)
|
[✔️](python%2F0309-best-time-to-buy-and-sell-stock-with-cooldown.py)
|
|
[✔️](rust%2F0309-best-time-to-buy-and-sell-stock-with-cooldown.rs)
|
|
[✔️](swift%2F0309-best-time-to-buy-and-sell-stock-with-cooldown.swift)
|
[✔️](typescript%2F0309-best-time-to-buy-and-sell-stock-with-cooldown.ts)
| +| [0518 - Coin Change II](https://leetcode.com/problems/coin-change-ii/) |
|
[✔️](c%2F0518-coin-change-ii.c)
|
[✔️](cpp%2F0518-coin-change-ii.cpp)
|
[✔️](csharp%2F0518-coin-change-ii.cs)
|
|
[✔️](go%2F0518-coin-change-ii.go)
|
|
[✔️](java%2F0518-coin-change-ii.java)
|
[✔️](javascript%2F0518-coin-change-ii.js)
|
[✔️](kotlin%2F0518-coin-change-ii.kt)
|
[✔️](python%2F0518-coin-change-ii.py)
|
|
[✔️](rust%2F0518-coin-change-ii.rs)
|
|
[✔️](swift%2F0518-coin-change-ii.swift)
|
[✔️](typescript%2F0518-coin-change-ii.ts)
| +| [0494 - Target Sum](https://leetcode.com/problems/target-sum/) |
|
[✔️](c%2F0494-target-sum.c)
|
[✔️](cpp%2F0494-target-sum.cpp)
|
[✔️](csharp%2F0494-target-sum.cs)
|
|
[✔️](go%2F0494-target-sum.go)
|
|
[✔️](java%2F0494-target-sum.java)
|
[✔️](javascript%2F0494-target-sum.js)
|
[✔️](kotlin%2F0494-target-sum.kt)
|
[✔️](python%2F0494-target-sum.py)
|
|
|
|
[✔️](swift%2F0494-target-sum.swift)
|
[✔️](typescript%2F0494-target-sum.ts)
| +| [0097 - Interleaving String](https://leetcode.com/problems/interleaving-string/) |
|
[✔️](c%2F0097-interleaving-string.c)
|
[✔️](cpp%2F0097-interleaving-string.cpp)
|
[✔️](csharp%2F0097-interleaving-string.cs)
|
|
[✔️](go%2F0097-interleaving-string.go)
|
|
[✔️](java%2F0097-interleaving-string.java)
|
[✔️](javascript%2F0097-interleaving-string.js)
|
[✔️](kotlin%2F0097-interleaving-string.kt)
|
[✔️](python%2F0097-interleaving-string.py)
|
|
|
[✔️](scala%2F0097-interleaving-string.scala)
|
[✔️](swift%2F0097-interleaving-string.swift)
|
[✔️](typescript%2F0097-interleaving-string.ts)
| +| [0877 - Stone Game](https://leetcode.com/problems/stone-game/) |
|
|
[✔️](cpp%2F0877-stone-game.cpp)
|
|
|
|
|
|
|
[✔️](kotlin%2F0877-stone-game.kt)
|
|
|
|
|
|
| +| [0064 - Minimum Path Sum](https://leetcode.com/problems/minimum-path-sum/) |
|
|
[✔️](cpp%2F0064-minimum-path-sum.cpp)
|
|
|
|
|
[✔️](java%2F0064-minimum-path-sum.java)
|
|
[✔️](kotlin%2F0064-minimum-path-sum.kt)
|
[✔️](python%2F0064-minimum-path-sum.py)
|
|
|
|
|
| +| [0329 - Longest Increasing Path In a Matrix](https://leetcode.com/problems/longest-increasing-path-in-a-matrix/) |
|
[✔️](c%2F0329-longest-increasing-path-in-a-matrix.c)
|
[✔️](cpp%2F0329-longest-increasing-path-in-a-matrix.cpp)
|
[✔️](csharp%2F0329-longest-increasing-path-in-a-matrix.cs)
|
|
|
|
[✔️](java%2F0329-longest-increasing-path-in-a-matrix.java)
|
[✔️](javascript%2F0329-longest-increasing-path-in-a-matrix.js)
|
[✔️](kotlin%2F0329-longest-increasing-path-in-a-matrix.kt)
|
[✔️](python%2F0329-longest-increasing-path-in-a-matrix.py)
|
|
[✔️](rust%2F0329-longest-increasing-path-in-a-matrix.rs)
|
|
[✔️](swift%2F0329-longest-increasing-path-in-a-matrix.swift)
|
| +| [0221 - Maximal Square](https://leetcode.com/problems/maximal-square/) |
|
|
[✔️](cpp%2F0221-maximal-square.cpp)
|
|
|
|
|
[✔️](java%2F0221-maximal-square.java)
|
|
[✔️](kotlin%2F0221-maximal-square.kt)
|
[✔️](python%2F0221-maximal-square.py)
|
|
|
|
|
| +| [0474 - Ones and Zeroes](https://leetcode.com/problems/ones-and-zeroes/) |
|
|
[✔️](cpp%2F0474-ones-and-zeroes.cpp)
|
|
|
|
|
[✔️](java%2F0474-ones-and-zeroes.java)
|
|
[✔️](kotlin%2F0474-ones-and-zeroes.kt)
|
[✔️](python%2F0474-ones-and-zeroes.py)
|
|
|
|
[✔️](swift%2F0474-ones-and-zeroes.swift)
|
[✔️](typescript%2F0474-ones-and-zeroes.ts)
| +| [5782 - Maximum Alternating Subsequence Sum](https://leetcode.com/problems/maximum-alternating-subsequence-sum/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| +| [0115 - Distinct Subsequences](https://leetcode.com/problems/distinct-subsequences/) |
|
[✔️](c%2F0115-distinct-subsequences.c)
|
[✔️](cpp%2F0115-distinct-subsequences.cpp)
|
[✔️](csharp%2F0115-distinct-subsequences.cs)
|
|
|
|
[✔️](java%2F0115-distinct-subsequences.java)
|
[✔️](javascript%2F0115-distinct-subsequences.js)
|
[✔️](kotlin%2F0115-distinct-subsequences.kt)
|
[✔️](python%2F0115-distinct-subsequences.py)
|
|
|
|
[✔️](swift%2F0115-distinct-subsequences.swift)
|
[✔️](typescript%2F0115-distinct-subsequences.ts)
| +| [0072 - Edit Distance](https://leetcode.com/problems/edit-distance/) |
|
[✔️](c%2F0072-edit-distance.c)
|
[✔️](cpp%2F0072-edit-distance.cpp)
|
[✔️](csharp%2F0072-edit-distance.cs)
|
|
|
|
[✔️](java%2F0072-edit-distance.java)
|
[✔️](javascript%2F0072-edit-distance.js)
|
[✔️](kotlin%2F0072-edit-distance.kt)
|
[✔️](python%2F0072-edit-distance.py)
|
|
[✔️](rust%2F0072-edit-distance.rs)
|
[✔️](scala%2F0072-edit-distance.scala)
|
[✔️](swift%2F0072-edit-distance.swift)
|
[✔️](typescript%2F0072-edit-distance.ts)
| +| [1220 - Count Vowels Permutation](https://leetcode.com/problems/count-vowels-permutation/) |
|
|
[✔️](cpp%2F1220-count-vowels-permutation.cpp)
|
|
|
[✔️](go%2F1220-count-vowels-permutation.go)
|
|
[✔️](java%2F1220-count-vowels-permutation.java)
|
|
[✔️](kotlin%2F1220-count-vowels-permutation.kt)
|
[✔️](python%2F1220-count-vowels-permutation.py)
|
|
|
|
|
| +| [0312 - Burst Balloons](https://leetcode.com/problems/burst-balloons/) |
|
[✔️](c%2F0312-burst-balloons.c)
|
[✔️](cpp%2F0312-burst-balloons.cpp)
|
[✔️](csharp%2F0312-burst-balloons.cs)
|
|
|
|
[✔️](java%2F0312-burst-balloons.java)
|
[✔️](javascript%2F0312-burst-balloons.js)
|
[✔️](kotlin%2F0312-burst-balloons.kt)
|
[✔️](python%2F0312-burst-balloons.py)
|
|
|
|
[✔️](swift%2F0312-burst-balloons.swift)
|
[✔️](typescript%2F0312-burst-balloons.ts)
| +| [1866 - Number of Ways to Rearrange Sticks With K Sticks Visible](https://leetcode.com/problems/number-of-ways-to-rearrange-sticks-with-k-sticks-visible/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1866-number-of-ways-to-rearrange-sticks-with-k-sticks-visible.kt)
|
|
|
|
|
|
| +| [0010 - Regular Expression Matching](https://leetcode.com/problems/regular-expression-matching/) |
|
[✔️](c%2F0010-regular-expression-matching.c)
|
[✔️](cpp%2F0010-regular-expression-matching.cpp)
|
[✔️](csharp%2F0010-regular-expression-matching.cs)
|
|
[✔️](go%2F0010-regular-expression-matching.go)
|
|
[✔️](java%2F0010-regular-expression-matching.java)
|
[✔️](javascript%2F0010-regular-expression-matching.js)
|
[✔️](kotlin%2F0010-regular-expression-matching.kt)
|
[✔️](python%2F0010-regular-expression-matching.py)
|
|
|
|
[✔️](swift%2F0010-regular-expression-matching.swift)
|
[✔️](typescript%2F0010-regular-expression-matching.ts)
| +| [1140 - Stone Game II](https://leetcode.com/problems/stone-game-ii/) |
|
|
|
|
|
|
|
[✔️](java%2F1140-stone-game-ii.java)
|
|
[✔️](kotlin%2F1140-stone-game-ii.kt)
|
|
|
|
|
|
| +| [0926 - Flip String to Monotone Increasing](https://leetcode.com/problems/flip-string-to-monotone-increasing/) |
|
|
|
|
|
[✔️](go%2F0926-flip-string-to-monotone-increasing.go)
|
|
|
[✔️](javascript%2F0926-flip-string-to-monotone-increasing.js)
|
[✔️](kotlin%2F0926-flip-string-to-monotone-increasing.kt)
|
|
|
[✔️](rust%2F0926-flip-string-to-monotone-increasing.rs)
|
|
|
[✔️](typescript%2F0926-flip-string-to-monotone-increasing.ts)
| +| [2218 - Maximum Value of K Coins from Piles](https://leetcode.com/problems/maximum-value-of-k-coins-from-piles/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F2218-maximum-value-of-k-coins-from-piles.kt)
|
|
|
|
|
|
| +| [0920 - Number of Music Playlists](https://leetcode.com/problems/number-of-music-playlists/) |
|
|
|
|
|
|
|
[✔️](java%2F0920-number-of-music-playlists.java)
|
|
[✔️](kotlin%2F0920-number-of-music-playlists.kt)
|
|
|
|
|
|
| +| [1639 - Number of Ways to Form a Target String Given a Dictionary](https://leetcode.com/problems/number-of-ways-to-form-a-target-string-given-a-dictionary/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1639-number-of-ways-to-form-a-target-string-given-a-dictionary.kt)
|
|
|
|
|
|
| +| [0879 - Profitable Schemes](https://leetcode.com/problems/profitable-schemes/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F0879-profitable-schemes.kt)
|
|
|
|
|
|
| +| [1547 - Minimum Cost to Cut a Stick](https://leetcode.com/problems/minimum-cost-to-cut-a-stick/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1547-minimum-cost-to-cut-a-stick.kt)
|
|
|
|
|
|
| ### Greedy -Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS ----- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- -[0053 - Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) |
|
[✔️](c%2F0053-maximum-subarray.c)
|
[✔️](cpp%2F0053-maximum-subarray.cpp)
|
[✔️](csharp%2F0053-maximum-subarray.cs)
|
|
[✔️](go%2F0053-maximum-subarray.go)
|
|
[✔️](java%2F0053-maximum-subarray.java)
|
[✔️](javascript%2F0053-maximum-subarray.js)
|
[✔️](kotlin%2F0053-maximum-subarray.kt)
|
[✔️](python%2F0053-maximum-subarray.py)
|
[✔️](ruby%2F0053-maximum-subarray.rb)
|
[✔️](rust%2F0053-maximum-subarray.rs)
|
|
[✔️](swift%2F0053-maximum-subarray.swift)
|
[✔️](typescript%2F0053-maximum-subarray.ts)
-[0918 - Maximum Sum Circular Subarray](https://leetcode.com/problems/maximum-sum-circular-subarray/) |
|
|
|
|
|
[✔️](go%2F0918-maximum-sum-circular-subarray.go)
|
|
[✔️](java%2F0918-maximum-sum-circular-subarray.java)
|
[✔️](javascript%2F0918-maximum-sum-circular-subarray.js)
|
[✔️](kotlin%2F0918-maximum-sum-circular-subarray.kt)
|
[✔️](python%2F0918-maximum-sum-circular-subarray.py)
|
|
[✔️](rust%2F0918-maximum-sum-circular-subarray.rs)
|
|
[✔️](swift%2F0918-maximum-sum-circular-subarray.swift)
|
[✔️](typescript%2F0918-maximum-sum-circular-subarray.ts)
-[0978 - Longest Turbulent Array](https://leetcode.com/problems/longest-turbulent-subarray/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F0978-longest-turbulent-subarray.js)
|
[✔️](kotlin%2F0978-longest-turbulent-subarray.kt)
|
[✔️](python%2F0978-longest-turbulent-subarray.py)
|
|
|
|
[✔️](swift%2F0978-longest-turbulent-subarray.swift)
|
-[0055 - Jump Game](https://leetcode.com/problems/jump-game/) |
|
[✔️](c%2F0055-jump-game.c)
|
[✔️](cpp%2F0055-jump-game.cpp)
|
[✔️](csharp%2F0055-jump-game.cs)
|
|
[✔️](go%2F0055-jump-game.go)
|
|
[✔️](java%2F0055-jump-game.java)
|
[✔️](javascript%2F0055-jump-game.js)
|
[✔️](kotlin%2F0055-jump-game.kt)
|
[✔️](python%2F0055-jump-game.py)
|
|
[✔️](rust%2F0055-jump-game.rs)
|
|
[✔️](swift%2F0055-jump-game.swift)
|
[✔️](typescript%2F0055-jump-game.ts)
-[0045 - Jump Game II](https://leetcode.com/problems/jump-game-ii/) |
|
[✔️](c%2F0045-jump-game-ii.c)
|
[✔️](cpp%2F0045-jump-game-ii.cpp)
|
[✔️](csharp%2F0045-jump-game-ii.cs)
|
|
[✔️](go%2F0045-jump-game-ii.go)
|
|
[✔️](java%2F0045-jump-game-ii.java)
|
[✔️](javascript%2F0045-jump-game-ii.js)
|
[✔️](kotlin%2F0045-jump-game-ii.kt)
|
[✔️](python%2F0045-jump-game-ii.py)
|
[✔️](ruby%2F0045-jump-game-ii.rb)
|
[✔️](rust%2F0045-jump-game-ii.rs)
|
|
[✔️](swift%2F0045-jump-game-ii.swift)
|
[✔️](typescript%2F0045-jump-game-ii.ts)
-[1871 - Jump Game VII](https://leetcode.com/problems/jump-game-vii/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1871-jump-game-vii.kt)
|
|
|
|
|
|
-[0134 - Gas Station](https://leetcode.com/problems/gas-station/) |
|
[✔️](c%2F0134-gas-station.c)
|
[✔️](cpp%2F0134-gas-station.cpp)
|
[✔️](csharp%2F0134-gas-station.cs)
|
|
[✔️](go%2F0134-gas-station.go)
|
|
[✔️](java%2F0134-gas-station.java)
|
[✔️](javascript%2F0134-gas-station.js)
|
[✔️](kotlin%2F0134-gas-station.kt)
|
[✔️](python%2F0134-gas-station.py)
|
[✔️](ruby%2F0134-gas-station.rb)
|
|
|
[✔️](swift%2F0134-gas-station.swift)
|
[✔️](typescript%2F0134-gas-station.ts)
-[0846 - Hand of Straights](https://leetcode.com/problems/hand-of-straights/) |
|
[✔️](c%2F0846-hand-of-straights.c)
|
[✔️](cpp%2F0846-hand-of-straights.cpp)
|
[✔️](csharp%2F0846-hand-of-straights.cs)
|
|
[✔️](go%2F0846-hand-of-straights.go)
|
|
[✔️](java%2F0846-hand-of-straights.java)
|
[✔️](javascript%2F0846-hand-of-straights.js)
|
[✔️](kotlin%2F0846-hand-of-straights.kt)
|
[✔️](python%2F0846-hand-of-straights.py)
|
[✔️](ruby%2F0846-hand-of-straights.rb)
|
|
|
[✔️](swift%2F0846-hand-of-straights.swift)
|
[✔️](typescript%2F0846-hand-of-straights.ts)
-[2439 - Minimize Maximum of Array](https://leetcode.com/problems/minimize-maximum-of-array/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2439-minimize-maximum-of-array.js)
|
[✔️](kotlin%2F2439-minimize-maximum-of-array.kt)
|
|
|
|
|
|
-[0649 - Dota2 Senate](https://leetcode.com/problems/dota2-senate/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F0649-dota2-senate.kt)
|
|
|
|
|
|
-[1423 - Maximum Points You Can Obtain From Cards](https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/) |
|
|
|
[✔️](csharp%2F1423-Maximum-Points-You-Can-Obtain-from-Cards.cs)
|
|
|
|
|
[✔️](javascript%2F1423-maximum-points-you-can-obtain-from-cards.js)
|
[✔️](kotlin%2F1423-maximum-points-you-can-obtain-from-cards.kt)
|
[✔️](python%2F1423-maximum-points-you-can-obtain-from-cards.py)
|
|
|
|
|
-[1899 - Merge Triplets to Form Target Triplet](https://leetcode.com/problems/merge-triplets-to-form-target-triplet/) |
|
[✔️](c%2F1899-merge-triplets-to-form-target-triplet.c)
|
[✔️](cpp%2F1899-merge-triplets-to-form-target-triplet.cpp)
|
[✔️](csharp%2F1899-Merge-Triplets-to-Form-Target-Triplet.cs)
|
|
|
|
[✔️](java%2F1899-merge-triplets-to-form-target-triplet.java)
|
[✔️](javascript%2F1899-merge-triplets-to-form-target-triplet.js)
|
[✔️](kotlin%2F1899-merge-triplets-to-form-target-triplet.kt)
|
[✔️](python%2F1899-merge-triplets-to-form-target-triplet.py)
|
[✔️](ruby%2F1899-merge-triplets-to-form-target-triplet.rb)
|
|
|
[✔️](swift%2F1899-Merge-Triplets-To-Form-Target-Triplet.swift)
|
[✔️](typescript%2F1899-Merge-Triplets-to-Form-Target-Triplet.ts)
-[0763 - Partition Labels](https://leetcode.com/problems/partition-labels/) |
|
[✔️](c%2F0763-partition-labels.c)
|
[✔️](cpp%2F0763-partition-labels.cpp)
|
[✔️](csharp%2F0763-partition-labels.cs)
|
|
[✔️](go%2F0763-partition-labels.go)
|
|
[✔️](java%2F0763-partition-labels.java)
|
[✔️](javascript%2F0763-partition-labels.js)
|
[✔️](kotlin%2F0763-partition-labels.kt)
|
[✔️](python%2F0763-partition-labels.py)
|
[✔️](ruby%2F0763-partition-labels.rb)
|
|
|
[✔️](swift%2F0763-partition-labels.swift)
|
-[0678 - Valid Parenthesis String](https://leetcode.com/problems/valid-parenthesis-string/) |
|
[✔️](c%2F0678-valid-parenthesis-string.c)
|
[✔️](cpp%2F0678-valid-parenthesis-string.cpp)
|
[✔️](csharp%2F0678-valid-parenthesis-string.cs)
|
|
[✔️](go%2F0678-valid-parenthesis-string.go)
|
|
[✔️](java%2F0678-valid-parenthesis-string.java)
|
[✔️](javascript%2F0678-valid-parenthesis-string.js)
|
[✔️](kotlin%2F0678-valid-parenthesis-string.kt)
|
[✔️](python%2F0678-valid-parenthesis-string.py)
|
|
[✔️](rust%2F0678-valid-parenthesis-string.rs)
|
|
[✔️](swift%2F0678-valid-parenthesis-string.swift)
|
[✔️](typescript%2F0678-valid-parenthesis-string.ts)
-[1921 - Eliminate Maximum Number of Monsters](https://leetcode.com/problems/eliminate-maximum-number-of-monsters/) |
|
|
[✔️](cpp%2F1921-eliminate-maximum-number-of-monsters.cpp)
|
|
|
|
|
[✔️](java%2F1921-eliminate-maximum-number-of-monsters.java)
|
[✔️](javascript%2F1921-eliminate-maximum-number-of-monsters.js)
|
[✔️](kotlin%2F1921-eliminate-maximum-number-of-monsters.kt)
|
|
|
|
|
|
-[1029 - Two City Scheduling](https://leetcode.com/problems/two-city-scheduling/) |
|
|
|
|
|
[✔️](go%2F1029-two-city-scheduling.go)
|
|
[✔️](java%2F1029-two-city-scheduling.java)
|
[✔️](javascript%2F1029-two-city-scheduling.js)
|
[✔️](kotlin%2F1029-two-city-scheduling.kt)
|
[✔️](python%2F1029-two-city-scheduling.py)
|
|
[✔️](rust%2F1029-two-city-scheduling.rs)
|
|
|
[✔️](typescript%2F1029-two-city-scheduling.ts)
-[0646 - Maximum Length of Pair Chain](https://leetcode.com/problems/maximum-length-of-pair-chain/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F0646-maximum-length-of-pair-chain.kt)
|
|
|
|
|
|
-[1647 - Minimum Deletions to Make Character Frequencies Unique](https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/) |
|
|
|
|
|
|
|
[✔️](java%2F1647-minimum-deletions-to-make-character-frequencies-unique.java)
|
[✔️](javascript%2F1647-minimum-deletions-to-make-character-frequencies-unique.js)
|
[✔️](kotlin%2F1647-minimum-deletions-to-make-character-frequencies-unique.kt)
|
|
|
|
|
|
-[135- - Candy](https://leetcode.com/problems/candy/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
+| Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS | +| ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | +| [0053 - Maximum Subarray](https://leetcode.com/problems/maximum-subarray/) |
|
[✔️](c%2F0053-maximum-subarray.c)
|
[✔️](cpp%2F0053-maximum-subarray.cpp)
|
[✔️](csharp%2F0053-maximum-subarray.cs)
|
|
[✔️](go%2F0053-maximum-subarray.go)
|
|
[✔️](java%2F0053-maximum-subarray.java)
|
[✔️](javascript%2F0053-maximum-subarray.js)
|
[✔️](kotlin%2F0053-maximum-subarray.kt)
|
[✔️](python%2F0053-maximum-subarray.py)
|
[✔️](ruby%2F0053-maximum-subarray.rb)
|
[✔️](rust%2F0053-maximum-subarray.rs)
|
|
[✔️](swift%2F0053-maximum-subarray.swift)
|
[✔️](typescript%2F0053-maximum-subarray.ts)
| +| [0918 - Maximum Sum Circular Subarray](https://leetcode.com/problems/maximum-sum-circular-subarray/) |
|
|
|
|
|
[✔️](go%2F0918-maximum-sum-circular-subarray.go)
|
|
[✔️](java%2F0918-maximum-sum-circular-subarray.java)
|
[✔️](javascript%2F0918-maximum-sum-circular-subarray.js)
|
[✔️](kotlin%2F0918-maximum-sum-circular-subarray.kt)
|
[✔️](python%2F0918-maximum-sum-circular-subarray.py)
|
|
[✔️](rust%2F0918-maximum-sum-circular-subarray.rs)
|
|
[✔️](swift%2F0918-maximum-sum-circular-subarray.swift)
|
[✔️](typescript%2F0918-maximum-sum-circular-subarray.ts)
| +| [0978 - Longest Turbulent Array](https://leetcode.com/problems/longest-turbulent-subarray/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F0978-longest-turbulent-subarray.js)
|
[✔️](kotlin%2F0978-longest-turbulent-subarray.kt)
|
[✔️](python%2F0978-longest-turbulent-subarray.py)
|
|
|
|
[✔️](swift%2F0978-longest-turbulent-subarray.swift)
|
| +| [0055 - Jump Game](https://leetcode.com/problems/jump-game/) |
|
[✔️](c%2F0055-jump-game.c)
|
[✔️](cpp%2F0055-jump-game.cpp)
|
[✔️](csharp%2F0055-jump-game.cs)
|
|
[✔️](go%2F0055-jump-game.go)
|
|
[✔️](java%2F0055-jump-game.java)
|
[✔️](javascript%2F0055-jump-game.js)
|
[✔️](kotlin%2F0055-jump-game.kt)
|
[✔️](python%2F0055-jump-game.py)
|
|
[✔️](rust%2F0055-jump-game.rs)
|
|
[✔️](swift%2F0055-jump-game.swift)
|
[✔️](typescript%2F0055-jump-game.ts)
| +| [0045 - Jump Game II](https://leetcode.com/problems/jump-game-ii/) |
|
[✔️](c%2F0045-jump-game-ii.c)
|
[✔️](cpp%2F0045-jump-game-ii.cpp)
|
[✔️](csharp%2F0045-jump-game-ii.cs)
|
|
[✔️](go%2F0045-jump-game-ii.go)
|
|
[✔️](java%2F0045-jump-game-ii.java)
|
[✔️](javascript%2F0045-jump-game-ii.js)
|
[✔️](kotlin%2F0045-jump-game-ii.kt)
|
[✔️](python%2F0045-jump-game-ii.py)
|
[✔️](ruby%2F0045-jump-game-ii.rb)
|
[✔️](rust%2F0045-jump-game-ii.rs)
|
|
[✔️](swift%2F0045-jump-game-ii.swift)
|
[✔️](typescript%2F0045-jump-game-ii.ts)
| +| [1871 - Jump Game VII](https://leetcode.com/problems/jump-game-vii/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1871-jump-game-vii.kt)
|
|
|
|
|
|
| +| [0134 - Gas Station](https://leetcode.com/problems/gas-station/) |
|
[✔️](c%2F0134-gas-station.c)
|
[✔️](cpp%2F0134-gas-station.cpp)
|
[✔️](csharp%2F0134-gas-station.cs)
|
|
[✔️](go%2F0134-gas-station.go)
|
|
[✔️](java%2F0134-gas-station.java)
|
[✔️](javascript%2F0134-gas-station.js)
|
[✔️](kotlin%2F0134-gas-station.kt)
|
[✔️](python%2F0134-gas-station.py)
|
[✔️](ruby%2F0134-gas-station.rb)
|
|
|
[✔️](swift%2F0134-gas-station.swift)
|
[✔️](typescript%2F0134-gas-station.ts)
| +| [0846 - Hand of Straights](https://leetcode.com/problems/hand-of-straights/) |
|
[✔️](c%2F0846-hand-of-straights.c)
|
[✔️](cpp%2F0846-hand-of-straights.cpp)
|
[✔️](csharp%2F0846-hand-of-straights.cs)
|
|
[✔️](go%2F0846-hand-of-straights.go)
|
|
[✔️](java%2F0846-hand-of-straights.java)
|
[✔️](javascript%2F0846-hand-of-straights.js)
|
[✔️](kotlin%2F0846-hand-of-straights.kt)
|
[✔️](python%2F0846-hand-of-straights.py)
|
[✔️](ruby%2F0846-hand-of-straights.rb)
|
|
|
[✔️](swift%2F0846-hand-of-straights.swift)
|
[✔️](typescript%2F0846-hand-of-straights.ts)
| +| [2439 - Minimize Maximum of Array](https://leetcode.com/problems/minimize-maximum-of-array/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2439-minimize-maximum-of-array.js)
|
[✔️](kotlin%2F2439-minimize-maximum-of-array.kt)
|
|
|
|
|
|
| +| [0649 - Dota2 Senate](https://leetcode.com/problems/dota2-senate/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F0649-dota2-senate.kt)
|
|
|
|
|
|
| +| [1423 - Maximum Points You Can Obtain From Cards](https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/) |
|
|
|
[✔️](csharp%2F1423-Maximum-Points-You-Can-Obtain-from-Cards.cs)
|
|
|
|
|
[✔️](javascript%2F1423-maximum-points-you-can-obtain-from-cards.js)
|
[✔️](kotlin%2F1423-maximum-points-you-can-obtain-from-cards.kt)
|
[✔️](python%2F1423-maximum-points-you-can-obtain-from-cards.py)
|
|
|
|
|
| +| [1899 - Merge Triplets to Form Target Triplet](https://leetcode.com/problems/merge-triplets-to-form-target-triplet/) |
|
[✔️](c%2F1899-merge-triplets-to-form-target-triplet.c)
|
[✔️](cpp%2F1899-merge-triplets-to-form-target-triplet.cpp)
|
[✔️](csharp%2F1899-Merge-Triplets-to-Form-Target-Triplet.cs)
|
|
|
|
[✔️](java%2F1899-merge-triplets-to-form-target-triplet.java)
|
[✔️](javascript%2F1899-merge-triplets-to-form-target-triplet.js)
|
[✔️](kotlin%2F1899-merge-triplets-to-form-target-triplet.kt)
|
[✔️](python%2F1899-merge-triplets-to-form-target-triplet.py)
|
[✔️](ruby%2F1899-merge-triplets-to-form-target-triplet.rb)
|
|
|
[✔️](swift%2F1899-Merge-Triplets-To-Form-Target-Triplet.swift)
|
[✔️](typescript%2F1899-Merge-Triplets-to-Form-Target-Triplet.ts)
| +| [0763 - Partition Labels](https://leetcode.com/problems/partition-labels/) |
|
[✔️](c%2F0763-partition-labels.c)
|
[✔️](cpp%2F0763-partition-labels.cpp)
|
[✔️](csharp%2F0763-partition-labels.cs)
|
|
[✔️](go%2F0763-partition-labels.go)
|
|
[✔️](java%2F0763-partition-labels.java)
|
[✔️](javascript%2F0763-partition-labels.js)
|
[✔️](kotlin%2F0763-partition-labels.kt)
|
[✔️](python%2F0763-partition-labels.py)
|
[✔️](ruby%2F0763-partition-labels.rb)
|
|
|
[✔️](swift%2F0763-partition-labels.swift)
|
| +| [0678 - Valid Parenthesis String](https://leetcode.com/problems/valid-parenthesis-string/) |
|
[✔️](c%2F0678-valid-parenthesis-string.c)
|
[✔️](cpp%2F0678-valid-parenthesis-string.cpp)
|
[✔️](csharp%2F0678-valid-parenthesis-string.cs)
|
|
[✔️](go%2F0678-valid-parenthesis-string.go)
|
|
[✔️](java%2F0678-valid-parenthesis-string.java)
|
[✔️](javascript%2F0678-valid-parenthesis-string.js)
|
[✔️](kotlin%2F0678-valid-parenthesis-string.kt)
|
[✔️](python%2F0678-valid-parenthesis-string.py)
|
|
[✔️](rust%2F0678-valid-parenthesis-string.rs)
|
|
[✔️](swift%2F0678-valid-parenthesis-string.swift)
|
[✔️](typescript%2F0678-valid-parenthesis-string.ts)
| +| [1921 - Eliminate Maximum Number of Monsters](https://leetcode.com/problems/eliminate-maximum-number-of-monsters/) |
|
|
[✔️](cpp%2F1921-eliminate-maximum-number-of-monsters.cpp)
|
|
|
|
|
[✔️](java%2F1921-eliminate-maximum-number-of-monsters.java)
|
[✔️](javascript%2F1921-eliminate-maximum-number-of-monsters.js)
|
[✔️](kotlin%2F1921-eliminate-maximum-number-of-monsters.kt)
|
|
|
|
|
|
| +| [1029 - Two City Scheduling](https://leetcode.com/problems/two-city-scheduling/) |
|
|
|
|
|
[✔️](go%2F1029-two-city-scheduling.go)
|
|
[✔️](java%2F1029-two-city-scheduling.java)
|
[✔️](javascript%2F1029-two-city-scheduling.js)
|
[✔️](kotlin%2F1029-two-city-scheduling.kt)
|
[✔️](python%2F1029-two-city-scheduling.py)
|
|
[✔️](rust%2F1029-two-city-scheduling.rs)
|
|
|
[✔️](typescript%2F1029-two-city-scheduling.ts)
| +| [0646 - Maximum Length of Pair Chain](https://leetcode.com/problems/maximum-length-of-pair-chain/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F0646-maximum-length-of-pair-chain.kt)
|
|
|
|
|
|
| +| [1647 - Minimum Deletions to Make Character Frequencies Unique](https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/) |
|
|
|
|
|
|
|
[✔️](java%2F1647-minimum-deletions-to-make-character-frequencies-unique.java)
|
[✔️](javascript%2F1647-minimum-deletions-to-make-character-frequencies-unique.js)
|
[✔️](kotlin%2F1647-minimum-deletions-to-make-character-frequencies-unique.kt)
|
|
|
|
|
|
| +| [135- - Candy](https://leetcode.com/problems/candy/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| ### Intervals -Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS ----- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- -[0057 - Insert Interval](https://leetcode.com/problems/insert-interval/) |
|
[✔️](c%2F0057-insert-interval.c)
|
[✔️](cpp%2F0057-insert-interval.cpp)
|
[✔️](csharp%2F0057-insert-interval.cs)
|
|
[✔️](go%2F0057-insert-interval.go)
|
|
[✔️](java%2F0057-insert-interval.java)
|
[✔️](javascript%2F0057-insert-interval.js)
|
[✔️](kotlin%2F0057-insert-interval.kt)
|
[✔️](python%2F0057-insert-interval.py)
|
|
[✔️](rust%2F0057-insert-interval.rs)
|
|
[✔️](swift%2F0057-insert-interval.swift)
|
[✔️](typescript%2F0057-insert-interval.ts)
-[0056 - Merge Intervals](https://leetcode.com/problems/merge-intervals/) |
|
[✔️](c%2F0056-merge-intervals.c)
|
[✔️](cpp%2F0056-merge-intervals.cpp)
|
[✔️](csharp%2F0056-merge-intervals.cs)
|
|
[✔️](go%2F0056-merge-intervals.go)
|
|
[✔️](java%2F0056-merge-intervals.java)
|
[✔️](javascript%2F0056-merge-intervals.js)
|
[✔️](kotlin%2F0056-merge-intervals.kt)
|
[✔️](python%2F0056-merge-intervals.py)
|
|
[✔️](rust%2F0056-merge-intervals.rs)
|
[✔️](scala%2F0056-merge-intervals.scala)
|
[✔️](swift%2F0056-merge-intervals.swift)
|
[✔️](typescript%2F0056-merge-intervals.ts)
-[0435 - Non Overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/) |
|
[✔️](c%2F0435-non-overlapping-intervals.c)
|
[✔️](cpp%2F0435-non-overlapping-intervals.cpp)
|
[✔️](csharp%2F0435-non-overlapping-intervals.cs)
|
|
[✔️](go%2F0435-non-overlapping-intervals.go)
|
|
[✔️](java%2F0435-non-overlapping-intervals.java)
|
[✔️](javascript%2F0435-non-overlapping-intervals.js)
|
[✔️](kotlin%2F0435-non-overlapping-intervals.kt)
|
[✔️](python%2F0435-non-overlapping-intervals.py)
|
|
[✔️](rust%2F0435-non-overlapping-intervals.rs)
|
[✔️](scala%2F0435-non-overlapping-intervals.scala)
|
[✔️](swift%2F0435-non-overlapping-intervals.swift)
|
[✔️](typescript%2F0435-non-overlapping-intervals.ts)
-[0252 - Meeting Rooms](https://leetcode.com/problems/meeting-rooms/) |
|
|
[✔️](cpp%2F0252-meeting-rooms.cpp)
|
[✔️](csharp%2F0252-meeting-rooms.cs)
|
|
[✔️](go%2F0252-meeting-rooms.go)
|
|
[✔️](java%2F0252-meeting-rooms.java)
|
[✔️](javascript%2F0252-meeting-rooms.js)
|
[✔️](kotlin%2F0252-meeting-rooms.kt)
|
[✔️](python%2F0252-meeting-rooms.py)
|
|
|
|
[✔️](swift%2F0252-meeting-rooms.swift)
|
-[0253 - Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/) |
|
|
[✔️](cpp%2F0253-meeting-rooms-ii.cpp)
|
[✔️](csharp%2F0253-meeting-rooms-ii.cs)
|
|
|
|
[✔️](java%2F0253-meeting-rooms-ii.java)
|
[✔️](javascript%2F0253-meeting-rooms-ii.js)
|
[✔️](kotlin%2F0253-meeting-rooms-ii.kt)
|
[✔️](python%2F0253-meeting-rooms-ii.py)
|
|
[✔️](rust%2F0253-meeting-rooms-ii.rs)
|
|
[✔️](swift%2F0253-meeting-rooms-ii.swift)
|
-[1288 - Remove Covered Intervals](https://leetcode.com/problems/remove-covered-intervals/) |
|
[✔️](c%2F1288-Remove-Covered-Intervals.c)
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1288-remove-covered-intervals.kt)
|
[✔️](python%2F1288-remove-covered-intervals.py)
|
|
|
|
|
-[1851 - Minimum Interval to Include Each Query](https://leetcode.com/problems/minimum-interval-to-include-each-query/) |
|
|
[✔️](cpp%2F1851-Minimum-Interval-To-Include-Each-Query.cpp)
|
[✔️](csharp%2F1851-Minimum-Interval-to-Include-Each-Query.cs)
|
|
|
|
[✔️](java%2F1851-Minimum-Interval-to-Include-Each-Query.java)
|
[✔️](javascript%2F1851-minimum-interval-to-include-each-query.js)
|
[✔️](kotlin%2F1851-minimum-interval-to-include-each-query.kt)
|
[✔️](python%2F1851-minimum-interval-to-include-each-query.py)
|
|
|
|
[✔️](swift%2F1851-minimum-interval-to-include-each-query.swift)
|
-[0352 - Data Stream as Disjoint Intervals](https://leetcode.com/problems/data-stream-as-disjoint-intervals/) |
|
|
|
|
|
[✔️](go%2F0352-data-stream-as-disjoint-intervals.go)
|
|
|
[✔️](javascript%2F0352-data-stream-as-disjoint-intervals.js)
|
[✔️](kotlin%2F0352-data-stream-as-disjoint-intervals.kt)
|
|
|
[✔️](rust%2F0352-data-stream-as-disjoint-intervals.rs)
|
|
|
[✔️](typescript%2F0352-data-stream-as-disjoint-intervals.ts)
+| Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS | +| --------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------- | --------------------------------------- | ----------------------------------------------------------------------------------------- | --------------------------------------- | -------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| [0057 - Insert Interval](https://leetcode.com/problems/insert-interval/) |
|
[✔️](c%2F0057-insert-interval.c)
|
[✔️](cpp%2F0057-insert-interval.cpp)
|
[✔️](csharp%2F0057-insert-interval.cs)
|
|
[✔️](go%2F0057-insert-interval.go)
|
|
[✔️](java%2F0057-insert-interval.java)
|
[✔️](javascript%2F0057-insert-interval.js)
|
[✔️](kotlin%2F0057-insert-interval.kt)
|
[✔️](python%2F0057-insert-interval.py)
|
|
[✔️](rust%2F0057-insert-interval.rs)
|
|
[✔️](swift%2F0057-insert-interval.swift)
|
[✔️](typescript%2F0057-insert-interval.ts)
| +| [0056 - Merge Intervals](https://leetcode.com/problems/merge-intervals/) |
|
[✔️](c%2F0056-merge-intervals.c)
|
[✔️](cpp%2F0056-merge-intervals.cpp)
|
[✔️](csharp%2F0056-merge-intervals.cs)
|
|
[✔️](go%2F0056-merge-intervals.go)
|
|
[✔️](java%2F0056-merge-intervals.java)
|
[✔️](javascript%2F0056-merge-intervals.js)
|
[✔️](kotlin%2F0056-merge-intervals.kt)
|
[✔️](python%2F0056-merge-intervals.py)
|
|
[✔️](rust%2F0056-merge-intervals.rs)
|
[✔️](scala%2F0056-merge-intervals.scala)
|
[✔️](swift%2F0056-merge-intervals.swift)
|
[✔️](typescript%2F0056-merge-intervals.ts)
| +| [0435 - Non Overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/) |
|
[✔️](c%2F0435-non-overlapping-intervals.c)
|
[✔️](cpp%2F0435-non-overlapping-intervals.cpp)
|
[✔️](csharp%2F0435-non-overlapping-intervals.cs)
|
|
[✔️](go%2F0435-non-overlapping-intervals.go)
|
|
[✔️](java%2F0435-non-overlapping-intervals.java)
|
[✔️](javascript%2F0435-non-overlapping-intervals.js)
|
[✔️](kotlin%2F0435-non-overlapping-intervals.kt)
|
[✔️](python%2F0435-non-overlapping-intervals.py)
|
|
[✔️](rust%2F0435-non-overlapping-intervals.rs)
|
[✔️](scala%2F0435-non-overlapping-intervals.scala)
|
[✔️](swift%2F0435-non-overlapping-intervals.swift)
|
[✔️](typescript%2F0435-non-overlapping-intervals.ts)
| +| [0252 - Meeting Rooms](https://leetcode.com/problems/meeting-rooms/) |
|
|
[✔️](cpp%2F0252-meeting-rooms.cpp)
|
[✔️](csharp%2F0252-meeting-rooms.cs)
|
|
[✔️](go%2F0252-meeting-rooms.go)
|
|
[✔️](java%2F0252-meeting-rooms.java)
|
[✔️](javascript%2F0252-meeting-rooms.js)
|
[✔️](kotlin%2F0252-meeting-rooms.kt)
|
[✔️](python%2F0252-meeting-rooms.py)
|
|
|
|
[✔️](swift%2F0252-meeting-rooms.swift)
|
| +| [0253 - Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/) |
|
|
[✔️](cpp%2F0253-meeting-rooms-ii.cpp)
|
[✔️](csharp%2F0253-meeting-rooms-ii.cs)
|
|
|
|
[✔️](java%2F0253-meeting-rooms-ii.java)
|
[✔️](javascript%2F0253-meeting-rooms-ii.js)
|
[✔️](kotlin%2F0253-meeting-rooms-ii.kt)
|
[✔️](python%2F0253-meeting-rooms-ii.py)
|
|
[✔️](rust%2F0253-meeting-rooms-ii.rs)
|
|
[✔️](swift%2F0253-meeting-rooms-ii.swift)
|
| +| [1288 - Remove Covered Intervals](https://leetcode.com/problems/remove-covered-intervals/) |
|
[✔️](c%2F1288-Remove-Covered-Intervals.c)
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1288-remove-covered-intervals.kt)
|
[✔️](python%2F1288-remove-covered-intervals.py)
|
|
|
|
|
| +| [1851 - Minimum Interval to Include Each Query](https://leetcode.com/problems/minimum-interval-to-include-each-query/) |
|
|
[✔️](cpp%2F1851-Minimum-Interval-To-Include-Each-Query.cpp)
|
[✔️](csharp%2F1851-Minimum-Interval-to-Include-Each-Query.cs)
|
|
|
|
[✔️](java%2F1851-Minimum-Interval-to-Include-Each-Query.java)
|
[✔️](javascript%2F1851-minimum-interval-to-include-each-query.js)
|
[✔️](kotlin%2F1851-minimum-interval-to-include-each-query.kt)
|
[✔️](python%2F1851-minimum-interval-to-include-each-query.py)
|
|
|
|
[✔️](swift%2F1851-minimum-interval-to-include-each-query.swift)
|
| +| [0352 - Data Stream as Disjoint Intervals](https://leetcode.com/problems/data-stream-as-disjoint-intervals/) |
|
|
|
|
|
[✔️](go%2F0352-data-stream-as-disjoint-intervals.go)
|
|
|
[✔️](javascript%2F0352-data-stream-as-disjoint-intervals.js)
|
[✔️](kotlin%2F0352-data-stream-as-disjoint-intervals.kt)
|
|
|
[✔️](rust%2F0352-data-stream-as-disjoint-intervals.rs)
|
|
|
[✔️](typescript%2F0352-data-stream-as-disjoint-intervals.ts)
| ### Math & Geometry -Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS ----- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- -[0168 - Excel Sheet Column Title](https://leetcode.com/problems/excel-sheet-column-title/) |
|
|
|
[✔️](csharp%2F0168-excel-sheet-column-title.cs)
|
|
|
|
[✔️](java%2F0168-excel-sheet-column-title.java)
|
|
[✔️](kotlin%2F0168-excel-sheet-column-title.kt)
|
[✔️](python%2F0168-excel-sheet-column-title.py)
|
|
|
|
|
-[1071 - Greatest Common Divisor of Strings](https://leetcode.com/problems/greatest-common-divisor-of-strings/) |
|
|
[✔️](cpp%2F1071-greatest-common-divisor-of-strings.cpp)
|
|
|
[✔️](go%2F1071-greatest-common-divisor-of-strings.go)
|
|
[✔️](java%2F1071-greatest-common-divisor-of-strings.java)
|
[✔️](javascript%2F1071-greatest-common-divisor-of-strings.js)
|
[✔️](kotlin%2F1071-greatest-common-divisor-of-strings.kt)
|
|
|
[✔️](rust%2F1071-greatest-common-divisor-of-strings.rs)
|
|
|
[✔️](typescript%2F1071-greatest-common-divisor-of-strings.ts)
-[1523 - Count Odd Numbers in an Interval Range](https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1523-count-odd-numbers-in-an-interval-range.kt)
|
[✔️](python%2F1523-count-odd-numbers-in-an-interval-range.py)
|
|
|
|
|
-[1572 - Matrix Diagonal Sum](https://leetcode.com/problems/matrix-diagonal-sum/) |
|
|
|
|
|
|
|
[✔️](java%2F1572-matrix-diagonal-sum.java)
|
[✔️](javascript%2F1572-matrix-diagonal-sum.js)
|
[✔️](kotlin%2F1572-matrix-diagonal-sum.kt)
|
[✔️](python%2F1572-matrix-diagonal-sum.py)
|
|
|
|
|
-[0149 - Maximum Points on a Line](https://leetcode.com/problems/max-points-on-a-line/) |
|
|
[✔️](cpp%2F0149-max-points-on-a-line.cpp)
|
|
|
|
|
[✔️](java%2F0149-max-points-on-a-line.java)
|
[✔️](javascript%2F0149-max-points-on-a-line.js)
|
[✔️](kotlin%2F0149-max-points-on-a-line.kt)
|
[✔️](python%2F0149-max-points-on-a-line.py)
|
|
[✔️](rust%2F0149-max-points-on-a-line.rs)
|
|
|
[✔️](typescript%2F0149-max-points-on-a-line.ts)
-[0048 - Rotate Image](https://leetcode.com/problems/rotate-image/) |
|
[✔️](c%2F0048-rotate-image.c)
|
[✔️](cpp%2F0048-rotate-image.cpp)
|
[✔️](csharp%2F0048-rotate-image.cs)
|
|
[✔️](go%2F0048-rotate-image.go)
|
|
[✔️](java%2F0048-rotate-image.java)
|
[✔️](javascript%2F0048-rotate-image.js)
|
[✔️](kotlin%2F0048-rotate-image.kt)
|
[✔️](python%2F0048-rotate-image.py)
|
[✔️](ruby%2F0048-rotate-image.rb)
|
[✔️](rust%2F0048-rotate-image.rs)
|
|
[✔️](swift%2F0048-rotate-image.swift)
|
[✔️](typescript%2F0048-rotate-image.ts)
-[0054 - Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) |
|
[✔️](c%2F0054-spiral-matrix.c)
|
[✔️](cpp%2F0054-spiral-matrix.cpp)
|
[✔️](csharp%2F0054-spiral-matrix.cs)
|
|
[✔️](go%2F0054-spiral-matrix.go)
|
|
[✔️](java%2F0054-spiral-matrix.java)
|
[✔️](javascript%2F0054-spiral-matrix.js)
|
[✔️](kotlin%2F0054-spiral-matrix.kt)
|
[✔️](python%2F0054-spiral-matrix.py)
|
[✔️](ruby%2F0054-spiral-matrix.rb)
|
|
|
[✔️](swift%2F0054-spiral-matrix.swift)
|
[✔️](typescript%2F0054-spiral-matrix.ts)
-[0059 - Spiral Matrix II ](https://leetcode.com/problems/spiral-matrix-ii/) |
|
|
[✔️](cpp%2F0059-spiral-matrix-ii.cpp)
|
|
|
|
|
[✔️](java%2F0059-spiral-matrix-ii.java)
|
[✔️](javascript%2F0059-spiral-matrix-ii.js)
|
[✔️](kotlin%2F0059-spiral-matrix-ii.kt)
|
|
|
|
|
|
-[0073 - Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/) |
|
[✔️](c%2F0073-set-matrix-zeroes.c)
|
[✔️](cpp%2F0073-set-matrix-zeroes.cpp)
|
[✔️](csharp%2F0073-set-matrix-zeroes.cs)
|
|
[✔️](go%2F0073-set-matrix-zeroes.go)
|
|
[✔️](java%2F0073-set-matrix-zeroes.java)
|
[✔️](javascript%2F0073-set-matrix-zeroes.js)
|
[✔️](kotlin%2F0073-set-matrix-zeroes.kt)
|
[✔️](python%2F0073-set-matrix-zeroes.py)
|
[✔️](ruby%2F0073-set-matrix-zeroes.rb)
|
|
|
[✔️](swift%2F0073-set-matrix-zeroes.swift)
|
[✔️](typescript%2F0073-set-matrix-zeroes.ts)
-[0202 - Happy Number](https://leetcode.com/problems/happy-number/) |
|
[✔️](c%2F0202-happy-number.c)
|
[✔️](cpp%2F0202-happy-number.cpp)
|
[✔️](csharp%2F0202-happy-number.cs)
|
|
[✔️](go%2F0202-happy-number.go)
|
|
[✔️](java%2F0202-happy-number.java)
|
[✔️](javascript%2F0202-happy-number.js)
|
[✔️](kotlin%2F0202-happy-number.kt)
|
[✔️](python%2F0202-happy-number.py)
|
[✔️](ruby%2F0202-happy-number.rb)
|
[✔️](rust%2F0202-happy-number.rs)
|
|
[✔️](swift%2F0202-happy-number.swift)
|
[✔️](typescript%2F0202-happy-number.ts)
-[0066 - Plus One](https://leetcode.com/problems/plus-one/) |
|
[✔️](c%2F0066-plus-one.c)
|
[✔️](cpp%2F0066-plus-one.cpp)
|
[✔️](csharp%2F0066-plus-one.cs)
|
|
[✔️](go%2F0066-plus-one.go)
|
|
[✔️](java%2F0066-plus-one.java)
|
[✔️](javascript%2F0066-plus-one.js)
|
[✔️](kotlin%2F0066-plus-one.kt)
|
[✔️](python%2F0066-plus-one.py)
|
[✔️](ruby%2F0066-plus-one.rb)
|
[✔️](rust%2F0066-plus-one.rs)
|
|
[✔️](swift%2F0066-plus-one.swift)
|
[✔️](typescript%2F0066-plus-one.ts)
-[0009 - Palindrome Number](https://leetcode.com/problems/palindrome-number/) |
|
[✔️](c%2F0009-palindrome-number.c)
|
[✔️](cpp%2F0009-palindrome-number.cpp)
|
|
|
[✔️](go%2F0009-palindrome-number.go)
|
|
[✔️](java%2F0009-palindrome-number.java)
|
[✔️](javascript%2F0009-palindrome-number.js)
|
[✔️](kotlin%2F0009-palindrome-number.kt)
|
[✔️](python%2F0009-palindrome-number.py)
|
|
[✔️](rust%2F0009-palindrome-number.rs)
|
|
[✔️](swift%2F0009-palindrome-number.swift)
|
[✔️](typescript%2F0009-palindrome-number.ts)
-[0263 - Ugly Number](https://leetcode.com/problems/ugly-number/) |
|
[✔️](c%2F0263-ugly-number.c)
|
[✔️](cpp%2F0263-ugly-number.cpp)
|
|
|
[✔️](go%2F0263-ugly-number.go)
|
|
[✔️](java%2F0263-ugly-number.java)
|
[✔️](javascript%2F0263-ugly-number.js)
|
[✔️](kotlin%2F0263-ugly-number.kt)
|
[✔️](python%2F0263-ugly-number.py)
|
|
[✔️](rust%2F0263-ugly-number.rs)
|
|
[✔️](swift%2F0263-ugly-number.swift)
|
[✔️](typescript%2F0263-ugly-number.ts)
-[1260 - Shift 2D Grid](https://leetcode.com/problems/shift-2d-grid/) |
|
|
[✔️](cpp%2F1260-shift-2d-grid.cpp)
|
|
|
|
|
[✔️](java%2F1260-shift-2d-grid.java)
|
[✔️](javascript%2F1260-shift-2d-grid.js)
|
[✔️](kotlin%2F1260-shift-2d-grid.kt)
|
[✔️](python%2F1260-shift-2d-grid.py)
|
|
|
|
|
-[0013 - Roman to Integer](https://leetcode.com/problems/roman-to-integer/) |
|
[✔️](c%2F0013-roman-to-integer.c)
|
[✔️](cpp%2F0013-roman-to-integer.cpp)
|
|
|
[✔️](go%2F0013-roman-to-integer.go)
|
|
[✔️](java%2F0013-roman-to-integer.java)
|
[✔️](javascript%2F0013-roman-to-integer.js)
|
[✔️](kotlin%2F0013-roman-to-integer.kt)
|
[✔️](python%2F0013-roman-to-integer.py)
|
|
[✔️](rust%2F0013-roman-to-integer.rs)
|
|
|
[✔️](typescript%2F0013-roman-to-integer.ts)
-[0012 - Integer to Roman](https://leetcode.com/problems/integer-to-roman/) |
|
|
[✔️](cpp%2F0012-integer-to-roman.cpp)
|
|
|
[✔️](go%2F0012-integer-to-roman.go)
|
|
[✔️](java%2F0012-integer-to-roman.java)
|
[✔️](javascript%2F0012-integer-to-roman.js)
|
[✔️](kotlin%2F0012-integer-to-roman.kt)
|
[✔️](python%2F0012-integer-to-roman.py)
|
|
[✔️](rust%2F0012-integer-to-roman.rs)
|
|
|
[✔️](typescript%2F0012-integer-to-roman.ts)
-[0050 - Pow(x, n)](https://leetcode.com/problems/powx-n/) |
|
[✔️](c%2F0050-powx-n.c)
|
[✔️](cpp%2F0050-powx-n.cpp)
|
[✔️](csharp%2F0050-powx-n.cs)
|
|
|
|
[✔️](java%2F0050-powx-n.java)
|
[✔️](javascript%2F0050-powx-n.js)
|
[✔️](kotlin%2F0050-powx-n.kt)
|
[✔️](python%2F0050-powx-n.py)
|
[✔️](ruby%2F0050-powx-n.rb)
|
[✔️](rust%2F0050-powx-n.rs)
|
|
[✔️](swift%2F0050-powx-n.swift)
|
[✔️](typescript%2F0050-powx-n.ts)
-[0043 - Multiply Strings](https://leetcode.com/problems/multiply-strings/) |
|
[✔️](c%2F0043-multiply-strings.c)
|
[✔️](cpp%2F0043-multiply-strings.cpp)
|
[✔️](csharp%2F0043-multiply-strings.cs)
|
|
|
|
[✔️](java%2F0043-multiply-strings.java)
|
[✔️](javascript%2F0043-multiply-strings.js)
|
[✔️](kotlin%2F0043-multiply-strings.kt)
|
[✔️](python%2F0043-multiply-strings.py)
|
[✔️](ruby%2F0043-multiply-strings.rb)
|
[✔️](rust%2F0043-multiply-strings.rs)
|
|
[✔️](swift%2F0043-multiply-strings.swift)
|
[✔️](typescript%2F0043-multiply-strings.ts)
-[2013 - Detect Squares](https://leetcode.com/problems/detect-squares/) |
|
|
[✔️](cpp%2F2013-Detect-Squares.cpp)
|
[✔️](csharp%2F2013-Detect-Squares.cs)
|
|
|
|
[✔️](java%2F2013-Detect-Squares.java)
|
[✔️](javascript%2F2013-Detect-Squares.js)
|
[✔️](kotlin%2F2013-detect-squares.kt)
|
[✔️](python%2F2013-detect-squares.py)
|
[✔️](ruby%2F2013-detect-squares.rb)
|
[✔️](rust%2F2013-detect-squares.rs)
|
|
[✔️](swift%2F2013-detect-squares.swift)
|
-[1041 - Robot Bounded In Circle](https://leetcode.com/problems/robot-bounded-in-circle/) |
|
|
|
|
|
|
|
[✔️](java%2F1041-robot-bounded-in-circle.java)
|
|
[✔️](kotlin%2F1041-robot-bounded-in-circle.kt)
|
|
|
|
|
|
-[0006 - Zigzag Conversion](https://leetcode.com/problems/zigzag-conversion/) |
|
|
[✔️](cpp%2F0006-zigzag-conversion.cpp)
|
|
|
[✔️](go%2F0006-zigzag-conversion.go)
|
|
[✔️](java%2F0006-zigzag-conversion.java)
|
|
[✔️](kotlin%2F0006-zigzag-conversion.kt)
|
[✔️](python%2F0006-zigzag-conversion.py)
|
|
|
|
|
-[2028 - Find Missing Observations](https://leetcode.com/problems/find-missing-observations/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F2028-find-missing-observations.kt)
|
|
|
|
|
|
+| Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS | +| --------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ----------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | --------------------------------------- | ------------------------------------------------------------------------------------------ | --------------------------------------- | ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | +| [0168 - Excel Sheet Column Title](https://leetcode.com/problems/excel-sheet-column-title/) |
|
|
|
[✔️](csharp%2F0168-excel-sheet-column-title.cs)
|
|
|
|
[✔️](java%2F0168-excel-sheet-column-title.java)
|
|
[✔️](kotlin%2F0168-excel-sheet-column-title.kt)
|
[✔️](python%2F0168-excel-sheet-column-title.py)
|
|
|
|
|
| +| [1071 - Greatest Common Divisor of Strings](https://leetcode.com/problems/greatest-common-divisor-of-strings/) |
|
|
[✔️](cpp%2F1071-greatest-common-divisor-of-strings.cpp)
|
|
|
[✔️](go%2F1071-greatest-common-divisor-of-strings.go)
|
|
[✔️](java%2F1071-greatest-common-divisor-of-strings.java)
|
[✔️](javascript%2F1071-greatest-common-divisor-of-strings.js)
|
[✔️](kotlin%2F1071-greatest-common-divisor-of-strings.kt)
|
|
|
[✔️](rust%2F1071-greatest-common-divisor-of-strings.rs)
|
|
|
[✔️](typescript%2F1071-greatest-common-divisor-of-strings.ts)
| +| [1523 - Count Odd Numbers in an Interval Range](https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F1523-count-odd-numbers-in-an-interval-range.kt)
|
[✔️](python%2F1523-count-odd-numbers-in-an-interval-range.py)
|
|
|
|
|
| +| [1572 - Matrix Diagonal Sum](https://leetcode.com/problems/matrix-diagonal-sum/) |
|
|
|
|
|
|
|
[✔️](java%2F1572-matrix-diagonal-sum.java)
|
[✔️](javascript%2F1572-matrix-diagonal-sum.js)
|
[✔️](kotlin%2F1572-matrix-diagonal-sum.kt)
|
[✔️](python%2F1572-matrix-diagonal-sum.py)
|
|
|
|
|
| +| [0149 - Maximum Points on a Line](https://leetcode.com/problems/max-points-on-a-line/) |
|
|
[✔️](cpp%2F0149-max-points-on-a-line.cpp)
|
|
|
|
|
[✔️](java%2F0149-max-points-on-a-line.java)
|
[✔️](javascript%2F0149-max-points-on-a-line.js)
|
[✔️](kotlin%2F0149-max-points-on-a-line.kt)
|
[✔️](python%2F0149-max-points-on-a-line.py)
|
|
[✔️](rust%2F0149-max-points-on-a-line.rs)
|
|
|
[✔️](typescript%2F0149-max-points-on-a-line.ts)
| +| [0048 - Rotate Image](https://leetcode.com/problems/rotate-image/) |
|
[✔️](c%2F0048-rotate-image.c)
|
[✔️](cpp%2F0048-rotate-image.cpp)
|
[✔️](csharp%2F0048-rotate-image.cs)
|
|
[✔️](go%2F0048-rotate-image.go)
|
|
[✔️](java%2F0048-rotate-image.java)
|
[✔️](javascript%2F0048-rotate-image.js)
|
[✔️](kotlin%2F0048-rotate-image.kt)
|
[✔️](python%2F0048-rotate-image.py)
|
[✔️](ruby%2F0048-rotate-image.rb)
|
[✔️](rust%2F0048-rotate-image.rs)
|
|
[✔️](swift%2F0048-rotate-image.swift)
|
[✔️](typescript%2F0048-rotate-image.ts)
| +| [0054 - Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) |
|
[✔️](c%2F0054-spiral-matrix.c)
|
[✔️](cpp%2F0054-spiral-matrix.cpp)
|
[✔️](csharp%2F0054-spiral-matrix.cs)
|
|
[✔️](go%2F0054-spiral-matrix.go)
|
|
[✔️](java%2F0054-spiral-matrix.java)
|
[✔️](javascript%2F0054-spiral-matrix.js)
|
[✔️](kotlin%2F0054-spiral-matrix.kt)
|
[✔️](python%2F0054-spiral-matrix.py)
|
[✔️](ruby%2F0054-spiral-matrix.rb)
|
|
|
[✔️](swift%2F0054-spiral-matrix.swift)
|
[✔️](typescript%2F0054-spiral-matrix.ts)
| +| [0059 - Spiral Matrix II ](https://leetcode.com/problems/spiral-matrix-ii/) |
|
|
[✔️](cpp%2F0059-spiral-matrix-ii.cpp)
|
|
|
|
|
[✔️](java%2F0059-spiral-matrix-ii.java)
|
[✔️](javascript%2F0059-spiral-matrix-ii.js)
|
[✔️](kotlin%2F0059-spiral-matrix-ii.kt)
|
|
|
|
|
|
| +| [0073 - Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/) |
|
[✔️](c%2F0073-set-matrix-zeroes.c)
|
[✔️](cpp%2F0073-set-matrix-zeroes.cpp)
|
[✔️](csharp%2F0073-set-matrix-zeroes.cs)
|
|
[✔️](go%2F0073-set-matrix-zeroes.go)
|
|
[✔️](java%2F0073-set-matrix-zeroes.java)
|
[✔️](javascript%2F0073-set-matrix-zeroes.js)
|
[✔️](kotlin%2F0073-set-matrix-zeroes.kt)
|
[✔️](python%2F0073-set-matrix-zeroes.py)
|
[✔️](ruby%2F0073-set-matrix-zeroes.rb)
|
|
|
[✔️](swift%2F0073-set-matrix-zeroes.swift)
|
[✔️](typescript%2F0073-set-matrix-zeroes.ts)
| +| [0202 - Happy Number](https://leetcode.com/problems/happy-number/) |
|
[✔️](c%2F0202-happy-number.c)
|
[✔️](cpp%2F0202-happy-number.cpp)
|
[✔️](csharp%2F0202-happy-number.cs)
|
|
[✔️](go%2F0202-happy-number.go)
|
|
[✔️](java%2F0202-happy-number.java)
|
[✔️](javascript%2F0202-happy-number.js)
|
[✔️](kotlin%2F0202-happy-number.kt)
|
[✔️](python%2F0202-happy-number.py)
|
[✔️](ruby%2F0202-happy-number.rb)
|
[✔️](rust%2F0202-happy-number.rs)
|
|
[✔️](swift%2F0202-happy-number.swift)
|
[✔️](typescript%2F0202-happy-number.ts)
| +| [0066 - Plus One](https://leetcode.com/problems/plus-one/) |
|
[✔️](c%2F0066-plus-one.c)
|
[✔️](cpp%2F0066-plus-one.cpp)
|
[✔️](csharp%2F0066-plus-one.cs)
|
|
[✔️](go%2F0066-plus-one.go)
|
|
[✔️](java%2F0066-plus-one.java)
|
[✔️](javascript%2F0066-plus-one.js)
|
[✔️](kotlin%2F0066-plus-one.kt)
|
[✔️](python%2F0066-plus-one.py)
|
[✔️](ruby%2F0066-plus-one.rb)
|
[✔️](rust%2F0066-plus-one.rs)
|
|
[✔️](swift%2F0066-plus-one.swift)
|
[✔️](typescript%2F0066-plus-one.ts)
| +| [0009 - Palindrome Number](https://leetcode.com/problems/palindrome-number/) |
|
[✔️](c%2F0009-palindrome-number.c)
|
[✔️](cpp%2F0009-palindrome-number.cpp)
|
|
|
[✔️](go%2F0009-palindrome-number.go)
|
|
[✔️](java%2F0009-palindrome-number.java)
|
[✔️](javascript%2F0009-palindrome-number.js)
|
[✔️](kotlin%2F0009-palindrome-number.kt)
|
[✔️](python%2F0009-palindrome-number.py)
|
|
[✔️](rust%2F0009-palindrome-number.rs)
|
|
[✔️](swift%2F0009-palindrome-number.swift)
|
[✔️](typescript%2F0009-palindrome-number.ts)
| +| [0263 - Ugly Number](https://leetcode.com/problems/ugly-number/) |
|
[✔️](c%2F0263-ugly-number.c)
|
[✔️](cpp%2F0263-ugly-number.cpp)
|
|
|
[✔️](go%2F0263-ugly-number.go)
|
|
[✔️](java%2F0263-ugly-number.java)
|
[✔️](javascript%2F0263-ugly-number.js)
|
[✔️](kotlin%2F0263-ugly-number.kt)
|
[✔️](python%2F0263-ugly-number.py)
|
|
[✔️](rust%2F0263-ugly-number.rs)
|
|
[✔️](swift%2F0263-ugly-number.swift)
|
[✔️](typescript%2F0263-ugly-number.ts)
| +| [1260 - Shift 2D Grid](https://leetcode.com/problems/shift-2d-grid/) |
|
|
[✔️](cpp%2F1260-shift-2d-grid.cpp)
|
|
|
|
|
[✔️](java%2F1260-shift-2d-grid.java)
|
[✔️](javascript%2F1260-shift-2d-grid.js)
|
[✔️](kotlin%2F1260-shift-2d-grid.kt)
|
[✔️](python%2F1260-shift-2d-grid.py)
|
|
|
|
|
| +| [0013 - Roman to Integer](https://leetcode.com/problems/roman-to-integer/) |
|
[✔️](c%2F0013-roman-to-integer.c)
|
[✔️](cpp%2F0013-roman-to-integer.cpp)
|
|
|
[✔️](go%2F0013-roman-to-integer.go)
|
|
[✔️](java%2F0013-roman-to-integer.java)
|
[✔️](javascript%2F0013-roman-to-integer.js)
|
[✔️](kotlin%2F0013-roman-to-integer.kt)
|
[✔️](python%2F0013-roman-to-integer.py)
|
|
[✔️](rust%2F0013-roman-to-integer.rs)
|
|
|
[✔️](typescript%2F0013-roman-to-integer.ts)
| +| [0012 - Integer to Roman](https://leetcode.com/problems/integer-to-roman/) |
|
|
[✔️](cpp%2F0012-integer-to-roman.cpp)
|
|
|
[✔️](go%2F0012-integer-to-roman.go)
|
|
[✔️](java%2F0012-integer-to-roman.java)
|
[✔️](javascript%2F0012-integer-to-roman.js)
|
[✔️](kotlin%2F0012-integer-to-roman.kt)
|
[✔️](python%2F0012-integer-to-roman.py)
|
|
[✔️](rust%2F0012-integer-to-roman.rs)
|
|
|
[✔️](typescript%2F0012-integer-to-roman.ts)
| +| [0050 - Pow(x, n)](https://leetcode.com/problems/powx-n/) |
|
[✔️](c%2F0050-powx-n.c)
|
[✔️](cpp%2F0050-powx-n.cpp)
|
[✔️](csharp%2F0050-powx-n.cs)
|
|
|
|
[✔️](java%2F0050-powx-n.java)
|
[✔️](javascript%2F0050-powx-n.js)
|
[✔️](kotlin%2F0050-powx-n.kt)
|
[✔️](python%2F0050-powx-n.py)
|
[✔️](ruby%2F0050-powx-n.rb)
|
[✔️](rust%2F0050-powx-n.rs)
|
|
[✔️](swift%2F0050-powx-n.swift)
|
[✔️](typescript%2F0050-powx-n.ts)
| +| [0043 - Multiply Strings](https://leetcode.com/problems/multiply-strings/) |
|
[✔️](c%2F0043-multiply-strings.c)
|
[✔️](cpp%2F0043-multiply-strings.cpp)
|
[✔️](csharp%2F0043-multiply-strings.cs)
|
|
|
|
[✔️](java%2F0043-multiply-strings.java)
|
[✔️](javascript%2F0043-multiply-strings.js)
|
[✔️](kotlin%2F0043-multiply-strings.kt)
|
[✔️](python%2F0043-multiply-strings.py)
|
[✔️](ruby%2F0043-multiply-strings.rb)
|
[✔️](rust%2F0043-multiply-strings.rs)
|
|
[✔️](swift%2F0043-multiply-strings.swift)
|
[✔️](typescript%2F0043-multiply-strings.ts)
| +| [2013 - Detect Squares](https://leetcode.com/problems/detect-squares/) |
|
|
[✔️](cpp%2F2013-Detect-Squares.cpp)
|
[✔️](csharp%2F2013-Detect-Squares.cs)
|
|
|
|
[✔️](java%2F2013-Detect-Squares.java)
|
[✔️](javascript%2F2013-Detect-Squares.js)
|
[✔️](kotlin%2F2013-detect-squares.kt)
|
[✔️](python%2F2013-detect-squares.py)
|
[✔️](ruby%2F2013-detect-squares.rb)
|
[✔️](rust%2F2013-detect-squares.rs)
|
|
[✔️](swift%2F2013-detect-squares.swift)
|
| +| [1041 - Robot Bounded In Circle](https://leetcode.com/problems/robot-bounded-in-circle/) |
|
|
|
|
|
|
|
[✔️](java%2F1041-robot-bounded-in-circle.java)
|
|
[✔️](kotlin%2F1041-robot-bounded-in-circle.kt)
|
|
|
|
|
|
| +| [0006 - Zigzag Conversion](https://leetcode.com/problems/zigzag-conversion/) |
|
|
[✔️](cpp%2F0006-zigzag-conversion.cpp)
|
|
|
[✔️](go%2F0006-zigzag-conversion.go)
|
|
[✔️](java%2F0006-zigzag-conversion.java)
|
|
[✔️](kotlin%2F0006-zigzag-conversion.kt)
|
[✔️](python%2F0006-zigzag-conversion.py)
|
|
|
|
|
| +| [2028 - Find Missing Observations](https://leetcode.com/problems/find-missing-observations/) |
|
|
|
|
|
|
|
|
|
[✔️](kotlin%2F2028-find-missing-observations.kt)
|
|
|
|
|
|
| ### Bit Manipulation -Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS ----- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- -[0136 - Single Number](https://leetcode.com/problems/single-number/) |
|
[✔️](c%2F0136-single-number.c)
|
[✔️](cpp%2F0136-single-number.cpp)
|
[✔️](csharp%2F0136-single-number.cs)
|
[✔️](dart%2F0136-single-number.dart)
|
[✔️](go%2F0136-single-number.go)
|
|
[✔️](java%2F0136-single-number.java)
|
[✔️](javascript%2F0136-single-number.js)
|
[✔️](kotlin%2F0136-single-number.kt)
|
[✔️](python%2F0136-single-number.py)
|
[✔️](ruby%2F0136-single-number.rb)
|
[✔️](rust%2F0136-single-number.rs)
|
|
[✔️](swift%2F0136-single-number.swift)
|
[✔️](typescript%2F0136-single-number.ts)
-[0191 - Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/) |
|
[✔️](c%2F0191-number-of-1-bits.c)
|
[✔️](cpp%2F0191-number-of-1-bits.cpp)
|
[✔️](csharp%2F0191-number-of-1-bits.cs)
|
|
[✔️](go%2F0191-number-of-1-bits.go)
|
|
[✔️](java%2F0191-number-of-1-bits.java)
|
[✔️](javascript%2F0191-number-of-1-bits.js)
|
[✔️](kotlin%2F0191-number-of-1-bits.kt)
|
[✔️](python%2F0191-number-of-1-bits.py)
|
[✔️](ruby%2F0191-number-of-1-bits.rb)
|
[✔️](rust%2F0191-number-of-1-bits.rs)
|
|
[✔️](swift%2F0191-number-of-1-bits.swift)
|
[✔️](typescript%2F0191-number-of-1-bits.ts)
-[0338 - Counting Bits](https://leetcode.com/problems/counting-bits/) |
|
[✔️](c%2F0338-counting-bits.c)
|
[✔️](cpp%2F0338-counting-bits.cpp)
|
[✔️](csharp%2F0338-counting-bits.cs)
|
|
[✔️](go%2F0338-counting-bits.go)
|
|
[✔️](java%2F0338-counting-bits.java)
|
[✔️](javascript%2F0338-counting-bits.js)
|
[✔️](kotlin%2F0338-counting-bits.kt)
|
[✔️](python%2F0338-counting-bits.py)
|
[✔️](ruby%2F0338-counting-bits.rb)
|
[✔️](rust%2F0338-counting-bits.rs)
|
|
[✔️](swift%2F0338-counting-bits.swift)
|
[✔️](typescript%2F0338-counting-bits.ts)
-[0190 - Reverse Bits](https://leetcode.com/problems/reverse-bits/) |
|
[✔️](c%2F0190-reverse-bits.c)
|
[✔️](cpp%2F0190-reverse-bits.cpp)
|
[✔️](csharp%2F0190-reverse-bits.cs)
|
|
[✔️](go%2F0190-reverse-bits.go)
|
|
[✔️](java%2F0190-reverse-bits.java)
|
[✔️](javascript%2F0190-reverse-bits.js)
|
[✔️](kotlin%2F0190-reverse-bits.kt)
|
[✔️](python%2F0190-reverse-bits.py)
|
[✔️](ruby%2F0190-reverse-bits.rb)
|
[✔️](rust%2F0190-reverse-bits.rs)
|
|
[✔️](swift%2F0190-reverse-bits.swift)
|
[✔️](typescript%2F0190-reverse-bits.ts)
-[0268 - Missing Number](https://leetcode.com/problems/missing-number/) |
|
[✔️](c%2F0268-missing-number.c)
|
[✔️](cpp%2F0268-missing-number.cpp)
|
[✔️](csharp%2F0268-missing-number.cs)
|
|
[✔️](go%2F0268-missing-number.go)
|
|
[✔️](java%2F0268-missing-number.java)
|
[✔️](javascript%2F0268-missing-number.js)
|
[✔️](kotlin%2F0268-missing-number.kt)
|
[✔️](python%2F0268-missing-number.py)
|
[✔️](ruby%2F0268-missing-number.rb)
|
[✔️](rust%2F0268-missing-number.rs)
|
|
[✔️](swift%2F0268-missing-number.swift)
|
[✔️](typescript%2F0268-missing-number.ts)
-[1470 - Shuffle the Array](https://leetcode.com/problems/shuffle-the-array/) |
|
[✔️](c%2F1470-shuffle-the-array.c)
|
[✔️](cpp%2F1470-shuffle-the-array.cpp)
|
|
|
[✔️](go%2F1470-shuffle-the-array.go)
|
|
|
[✔️](javascript%2F1470-shuffle-the-array.js)
|
[✔️](kotlin%2F1470-shuffle-the-array.kt)
|
|
|
[✔️](rust%2F1470-shuffle-the-array.rs)
|
|
|
[✔️](typescript%2F1470-shuffle-the-array.ts)
-[0989 - Add to Array-Form of Integer](https://leetcode.com/problems/add-to-array-form-of-integer/) |
|
[✔️](c%2F0989-add-to-array-form-of-integer.c)
|
|
|
|
[✔️](go%2F0989-add-to-array-form-of-integer.go)
|
|
|
[✔️](javascript%2F0989-add-to-array-form-of-integer.js)
|
[✔️](kotlin%2F0989-add-to-array-form-of-integer.kt)
|
|
|
[✔️](rust%2F0989-add-to-array-form-of-integer.rs)
|
|
|
[✔️](typescript%2F0989-add-to-array-form-of-integer.ts)
-[0371 - Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers/) |
|
[✔️](c%2F0371-sum-of-two-integers.c)
|
[✔️](cpp%2F0371-sum-of-two-integers.cpp)
|
[✔️](csharp%2F0371-sum-of-two-integers.cs)
|
|
[✔️](go%2F0371-sum-of-two-integers.go)
|
|
[✔️](java%2F0371-sum-of-two-integers.java)
|
[✔️](javascript%2F0371-sum-of-two-integers.js)
|
[✔️](kotlin%2F0371-sum-of-two-integers.kt)
|
[✔️](python%2F0371-sum-of-two-integers.py)
|
[✔️](ruby%2F0371-sum-of-two-integers.rb)
|
[✔️](rust%2F0371-sum-of-two-integers.rs)
|
|
[✔️](swift%2F0371-sum-of-two-integers.swift)
|
[✔️](typescript%2F0371-sum-of-two-integers.ts)
-[0007 - Reverse Integer](https://leetcode.com/problems/reverse-integer/) |
|
[✔️](c%2F0007-reverse-integer.c)
|
[✔️](cpp%2F0007-reverse-integer.cpp)
|
[✔️](csharp%2F0007-reverse-integer.cs)
|
|
[✔️](go%2F0007-reverse-integer.go)
|
|
[✔️](java%2F0007-reverse-integer.java)
|
[✔️](javascript%2F0007-reverse-integer.js)
|
[✔️](kotlin%2F0007-reverse-integer.kt)
|
[✔️](python%2F0007-reverse-integer.py)
|
[✔️](ruby%2F0007-reverse-integer.rb)
|
[✔️](rust%2F0007-reverse-integer.rs)
|
[✔️](scala%2F0007-reverse-integer.scala)
|
[✔️](swift%2F0007-reverse-integer.swift)
|
[✔️](typescript%2F0007-reverse-integer.ts)
-[0067 - Add Binary](https://leetcode.com/problems/add-binary/) |
|
[✔️](c%2F0067-add-binary.c)
|
[✔️](cpp%2F0067-Add-Binary.cpp)
|
|
|
|
|
[✔️](java%2F0067-Add-Binary.java)
|
[✔️](javascript%2F0067-add-binary.js)
|
[✔️](kotlin%2F0067-add-binary.kt)
|
[✔️](python%2F0067-add-binary.py)
|
|
[✔️](rust%2F0067-add-binary.rs)
|
|
|
[✔️](typescript%2F0067-add-binary.ts)
+| Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS | +| ------------------------------------------------------------------------------------------------------------- | --------------------------------------- | ---------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | --------------------------------------- | ------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | +| [0136 - Single Number](https://leetcode.com/problems/single-number/) |
|
[✔️](c%2F0136-single-number.c)
|
[✔️](cpp%2F0136-single-number.cpp)
|
[✔️](csharp%2F0136-single-number.cs)
|
[✔️](dart%2F0136-single-number.dart)
|
[✔️](go%2F0136-single-number.go)
|
|
[✔️](java%2F0136-single-number.java)
|
[✔️](javascript%2F0136-single-number.js)
|
[✔️](kotlin%2F0136-single-number.kt)
|
[✔️](python%2F0136-single-number.py)
|
[✔️](ruby%2F0136-single-number.rb)
|
[✔️](rust%2F0136-single-number.rs)
|
|
[✔️](swift%2F0136-single-number.swift)
|
[✔️](typescript%2F0136-single-number.ts)
| +| [0191 - Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/) |
|
[✔️](c%2F0191-number-of-1-bits.c)
|
[✔️](cpp%2F0191-number-of-1-bits.cpp)
|
[✔️](csharp%2F0191-number-of-1-bits.cs)
|
|
[✔️](go%2F0191-number-of-1-bits.go)
|
|
[✔️](java%2F0191-number-of-1-bits.java)
|
[✔️](javascript%2F0191-number-of-1-bits.js)
|
[✔️](kotlin%2F0191-number-of-1-bits.kt)
|
[✔️](python%2F0191-number-of-1-bits.py)
|
[✔️](ruby%2F0191-number-of-1-bits.rb)
|
[✔️](rust%2F0191-number-of-1-bits.rs)
|
|
[✔️](swift%2F0191-number-of-1-bits.swift)
|
[✔️](typescript%2F0191-number-of-1-bits.ts)
| +| [0338 - Counting Bits](https://leetcode.com/problems/counting-bits/) |
|
[✔️](c%2F0338-counting-bits.c)
|
[✔️](cpp%2F0338-counting-bits.cpp)
|
[✔️](csharp%2F0338-counting-bits.cs)
|
|
[✔️](go%2F0338-counting-bits.go)
|
|
[✔️](java%2F0338-counting-bits.java)
|
[✔️](javascript%2F0338-counting-bits.js)
|
[✔️](kotlin%2F0338-counting-bits.kt)
|
[✔️](python%2F0338-counting-bits.py)
|
[✔️](ruby%2F0338-counting-bits.rb)
|
[✔️](rust%2F0338-counting-bits.rs)
|
|
[✔️](swift%2F0338-counting-bits.swift)
|
[✔️](typescript%2F0338-counting-bits.ts)
| +| [0190 - Reverse Bits](https://leetcode.com/problems/reverse-bits/) |
|
[✔️](c%2F0190-reverse-bits.c)
|
[✔️](cpp%2F0190-reverse-bits.cpp)
|
[✔️](csharp%2F0190-reverse-bits.cs)
|
|
[✔️](go%2F0190-reverse-bits.go)
|
|
[✔️](java%2F0190-reverse-bits.java)
|
[✔️](javascript%2F0190-reverse-bits.js)
|
[✔️](kotlin%2F0190-reverse-bits.kt)
|
[✔️](python%2F0190-reverse-bits.py)
|
[✔️](ruby%2F0190-reverse-bits.rb)
|
[✔️](rust%2F0190-reverse-bits.rs)
|
|
[✔️](swift%2F0190-reverse-bits.swift)
|
[✔️](typescript%2F0190-reverse-bits.ts)
| +| [0268 - Missing Number](https://leetcode.com/problems/missing-number/) |
|
[✔️](c%2F0268-missing-number.c)
|
[✔️](cpp%2F0268-missing-number.cpp)
|
[✔️](csharp%2F0268-missing-number.cs)
|
|
[✔️](go%2F0268-missing-number.go)
|
|
[✔️](java%2F0268-missing-number.java)
|
[✔️](javascript%2F0268-missing-number.js)
|
[✔️](kotlin%2F0268-missing-number.kt)
|
[✔️](python%2F0268-missing-number.py)
|
[✔️](ruby%2F0268-missing-number.rb)
|
[✔️](rust%2F0268-missing-number.rs)
|
|
[✔️](swift%2F0268-missing-number.swift)
|
[✔️](typescript%2F0268-missing-number.ts)
| +| [1470 - Shuffle the Array](https://leetcode.com/problems/shuffle-the-array/) |
|
[✔️](c%2F1470-shuffle-the-array.c)
|
[✔️](cpp%2F1470-shuffle-the-array.cpp)
|
|
|
[✔️](go%2F1470-shuffle-the-array.go)
|
|
|
[✔️](javascript%2F1470-shuffle-the-array.js)
|
[✔️](kotlin%2F1470-shuffle-the-array.kt)
|
|
|
[✔️](rust%2F1470-shuffle-the-array.rs)
|
|
|
[✔️](typescript%2F1470-shuffle-the-array.ts)
| +| [0989 - Add to Array-Form of Integer](https://leetcode.com/problems/add-to-array-form-of-integer/) |
|
[✔️](c%2F0989-add-to-array-form-of-integer.c)
|
|
|
|
[✔️](go%2F0989-add-to-array-form-of-integer.go)
|
|
|
[✔️](javascript%2F0989-add-to-array-form-of-integer.js)
|
[✔️](kotlin%2F0989-add-to-array-form-of-integer.kt)
|
|
|
[✔️](rust%2F0989-add-to-array-form-of-integer.rs)
|
|
|
[✔️](typescript%2F0989-add-to-array-form-of-integer.ts)
| +| [0371 - Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers/) |
|
[✔️](c%2F0371-sum-of-two-integers.c)
|
[✔️](cpp%2F0371-sum-of-two-integers.cpp)
|
[✔️](csharp%2F0371-sum-of-two-integers.cs)
|
|
[✔️](go%2F0371-sum-of-two-integers.go)
|
|
[✔️](java%2F0371-sum-of-two-integers.java)
|
[✔️](javascript%2F0371-sum-of-two-integers.js)
|
[✔️](kotlin%2F0371-sum-of-two-integers.kt)
|
[✔️](python%2F0371-sum-of-two-integers.py)
|
[✔️](ruby%2F0371-sum-of-two-integers.rb)
|
[✔️](rust%2F0371-sum-of-two-integers.rs)
|
|
[✔️](swift%2F0371-sum-of-two-integers.swift)
|
[✔️](typescript%2F0371-sum-of-two-integers.ts)
| +| [0007 - Reverse Integer](https://leetcode.com/problems/reverse-integer/) |
|
[✔️](c%2F0007-reverse-integer.c)
|
[✔️](cpp%2F0007-reverse-integer.cpp)
|
[✔️](csharp%2F0007-reverse-integer.cs)
|
|
[✔️](go%2F0007-reverse-integer.go)
|
|
[✔️](java%2F0007-reverse-integer.java)
|
[✔️](javascript%2F0007-reverse-integer.js)
|
[✔️](kotlin%2F0007-reverse-integer.kt)
|
[✔️](python%2F0007-reverse-integer.py)
|
[✔️](ruby%2F0007-reverse-integer.rb)
|
[✔️](rust%2F0007-reverse-integer.rs)
|
[✔️](scala%2F0007-reverse-integer.scala)
|
[✔️](swift%2F0007-reverse-integer.swift)
|
[✔️](typescript%2F0007-reverse-integer.ts)
| +| [0067 - Add Binary](https://leetcode.com/problems/add-binary/) |
|
[✔️](c%2F0067-add-binary.c)
|
[✔️](cpp%2F0067-Add-Binary.cpp)
|
|
|
|
|
[✔️](java%2F0067-Add-Binary.java)
|
[✔️](javascript%2F0067-add-binary.js)
|
[✔️](kotlin%2F0067-add-binary.kt)
|
[✔️](python%2F0067-add-binary.py)
|
|
[✔️](rust%2F0067-add-binary.rs)
|
|
|
[✔️](typescript%2F0067-add-binary.ts)
| ### JavaScript -Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS ----- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- -[2667 - Create Hello World Function](https://leetcode.com/problems/create-hello-world-function/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2667-create-hello-world-function.js)
|
|
|
|
|
|
|
[✔️](typescript%2F2667-create-hello-world-function.ts)
-[2620 - Counter](https://leetcode.com/problems/counter/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2620-counter.js)
|
|
|
|
|
|
|
[✔️](typescript%2F2620-counter.ts)
-[2665 - Counter II](https://leetcode.com/problems/counter-ii/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2665-counter-ii.js)
|
|
|
|
|
|
|
-[2635 - Apply Transform over each Element in Array](https://leetcode.com/problems/apply-transform-over-each-element-in-array/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2635-apply-transform-over-each-element-in-array.js)
|
|
|
|
|
|
|
-[2634 - Filter Elements from Array](https://leetcode.com/problems/filter-elements-from-array/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2634-filter-elements-from-array.js)
|
|
|
|
|
|
|
-[2626 - Array Reduce Transformation](https://leetcode.com/problems/array-reduce-transformation/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2626-array-reduce-transformation.js)
|
|
|
|
|
|
|
-[2629 - Function Composition](https://leetcode.com/problems/function-composition/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2629-function-composition.js)
|
|
|
|
|
|
|
-[2666 - Allow One Function Call](https://leetcode.com/problems/allow-one-function-call/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2666-allow-one-function-call.js)
|
|
|
|
|
|
|
-[2623 - Memoize](https://leetcode.com/problems/memoize/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2623-memoize.js)
|
|
|
|
|
|
|
-[2632 - Curry](https://leetcode.com/problems/curry/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2632-curry.js)
|
|
|
|
|
|
|
-[2621 - Sleep](https://leetcode.com/problems/sleep/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2621-sleep.js)
|
|
|
|
|
|
|
-[2637 - Promise Time Limit](https://leetcode.com/problems/promise-time-limit/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
-[2636 - Promise Pool](https://leetcode.com/problems/promise-pool/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
-[2622 - Cache With Time Limit](https://leetcode.com/problems/cache-with-time-limit/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
-[2627 - Debounce](https://leetcode.com/problems/debounce/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2627-debounce.js)
|
|
|
|
|
|
|
-[2676 - Throttle](https://leetcode.com/problems/throttle/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
-[2628 - JSON Deep Equal](https://leetcode.com/problems/json-deep-equal/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2628-json-deep-equal.js)
|
|
|
|
|
|
|
-[2633 - Convert Object to JSON String](https://leetcode.com/problems/convert-object-to-json-string/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
-[2675 - Array of Objects to Matrix](https://leetcode.com/problems/array-of-objects-to-matrix/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
-[2700 - Difference Between Two Objects](https://leetcode.com/problems/differences-between-two-objects/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
-[2677 - Chunk Array](https://leetcode.com/problems/chunk-array/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
-[2625 - Flatten Deeply Nested Array](https://leetcode.com/problems/flatten-deeply-nested-array/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
-[2619 - Array Prototype Last](https://leetcode.com/problems/array-prototype-last/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
-[2631 - Group By](https://leetcode.com/problems/group-by/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
-[2618 - Check if Object Instance of Class](https://leetcode.com/problems/check-if-object-instance-of-class/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
-[2693 - Call Function with Custom Context](https://leetcode.com/problems/call-function-with-custom-context/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
-[2694 - Event Emitter](https://leetcode.com/problems/event-emitter/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
-[2695 - Array Wrapper](https://leetcode.com/problems/array-wrapper/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
-[2648 - Generate Fibonacci Sequence](https://leetcode.com/problems/generate-fibonacci-sequence/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
-[2649 - Nested Array Generator](https://leetcode.com/problems/nested-array-generator/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
- - +| Problem | articles | C | C++ | C# | Dart | GO | hints | Java | JS | Kotlin | Python | Ruby | Rust | Scala | Swift | TS | +| ----------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------- | --------------------------------------- | --------------------------------------- | --------------------------------------- | --------------------------------------- | --------------------------------------- | --------------------------------------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------- | --------------------------------------- | --------------------------------------- | --------------------------------------- | --------------------------------------- | --------------------------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------- | +| [2667 - Create Hello World Function](https://leetcode.com/problems/create-hello-world-function/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2667-create-hello-world-function.js)
|
|
|
|
|
|
|
[✔️](typescript%2F2667-create-hello-world-function.ts)
| +| [2620 - Counter](https://leetcode.com/problems/counter/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2620-counter.js)
|
|
|
|
|
|
|
[✔️](typescript%2F2620-counter.ts)
| +| [2665 - Counter II](https://leetcode.com/problems/counter-ii/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2665-counter-ii.js)
|
|
|
|
|
|
|
| +| [2635 - Apply Transform over each Element in Array](https://leetcode.com/problems/apply-transform-over-each-element-in-array/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2635-apply-transform-over-each-element-in-array.js)
|
|
|
|
|
|
|
| +| [2634 - Filter Elements from Array](https://leetcode.com/problems/filter-elements-from-array/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2634-filter-elements-from-array.js)
|
|
|
|
|
|
|
| +| [2626 - Array Reduce Transformation](https://leetcode.com/problems/array-reduce-transformation/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2626-array-reduce-transformation.js)
|
|
|
|
|
|
|
| +| [2629 - Function Composition](https://leetcode.com/problems/function-composition/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2629-function-composition.js)
|
|
|
|
|
|
|
| +| [2666 - Allow One Function Call](https://leetcode.com/problems/allow-one-function-call/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2666-allow-one-function-call.js)
|
|
|
|
|
|
|
| +| [2623 - Memoize](https://leetcode.com/problems/memoize/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2623-memoize.js)
|
|
|
|
|
|
|
| +| [2632 - Curry](https://leetcode.com/problems/curry/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2632-curry.js)
|
|
|
|
|
|
|
| +| [2621 - Sleep](https://leetcode.com/problems/sleep/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2621-sleep.js)
|
|
|
|
|
|
|
| +| [2637 - Promise Time Limit](https://leetcode.com/problems/promise-time-limit/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| +| [2636 - Promise Pool](https://leetcode.com/problems/promise-pool/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| +| [2622 - Cache With Time Limit](https://leetcode.com/problems/cache-with-time-limit/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| +| [2627 - Debounce](https://leetcode.com/problems/debounce/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2627-debounce.js)
|
|
|
|
|
|
|
| +| [2676 - Throttle](https://leetcode.com/problems/throttle/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| +| [2628 - JSON Deep Equal](https://leetcode.com/problems/json-deep-equal/) |
|
|
|
|
|
|
|
|
[✔️](javascript%2F2628-json-deep-equal.js)
|
|
|
|
|
|
|
| +| [2633 - Convert Object to JSON String](https://leetcode.com/problems/convert-object-to-json-string/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| +| [2675 - Array of Objects to Matrix](https://leetcode.com/problems/array-of-objects-to-matrix/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| +| [2700 - Difference Between Two Objects](https://leetcode.com/problems/differences-between-two-objects/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| +| [2677 - Chunk Array](https://leetcode.com/problems/chunk-array/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| +| [2625 - Flatten Deeply Nested Array](https://leetcode.com/problems/flatten-deeply-nested-array/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| +| [2619 - Array Prototype Last](https://leetcode.com/problems/array-prototype-last/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| +| [2631 - Group By](https://leetcode.com/problems/group-by/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| +| [2618 - Check if Object Instance of Class](https://leetcode.com/problems/check-if-object-instance-of-class/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| +| [2693 - Call Function with Custom Context](https://leetcode.com/problems/call-function-with-custom-context/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| +| [2694 - Event Emitter](https://leetcode.com/problems/event-emitter/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| +| [2695 - Array Wrapper](https://leetcode.com/problems/array-wrapper/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| +| [2648 - Generate Fibonacci Sequence](https://leetcode.com/problems/generate-fibonacci-sequence/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| +| [2649 - Nested Array Generator](https://leetcode.com/problems/nested-array-generator/) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| --- diff --git a/README_template.md b/README_template.md index 177477379..53e56cae0 100644 --- a/README_template.md +++ b/README_template.md @@ -1,20 +1,22 @@ # Leetcode solutions for 🚀 [NeetCode.io](https://neetcode.io) + > This repo hosts the solutions found on [NeetCode.io](https://neetcode.io) including the solutions shown on the [NeetCode YouTube channel](https://www.youtube.com/c/neetcode). The site will periodically be updated with new solutions from this repo!
Solutions from these languages will be linked from [NeetCode.io](https://neetcode.io): + > Python, Java, JavaScript, C++, Go, Swift, C#, TypeScript, Rust, Kotlin, Ruby, C, Scala and Dart -Solutions are also welcome for any other *supported* language on leetcode.com! +Solutions are also welcome for any other _supported_ language on leetcode.com! ## Contributing -**Please read the [contributing guidlines](./CONTRIBUTING.md) before opening a PR** +**Please read the [contributing guidlines](./CONTRIBUTING.md) before opening a PR** To contribute, please fork this repo and open a PR adding a [missing solution](#missing-solutions) from the supported languages. -If you would like to have collaborator permissions on the repo to merge your own PRs or review others' PRs please let me know. +If you would like to have collaborator permissions on the repo to merge your own PRs or review others' PRs please let me know. ## Credits diff --git a/articles/132-pattern.md b/articles/132-pattern.md index b0dc31957..5bdc63728 100644 --- a/articles/132-pattern.md +++ b/articles/132-pattern.md @@ -100,8 +100,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -205,8 +205,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -218,11 +218,11 @@ class Solution { class Solution: def find132pattern(self, nums: List[int]) -> bool: stack, k = [], float('-inf') - + for i in range(len(nums) - 1, -1, -1): if nums[i] < k: return True - + while stack and stack[-1] < nums[i]: k = stack.pop() stack.append(nums[i]) @@ -235,18 +235,18 @@ public class Solution { public boolean find132pattern(int[] nums) { Stack stack = new Stack<>(); int k = Integer.MIN_VALUE; - + for (int i = nums.length - 1; i >= 0; i--) { if (nums[i] < k) { return true; } - + while (!stack.isEmpty() && stack.peek() < nums[i]) { k = stack.pop(); } stack.push(nums[i]); } - + return false; } } @@ -258,19 +258,19 @@ public: bool find132pattern(vector& nums) { stack stack; int k = INT_MIN; - + for (int i = nums.size() - 1; i >= 0; i--) { if (nums[i] < k) { return true; } - + while (!stack.empty() && stack.top() < nums[i]) { k = stack.top(); stack.pop(); } stack.push(nums[i]); } - + return false; } }; @@ -285,18 +285,18 @@ class Solution { find132pattern(nums) { const stack = []; let k = -Infinity; - + for (let i = nums.length - 1; i >= 0; i--) { if (nums[i] < k) { return true; } - + while (stack.length > 0 && stack[stack.length - 1] < nums[i]) { k = stack.pop(); } stack.push(nums[i]); } - + return false; } } @@ -306,8 +306,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -324,14 +324,14 @@ class Solution: for i in range(n - 1, -1, -1): if nums[i] < k: return True - + while stkTop < n and nums[i] > nums[stkTop]: k = nums[stkTop] stkTop += 1 - + stkTop -= 1 nums[stkTop] = nums[i] - + return False ``` @@ -346,14 +346,14 @@ public class Solution { if (nums[i] < k) { return true; } - + while (stkTop < n && nums[i] > nums[stkTop]) { k = nums[stkTop++]; } - + nums[--stkTop] = nums[i]; } - + return false; } } @@ -399,14 +399,14 @@ class Solution { if (nums[i] < k) { return true; } - + while (stkTop < n && nums[i] > nums[stkTop]) { k = nums[stkTop++]; } nums[--stkTop] = nums[i]; } - + return false; } } @@ -416,5 +416,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/4sum.md b/articles/4sum.md index b590cf39e..c1675c054 100644 --- a/articles/4sum.md +++ b/articles/4sum.md @@ -84,7 +84,14 @@ class Solution { for (let c = b + 1; c < n; c++) { for (let d = c + 1; d < n; d++) { if (nums[a] + nums[b] + nums[c] + nums[d] === target) { - res.add(JSON.stringify([nums[a], nums[b], nums[c], nums[d]])); + res.add( + JSON.stringify([ + nums[a], + nums[b], + nums[c], + nums[d], + ]), + ); } } } @@ -129,8 +136,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 4)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n ^ 4)$ +- Space complexity: $O(m)$ > Where $n$ is the size of the array $nums$ and $m$ is the number of quadruplets. @@ -372,10 +379,10 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 3)$ -* Space complexity: - * $O(n)$ space for the hash map. - * $O(m)$ space for the output array. +- Time complexity: $O(n ^ 3)$ +- Space complexity: + - $O(n)$ space for the hash map. + - $O(m)$ space for the output array. > Where $n$ is the size of the array $nums$ and $m$ is the number of quadruplets. @@ -506,15 +513,18 @@ class Solution { for (let j = i + 1; j < n; j++) { if (j > i + 1 && nums[j] === nums[j - 1]) continue; - let left = j + 1, right = n - 1; + let left = j + 1, + right = n - 1; while (left < right) { const sum = nums[i] + nums[j] + nums[left] + nums[right]; if (sum === target) { res.push([nums[i], nums[j], nums[left], nums[right]]); left++; right--; - while (left < right && nums[left] === nums[left - 1]) left++; - while (left < right && nums[right] === nums[right + 1]) right--; + while (left < right && nums[left] === nums[left - 1]) + left++; + while (left < right && nums[right] === nums[right + 1]) + right--; } else if (sum < target) { left++; } else { @@ -569,10 +579,10 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 3)$ -* Space complexity: - * $O(1)$ or $O(n)$ space depending on the sorting algorithm. - * $O(m)$ space for the output array. +- Time complexity: $O(n ^ 3)$ +- Space complexity: + - $O(1)$ or $O(n)$ space depending on the sorting algorithm. + - $O(m)$ space for the output array. --- @@ -722,7 +732,8 @@ class Solution { const kSum = (k, start, target) => { if (k === 2) { - let l = start, r = nums.length - 1; + let l = start, + r = nums.length - 1; while (l < r) { const sum = nums[l] + nums[r]; if (sum < target) { @@ -804,7 +815,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 3)$ -* Space complexity: - * $O(1)$ or $O(n)$ space depending on the sorting algorithm. - * $O(m)$ space for the output array. \ No newline at end of file +- Time complexity: $O(n ^ 3)$ +- Space complexity: + - $O(1)$ or $O(n)$ space depending on the sorting algorithm. + - $O(m)$ space for the output array. diff --git a/articles/accounts-merge.md b/articles/accounts-merge.md index 15b8e9881..849adad95 100644 --- a/articles/accounts-merge.md +++ b/articles/accounts-merge.md @@ -20,7 +20,7 @@ class Solution: emailIdx[email] = m emailToAcc[m] = accId m += 1 - + adj = [[] for _ in range(m)] for a in accounts: for i in range(2, len(a)): @@ -28,7 +28,7 @@ class Solution: id2 = emailIdx[a[i - 1]] adj[id1].append(id2) adj[id2].append(id1) - + emailGroup = defaultdict(list) # index of acc -> list of emails visited = [False] * m def dfs(node, accId): @@ -37,16 +37,16 @@ class Solution: for nei in adj[node]: if not visited[nei]: dfs(nei, accId) - + for i in range(m): if not visited[i]: dfs(i, emailToAcc[i]) - + res = [] for accId in emailGroup: name = accounts[accId][0] res.append([name] + sorted(emailGroup[accId])) - + return res ``` @@ -361,8 +361,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O((n * m)\log (n * m))$ -* Space complexity: $O(n * m)$ +- Time complexity: $O((n * m)\log (n * m))$ +- Space complexity: $O(n * m)$ > Where $n$ is the number of accounts and $m$ is the number of emails. @@ -390,7 +390,7 @@ class Solution: emailIdx[email] = m emailToAcc[m] = accId m += 1 - + adj = [[] for _ in range(m)] for a in accounts: for i in range(2, len(a)): @@ -398,7 +398,7 @@ class Solution: id2 = emailIdx[a[i - 1]] adj[id1].append(id2) adj[id2].append(id1) - + emailGroup = defaultdict(list) # index of acc -> list of emails visited = [False] * m @@ -412,16 +412,16 @@ class Solution: if not visited[nei]: visited[nei] = True queue.append(nei) - + for i in range(m): if not visited[i]: bfs(i, emailToAcc[i]) - + res = [] for accId in emailGroup: name = accounts[accId][0] res.append([name] + sorted(emailGroup[accId])) - + return res ``` @@ -704,7 +704,7 @@ public class Solution { List> adj = new List>(); for (int i = 0; i < m; i++) adj.Add(new List()); - + foreach (var account in accounts) { for (int i = 2; i < account.Count; i++) { int id1 = emailIdx[account[i]]; @@ -763,8 +763,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O((n * m)\log (n * m))$ -* Space complexity: $O(n * m)$ +- Time complexity: $O((n * m)\log (n * m))$ +- Space complexity: $O(n * m)$ > Where $n$ is the number of accounts and $m$ is the number of emails. @@ -1159,7 +1159,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O((n * m)\log (n * m))$ -* Space complexity: $O(n * m)$ +- Time complexity: $O((n * m)\log (n * m))$ +- Space complexity: $O(n * m)$ -> Where $n$ is the number of accounts and $m$ is the number of emails. \ No newline at end of file +> Where $n$ is the number of accounts and $m$ is the number of emails. diff --git a/articles/add-binary.md b/articles/add-binary.md index e34e45d39..650317c2e 100644 --- a/articles/add-binary.md +++ b/articles/add-binary.md @@ -29,24 +29,24 @@ public class Solution { public String addBinary(String a, String b) { StringBuilder res = new StringBuilder(); int carry = 0; - + StringBuilder sa = new StringBuilder(a).reverse(); StringBuilder sb = new StringBuilder(b).reverse(); - + for (int i = 0; i < Math.max(sa.length(), sb.length()); i++) { int digitA = i < sa.length() ? sa.charAt(i) - '0' : 0; int digitB = i < sb.length() ? sb.charAt(i) - '0' : 0; - + int total = digitA + digitB + carry; char c = (char)((total % 2) + '0'); res.append(c); carry = total / 2; } - + if (carry > 0) { res.append('1'); } - + return res.reverse().toString(); } } @@ -58,20 +58,20 @@ public: string addBinary(string a, string b) { string res = ""; int carry = 0; - + reverse(a.begin(), a.end()); reverse(b.begin(), b.end()); - + for (int i = 0; i < max(a.length(), b.length()); i++) { int digitA = i < a.length() ? a[i] - '0' : 0; int digitB = i < b.length() ? b[i] - '0' : 0; - + int total = digitA + digitB + carry; char c = (total % 2) + '0'; res += c; carry = total / 2; } - + if (carry) { res += '1'; } @@ -91,24 +91,24 @@ class Solution { addBinary(a, b) { let res = []; let carry = 0; - - a = a.split("").reverse().join(""); - b = b.split("").reverse().join(""); - + + a = a.split('').reverse().join(''); + b = b.split('').reverse().join(''); + for (let i = 0; i < Math.max(a.length, b.length); i++) { const digitA = i < a.length ? a[i] - '0' : 0; const digitB = i < b.length ? b[i] - '0' : 0; - + const total = digitA + digitB + carry; const char = (total % 2).toString(); - res.push(char) + res.push(char); carry = Math.floor(total / 2); } - + if (carry) { res.push('1'); } - res.reverse() + res.reverse(); return res.join(''); } } @@ -151,8 +151,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(max(m, n))$ -* Space complexity: $O(m + n)$ +- Time complexity: $O(max(m, n))$ +- Space complexity: $O(m + n)$ > Where $m$ and $n$ are the lengths of the strings $a$ and $b$ respectively. @@ -245,10 +245,11 @@ class Solution { let res = []; let carry = 0; - let i = a.length - 1, j = b.length - 1; + let i = a.length - 1, + j = b.length - 1; while (i >= 0 || j >= 0 || carry > 0) { - const digitA = i >= 0 ? a[i] - "0" : 0; - const digitB = j >= 0 ? b[j] - "0" : 0; + const digitA = i >= 0 ? a[i] - '0' : 0; + const digitB = j >= 0 ? b[j] - '0' : 0; const total = digitA + digitB + carry; res.push(total % 2); @@ -257,7 +258,7 @@ class Solution { i--; j--; } - res.reverse() + res.reverse(); return res.join(''); } } @@ -293,7 +294,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(max(m, n))$ -* Space complexity: $O(max(m, n))$ +- Time complexity: $O(max(m, n))$ +- Space complexity: $O(max(m, n))$ -> Where $m$ and $n$ are the lengths of the strings $a$ and $b$ respectively. \ No newline at end of file +> Where $m$ and $n$ are the lengths of the strings $a$ and $b$ respectively. diff --git a/articles/add-to-array-form-of-integer.md b/articles/add-to-array-form-of-integer.md index ecab6ca84..7cb704555 100644 --- a/articles/add-to-array-form-of-integer.md +++ b/articles/add-to-array-form-of-integer.md @@ -98,8 +98,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(max(n, m))$ -* Space complexity: $O(n)$. +- Time complexity: $O(max(n, m))$ +- Space complexity: $O(n)$. > Where $n$ is the size of the array $num$ and $m$ is the number of digits in $k$. @@ -184,7 +184,8 @@ class Solution { */ addToArrayForm(num, k) { let res = new Deque(); - let carry = 0, i = num.length - 1; + let carry = 0, + i = num.length - 1; while (i >= 0 || k > 0 || carry > 0) { const digit = k % 10; @@ -211,7 +212,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(max(n, m))$ -* Space complexity: $O(n)$ +- Time complexity: $O(max(n, m))$ +- Space complexity: $O(n)$ -> Where $n$ is the size of the array $num$ and $m$ is the number of digits in $k$. \ No newline at end of file +> Where $n$ is the size of the array $num$ and $m$ is the number of digits in $k$. diff --git a/articles/add-two-numbers.md b/articles/add-two-numbers.md index 118adab49..87ffdefc1 100644 --- a/articles/add-two-numbers.md +++ b/articles/add-two-numbers.md @@ -13,15 +13,15 @@ class Solution: def add(self, l1: Optional[ListNode], l2: Optional[ListNode], carry: int) -> Optional[ListNode]: if not l1 and not l2 and carry == 0: return None - + v1 = l1.val if l1 else 0 v2 = l2.val if l2 else 0 - + carry, val = divmod(v1 + v2 + carry, 10) - + next_node = self.add( - l1.next if l1 else None, - l2.next if l2 else None, + l1.next if l1 else None, + l2.next if l2 else None, carry ) return ListNode(val, next_node) @@ -47,7 +47,7 @@ public class Solution { if (l1 == null && l2 == null && carry == 0) { return null; } - + int v1 = 0; int v2 = 0; if (l1 != null) { @@ -56,17 +56,17 @@ public class Solution { if (l2 != null) { v2 = l2.val; } - + int sum = v1 + v2 + carry; int newCarry = sum / 10; int nodeValue = sum % 10; - + ListNode nextNode = add( - (l1 != null) ? l1.next : null, - (l2 != null) ? l2.next : null, + (l1 != null) ? l1.next : null, + (l2 != null) ? l2.next : null, newCarry ); - + return new ListNode(nodeValue, nextNode); } @@ -94,7 +94,7 @@ public: if (!l1 && !l2 && carry == 0) { return nullptr; } - + int v1 = 0; int v2 = 0; if (l1) { @@ -103,14 +103,14 @@ public: if (l2) { v2 = l2->val; } - + int sum = v1 + v2 + carry; int newCarry = sum / 10; int nodeValue = sum % 10; ListNode* nextNode = add( - (l1 ? l1->next : nullptr), - (l2 ? l2->next : nullptr), + (l1 ? l1->next : nullptr), + (l2 ? l2->next : nullptr), newCarry ); @@ -145,7 +145,7 @@ class Solution { if (!l1 && !l2 && carry === 0) { return null; } - + let v1 = 0; let v2 = 0; if (l1) { @@ -154,15 +154,15 @@ class Solution { if (l2) { v2 = l2.val; } - + let sum = v1 + v2 + carry; let newCarry = Math.floor(sum / 10); let nodeValue = sum % 10; let nextNode = this.add( - (l1 ? l1.next : null), - (l2 ? l2.next : null), - newCarry + l1 ? l1.next : null, + l2 ? l2.next : null, + newCarry, ); return new ListNode(nodeValue, nextNode); @@ -197,7 +197,7 @@ public class Solution { if (l1 == null && l2 == null && carry == 0) { return null; } - + int v1 = 0; int v2 = 0; if (l1 != null) { @@ -212,8 +212,8 @@ public class Solution { int nodeValue = sum % 10; ListNode nextNode = Add( - (l1 != null ? l1.next : null), - (l2 != null ? l2.next : null), + (l1 != null ? l1.next : null), + (l2 != null ? l2.next : null), newCarry ); @@ -238,7 +238,7 @@ func add(l1 *ListNode, l2 *ListNode, carry int) *ListNode { if l1 == nil && l2 == nil && carry == 0 { return nil } - + v1, v2 := 0, 0 if l1 != nil { v1 = l1.Val @@ -246,10 +246,10 @@ func add(l1 *ListNode, l2 *ListNode, carry int) *ListNode { if l2 != nil { v2 = l2.Val } - + sum := v1 + v2 + carry carry, val := sum/10, sum%10 - + var nextNode *ListNode nextL1 := l1 nextL2 := l2 @@ -319,14 +319,14 @@ class Solution { if l1 == nil && l2 == nil && carry == 0 { return nil } - + let v1 = l1?.val ?? 0 let v2 = l2?.val ?? 0 - + let sum = v1 + v2 + carry let newCarry = sum / 10 let val = sum % 10 - + let nextNode = add(l1?.next, l2?.next, newCarry) return ListNode(val, nextNode) } @@ -341,8 +341,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n)$ -* Space complexity: $O(m + n)$ +- Time complexity: $O(m + n)$ +- Space complexity: $O(m + n)$ > Where $m$ is the length of $l1$ and $n$ is the length of $l2$. @@ -557,7 +557,7 @@ func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { v1 = l1.Val l1 = l1.Next } - + v2 := 0 if l2 != nil { v2 = l2.Val @@ -651,9 +651,9 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(max(m, n))$ for the output list. +- Time complexity: $O(m + n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(max(m, n))$ for the output list. -> Where $m$ is the length of $l1$ and $n$ is the length of $l2$. \ No newline at end of file +> Where $m$ is the length of $l1$ and $n$ is the length of $l2$. diff --git a/articles/all-possible-full-binary-trees.md b/articles/all-possible-full-binary-trees.md index 1e75b0293..58ce3a748 100644 --- a/articles/all-possible-full-binary-trees.md +++ b/articles/all-possible-full-binary-trees.md @@ -169,8 +169,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n * 2 ^ n)$ +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n * 2 ^ n)$ --- @@ -326,8 +326,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n * 2 ^ n)$ +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n * 2 ^ n)$ --- @@ -364,7 +364,7 @@ class Solution: dp[n] = res return res - + return dfs(n) ``` @@ -521,8 +521,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n * 2 ^ n)$ +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n * 2 ^ n)$ --- @@ -541,7 +541,7 @@ class Solution: def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]: if n % 2 == 0: return [] - + dp = [[] for _ in range(n + 1)] dp[1] = [TreeNode(0)] @@ -689,5 +689,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n * 2 ^ n)$ \ No newline at end of file +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n * 2 ^ n)$ diff --git a/articles/anagram-groups.md b/articles/anagram-groups.md index bf41aaa79..0969c406c 100644 --- a/articles/anagram-groups.md +++ b/articles/anagram-groups.md @@ -80,7 +80,7 @@ public class Solution { } res[sortedS].Add(s); } - return res.Values.ToList>(); + return res.Values.ToList>(); } } ``` @@ -144,8 +144,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n \log n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n \log n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of strings and $n$ is the length of the longest string. @@ -249,7 +249,7 @@ public class Solution { } res[key].Add(s); } - return res.Values.ToList>(); + return res.Values.ToList>(); } } ``` @@ -314,9 +314,9 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: - * $O(m)$ extra space. - * $O(m * n)$ space for the output list. +- Time complexity: $O(m * n)$ +- Space complexity: + - $O(m)$ extra space. + - $O(m * n)$ space for the output list. -> Where $m$ is the number of strings and $n$ is the length of the longest string. \ No newline at end of file +> Where $m$ is the number of strings and $n$ is the length of the longest string. diff --git a/articles/analyze-user-website-visit-pattern.md b/articles/analyze-user-website-visit-pattern.md index c43fce6ba..849afb47e 100644 --- a/articles/analyze-user-website-visit-pattern.md +++ b/articles/analyze-user-website-visit-pattern.md @@ -109,7 +109,7 @@ public: vector ans; string tmp; for (char ch : res) { - if (ch == '#') { + if (ch == '#') { ans.push_back(tmp); tmp.clear(); } else { @@ -138,7 +138,8 @@ class Solution { const mp = new Map(); for (const [, idx] of arr) { - const user = username[idx], site = website[idx]; + const user = username[idx], + site = website[idx]; if (!mp.has(user)) mp.set(user, []); mp.get(user).push(site); } @@ -159,14 +160,15 @@ class Solution { } } - let maxCnt = 0, res = ""; + let maxCnt = 0, + res = ''; for (const [pat, c] of count.entries()) { - if (c > maxCnt || (c === maxCnt && (res === "" || pat < res))) { + if (c > maxCnt || (c === maxCnt && (res === '' || pat < res))) { maxCnt = c; res = pat; } } - return res.split("#"); + return res.split('#'); } } ``` @@ -218,7 +220,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n + n * u + n ^ 3 * w)$ -* Space complexity: $O(n * u + n ^ 3 * w)$ +- Time complexity: $O(n \log n + n * u + n ^ 3 * w)$ +- Space complexity: $O(n * u + n ^ 3 * w)$ -> Where $n$ is the size of the array $timestamp$, $u$ is the maximum length of any string in the array $username$, and $w$ is the maximum length of any string in the array $website$. \ No newline at end of file +> Where $n$ is the size of the array $timestamp$, $u$ is the maximum length of any string in the array $username$, and $w$ is the maximum length of any string in the array $website$. diff --git a/articles/append-characters-to-string-to-make-subsequence.md b/articles/append-characters-to-string-to-make-subsequence.md index de5f09613..66c5b6eb5 100644 --- a/articles/append-characters-to-string-to-make-subsequence.md +++ b/articles/append-characters-to-string-to-make-subsequence.md @@ -61,7 +61,8 @@ class Solution { * @return {number} */ appendCharacters(s, t) { - let i = 0, j = 0; + let i = 0, + j = 0; while (i < s.length && j < t.length) { if (s[i] === t[j]) { @@ -80,8 +81,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(1)$ > Where $n$ and $m$ are the lengths of the strings $s$ and $t$, respectively. @@ -106,7 +107,7 @@ class Solution: while i < n and j < m: if store[i][ord(t[j]) - ord('a')] == n + 1: break - + i = store[i][ord(t[j]) - ord('a')] + 1 j += 1 @@ -177,7 +178,8 @@ class Solution { * @return {number} */ appendCharacters(s, t) { - const n = s.length, m = t.length; + const n = s.length, + m = t.length; const store = Array.from({ length: n }, () => Array(26).fill(n + 1)); store[n - 1][s.charCodeAt(n - 1) - 97] = n - 1; @@ -186,7 +188,8 @@ class Solution { store[i][s.charCodeAt(i) - 97] = i; } - let i = 0, j = 0; + let i = 0, + j = 0; while (i < n && j < m) { if (store[i][t.charCodeAt(j) - 97] === n + 1) { break; @@ -204,7 +207,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(n)$ -> Where $n$ and $m$ are the lengths of the strings $s$ and $t$, respectively. \ No newline at end of file +> Where $n$ and $m$ are the lengths of the strings $s$ and $t$, respectively. diff --git a/articles/arithmetic-slices-ii-subsequence.md b/articles/arithmetic-slices-ii-subsequence.md index 427b1557c..ec1718c72 100644 --- a/articles/arithmetic-slices-ii-subsequence.md +++ b/articles/arithmetic-slices-ii-subsequence.md @@ -155,8 +155,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 3)$ -* Space complexity: $O(n ^ 3)$ +- Time complexity: $O(n ^ 3)$ +- Space complexity: $O(n ^ 3)$ --- @@ -185,7 +185,7 @@ public class Solution { int n = nums.length; int res = 0; Map[] dp = new HashMap[n]; - + for (int i = 0; i < n; i++) { dp[i] = new HashMap<>(); for (int j = 0; j < i; j++) { @@ -207,7 +207,7 @@ public: int n = nums.size(); int res = 0; vector> dp(n); - + for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { long long diff = (long long) nums[i] - nums[j]; @@ -249,8 +249,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -331,7 +331,8 @@ class Solution { * @return {number} */ numberOfArithmeticSlices(nums) { - let res = 0, n = nums.length; + let res = 0, + n = nums.length; const s = new Set(nums); const dp = Array.from({ length: n }, () => new Map()); @@ -354,8 +355,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -495,5 +496,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ \ No newline at end of file +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ diff --git a/articles/arranging-coins.md b/articles/arranging-coins.md index cb8920a4a..bb228d732 100644 --- a/articles/arranging-coins.md +++ b/articles/arranging-coins.md @@ -60,8 +60,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\sqrt {n})$ -* Space complexity: $O(1)$ +- Time complexity: $O(\sqrt {n})$ +- Space complexity: $O(1)$ --- @@ -83,7 +83,7 @@ class Solution: else: l = mid + 1 res = max(res, mid) - + return res ``` @@ -102,7 +102,7 @@ public class Solution { res = Math.max(res, mid); } } - + return res; } } @@ -124,7 +124,7 @@ public: res = max(res, mid); } } - + return res; } }; @@ -137,7 +137,9 @@ class Solution { * @return {number} */ arrangeCoins(n) { - let l = 1, r = n, res = 0; + let l = 1, + r = n, + res = 0; while (l <= r) { let mid = Math.floor((l + r) / 2); @@ -159,8 +161,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ --- @@ -181,7 +183,7 @@ class Solution: l = mid + 1 else: r = mid - + return l - 1 ``` @@ -226,7 +228,7 @@ public: r = mid; } } - + return l - 1; } }; @@ -243,7 +245,8 @@ class Solution { return n == 1 ? 1 : n - 1; } - let l = 1, r = (n / 2) + 1; + let l = 1, + r = n / 2 + 1; while (l < r) { let mid = Math.floor((l + r) / 2); let coins = (mid * (mid + 1)) / 2; @@ -263,8 +266,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ --- @@ -349,8 +352,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ since we iterate $15$ times. -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ since we iterate $15$ times. +- Space complexity: $O(1)$ --- @@ -397,5 +400,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ or $O(\sqrt {n})$ depending on the language. -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(1)$ or $O(\sqrt {n})$ depending on the language. +- Space complexity: $O(1)$ diff --git a/articles/array-with-elements-not-equal-to-average-of-neighbors.md b/articles/array-with-elements-not-equal-to-average-of-neighbors.md index 4e4a1daa1..ae5064818 100644 --- a/articles/array-with-elements-not-equal-to-average-of-neighbors.md +++ b/articles/array-with-elements-not-equal-to-average-of-neighbors.md @@ -66,7 +66,8 @@ class Solution { rearrangeArray(nums) { nums.sort((a, b) => a - b); const res = []; - let l = 0, r = nums.length - 1; + let l = 0, + r = nums.length - 1; while (res.length !== nums.length) { res.push(nums[l++]); @@ -84,8 +85,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n\log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n\log n)$ +- Space complexity: $O(n)$ --- @@ -149,8 +150,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -166,11 +167,11 @@ class Solution: for i in range(1, n - 1): if 2 * nums[i] == (nums[i - 1] + nums[i + 1]): nums[i], nums[i + 1] = nums[i + 1], nums[i] - + for i in range(n - 2, 0, -1): if 2 * nums[i] == (nums[i - 1] + nums[i + 1]): nums[i], nums[i - 1] = nums[i - 1], nums[i] - + return nums ``` @@ -253,8 +254,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -319,8 +320,10 @@ class Solution { rearrangeArray(nums) { let increase = nums[0] < nums[1]; for (let i = 1; i < nums.length - 1; i++) { - if ((increase && nums[i] < nums[i + 1]) || - (!increase && nums[i] > nums[i + 1])) { + if ( + (increase && nums[i] < nums[i + 1]) || + (!increase && nums[i] > nums[i + 1]) + ) { [nums[i], nums[i + 1]] = [nums[i + 1], nums[i]]; } increase = !increase; @@ -334,5 +337,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/as-far-from-land-as-possible.md b/articles/as-far-from-land-as-possible.md index 15382ba80..dd17d099c 100644 --- a/articles/as-far-from-land-as-possible.md +++ b/articles/as-far-from-land-as-possible.md @@ -145,7 +145,12 @@ class Solution { */ maxDistance(grid) { const N = grid.length; - const direct = [[0, 1], [0, -1], [1, 0], [-1, 0]]; + const direct = [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ]; const bfs = (row, col) => { const q = new Queue([[row, col]]); @@ -158,11 +163,17 @@ class Solution { for (let i = q.size(); i > 0; i--) { const [r, c] = q.pop(); for (let d = 0; d < 4; d++) { - let newR = r + direct[d][0], newC = c + direct[d][1]; - if (newR < 0 || newC < 0 || newR >= N || newC >= N || visit[newR][newC]) + let newR = r + direct[d][0], + newC = c + direct[d][1]; + if ( + newR < 0 || + newC < 0 || + newR >= N || + newC >= N || + visit[newR][newC] + ) continue; - if (grid[newR][newC] === 1) - return dist; + if (grid[newR][newC] === 1) return dist; visit[newR][newC] = true; q.push([newR, newC]); @@ -190,8 +201,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 4)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 4)$ +- Space complexity: $O(n ^ 2)$ --- @@ -204,7 +215,7 @@ class Solution: def maxDistance(self, grid: List[List[int]]) -> int: N = len(grid) q = deque() - + for r in range(N): for c in range(N): if grid[r][c]: @@ -216,7 +227,7 @@ class Solution: while q: r, c = q.popleft() res = grid[r][c] - + for dr, dc in direct: newR, newC = r + dr, c + dc if min(newR, newC) >= 0 and max(newR, newC) < N and grid[newR][newC] == 0: @@ -310,13 +321,25 @@ class Solution { } let res = -1; - const direct = [[0, 1], [0, -1], [1, 0], [-1, 0]]; + const direct = [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ]; while (!q.isEmpty()) { const [r, c] = q.pop(); res = grid[r][c]; for (let d = 0; d < 4; d++) { - let newR = r + direct[d][0], newC = c + direct[d][1]; - if (newR >= 0 && newC >= 0 && newR < N && newC < N && grid[newR][newC] === 0) { + let newR = r + direct[d][0], + newC = c + direct[d][1]; + if ( + newR >= 0 && + newC >= 0 && + newR < N && + newC < N && + grid[newR][newC] === 0 + ) { q.push([newR, newC]); grid[newR][newC] = grid[r][c] + 1; } @@ -331,8 +354,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -466,8 +489,15 @@ class Solution { for (let i = q.size(); i > 0; i--) { const [r, c] = q.pop(); for (let d = 0; d < 4; d++) { - let newR = r + direct[d], newC = c + direct[d + 1]; - if (newR >= 0 && newC >= 0 && newR < N && newC < N && !visit[newR][newC]) { + let newR = r + direct[d], + newC = c + direct[d + 1]; + if ( + newR >= 0 && + newC >= 0 && + newR < N && + newC < N && + !visit[newR][newC] + ) { q.push([newR, newC]); visit[newR][newC] = true; } @@ -483,8 +513,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -587,14 +617,17 @@ class Solution { * @return {number} */ maxDistance(grid) { - const N = grid.length, INF = 1000000; + const N = grid.length, + INF = 1000000; for (let r = 0; r < N; r++) { for (let c = 0; c < N; c++) { if (grid[r][c] === 1) continue; grid[r][c] = INF; - if (r > 0) grid[r][c] = Math.min(grid[r][c], grid[r - 1][c] + 1); - if (c > 0) grid[r][c] = Math.min(grid[r][c], grid[r][c - 1] + 1); + if (r > 0) + grid[r][c] = Math.min(grid[r][c], grid[r - 1][c] + 1); + if (c > 0) + grid[r][c] = Math.min(grid[r][c], grid[r][c - 1] + 1); } } @@ -602,8 +635,10 @@ class Solution { for (let r = N - 1; r >= 0; r--) { for (let c = N - 1; c >= 0; c--) { if (grid[r][c] === 1) continue; - if (r < N - 1) grid[r][c] = Math.min(grid[r][c], grid[r + 1][c] + 1); - if (c < N - 1) grid[r][c] = Math.min(grid[r][c], grid[r][c + 1] + 1); + if (r < N - 1) + grid[r][c] = Math.min(grid[r][c], grid[r + 1][c] + 1); + if (c < N - 1) + grid[r][c] = Math.min(grid[r][c], grid[r][c + 1] + 1); res = Math.max(res, grid[r][c]); } } @@ -617,8 +652,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ extra space. --- @@ -739,7 +774,10 @@ class Solution { for (let r = N; r > 0; r--) { for (let c = N; c > 0; c--) { if (grid[r - 1][c - 1] === 0) { - dp[r][c] = Math.min(dp[r][c], Math.min(dp[r + 1][c], dp[r][c + 1]) + 1); + dp[r][c] = Math.min( + dp[r][c], + Math.min(dp[r + 1][c], dp[r][c + 1]) + 1, + ); res = Math.max(res, dp[r][c]); } } @@ -753,5 +791,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ \ No newline at end of file +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ diff --git a/articles/assign-cookies.md b/articles/assign-cookies.md index b591a8ef9..8c471f4f4 100644 --- a/articles/assign-cookies.md +++ b/articles/assign-cookies.md @@ -13,14 +13,14 @@ class Solution: for j in range(len(s)): if s[j] < i: continue - + if minIdx == -1 or s[minIdx] > s[j]: minIdx = j - + if minIdx != -1: s[minIdx] = -1 res += 1 - + return res ``` @@ -115,8 +115,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m + m \log m)$ -* Space complexity: $O(1)$ or $O(m)$ depending on the sorting algorithm. +- Time complexity: $O(n * m + m \log m)$ +- Space complexity: $O(1)$ or $O(m)$ depending on the sorting algorithm. > Where $n$ is the size of the array $g$ and $m$ is the size of the array $s$. @@ -131,7 +131,7 @@ class Solution: def findContentChildren(self, g: List[int], s: List[int]) -> int: g.sort() s.sort() - + i = j = 0 while i < len(g): while j < len(s) and g[i] > s[j]: @@ -195,7 +195,8 @@ class Solution { g.sort((a, b) => a - b); s.sort((a, b) => a - b); - let i = 0, j = 0; + let i = 0, + j = 0; while (i < g.length) { while (j < s.length && g[i] > s[j]) { j++; @@ -213,8 +214,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n + m \log m)$ -* Space complexity: $O(1)$ or $O(n + m)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n + m \log m)$ +- Space complexity: $O(1)$ or $O(n + m)$ depending on the sorting algorithm. > Where $n$ is the size of the array $g$ and $m$ is the size of the array $s$. @@ -229,13 +230,13 @@ class Solution: def findContentChildren(self, g: List[int], s: List[int]) -> int: g.sort() s.sort() - + i = j = 0 while i < len(g) and j < len(s): if g[i] <= s[j]: i += 1 j += 1 - + return i ``` @@ -294,7 +295,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n + m \log m)$ -* Space complexity: $O(1)$ or $O(n + m)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n + m \log m)$ +- Space complexity: $O(1)$ or $O(n + m)$ depending on the sorting algorithm. -> Where $n$ is the size of the array $g$ and $m$ is the size of the array $s$. \ No newline at end of file +> Where $n$ is the size of the array $g$ and $m$ is the size of the array $s$. diff --git a/articles/asteroid-collision.md b/articles/asteroid-collision.md index 94a5993d3..d8926e704 100644 --- a/articles/asteroid-collision.md +++ b/articles/asteroid-collision.md @@ -134,8 +134,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -298,5 +298,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for the output array. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for the output array. diff --git a/articles/average-waiting-time.md b/articles/average-waiting-time.md index 0d6c7c818..3aac9a698 100644 --- a/articles/average-waiting-time.md +++ b/articles/average-waiting-time.md @@ -69,7 +69,8 @@ class Solution { * @return {number} */ averageWaitingTime(customers) { - let t = 0, total = 0; + let t = 0, + total = 0; for (let [arrival, order] of customers) { if (t > arrival) { @@ -90,8 +91,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -149,7 +150,8 @@ class Solution { * @return {number} */ averageWaitingTime(customers) { - let t = 0, total = 0; + let t = 0, + total = 0; for (let [arrival, order] of customers) { t = Math.max(t, arrival) + order; @@ -165,5 +167,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/backspace-string-compare.md b/articles/backspace-string-compare.md index 6064e5bd6..b95f0c691 100644 --- a/articles/backspace-string-compare.md +++ b/articles/backspace-string-compare.md @@ -94,8 +94,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n + m)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(n + m)$ > Where $n$ is the length of the string $s$ and $m$ is the length of the string $t$. @@ -180,7 +180,7 @@ class Solution { */ backspaceCompare(s, t) { const convert = (s) => { - const res = []; + const res = []; let backspace = 0; for (let i = s.length - 1; i >= 0; i--) { if (s[i] === '#') { @@ -202,8 +202,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n + m)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(n + m)$ > Where $n$ is the length of the string $s$ and $m$ is the length of the string $t$. @@ -353,7 +353,8 @@ class Solution { return index; }; - let indexS = s.length - 1, indexT = t.length - 1; + let indexS = s.length - 1, + indexT = t.length - 1; while (indexS >= 0 || indexT >= 0) { indexS = nextValidChar(s, indexS); @@ -377,8 +378,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(1)$ > Where $n$ is the length of the string $s$ and $m$ is the length of the string $t$. @@ -393,7 +394,7 @@ class Solution: def backspaceCompare(self, s: str, t: str) -> bool: index_s, index_t = len(s) - 1, len(t) - 1 backspace_s = backspace_t = 0 - + while True: while index_s >= 0 and (backspace_s or s[index_s] == '#'): backspace_s += 1 if s[index_s] == '#' else -1 @@ -419,7 +420,7 @@ public class Solution { backspaceS += s.charAt(indexS) == '#' ? 1 : -1; indexS--; } - + while (indexT >= 0 && (backspaceT > 0 || t.charAt(indexT) == '#')) { backspaceT += t.charAt(indexT) == '#' ? 1 : -1; indexT--; @@ -443,7 +444,7 @@ public: int backspaceS = 0, backspaceT = 0; while (true) { - + while (indexS >= 0 && (backspaceS > 0 || s[indexS] == '#')) { backspaceS += (s[indexS] == '#') ? 1 : -1; indexS--; @@ -472,8 +473,10 @@ class Solution { * @return {boolean} */ backspaceCompare(s, t) { - let indexS = s.length - 1, indexT = t.length - 1; - let backspaceS = 0, backspaceT = 0; + let indexS = s.length - 1, + indexT = t.length - 1; + let backspaceS = 0, + backspaceT = 0; while (true) { while (indexS >= 0 && (backspaceS > 0 || s[indexS] === '#')) { @@ -486,7 +489,13 @@ class Solution { indexT--; } - if (!(indexS >= 0 && indexT >= 0 && s.charAt(indexS) === t.charAt(indexT))) { + if ( + !( + indexS >= 0 && + indexT >= 0 && + s.charAt(indexS) === t.charAt(indexT) + ) + ) { return indexS === -1 && indexT === -1; } indexS--; @@ -500,7 +509,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(1)$ -> Where $n$ is the length of the string $s$ and $m$ is the length of the string $t$. \ No newline at end of file +> Where $n$ is the length of the string $s$ and $m$ is the length of the string $t$. diff --git a/articles/bag-of-tokens.md b/articles/bag-of-tokens.md index e6db737b8..a0faabc0f 100644 --- a/articles/bag-of-tokens.md +++ b/articles/bag-of-tokens.md @@ -81,7 +81,10 @@ class Solution { */ bagOfTokensScore(tokens, power) { tokens.sort((a, b) => a - b); - let res = 0, score = 0, l = 0, r = tokens.length - 1; + let res = 0, + score = 0, + l = 0, + r = tokens.length - 1; while (l <= r) { if (power >= tokens[l]) { @@ -105,5 +108,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. diff --git a/articles/balanced-binary-tree.md b/articles/balanced-binary-tree.md index 21715bc6f..a2e4a230c 100644 --- a/articles/balanced-binary-tree.md +++ b/articles/balanced-binary-tree.md @@ -14,7 +14,7 @@ class Solution: def isBalanced(self, root: Optional[TreeNode]) -> bool: if not root: return True - + left = self.height(root.left) right = self.height(root.right) if abs(left - right) > 1: @@ -83,10 +83,10 @@ public: bool isBalanced(TreeNode* root) { if (!root) return true; - int left = height(root->left); + int left = height(root->left); int right = height(root->right); if (abs(left - right) > 1) return false; - return isBalanced(root->left) && isBalanced(root->right); + return isBalanced(root->left) && isBalanced(root->right); } int height(TreeNode* root) { @@ -134,9 +134,7 @@ class Solution { return 0; } - return ( - 1 + Math.max(this.height(root.left), this.height(root.right)) - ); + return 1 + Math.max(this.height(root.left), this.height(root.right)); } } ``` @@ -189,7 +187,7 @@ func isBalanced(root *TreeNode) bool { if root == nil { return true } - + left := height(root.Left) right := height(root.Right) if abs(left-right) > 1 { @@ -236,7 +234,7 @@ class Solution { if (root == null) { return true } - + val left = height(root.left) val right = height(root.right) if (Math.abs(left - right) > 1) { @@ -244,7 +242,7 @@ class Solution { } return isBalanced(root.left) && isBalanced(root.right) } - + private fun height(root: TreeNode?): Int { if (root == null) { return 0 @@ -295,8 +293,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -343,7 +341,7 @@ class Solution: */ class Solution { - + public boolean isBalanced(TreeNode root) { return dfs(root)[0] == 1; } @@ -356,7 +354,7 @@ class Solution { int[] left = dfs(root.left); int[] right = dfs(root.right); - boolean balanced = (left[0] == 1 && right[0] == 1) && + boolean balanced = (left[0] == 1 && right[0] == 1) && (Math.abs(left[1] - right[1]) <= 1); int height = 1 + Math.max(left[1], right[1]); @@ -393,7 +391,7 @@ private: vector left = dfs(root->left); vector right = dfs(root->right); - bool balanced = (left[0] == 1 && right[0] == 1) && + bool balanced = (left[0] == 1 && right[0] == 1) && (abs(left[1] - right[1]) <= 1); int height = 1 + max(left[1], right[1]); @@ -462,7 +460,7 @@ class Solution { */ public class Solution { - + public bool IsBalanced(TreeNode root) { return Dfs(root)[0] == 1; } @@ -506,10 +504,10 @@ func dfs(root *TreeNode) Result { if root == nil { return Result{true, 0} } - + left := dfs(root.Left) right := dfs(root.Right) - + balanced := left.balanced && right.balanced && abs(left.height - right.height) <= 1 return Result{balanced, 1 + max(left.height, right.height)} } @@ -544,12 +542,12 @@ class Solution { fun isBalanced(root: TreeNode?): Boolean { return dfs(root).first } - + private fun dfs(root: TreeNode?): Pair { if (root == null) { return Pair(true, 0) } - + val left = dfs(root.left) val right = dfs(root.right) val balanced = left.first && right.first && Math.abs(left.second - right.second) <= 1 @@ -595,10 +593,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(h)$ - * Best Case ([balanced tree](https://www.geeksforgeeks.org/balanced-binary-tree/)): $O(log(n))$ - * Worst Case ([degenerate tree](https://www.geeksforgeeks.org/introduction-to-degenerate-binary-tree/)): $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(h)$ + - Best Case ([balanced tree](https://www.geeksforgeeks.org/balanced-binary-tree/)): $O(log(n))$ + - Worst Case ([degenerate tree](https://www.geeksforgeeks.org/introduction-to-degenerate-binary-tree/)): $O(n)$ > Where $n$ is the number of nodes in the tree and $h$ is the height of the tree. @@ -668,7 +666,7 @@ public class Solution { Stack stack = new Stack<>(); TreeNode node = root, last = null; Map depths = new HashMap<>(); - + while (!stack.isEmpty() || node != null) { if (node != null) { stack.push(node); @@ -757,7 +755,8 @@ class Solution { */ isBalanced(root) { let stack = []; - let node = root, last = null; + let node = root, + last = null; let depths = new Map(); while (stack.length > 0 || node !== null) { @@ -813,10 +812,10 @@ public class Solution { node = stack.Peek(); if (node.right == null || last == node.right) { stack.Pop(); - - int left = (node.left != null && depths.ContainsKey(node.left)) + + int left = (node.left != null && depths.ContainsKey(node.left)) ? depths[node.left] : 0; - int right = (node.right != null && depths.ContainsKey(node.right)) + int right = (node.right != null && depths.ContainsKey(node.right)) ? depths[node.right] : 0; if (Math.Abs(left - right) > 1) return false; @@ -992,5 +991,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/baseball-game.md b/articles/baseball-game.md index ac8e53feb..f62506f65 100644 --- a/articles/baseball-game.md +++ b/articles/baseball-game.md @@ -78,14 +78,14 @@ class Solution { calPoints(operations) { const stack = []; for (const op of operations) { - if (op === "+") { + if (op === '+') { const top = stack.pop(); const newTop = top + stack[stack.length - 1]; stack.push(top); stack.push(newTop); - } else if (op === "D") { + } else if (op === 'D') { stack.push(2 * stack[stack.length - 1]); - } else if (op === "C") { + } else if (op === 'C') { stack.pop(); } else { stack.push(parseInt(op)); @@ -130,8 +130,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -224,16 +224,16 @@ class Solution { const stack = []; let res = 0; for (const op of operations) { - if (op === "+") { + if (op === '+') { const top = stack.pop(); const newTop = top + stack[stack.length - 1]; stack.push(top); stack.push(newTop); res += newTop; - } else if (op === "D") { + } else if (op === 'D') { stack.push(2 * stack[stack.length - 1]); res += stack[stack.length - 1]; - } else if (op === "C") { + } else if (op === 'C') { res -= stack.pop(); } else { stack.push(parseInt(op)); @@ -281,5 +281,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/basic-calculator-ii.md b/articles/basic-calculator-ii.md index 99ce57902..a38710b58 100644 --- a/articles/basic-calculator-ii.md +++ b/articles/basic-calculator-ii.md @@ -36,7 +36,7 @@ public class Solution { Stack stack = new Stack<>(); int num = 0; char op = '+'; - + for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (Character.isDigit(ch)) { @@ -57,7 +57,7 @@ public class Solution { num = 0; } } - + int res = 0; while (!stack.isEmpty()) { res += stack.pop(); @@ -146,7 +146,7 @@ public class Solution { var stack = new Stack(); int num = 0; char op = '+'; - + for (int i = 0; i < s.Length; i++) { char ch = s[i]; if (char.IsDigit(ch)) { @@ -168,7 +168,7 @@ public class Solution { num = 0; } } - + int res = 0; while (stack.Count > 0) { res += stack.Pop(); @@ -182,8 +182,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -317,7 +317,9 @@ class Solution { * @return {number} */ calculate(s) { - let total = 0, prev = 0, num = 0; + let total = 0, + prev = 0, + num = 0; let op = '+'; const n = s.length; let i = 0; @@ -339,7 +341,7 @@ class Solution { } else if (op === '*') { prev = prev * num; } else { - prev = prev / num | 0; + prev = (prev / num) | 0; } op = ch; num = 0; @@ -398,5 +400,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/best-team-with-no-conflicts.md b/articles/best-team-with-no-conflicts.md index a4e77a374..778922672 100644 --- a/articles/best-team-with-no-conflicts.md +++ b/articles/best-team-with-no-conflicts.md @@ -159,8 +159,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -171,7 +171,7 @@ class Solution { ```python class Solution: def bestTeamScore(self, scores: List[int], ages: List[int]) -> int: - pairs = [[scores[i], ages[i]] for i in range(len(scores))] + pairs = [[scores[i], ages[i]] for i in range(len(scores))] pairs.sort() dp = [pairs[i][0] for i in range(len(pairs))] @@ -290,8 +290,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -542,7 +542,7 @@ public: class SegmentTree { /** * @constructor - * @param {number} N + * @param {number} N */ constructor(N) { this.n = N; @@ -569,7 +569,10 @@ class SegmentTree { this.tree[pos] = Math.max(this.tree[pos], val); pos >>= 1; while (pos >= 1) { - this.tree[pos] = Math.max(this.tree[pos << 1], this.tree[pos << 1 | 1]); + this.tree[pos] = Math.max( + this.tree[pos << 1], + this.tree[(pos << 1) | 1], + ); pos >>= 1; } } @@ -619,7 +622,9 @@ class Solution { dp[i] = pairs[i][0]; } - const uniqueAges = [...new Set(pairs.map((p) => p[1]))].sort((a, b) => a - b); + const uniqueAges = [...new Set(pairs.map((p) => p[1]))].sort( + (a, b) => a - b, + ); const ageId = new Map(); uniqueAges.forEach((val, idx) => ageId.set(val, idx)); @@ -645,5 +650,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ diff --git a/articles/best-time-to-buy-and-sell-stock-ii.md b/articles/best-time-to-buy-and-sell-stock-ii.md index 6562e3544..cc1d82833 100644 --- a/articles/best-time-to-buy-and-sell-stock-ii.md +++ b/articles/best-time-to-buy-and-sell-stock-ii.md @@ -113,8 +113,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ --- @@ -276,8 +276,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -290,11 +290,11 @@ class Solution: def maxProfit(self, prices: List[int]) -> int: n = len(prices) dp = [[0] * 2 for _ in range(n + 1)] - + for i in range(n - 1, -1, -1): dp[i][0] = max(dp[i + 1][0], -prices[i] + dp[i + 1][1]) dp[i][1] = max(dp[i + 1][1], prices[i] + dp[i + 1][0]) - + return dp[0][0] ``` @@ -303,12 +303,12 @@ public class Solution { public int maxProfit(int[] prices) { int n = prices.length; int[][] dp = new int[n + 1][2]; - + for (int i = n - 1; i >= 0; i--) { dp[i][0] = Math.max(dp[i + 1][0], -prices[i] + dp[i + 1][1]); dp[i][1] = Math.max(dp[i + 1][1], prices[i] + dp[i + 1][0]); } - + return dp[0][0]; } } @@ -320,12 +320,12 @@ public: int maxProfit(vector& prices) { int n = prices.size(); vector> dp(n + 1, vector(2, 0)); - + for (int i = n - 1; i >= 0; i--) { dp[i][0] = max(dp[i + 1][0], -prices[i] + dp[i + 1][1]); dp[i][1] = max(dp[i + 1][1], prices[i] + dp[i + 1][0]); } - + return dp[0][0]; } }; @@ -340,12 +340,12 @@ class Solution { maxProfit(prices) { const n = prices.length; const dp = Array.from({ length: n + 1 }, () => Array(2).fill(0)); - + for (let i = n - 1; i >= 0; i--) { dp[i][0] = Math.max(dp[i + 1][0], -prices[i] + dp[i + 1][1]); dp[i][1] = Math.max(dp[i + 1][1], prices[i] + dp[i + 1][0]); } - + return dp[0][0]; } } @@ -371,8 +371,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -386,13 +386,13 @@ class Solution: n = len(prices) next_buy = next_sell = 0 cur_buy = cur_sell = 0 - + for i in range(n - 1, -1, -1): cur_buy = max(next_buy, -prices[i] + next_sell) cur_sell = max(next_sell, prices[i] + next_buy) next_buy = cur_buy next_sell = cur_sell - + return cur_buy ``` @@ -440,8 +440,10 @@ class Solution { * @return {number} */ maxProfit(prices) { - let nextBuy = 0, nextSell = 0; - let curBuy = 0, curSell = 0; + let nextBuy = 0, + nextSell = 0; + let curBuy = 0, + curSell = 0; for (let i = prices.length - 1; i >= 0; i--) { curBuy = Math.max(nextBuy, -prices[i] + nextSell); @@ -477,8 +479,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -494,7 +496,7 @@ class Solution: for i in range(1, len(prices)): if prices[i] > prices[i - 1]: profit += (prices[i] - prices[i - 1]) - + return profit ``` @@ -537,7 +539,7 @@ class Solution { let profit = 0; for (let i = 1; i < prices.length; i++) { if (prices[i] > prices[i - 1]) { - profit += (prices[i] - prices[i - 1]); + profit += prices[i] - prices[i - 1]; } } return profit; @@ -563,5 +565,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/binary-search-tree-iterator.md b/articles/binary-search-tree-iterator.md index 873698c70..4eccdb1ef 100644 --- a/articles/binary-search-tree-iterator.md +++ b/articles/binary-search-tree-iterator.md @@ -21,7 +21,7 @@ class BSTIterator: dfs(node.left) self.arr.append(node.val) dfs(node.right) - + dfs(root) def next(self) -> int: @@ -172,10 +172,10 @@ class BSTIterator { ### Time & Space Complexity -* Time complexity: - * $O(n)$ time for initialization. - * $O(n)$ time for each $next()$ and $hasNext()$ function calls. -* Space complexity: $O(n)$ +- Time complexity: + - $O(n)$ time for initialization. + - $O(n)$ time for each $next()$ and $hasNext()$ function calls. +- Space complexity: $O(n)$ --- @@ -354,10 +354,10 @@ class BSTIterator { ### Time & Space Complexity -* Time complexity: - * $O(n)$ time for initialization. - * $O(n)$ time for each $next()$ and $hasNext()$ function calls. -* Space complexity: $O(n)$ +- Time complexity: + - $O(n)$ time for initialization. + - $O(n)$ time for each $next()$ and $hasNext()$ function calls. +- Space complexity: $O(n)$ --- @@ -526,8 +526,8 @@ class BSTIterator { ### Time & Space Complexity -* Time complexity: $O(1)$ in average for each function call. -* Space complexity: $O(h)$ +- Time complexity: $O(1)$ in average for each function call. +- Space complexity: $O(h)$ > Where $n$ is the number of nodes and $h$ is the height of the given tree. @@ -554,7 +554,7 @@ class BSTIterator: while self.cur: self.stack.append(self.cur) self.cur = self.cur.left - + node = self.stack.pop() self.cur = node.right return node.val @@ -593,7 +593,7 @@ public class BSTIterator { stack.push(cur); cur = cur.left; } - + TreeNode node = stack.pop(); cur = node.right; return node.val; @@ -632,7 +632,7 @@ public: stack.push(cur); cur = cur->left; } - + TreeNode* node = stack.top(); stack.pop(); cur = node->right; @@ -693,7 +693,7 @@ class BSTIterator { ### Time & Space Complexity -* Time complexity: $O(1)$ in average for each function call. -* Space complexity: $O(h)$ +- Time complexity: $O(1)$ in average for each function call. +- Space complexity: $O(h)$ -> Where $n$ is the number of nodes and $h$ is the height of the given tree. \ No newline at end of file +> Where $n$ is the number of nodes and $h$ is the height of the given tree. diff --git a/articles/binary-search.md b/articles/binary-search.md index 59a970a26..83a4584ab 100644 --- a/articles/binary-search.md +++ b/articles/binary-search.md @@ -8,7 +8,7 @@ class Solution: if l > r: return -1 m = l + (r - l) // 2 - + if nums[m] == target: return m if nums[m] < target: @@ -24,10 +24,10 @@ public class Solution { public int binary_search(int l, int r, int[] nums, int target) { if (l > r) return -1; int m = l + (r - l) / 2; - + if (nums[m] == target) return m; - return (nums[m] < target) ? - binary_search(m + 1, r, nums, target) : + return (nums[m] < target) ? + binary_search(m + 1, r, nums, target) : binary_search(l, m - 1, nums, target); } @@ -43,10 +43,10 @@ public: int binary_search(int l, int r, vector& nums, int target){ if (l > r) return -1; int m = l + (r - l) / 2; - + if (nums[m] == target) return m; - return ((nums[m] < target) ? - binary_search(m + 1, r, nums, target) : + return ((nums[m] < target) ? + binary_search(m + 1, r, nums, target) : binary_search(l, m - 1, nums, target)); } @@ -66,11 +66,11 @@ class Solution { binary_search(l, r, nums, target) { if (l > r) return -1; let m = l + Math.floor((r - l) / 2); - + if (nums[m] === target) return m; - return (nums[m] < target) ? - this.binary_search(m + 1, r, nums, target) : - this.binary_search(l, m - 1, nums, target); + return nums[m] < target + ? this.binary_search(m + 1, r, nums, target) + : this.binary_search(l, m - 1, nums, target); } search(nums, target) { @@ -84,10 +84,10 @@ public class Solution { public int BinarySearch(int l, int r, int[] nums, int target) { if (l > r) return -1; int m = l + (r - l) / 2; - + if (nums[m] == target) return m; - return (nums[m] < target) ? - BinarySearch(m + 1, r, nums, target) : + return (nums[m] < target) ? + BinarySearch(m + 1, r, nums, target) : BinarySearch(l, m - 1, nums, target); } @@ -166,8 +166,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(\log n)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(\log n)$ --- @@ -182,7 +182,7 @@ class Solution: while l <= r: # (l + r) // 2 can lead to overflow - m = l + ((r - l) // 2) + m = l + ((r - l) // 2) if nums[m] > target: r = m - 1 @@ -345,8 +345,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ --- @@ -360,12 +360,12 @@ class Solution: l, r = 0, len(nums) while l < r: - m = l + ((r - l) // 2) + m = l + ((r - l) // 2) if nums[m] > target: r = m elif nums[m] <= target: l = m + 1 - return l - 1 if (l and nums[l - 1] == target) else -1 + return l - 1 if (l and nums[l - 1] == target) else -1 ``` ```java @@ -413,7 +413,8 @@ class Solution { * @return {number} */ search(nums, target) { - let l = 0, r = nums.length; + let l = 0, + r = nums.length; while (l < r) { let m = l + Math.floor((r - l) / 2); @@ -423,7 +424,7 @@ class Solution { l = m + 1; } } - return (l > 0 && nums[l - 1] === target) ? l - 1 : -1; + return l > 0 && nums[l - 1] === target ? l - 1 : -1; } } ``` @@ -490,7 +491,7 @@ class Solution { var l = 0, r = nums.count while l < r { - let m = l + (r - l) / 2 + let m = l + (r - l) / 2 if nums[m] > target { r = m } else { @@ -506,8 +507,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ --- @@ -521,12 +522,12 @@ class Solution: l, r = 0, len(nums) while l < r: - m = l + ((r - l) // 2) + m = l + ((r - l) // 2) if nums[m] >= target: r = m elif nums[m] < target: l = m + 1 - return l if (l < len(nums) and nums[l] == target) else -1 + return l if (l < len(nums) and nums[l] == target) else -1 ``` ```java @@ -574,7 +575,8 @@ class Solution { * @return {number} */ search(nums, target) { - let l = 0, r = nums.length; + let l = 0, + r = nums.length; while (l < r) { let m = l + Math.floor((r - l) / 2); @@ -584,7 +586,7 @@ class Solution { l = m + 1; } } - return (l < nums.length && nums[l] === target) ? l : -1; + return l < nums.length && nums[l] === target ? l : -1; } } ``` @@ -651,7 +653,7 @@ class Solution { var l = 0, r = nums.count while l < r { - let m = l + (r - l) / 2 + let m = l + (r - l) / 2 if nums[m] >= target { r = m } else { @@ -667,8 +669,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ --- @@ -758,5 +760,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ diff --git a/articles/binary-subarrays-with-sum.md b/articles/binary-subarrays-with-sum.md index 65a07ca78..e6b42256d 100644 --- a/articles/binary-subarrays-with-sum.md +++ b/articles/binary-subarrays-with-sum.md @@ -88,8 +88,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -157,7 +157,8 @@ class Solution { * @return {number} */ numSubarraysWithSum(nums, goal) { - let prefixSum = 0, res = 0; + let prefixSum = 0, + res = 0; const count = new Map(); count.set(0, 1); @@ -176,8 +177,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -254,7 +255,8 @@ class Solution { const n = nums.length; const count = Array(n + 1).fill(0); count[0] = 1; - let prefixSum = 0, res = 0; + let prefixSum = 0, + res = 0; for (const num of nums) { prefixSum += num; @@ -273,8 +275,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -305,7 +307,7 @@ public class Solution { public int numSubarraysWithSum(int[] nums, int goal) { return helper(nums, goal) - helper(nums, goal - 1); } - + private int helper(int[] nums, int x) { if (x < 0) return 0; int res = 0, l = 0, cur = 0; @@ -328,7 +330,7 @@ public: int numSubarraysWithSum(vector& nums, int goal) { return helper(nums, goal) - helper(nums, goal - 1); } - + private: int helper(vector& nums, int x) { if (x < 0) return 0; @@ -356,14 +358,16 @@ class Solution { numSubarraysWithSum(nums, goal) { const helper = (x) => { if (x < 0) return 0; - let res = 0, l = 0, cur = 0; + let res = 0, + l = 0, + cur = 0; for (let r = 0; r < nums.length; r++) { cur += nums[r]; while (cur > x) { cur -= nums[l]; l++; } - res += (r - l + 1); + res += r - l + 1; } return res; }; @@ -377,5 +381,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/binary-tree-diameter.md b/articles/binary-tree-diameter.md index b11c3e40e..de04dd9e6 100644 --- a/articles/binary-tree-diameter.md +++ b/articles/binary-tree-diameter.md @@ -14,10 +14,10 @@ class Solution: def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int: if not root: return 0 - + leftHeight = self.maxHeight(root.left) rightHeight = self.maxHeight(root.right) - diameter = leftHeight + rightHeight + diameter = leftHeight + rightHeight sub = max(self.diameterOfBinaryTree(root.left), self.diameterOfBinaryTree(root.right)) return max(diameter, sub) @@ -52,7 +52,7 @@ public class Solution { if (root == null) { return 0; } - + int leftHeight = maxHeight(root.left); int rightHeight = maxHeight(root.right); int diameter = leftHeight + rightHeight; @@ -87,7 +87,7 @@ class Solution { public: int diameterOfBinaryTree(TreeNode* root) { if (!root) return 0; - + int leftHeight = maxHeight(root->left); int rightHeight = maxHeight(root->right); int diameter = leftHeight + rightHeight; @@ -122,12 +122,14 @@ class Solution { */ diameterOfBinaryTree(root) { if (!root) return 0; - + let leftHeight = this.maxHeight(root.left); let rightHeight = this.maxHeight(root.right); let diameter = leftHeight + rightHeight; - let sub = Math.max(this.diameterOfBinaryTree(root.left), - this.diameterOfBinaryTree(root.right)); + let sub = Math.max( + this.diameterOfBinaryTree(root.left), + this.diameterOfBinaryTree(root.right), + ); return Math.max(diameter, sub); } @@ -137,7 +139,9 @@ class Solution { */ maxHeight(root) { if (!root) return 0; - return 1 + Math.max(this.maxHeight(root.left), this.maxHeight(root.right)); + return ( + 1 + Math.max(this.maxHeight(root.left), this.maxHeight(root.right)) + ); } } ``` @@ -166,7 +170,7 @@ public class Solution { int leftHeight = MaxHeight(root.left); int rightHeight = MaxHeight(root.right); int diameter = leftHeight + rightHeight; - int sub = Math.Max(DiameterOfBinaryTree(root.left), + int sub = Math.Max(DiameterOfBinaryTree(root.left), DiameterOfBinaryTree(root.right)); return Math.Max(diameter, sub); } @@ -193,14 +197,14 @@ func diameterOfBinaryTree(root *TreeNode) int { if root == nil { return 0 } - + leftHeight := maxHeight(root.Left) rightHeight := maxHeight(root.Right) diameter := leftHeight + rightHeight - - sub := max(diameterOfBinaryTree(root.Left), + + sub := max(diameterOfBinaryTree(root.Left), diameterOfBinaryTree(root.Right)) - + return max(diameter, sub) } @@ -208,7 +212,7 @@ func maxHeight(root *TreeNode) int { if root == nil { return 0 } - + return 1 + max(maxHeight(root.Left), maxHeight(root.Right)) } @@ -236,24 +240,24 @@ class Solution { if (root == null) { return 0 } - + val leftHeight = maxHeight(root.left) val rightHeight = maxHeight(root.right) val diameter = leftHeight + rightHeight - + val sub = maxOf( diameterOfBinaryTree(root.left), diameterOfBinaryTree(root.right) ) - + return maxOf(diameter, sub) } - + private fun maxHeight(root: TreeNode?): Int { if (root == null) { return 0 } - + return 1 + maxOf(maxHeight(root.left), maxHeight(root.right)) } } @@ -283,7 +287,7 @@ class Solution { let rightHeight = maxHeight(root.right) let diameter = leftHeight + rightHeight let sub = max(diameterOfBinaryTree(root.left), diameterOfBinaryTree(root.right)) - + return max(diameter, sub) } @@ -298,8 +302,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -352,7 +356,7 @@ class Solution: */ class Solution { - + public int diameterOfBinaryTree(TreeNode root) { int[] res = new int[1]; dfs(root, res); @@ -461,7 +465,7 @@ class Solution { */ public class Solution { - + public int DiameterOfBinaryTree(TreeNode root) { int res = 0; DFS(root, ref res); @@ -491,20 +495,20 @@ public class Solution { */ func diameterOfBinaryTree(root *TreeNode) int { res := 0 - + var dfs func(*TreeNode) int dfs = func(root *TreeNode) int { if root == nil { return 0 } - + left := dfs(root.Left) right := dfs(root.Right) res = max(res, left + right) - + return 1 + max(left, right) } - + dfs(root) return res } @@ -530,21 +534,21 @@ func max(a, b int) int { */ class Solution { private var res = 0 - + fun diameterOfBinaryTree(root: TreeNode?): Int { dfs(root) return res } - + private fun dfs(root: TreeNode?): Int { if (root == null) { return 0 } - + val left = dfs(root.left) val right = dfs(root.right) res = maxOf(res, left + right) - + return 1 + maxOf(left, right) } } @@ -588,10 +592,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(h)$ - * Best Case ([balanced tree](https://www.geeksforgeeks.org/balanced-binary-tree/)): $O(log(n))$ - * Worst Case ([degenerate tree](https://www.geeksforgeeks.org/introduction-to-degenerate-binary-tree/)): $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(h)$ + - Best Case ([balanced tree](https://www.geeksforgeeks.org/balanced-binary-tree/)): $O(log(n))$ + - Worst Case ([degenerate tree](https://www.geeksforgeeks.org/introduction-to-degenerate-binary-tree/)): $O(n)$ > Where $n$ is the number of nodes in the tree and $h$ is the height of the tree. @@ -674,7 +678,7 @@ public class Solution { int rightHeight = rightData[0], rightDiameter = rightData[1]; int height = 1 + Math.max(leftHeight, rightHeight); - int diameter = Math.max(leftHeight + rightHeight, + int diameter = Math.max(leftHeight + rightHeight, Math.max(leftDiameter, rightDiameter)); mp.put(node, new int[]{height, diameter}); @@ -721,7 +725,7 @@ public: auto[rightHeight, rightDiameter] = mp[node->right]; int height = 1 + std::max(leftHeight, rightHeight); - int diameter = max(leftHeight + rightHeight, + int diameter = max(leftHeight + rightHeight, max(leftDiameter, rightDiameter)); mp[node] = {height, diameter}; @@ -768,8 +772,10 @@ class Solution { let [rightHeight, rightDiameter] = mp.get(node.right); let height = 1 + Math.max(leftHeight, rightHeight); - let diameter = Math.max(leftHeight + rightHeight, - Math.max(leftDiameter, rightDiameter)); + let diameter = Math.max( + leftHeight + rightHeight, + Math.max(leftDiameter, rightDiameter), + ); mp.set(node, [height, diameter]); } @@ -825,7 +831,7 @@ public class Solution { } int height = 1 + Math.Max(leftHeight, rightHeight); - int diameter = Math.Max(leftHeight + rightHeight, + int diameter = Math.Max(leftHeight + rightHeight, Math.Max(leftDiameter, rightDiameter)); mp[node] = (height, diameter); @@ -850,36 +856,36 @@ func diameterOfBinaryTree(root *TreeNode) int { if root == nil { return 0 } - + stack := linkedliststack.New() stack.Push(root) mp := make(map[*TreeNode][]int) mp[nil] = []int{0, 0} - + for !stack.Empty() { val, _ := stack.Peek() node := val.(*TreeNode) - + if node.Left != nil && len(mp[node.Left]) == 0 { stack.Push(node.Left) } else if node.Right != nil && len(mp[node.Right]) == 0 { stack.Push(node.Right) } else { stack.Pop() - + leftHeight := mp[node.Left][0] leftDiameter := mp[node.Left][1] rightHeight := mp[node.Right][0] rightDiameter := mp[node.Right][1] - + height := 1 + max(leftHeight, rightHeight) - diameter := max(leftHeight+rightHeight, + diameter := max(leftHeight+rightHeight, max(leftDiameter, rightDiameter)) - + mp[node] = []int{height, diameter} } } - + return mp[root][1] } @@ -907,16 +913,16 @@ class Solution { if (root == null) { return 0 } - + val stack = ArrayDeque() stack.addLast(root) - + val mp = HashMap>() mp[null] = Pair(0, 0) - + while (stack.isNotEmpty()) { val node = stack.last() - + when { node.left != null && !mp.containsKey(node.left) -> { stack.addLast(node.left) @@ -926,20 +932,20 @@ class Solution { } else -> { stack.removeLast() - + val (leftHeight, leftDiameter) = mp[node.left] ?: Pair(0, 0) val (rightHeight, rightDiameter) = mp[node.right] ?: Pair(0, 0) - + val height = 1 + maxOf(leftHeight, rightHeight) - val diameter = maxOf(leftHeight + rightHeight, - leftDiameter, + val diameter = maxOf(leftHeight + rightHeight, + leftDiameter, rightDiameter) - + mp[node] = Pair(height, diameter) } } } - + return mp[root]?.second ?: 0 } } @@ -992,5 +998,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/binary-tree-from-preorder-and-inorder-traversal.md b/articles/binary-tree-from-preorder-and-inorder-traversal.md index b21106a35..04b56213c 100644 --- a/articles/binary-tree-from-preorder-and-inorder-traversal.md +++ b/articles/binary-tree-from-preorder-and-inorder-traversal.md @@ -181,9 +181,9 @@ func buildTree(preorder []int, inorder []int) *TreeNode { if len(preorder) == 0 || len(inorder) == 0 { return nil } - + root := &TreeNode{Val: preorder[0]} - + mid := 0 for i, val := range inorder { if val == preorder[0] { @@ -191,10 +191,10 @@ func buildTree(preorder []int, inorder []int) *TreeNode { break } } - + root.Left = buildTree(preorder[1:mid+1], inorder[:mid]) root.Right = buildTree(preorder[mid+1:], inorder[mid+1:]) - + return root } ``` @@ -215,21 +215,21 @@ class Solution { if (preorder.isEmpty() || inorder.isEmpty()) { return null } - + val root = TreeNode(preorder[0]) - + val mid = inorder.indexOf(preorder[0]) - + root.left = buildTree( preorder.slice(1..mid).toIntArray(), inorder.slice(0 until mid).toIntArray() ) - + root.right = buildTree( preorder.slice(mid + 1 until preorder.size).toIntArray(), inorder.slice(mid + 1 until inorder.size).toIntArray() ) - + return root } } @@ -264,12 +264,12 @@ class Solution { } root.left = buildTree( - Array(preorder[1..<(mid + 1)]), + Array(preorder[1..<(mid + 1)]), Array(inorder[0.. Optional[TreeNode]: indices = {val: idx for idx, val in enumerate(inorder)} - + self.pre_idx = 0 def dfs(l, r): if l > r: @@ -375,7 +375,7 @@ public class Solution { class Solution { int pre_idx = 0; unordered_map indices; - + TreeNode* dfs(vector& preorder, int l, int r) { if (l > r) return nullptr; int root_val = preorder[pre_idx++]; @@ -385,7 +385,7 @@ class Solution { root->right = dfs(preorder, mid + 1, r); return root; } - + public: TreeNode* buildTree(vector& preorder, vector& inorder) { for (int i = 0; i < inorder.size(); ++i) { @@ -417,9 +417,9 @@ class Solution { buildTree(preorder, inorder) { let pre_idx = 0; let indices = new Map(); - + inorder.forEach((val, i) => indices.set(val, i)); - + function dfs(l, r) { if (l > r) return null; let root_val = preorder[pre_idx++]; @@ -429,7 +429,7 @@ class Solution { root.right = dfs(mid + 1, r); return root; } - + return dfs(0, inorder.length - 1); } } @@ -487,27 +487,27 @@ func buildTree(preorder []int, inorder []int) *TreeNode { for i, val := range inorder { indices[val] = i } - + preIdx := 0 - + var dfs func(int, int) *TreeNode dfs = func(left, right int) *TreeNode { if left > right { return nil } - + rootVal := preorder[preIdx] preIdx++ - + root := &TreeNode{Val: rootVal} mid := indices[rootVal] - + root.Left = dfs(left, mid - 1) root.Right = dfs(mid + 1, right) - + return root } - + return dfs(0, len(inorder) - 1) } ``` @@ -525,26 +525,26 @@ func buildTree(preorder []int, inorder []int) *TreeNode { */ class Solution { private var preIdx = 0 - + fun buildTree(preorder: IntArray, inorder: IntArray): TreeNode? { val indices = inorder.withIndex() .associate { (index, value) -> value to index } - + fun dfs(left: Int, right: Int): TreeNode? { if (left > right) { return null } - + val rootVal = preorder[preIdx++] val root = TreeNode(rootVal) val mid = indices[rootVal]!! - + root.left = dfs(left, mid - 1) root.right = dfs(mid + 1, right) - + return root } - + return dfs(0, inorder.lastIndex) } } @@ -599,8 +599,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -626,7 +626,7 @@ class Solution: if inorder[inIdx] == limit: inIdx += 1 return None - + root = TreeNode(preorder[preIdx]) preIdx += 1 root.left = dfs(root.val) @@ -731,21 +731,22 @@ class Solution { * @return {TreeNode} */ buildTree(preorder, inorder) { - let preIdx = 0, inIdx = 0; - + let preIdx = 0, + inIdx = 0; + function dfs(limit) { if (preIdx >= preorder.length) return null; if (inorder[inIdx] === limit) { inIdx++; return null; } - + let root = new TreeNode(preorder[preIdx++]); root.left = dfs(root.val); root.right = dfs(limit); return root; } - + return dfs(Infinity); } } @@ -800,7 +801,7 @@ public class Solution { */ func buildTree(preorder []int, inorder []int) *TreeNode { preIdx, inIdx := 0, 0 - + var dfs func(int) *TreeNode dfs = func(limit int) *TreeNode { if preIdx >= len(preorder) { @@ -810,16 +811,16 @@ func buildTree(preorder []int, inorder []int) *TreeNode { inIdx++ return nil } - + root := &TreeNode{Val: preorder[preIdx]} preIdx++ - + root.Left = dfs(root.Val) root.Right = dfs(limit) - + return root } - + return dfs(math.MaxInt) } ``` @@ -838,7 +839,7 @@ func buildTree(preorder []int, inorder []int) *TreeNode { class Solution { private var preIdx = 0 private var inIdx = 0 - + fun buildTree(preorder: IntArray, inorder: IntArray): TreeNode? { fun dfs(limit: Int): TreeNode? { if (preIdx >= preorder.size) { @@ -848,16 +849,16 @@ class Solution { inIdx++ return null } - + val root = TreeNode(preorder[preIdx]) preIdx++ - + root.left = dfs(root.`val`) root.right = dfs(limit) - + return root } - + return dfs(Int.MAX_VALUE) } } @@ -909,5 +910,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. diff --git a/articles/binary-tree-inorder-traversal.md b/articles/binary-tree-inorder-traversal.md index 84e525d71..79a7a36f9 100644 --- a/articles/binary-tree-inorder-traversal.md +++ b/articles/binary-tree-inorder-traversal.md @@ -16,11 +16,11 @@ class Solution: def inorder(node): if not node: return - + inorder(node.left) res.append(node.val) inorder(node.right) - + inorder(root) return res ``` @@ -159,10 +159,10 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(n)$ space for the recursion stack. - * $O(n)$ space for the output array. +- Time complexity: $O(n)$ +- Space complexity: + - $O(n)$ space for the recursion stack. + - $O(n)$ space for the output array. --- @@ -190,7 +190,7 @@ class Solution: cur = stack.pop() res.append(cur.val) cur = cur.right - + return res ``` @@ -341,10 +341,10 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(n)$ space for the stack. - * $O(n)$ space for the output array. +- Time complexity: $O(n)$ +- Space complexity: + - $O(n)$ space for the stack. + - $O(n)$ space for the output array. --- @@ -570,7 +570,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ space for the output array. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ space for the output array. diff --git a/articles/binary-tree-maximum-path-sum.md b/articles/binary-tree-maximum-path-sum.md index ebd5467bc..a783160d0 100644 --- a/articles/binary-tree-maximum-path-sum.md +++ b/articles/binary-tree-maximum-path-sum.md @@ -16,7 +16,7 @@ class Solution: def dfs(root): nonlocal res if not root: - return + return left = self.getMax(root.left) right = self.getMax(root.right) res =max(res, root.val + left + right) @@ -24,11 +24,11 @@ class Solution: dfs(root.right) dfs(root) return res - + def getMax(self, root: Optional[TreeNode]) -> int: if not root: return 0 - + left = self.getMax(root.left) right = self.getMax(root.right) path = root.val + max(left, right) @@ -215,7 +215,7 @@ public class Solution { * } */ func maxPathSum(root *TreeNode) int { - res := -1 << 31 + res := -1 << 31 dfs(root, &res) return res } @@ -337,8 +337,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -539,24 +539,24 @@ public class Solution { */ func maxPathSum(root *TreeNode) int { res := []int{root.Val} - + var dfs func(node *TreeNode) int dfs = func(node *TreeNode) int { if node == nil { return 0 } - + leftMax := dfs(node.Left) rightMax := dfs(node.Right) - + leftMax = max(leftMax, 0) rightMax = max(rightMax, 0) - + res[0] = max(res[0], node.Val+leftMax+rightMax) - + return node.Val + max(leftMax, rightMax) } - + dfs(root) return res[0] } @@ -582,22 +582,22 @@ func max(a, b int) int { */ class Solution { private var res = Int.MIN_VALUE - + fun maxPathSum(root: TreeNode?): Int { dfs(root) return res } - + private fun dfs(node: TreeNode?): Int { if (node == null) { return 0 } - + val leftMax = maxOf(dfs(node.left), 0) val rightMax = maxOf(dfs(node.right), 0) - + res = maxOf(res, node.`val` + leftMax + rightMax) - + return node.`val` + maxOf(leftMax, rightMax) } } @@ -643,5 +643,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/binary-tree-postorder-traversal.md b/articles/binary-tree-postorder-traversal.md index 8853be764..4b1ea9958 100644 --- a/articles/binary-tree-postorder-traversal.md +++ b/articles/binary-tree-postorder-traversal.md @@ -16,11 +16,11 @@ class Solution: def postorder(node): if not node: return - + postorder(node.left) postorder(node.right) res.append(node.val) - + postorder(root) return res ``` @@ -161,10 +161,10 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(n)$ space for the recursion stack. - * $O(n)$ space for the output array. +- Time complexity: $O(n)$ +- Space complexity: + - $O(n)$ space for the recursion stack. + - $O(n)$ space for the output array. --- @@ -390,10 +390,10 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(n)$ space for the stacks. - * $O(n)$ space for the output array. +- Time complexity: $O(n)$ +- Space complexity: + - $O(n)$ space for the stacks. + - $O(n)$ space for the output array. --- @@ -582,10 +582,10 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(n)$ space for the stack. - * $O(n)$ space for the output array. +- Time complexity: $O(n)$ +- Space complexity: + - $O(n)$ space for the stack. + - $O(n)$ space for the output array. --- @@ -621,7 +621,7 @@ class Solution: else: prev.left = None cur = cur.left - + res.reverse() return res ``` @@ -816,7 +816,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ space for the output array. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ space for the output array. diff --git a/articles/binary-tree-preorder-traversal.md b/articles/binary-tree-preorder-traversal.md index f7f86ffb9..fe9cecef4 100644 --- a/articles/binary-tree-preorder-traversal.md +++ b/articles/binary-tree-preorder-traversal.md @@ -16,11 +16,11 @@ class Solution: def preorder(node): if not node: return - + res.append(node.val) preorder(node.left) preorder(node.right) - + preorder(root) return res ``` @@ -161,10 +161,10 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(n)$ space for the recursion stack. - * $O(n)$ space for the output array. +- Time complexity: $O(n)$ +- Space complexity: + - $O(n)$ space for the recursion stack. + - $O(n)$ space for the output array. --- @@ -192,7 +192,7 @@ class Solution: cur = cur.left else: cur = stack.pop() - + return res ``` @@ -296,7 +296,6 @@ class Solution { cur = cur.left; } else { cur = stack.pop(); - } } @@ -344,10 +343,10 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(n)$ space for the stack. - * $O(n)$ space for the output array. +- Time complexity: $O(n)$ +- Space complexity: + - $O(n)$ space for the stack. + - $O(n)$ space for the output array. --- @@ -573,7 +572,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ space for the output array. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ space for the output array. diff --git a/articles/binary-tree-right-side-view.md b/articles/binary-tree-right-side-view.md index 4d8a68b19..4d64bb984 100644 --- a/articles/binary-tree-right-side-view.md +++ b/articles/binary-tree-right-side-view.md @@ -19,10 +19,10 @@ class Solution: return None if depth == len(res): res.append(node.val) - + dfs(node.right, depth + 1) dfs(node.left, depth + 1) - + dfs(root, 0) return res ``` @@ -46,21 +46,21 @@ class Solution: public class Solution { List res = new ArrayList<>(); - + public List rightSideView(TreeNode root) { dfs(root, 0); return res; } - + private void dfs(TreeNode node, int depth) { if (node == null) { return; } - + if (res.size() == depth) { res.add(node.val); } - + dfs(node.right, depth + 1); dfs(node.left, depth + 1); } @@ -83,19 +83,19 @@ public class Solution { class Solution { public: vector res; - + vector rightSideView(TreeNode* root) { dfs(root, 0); return res; } - + void dfs(TreeNode* node, int depth) { if (!node) return; - + if (res.size() == depth) { res.push_back(node->val); } - + dfs(node->right, depth + 1); dfs(node->left, depth + 1); } @@ -156,21 +156,21 @@ class Solution { public class Solution { List res = new List(); - + public List RightSideView(TreeNode root) { dfs(root, 0); return res; } - + private void dfs(TreeNode node, int depth) { if (node == null) { return; } - + if (res.Count == depth) { res.Add(node.val); } - + dfs(node.right, depth + 1); dfs(node.left, depth + 1); } @@ -200,7 +200,7 @@ func rightSideView(root *TreeNode) []int { dfs(node.Right, depth+1) dfs(node.Left, depth+1) } - + dfs(root, 0) return res } @@ -276,8 +276,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -498,7 +498,7 @@ func rightSideView(root *TreeNode) []int { if root == nil { return []int{} } - + res := []int{} q := []*TreeNode{root} @@ -509,7 +509,7 @@ func rightSideView(root *TreeNode) []int { for i := 0; i < qLen; i++ { node := q[0] q = q[1:] - + if node != nil { rightSide = node.Val if node.Left != nil { @@ -522,7 +522,7 @@ func rightSideView(root *TreeNode) []int { } res = append(res, rightSide) } - + return res } ``` @@ -560,7 +560,7 @@ class Solution { } rightSide?.let { res.add(it.`val`) } } - + return res } } @@ -612,5 +612,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/binary-tree-vertical-order-traversal.md b/articles/binary-tree-vertical-order-traversal.md index c66e08d0b..fced1c8fa 100644 --- a/articles/binary-tree-vertical-order-traversal.md +++ b/articles/binary-tree-vertical-order-traversal.md @@ -131,7 +131,7 @@ class Solution { } const sortedKeys = Array.from(cols.keys()).sort((a, b) => a - b); - return sortedKeys.map(k => cols.get(k)); + return sortedKeys.map((k) => cols.get(k)); } } ``` @@ -178,8 +178,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -329,9 +329,11 @@ class Solution { dfs(root, 0, 0); - const sortedCols = Array.from(cols.entries()).sort((a, b) => a[0] - b[0]); + const sortedCols = Array.from(cols.entries()).sort( + (a, b) => a[0] - b[0], + ); return sortedCols.map(([_, vec]) => - vec.sort((a, b) => a[0] - b[0]).map(([_, val]) => val) + vec.sort((a, b) => a[0] - b[0]).map(([_, val]) => val), ); } } @@ -380,8 +382,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n \log n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n \log n)$ --- @@ -528,7 +530,8 @@ class Solution { const cols = new Map(); const queue = new Queue([[root, 0]]); - let minCol = 0, maxCol = 0; + let minCol = 0, + maxCol = 0; while (!queue.isEmpty()) { const [node, col] = queue.pop(); @@ -599,8 +602,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -757,7 +760,8 @@ class Solution { if (!root) return []; const cols = new Map(); - let minCol = 0, maxCol = 0; + let minCol = 0, + maxCol = 0; const dfs = (node, row, col) => { if (!node) return; @@ -831,7 +835,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(w * h \log h)$ -* Space complexity: $O(n)$ +- Time complexity: $O(w * h \log h)$ +- Space complexity: $O(n)$ -> Where $n$ is the number of nodes, $h$ is the height of the tree (i.e. maximum number of nodes in any vertical line of the tree), and $w$ is the width of the tree (i.e. maximum number of nodes in any of the levels of the tree). \ No newline at end of file +> Where $n$ is the number of nodes, $h$ is the height of the tree (i.e. maximum number of nodes in any vertical line of the tree), and $w$ is the width of the tree (i.e. maximum number of nodes in any of the levels of the tree). diff --git a/articles/binary-tree-zigzag-level-order-traversal.md b/articles/binary-tree-zigzag-level-order-traversal.md index d41aac9cd..449ee2151 100644 --- a/articles/binary-tree-zigzag-level-order-traversal.md +++ b/articles/binary-tree-zigzag-level-order-traversal.md @@ -148,8 +148,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -307,8 +307,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -335,12 +335,12 @@ class Solution: res[depth].append(node.val) dfs(node.left, depth + 1) dfs(node.right, depth + 1) - + dfs(root, 0) for i, level in enumerate(res): if i & 1: level.reverse() - + return res ``` @@ -461,8 +461,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -481,7 +481,7 @@ class Solution: def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: if not root: return [] - + res = [] stack = [(root, 0)] @@ -489,7 +489,7 @@ class Solution: node, depth = stack.pop() if depth == len(res): res.append([]) - + res[depth].append(node.val) if node.right: @@ -500,7 +500,7 @@ class Solution: for i in range(len(res)): if i % 2 == 1: res[i].reverse() - + return res ``` @@ -643,5 +643,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/bitwise-and-of-numbers-range.md b/articles/bitwise-and-of-numbers-range.md index 2a47d9539..95b3e306d 100644 --- a/articles/bitwise-and-of-numbers-range.md +++ b/articles/bitwise-and-of-numbers-range.md @@ -69,8 +69,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -156,7 +156,7 @@ class Solution { const remain = left % next; const diff = next - remain; if (right - left < diff) { - res |= (1 << i); + res |= 1 << i; } } return res; @@ -187,8 +187,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ since we iterate $32$ times. -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ since we iterate $32$ times. +- Space complexity: $O(1)$ --- @@ -273,8 +273,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ --- @@ -322,7 +322,7 @@ class Solution { */ rangeBitwiseAnd(left, right) { while (left < right) { - right &= (right - 1); + right &= right - 1; } return right; } @@ -344,5 +344,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ diff --git a/articles/boats-to-save-people.md b/articles/boats-to-save-people.md index ce0498e89..0ec01c654 100644 --- a/articles/boats-to-save-people.md +++ b/articles/boats-to-save-people.md @@ -60,7 +60,9 @@ class Solution { */ numRescueBoats(people, limit) { people.sort((a, b) => a - b); - let res = 0, l = 0, r = people.length - 1; + let res = 0, + l = 0, + r = people.length - 1; while (l <= r) { let remain = limit - people[r--]; res++; @@ -98,8 +100,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -114,7 +116,7 @@ class Solution: count = [0] * (m + 1) for p in people: count[p] += 1 - + idx, i = 0, 1 while idx < len(people): while count[i] == 0: @@ -141,7 +143,7 @@ public class Solution { for (int p : people) { count[p]++; } - + int idx = 0, i = 1; while (idx < people.length) { while (count[i] == 0) { @@ -150,7 +152,7 @@ public class Solution { people[idx++] = i; count[i]--; } - + int res = 0, l = 0, r = people.length - 1; while (l <= r) { int remain = limit - people[r--]; @@ -173,7 +175,7 @@ public: for (int p : people) { count[p]++; } - + int idx = 0, i = 1; while (idx < people.size()) { while (count[i] == 0) { @@ -182,7 +184,7 @@ public: people[idx++] = i; count[i]--; } - + int res = 0, l = 0, r = people.size() - 1; while (l <= r) { int remain = limit - people[r--]; @@ -209,8 +211,9 @@ class Solution { for (const p of people) { count[p]++; } - - let idx = 0, i = 1; + + let idx = 0, + i = 1; while (idx < people.length) { while (count[i] === 0) { i++; @@ -218,8 +221,10 @@ class Solution { people[idx++] = i; count[i]--; } - - let res = 0, l = 0, r = people.length - 1; + + let res = 0, + l = 0, + r = people.length - 1; while (l <= r) { const remain = limit - people[r--]; res++; @@ -274,7 +279,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n)$ +- Space complexity: $O(m)$ -> Where $n$ is the size of the input array and $m$ is the maximum value in the array. \ No newline at end of file +> Where $n$ is the size of the input array and $m$ is the maximum value in the array. diff --git a/articles/brick-wall.md b/articles/brick-wall.md index 991f98ce3..c0c470210 100644 --- a/articles/brick-wall.md +++ b/articles/brick-wall.md @@ -16,14 +16,14 @@ class Solution: for brick in wall[i]: gap += brick gaps[i].append(gap) - + res = n for line in range(1, m): cuts = 0 for i in range(n): if line not in gaps[i]: cuts += 1 - + res = min(res, cuts) return res ``` @@ -140,8 +140,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n * g)$ -* Space complexity: $O(n * g)$ +- Time complexity: $O(m * n * g)$ +- Space complexity: $O(n * g)$ > Where $m$ is the sum of widths of the bricks in the first row, $n$ is the number of rows and $g$ is the average number of gaps in each row. @@ -239,7 +239,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(N)$ -* Space complexity: $O(g)$ +- Time complexity: $O(N)$ +- Space complexity: $O(g)$ -> Where $N$ is the total number of bricks in the wall and $g$ is the total number of gaps in all the rows. \ No newline at end of file +> Where $N$ is the total number of bricks in the wall and $g$ is the total number of gaps in all the rows. diff --git a/articles/build-a-matrix-with-conditions.md b/articles/build-a-matrix-with-conditions.md index 3754c9da3..319bca3c3 100644 --- a/articles/build-a-matrix-with-conditions.md +++ b/articles/build-a-matrix-with-conditions.md @@ -23,7 +23,7 @@ class Solution: adj = defaultdict(list) for src, dst in edges: adj[src].append(dst) - + visit, path = set(), set() order = [] for src in range(1, k + 1): @@ -34,17 +34,17 @@ class Solution: row_order = topo_sort(rowConditions) if not row_order: return [] - + col_order = topo_sort(colConditions) if not col_order: return [] - + val_to_row = {num: i for i, num in enumerate(row_order)} val_to_col = {num: i for i, num in enumerate(col_order)} res = [[0] * k for _ in range(k)] for num in range(1, k + 1): r, c = val_to_row[num], val_to_col[num] res[r][c] = num - + return res ``` @@ -355,10 +355,10 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(k ^ 2 + n + m)$ -* Space complexity: - * $O(k + n + m)$ extra space. - * $O(k ^ 2)$ space for the output matrix. +- Time complexity: $O(k ^ 2 + n + m)$ +- Space complexity: + - $O(k + n + m)$ extra space. + - $O(k ^ 2)$ space for the output matrix. > Where $n$ is the size of the array $rowConditions$, $m$ is the size of the array $colConditions$, and $k$ is the size of the output matrix. @@ -377,13 +377,13 @@ class Solution: for u, v in edges: adj[u].append(v) indegree[v] += 1 - + order = [] q = deque() for i in range(1, k + 1): if not indegree[i]: q.append(i) - + while q: node = q.popleft() order.append(node) @@ -391,20 +391,20 @@ class Solution: indegree[nei] -= 1 if not indegree[nei]: q.append(nei) - + return order row_order = topo_sort(rowConditions) if len(row_order) != k: return [] - + col_order = topo_sort(colConditions) if len(col_order) != k: return [] - + res = [[0] * k for _ in range(k)] colIndex = [0] * (k + 1) for i in range(k): colIndex[col_order[i]] = i - + for i in range(k): res[i][colIndex[row_order[i]]] = row_order[i] return res @@ -463,7 +463,7 @@ public class Solution { } } } - + if (idx != k) return new int[0]; return order; } @@ -661,9 +661,9 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(k ^ 2 + n + m)$ -* Space complexity: - * $O(k + n + m)$ extra space. - * $O(k ^ 2)$ space for the output matrix. +- Time complexity: $O(k ^ 2 + n + m)$ +- Space complexity: + - $O(k + n + m)$ extra space. + - $O(k ^ 2)$ space for the output matrix. -> Where $n$ is the size of the array $rowConditions$, $m$ is the size of the array $colConditions$, and $k$ is the size of the output matrix. \ No newline at end of file +> Where $n$ is the size of the array $rowConditions$, $m$ is the size of the array $colConditions$, and $k$ is the size of the output matrix. diff --git a/articles/buildings-with-an-ocean-view.md b/articles/buildings-with-an-ocean-view.md index 9c418c11c..91e816ec0 100644 --- a/articles/buildings-with-an-ocean-view.md +++ b/articles/buildings-with-an-ocean-view.md @@ -121,8 +121,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ for the output array. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ for the output array. --- @@ -194,7 +194,10 @@ class Solution { const stack = []; for (let i = 0; i < heights.length; i++) { - while (stack.length && heights[stack[stack.length - 1]] <= heights[i]) { + while ( + stack.length && + heights[stack[stack.length - 1]] <= heights[i] + ) { stack.pop(); } stack.push(i); @@ -226,8 +229,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -333,7 +336,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ for the output array. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ for the output array. diff --git a/articles/burst-balloons.md b/articles/burst-balloons.md index a52c66027..3c74cbfab 100644 --- a/articles/burst-balloons.md +++ b/articles/burst-balloons.md @@ -177,7 +177,7 @@ class Solution { var maxCoins = 0 for (i in 1 until nums.size - 1) { val coins = nums[i - 1] * nums[i] * nums[i + 1] - val nextCoins = dfs(nums.take(i).toIntArray() + + val nextCoins = dfs(nums.take(i).toIntArray() + nums.drop(i + 1).toIntArray()) maxCoins = maxOf(maxCoins, coins + nextCoins) } @@ -217,8 +217,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n*2^n)$ -* Space complexity: $O(n*2^n)$ +- Time complexity: $O(n*2^n)$ +- Space complexity: $O(n*2^n)$ --- @@ -346,7 +346,8 @@ class Solution { dp[l][r] = 0; for (let i = l; i <= r; i++) { let coins = nums[l - 1] * nums[i] * nums[r + 1]; - coins += this.dfs(nums, l, i - 1, dp) + this.dfs(nums, i + 1, r, dp); + coins += + this.dfs(nums, l, i - 1, dp) + this.dfs(nums, i + 1, r, dp); dp[l][r] = Math.max(dp[l][r], coins); } return dp[l][r]; @@ -486,8 +487,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 3)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 3)$ +- Space complexity: $O(n ^ 2)$ --- @@ -700,5 +701,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n^3)$ -* Space complexity: $O(n^2)$ \ No newline at end of file +- Time complexity: $O(n^3)$ +- Space complexity: $O(n^2)$ diff --git a/articles/buy-and-sell-crypto-with-cooldown.md b/articles/buy-and-sell-crypto-with-cooldown.md index 9c4ae550b..6dcebbcd8 100644 --- a/articles/buy-and-sell-crypto-with-cooldown.md +++ b/articles/buy-and-sell-crypto-with-cooldown.md @@ -5,11 +5,11 @@ ```python class Solution: def maxProfit(self, prices: List[int]) -> int: - + def dfs(i, buying): if i >= len(prices): return 0 - + cooldown = dfs(i + 1, buying) if buying: buy = dfs(i + 1, not buying) - prices[i] @@ -17,17 +17,17 @@ class Solution: else: sell = dfs(i + 2, not buying) + prices[i] return max(sell, cooldown) - + return dfs(0, True) ``` ```java public class Solution { public int maxProfit(int[] prices) { - + return dfs(0, true, prices); } - + private int dfs(int i, boolean buying, int[] prices) { if (i >= prices.length) { return 0; @@ -51,7 +51,7 @@ public: int maxProfit(vector& prices) { return dfs(0, true, prices); } - + private: int dfs(int i, bool buying, vector& prices) { if (i >= prices.size()) { @@ -77,7 +77,6 @@ class Solution { * @return {number} */ maxProfit(prices) { - const dfs = (i, buying) => { if (i >= prices.length) { return 0; @@ -91,8 +90,8 @@ class Solution { let sell = dfs(i + 2, true) + prices[i]; return Math.max(sell, cooldown); } - } - + }; + return dfs(0, true); } } @@ -128,7 +127,7 @@ func maxProfit(prices []int) int { if i >= len(prices) { return 0 } - + cooldown := dfs(i + 1, buying) if buying { buy := dfs(i + 1, false) - prices[i] @@ -155,7 +154,7 @@ class Solution { fun maxProfit(prices: IntArray): Int { fun dfs(i: Int, buying: Boolean): Int { if (i >= prices.size) return 0 - + val cooldown = dfs(i + 1, buying) return if (buying) { val buy = dfs(i + 1, false) - prices[i] @@ -165,7 +164,7 @@ class Solution { maxOf(sell, cooldown) } } - + return dfs(0, true) } } @@ -200,8 +199,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ --- @@ -235,16 +234,16 @@ class Solution: ```java public class Solution { private Map dp = new HashMap<>(); - + public int maxProfit(int[] prices) { return dfs(0, true, prices); } - + private int dfs(int i, boolean buying, int[] prices) { if (i >= prices.length) { return 0; } - + String key = i + "-" + buying; if (dp.containsKey(key)) { return dp.get(key); @@ -268,7 +267,7 @@ public class Solution { class Solution { public: unordered_map dp; - + int maxProfit(vector& prices) { return dfs(0, true, prices); } @@ -324,8 +323,8 @@ class Solution { dp[key] = Math.max(sell, cooldown); } return dp[key]; - } - + }; + return dfs(0, true); } } @@ -333,7 +332,7 @@ class Solution { ```csharp public class Solution { - private Dictionary<(int, bool), int> dp = + private Dictionary<(int, bool), int> dp = new Dictionary<(int, bool), int>(); public int MaxProfit(int[] prices) { @@ -471,8 +470,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -484,7 +483,7 @@ class Solution { class Solution: def maxProfit(self, prices: List[int]) -> int: n = len(prices) - dp = [[0] * 2 for _ in range(n + 1)] + dp = [[0] * 2 for _ in range(n + 1)] for i in range(n - 1, -1, -1): for buying in [True, False]: @@ -504,7 +503,7 @@ class Solution: public class Solution { public int maxProfit(int[] prices) { int n = prices.length; - int[][] dp = new int[n + 1][2]; + int[][] dp = new int[n + 1][2]; for (int i = n - 1; i >= 0; i--) { for (int buying = 1; buying >= 0; buying--) { @@ -530,7 +529,7 @@ class Solution { public: int maxProfit(vector& prices) { int n = prices.size(); - vector> dp(n + 1, vector(2, 0)); + vector> dp(n + 1, vector(2, 0)); for (int i = n - 1; i >= 0; --i) { for (int buying = 1; buying >= 0; --buying) { @@ -559,7 +558,7 @@ class Solution { */ maxProfit(prices) { const n = prices.length; - const dp = Array.from({ length: n + 1 }, () => [0, 0]); + const dp = Array.from({ length: n + 1 }, () => [0, 0]); for (let i = n - 1; i >= 0; i--) { for (let buying = 1; buying >= 0; buying--) { @@ -568,7 +567,7 @@ class Solution { let cooldown = dp[i + 1][1]; dp[i][1] = Math.max(buy, cooldown); } else { - let sell = (i + 2 < n) ? dp[i + 2][1] + prices[i] : prices[i]; + let sell = i + 2 < n ? dp[i + 2][1] + prices[i] : prices[i]; let cooldown = dp[i + 1][0]; dp[i][0] = Math.max(sell, cooldown); } @@ -584,7 +583,7 @@ class Solution { public class Solution { public int MaxProfit(int[] prices) { int n = prices.Length; - int[,] dp = new int[n + 1, 2]; + int[,] dp = new int[n + 1, 2]; for (int i = n - 1; i >= 0; i--) { for (int buying = 1; buying >= 0; buying--) { @@ -695,8 +694,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -708,7 +707,7 @@ class Solution { class Solution: def maxProfit(self, prices: List[int]) -> int: n = len(prices) - dp1_buy, dp1_sell = 0, 0 + dp1_buy, dp1_sell = 0, 0 dp2_buy = 0 for i in range(n - 1, -1, -1): @@ -769,7 +768,8 @@ class Solution { */ maxProfit(prices) { const n = prices.length; - let dp1_buy = 0, dp1_sell = 0; + let dp1_buy = 0, + dp1_sell = 0; let dp2_buy = 0; for (let i = n - 1; i >= 0; i--) { @@ -873,5 +873,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/buy-and-sell-crypto.md b/articles/buy-and-sell-crypto.md index b983fd272..40e943308 100644 --- a/articles/buy-and-sell-crypto.md +++ b/articles/buy-and-sell-crypto.md @@ -140,8 +140,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -213,7 +213,8 @@ class Solution { * @return {number} */ maxProfit(prices) { - let l = 0, r = 1; + let l = 0, + r = 1; let maxP = 0; while (r < prices.length) { @@ -315,8 +316,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -452,5 +453,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/buy-two-chocolates.md b/articles/buy-two-chocolates.md index 0b6edc79d..99fbe6af6 100644 --- a/articles/buy-two-chocolates.md +++ b/articles/buy-two-chocolates.md @@ -66,8 +66,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ extra space. --- @@ -118,8 +118,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -137,7 +137,7 @@ class Solution: min1, min2 = p, min1 elif p < min2: min2 = p - + leftover = money - min1 - min2 return leftover if leftover >= 0 else money ``` @@ -186,7 +186,8 @@ public: ```javascript class Solution { buyChoco(prices, money) { - let min1 = Infinity, min2 = Infinity; + let min1 = Infinity, + min2 = Infinity; for (const p of prices) { if (p < min1) { @@ -207,5 +208,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/calculate-money-in-leetcode-bank.md b/articles/calculate-money-in-leetcode-bank.md index 1735a4724..2e9b10133 100644 --- a/articles/calculate-money-in-leetcode-bank.md +++ b/articles/calculate-money-in-leetcode-bank.md @@ -67,7 +67,9 @@ class Solution { * @return {number} */ totalMoney(n) { - let day = 0, deposit = 1, res = 0; + let day = 0, + deposit = 1, + res = 0; while (day < n) { res += deposit; @@ -88,8 +90,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -108,7 +110,7 @@ class Solution: monday = weeks + 1 for i in range(n % 7): res += i + monday - + return res ``` @@ -159,7 +161,7 @@ class Solution { const weeks = Math.floor(n / 7); const low = 28; const high = 28 + 7 * (weeks - 1); - let res = weeks * (low + high) / 2; + let res = (weeks * (low + high)) / 2; const monday = weeks + 1; for (let i = 0; i < n % 7; i++) { @@ -175,8 +177,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ --- @@ -230,7 +232,7 @@ class Solution { * @return {number} */ totalMoney(n) { - const SUM = x => (x * (x + 1)) / 2; + const SUM = (x) => (x * (x + 1)) / 2; const weeks = Math.floor(n / 7); let res = SUM(weeks - 1) * 7 + weeks * SUM(7); @@ -244,5 +246,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ diff --git a/articles/can-place-flowers.md b/articles/can-place-flowers.md index 7ccaeba96..80aa4a5b7 100644 --- a/articles/can-place-flowers.md +++ b/articles/can-place-flowers.md @@ -6,23 +6,23 @@ class Solution: def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: f = [0] + flowerbed + [0] - + for i in range(1, len(f) - 1): if f[i - 1] == 0 and f[i] == 0 and f[i + 1] == 0: f[i] = 1 n -= 1 - + return n <= 0 ``` ```java public class Solution { public boolean canPlaceFlowers(int[] flowerbed, int n) { - int[] f = new int[flowerbed.length + 2]; + int[] f = new int[flowerbed.length + 2]; for (int i = 0; i < flowerbed.length; i++) { f[i + 1] = flowerbed[i]; } - + for (int i = 1; i < f.length - 1; i++) { if (f[i - 1] == 0 && f[i] == 0 && f[i + 1] == 0) { f[i] = 1; @@ -42,7 +42,7 @@ public: for (int i = 0; i < flowerbed.size(); i++) { f[i + 1] = flowerbed[i]; } - + for (int i = 1; i < f.size() - 1; i++) { if (f[i - 1] == 0 && f[i] == 0 && f[i + 1] == 0) { f[i] = 1; @@ -63,7 +63,7 @@ class Solution { */ canPlaceFlowers(flowerbed, n) { const f = [0, ...flowerbed, 0]; - + for (let i = 1; i < f.length - 1; i++) { if (f[i - 1] === 0 && f[i] === 0 && f[i + 1] === 0) { f[i] = 1; @@ -79,8 +79,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -92,14 +92,14 @@ class Solution { class Solution: def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: empty = 0 if flowerbed[0] else 1 - + for f in flowerbed: if f: n -= int((empty - 1) / 2) empty = 0 else: empty += 1 - + n -= empty // 2 return n <= 0 ``` @@ -108,7 +108,7 @@ class Solution: public class Solution { public boolean canPlaceFlowers(int[] flowerbed, int n) { int empty = flowerbed[0] == 0 ? 1 : 0; - + for (int f : flowerbed) { if (f == 1) { n -= (empty - 1) / 2; @@ -117,7 +117,7 @@ public class Solution { empty++; } } - + n -= empty / 2; return n <= 0; } @@ -129,7 +129,7 @@ class Solution { public: bool canPlaceFlowers(vector& flowerbed, int n) { int empty = flowerbed[0] == 0 ? 1 : 0; - + for (int f : flowerbed) { if (f == 1) { n -= (empty - 1) / 2; @@ -138,7 +138,7 @@ public: empty++; } } - + n -= empty / 2; return n <= 0; } @@ -154,7 +154,7 @@ class Solution { */ canPlaceFlowers(flowerbed, n) { let empty = flowerbed[0] === 0 ? 1 : 0; - + for (let f of flowerbed) { if (f === 1) { n -= Math.floor(Math.max(0, empty - 1) / 2); @@ -163,7 +163,7 @@ class Solution { empty++; } } - + n -= Math.floor(empty / 2); return n <= 0; } @@ -174,5 +174,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/candy.md b/articles/candy.md index 82a35a481..e7675e571 100644 --- a/articles/candy.md +++ b/articles/candy.md @@ -170,8 +170,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -188,11 +188,11 @@ class Solution: for i in range(1, n): if ratings[i - 1] < ratings[i]: arr[i] = arr[i - 1] + 1 - + for i in range(n - 2, -1, -1): if ratings[i] > ratings[i + 1]: arr[i] = max(arr[i], arr[i + 1] + 1) - + return sum(arr) ``` @@ -307,8 +307,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -327,7 +327,7 @@ class Solution: if ratings[i] == ratings[i - 1]: i += 1 continue - + inc = 0 while i < n and ratings[i] > ratings[i - 1]: inc += 1 @@ -339,9 +339,9 @@ class Solution: dec += 1 res += dec i += 1 - + res -= min(inc, dec) - + return res ``` @@ -494,5 +494,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/capacity-to-ship-packages-within-d-days.md b/articles/capacity-to-ship-packages-within-d-days.md index dfc4f2146..caf60abe3 100644 --- a/articles/capacity-to-ship-packages-within-d-days.md +++ b/articles/capacity-to-ship-packages-within-d-days.md @@ -80,7 +80,8 @@ class Solution { shipWithinDays(weights, days) { let res = Math.max(...weights); while (true) { - let ships = 1, cap = res; + let ships = 1, + cap = res; for (let w of weights) { if (cap - w < 0) { ships++; @@ -124,8 +125,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -252,7 +253,8 @@ class Solution { let res = r; const canShip = (cap) => { - let ships = 1, currCap = cap; + let ships = 1, + currCap = cap; for (const w of weights) { if (currCap - w < 0) { ships++; @@ -323,5 +325,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ diff --git a/articles/car-fleet.md b/articles/car-fleet.md index 22c7a9d0f..3f863baf7 100644 --- a/articles/car-fleet.md +++ b/articles/car-fleet.md @@ -27,8 +27,8 @@ public class Solution { Stack stack = new Stack<>(); for (int[] p : pair) { stack.push((double) (target - p[0]) / p[1]); - if (stack.size() >= 2 && - stack.peek() <= stack.get(stack.size() - 2)) + if (stack.size() >= 2 && + stack.peek() <= stack.get(stack.size() - 2)) { stack.pop(); } @@ -50,8 +50,8 @@ public: vector stack; for (auto& p : pair) { stack.push_back((double)(target - p.first) / p.second); - if (stack.size() >= 2 && - stack.back() <= stack[stack.size() - 2]) + if (stack.size() >= 2 && + stack.back() <= stack[stack.size() - 2]) { stack.pop_back(); } @@ -75,9 +75,10 @@ class Solution { let stack = []; for (let [p, s] of pair) { stack.push((target - p) / s); - if (stack.length >= 2 && - stack[stack.length - 1] <= stack[stack.length - 2]) - { + if ( + stack.length >= 2 && + stack[stack.length - 1] <= stack[stack.length - 2] + ) { stack.pop(); } } @@ -113,11 +114,11 @@ func carFleet(target int, position []int, speed []int) int { for i := 0; i < n; i++ { pair[i] = [2]int{position[i], speed[i]} } - + sort.Slice(pair, func(i, j int) bool { return pair[i][0] > pair[j][0] }) - + stack := []float64{} for _, p := range pair { time := float64(target - p[0]) / float64(p[1]) @@ -126,7 +127,7 @@ func carFleet(target int, position []int, speed []int) int { stack = stack[:len(stack)-1] } } - + return len(stack) } ``` @@ -174,8 +175,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -188,7 +189,7 @@ class Solution: def carFleet(self, target: int, position: List[int], speed: List[int]) -> int: pair = [(p, s) for p, s in zip(position, speed)] pair.sort(reverse=True) - + fleets = 1 prevTime = (target - pair[0][0]) / pair[0][1] for i in range(1, len(pair)): @@ -210,7 +211,7 @@ public class Solution { pair[i][1] = speed[i]; } Arrays.sort(pair, (a, b) -> Integer.compare(b[0], a[0])); - + int fleets = 1; double prevTime = (double)(target - pair[0][0]) / pair[0][1]; for (int i = 1; i < n; i++) { @@ -235,7 +236,7 @@ public: pair.push_back({position[i], speed[i]}); } sort(pair.rbegin(), pair.rend()); - + int fleets = 1; double prevTime = (double)(target - pair[0].first) / pair[0].second; for (int i = 1; i < n; i++) { @@ -261,7 +262,7 @@ class Solution { carFleet(target, position, speed) { let pair = position.map((p, i) => [p, speed[i]]); pair.sort((a, b) => b[0] - a[0]); - + let fleets = 1; let prevTime = (target - pair[0][0]) / pair[0][1]; for (let i = 1; i < pair.length; i++) { @@ -285,7 +286,7 @@ public class Solution { pair[i] = new int[] { position[i], speed[i] }; } Array.Sort(pair, (a, b) => b[0].CompareTo(a[0])); - + int fleets = 1; double prevTime = (double)(target - pair[0][0]) / pair[0][1]; for (int i = 1; i < n; i++) { @@ -307,11 +308,11 @@ func carFleet(target int, position []int, speed []int) int { for i := 0; i < n; i++ { pair[i] = [2]int{position[i], speed[i]} } - + sort.Slice(pair, func(i, j int) bool { return pair[i][0] > pair[j][0] }) - + fleets := 1 prevTime := float64(target - pair[0][0]) / float64(pair[0][1]) for i := 1; i < n; i++ { @@ -321,7 +322,7 @@ func carFleet(target int, position []int, speed []int) int { prevTime = currTime } } - + return fleets } ``` @@ -330,7 +331,7 @@ func carFleet(target int, position []int, speed []int) int { class Solution { fun carFleet(target: Int, position: IntArray, speed: IntArray): Int { val pair = position.zip(speed).sortedByDescending { it.first } - + var fleets = 1 var prevTime = (target - pair[0].first).toDouble() / pair[0].second for (i in 1 until pair.size) { @@ -341,7 +342,7 @@ class Solution { prevTime = currTime } } - + return fleets } } @@ -375,5 +376,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ diff --git a/articles/car-pooling.md b/articles/car-pooling.md index df5745d6d..c67ff6e99 100644 --- a/articles/car-pooling.md +++ b/articles/car-pooling.md @@ -118,8 +118,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -131,20 +131,20 @@ public class Solution { class Solution: def carPooling(self, trips: List[List[int]], capacity: int) -> bool: trips.sort(key=lambda t: t[1]) - + minHeap = [] # pair of [end, numPassengers] curPass = 0 - + for numPass, start, end in trips: while minHeap and minHeap[0][0] <= start: curPass -= heapq.heappop(minHeap)[1] - + curPass += numPass if curPass > capacity: return False - + heapq.heappush(minHeap, [end, numPass]) - + return True ``` @@ -152,25 +152,25 @@ class Solution: public class Solution { public boolean carPooling(int[][] trips, int capacity) { Arrays.sort(trips, Comparator.comparingInt(a -> a[1])); - + PriorityQueue minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])); // [end, numPassengers] int curPass = 0; - + for (int[] trip : trips) { int numPass = trip[0], start = trip[1], end = trip[2]; - + while (!minHeap.isEmpty() && minHeap.peek()[0] <= start) { curPass -= minHeap.poll()[1]; } - + curPass += numPass; if (curPass > capacity) { return false; } - + minHeap.offer(new int[]{end, numPass}); } - + return true; } } @@ -218,7 +218,7 @@ class Solution { carPooling(trips, capacity) { trips.sort((a, b) => a[1] - b[1]); - const minHeap = new MinPriorityQueue(x => x[0]); // [end, numPassengers] + const minHeap = new MinPriorityQueue((x) => x[0]); // [end, numPassengers] let curPass = 0; for (const [numPass, start, end] of trips) { @@ -243,7 +243,7 @@ class Solution { public class Solution { public bool CarPooling(int[][] trips, int capacity) { Array.Sort(trips, (a, b) => a[1].CompareTo(b[1])); - + var minHeap = new PriorityQueue(); int curPass = 0; @@ -273,8 +273,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -289,14 +289,14 @@ class Solution: for passengers, start, end in trips: points.append([start, passengers]) points.append([end, -passengers]) - + points.sort() curPass = 0 for point, passengers in points: curPass += passengers if curPass > capacity: return False - + return True ``` @@ -309,9 +309,9 @@ public class Solution { points.add(new int[]{start, passengers}); points.add(new int[]{end, -passengers}); } - + points.sort((a, b) -> a[0] == b[0] ? Integer.compare(a[1], b[1]) : Integer.compare(a[0], b[0])); - + int curPass = 0; for (int[] point : points) { curPass += point[1]; @@ -319,7 +319,7 @@ public class Solution { return false; } } - + return true; } } @@ -366,9 +366,9 @@ class Solution { points.push([start, passengers]); points.push([end, -passengers]); } - - points.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]); - + + points.sort((a, b) => (a[0] === b[0] ? a[1] - b[1] : a[0] - b[0])); + let curPass = 0; for (const [point, passengers] of points) { curPass += passengers; @@ -376,7 +376,7 @@ class Solution { return false; } } - + return true; } } @@ -386,7 +386,7 @@ class Solution { public class Solution { public bool CarPooling(int[][] trips, int capacity) { List points = new List(); - + foreach (var trip in trips) { int passengers = trip[0]; int start = trip[1]; @@ -416,8 +416,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -432,19 +432,19 @@ class Solution: for _, start, end in trips: L = min(L, start) R = max(R, end) - + N = R - L + 1 passChange = [0] * (N + 1) for passengers, start, end in trips: passChange[start - L] += passengers passChange[end - L] -= passengers - + curPass = 0 for change in passChange: curPass += change if curPass > capacity: return False - + return True ``` @@ -515,7 +515,8 @@ class Solution { * @return {boolean} */ carPooling(trips, capacity) { - let L = Infinity, R = -Infinity; + let L = Infinity, + R = -Infinity; for (const [passengers, start, end] of trips) { L = Math.min(L, start); R = Math.max(R, end); @@ -579,7 +580,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n + N)$ -* Space complexity: $O(N)$ +- Time complexity: $O(n + N)$ +- Space complexity: $O(N)$ -> Where $n$ is the size of the array $trips$ and $N$ is the difference between the rightmost location and the leftmost location. \ No newline at end of file +> Where $n$ is the size of the array $trips$ and $N$ is the difference between the rightmost location and the leftmost location. diff --git a/articles/champagne-tower.md b/articles/champagne-tower.md index d2f36a28e..fa765bf91 100644 --- a/articles/champagne-tower.md +++ b/articles/champagne-tower.md @@ -8,15 +8,15 @@ class Solution: def rec(row, glass): if row < 0 or glass < 0 or glass > row: return 0 - + if row == 0 and glass == 0: return poured - + left_parent = max(0, rec(row - 1, glass - 1) - 1) right_parent = max(0, rec(row - 1, glass) - 1) - + return (left_parent + right_parent) / 2 - + return min(1, rec(query_row, query_glass)) ``` @@ -101,8 +101,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ > Where $n$ is the given $queryRow$. @@ -116,19 +116,19 @@ class Solution { class Solution: def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: memo = { (0, 0) : poured } - + def rec(row, glass): if row < 0 or glass < 0 or glass > row: return 0 if (row, glass) in memo: return memo[(row, glass)] - + left_parent = max(0, rec(row - 1, glass - 1) - 1) right_parent = max(0, rec(row - 1, glass) - 1) - + memo[(row, glass)] = (left_parent + right_parent) / 2 return memo[(row, glass)] - + return min(1, rec(query_row, query_glass)) ``` @@ -149,7 +149,7 @@ public class Solution { if (row < 0 || glass < 0 || glass > row) { return 0; } - + if (memo[row][glass] != -1) { return memo[row][glass]; } @@ -181,7 +181,7 @@ private: if (row < 0 || glass < 0 || glass > row) { return 0; } - + if (memo[row][glass] != -1) { return memo[row][glass]; } @@ -204,7 +204,9 @@ class Solution { * @return {number} */ champagneTower(poured, query_row, query_glass) { - const memo = Array.from({ length: query_row + 5 }, (_, i) => Array(i + 1).fill(-1)); + const memo = Array.from({ length: query_row + 5 }, (_, i) => + Array(i + 1).fill(-1), + ); memo[0][0] = poured; const rec = (row, glass) => { @@ -234,8 +236,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n * m)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n * m)$ > Where $n$ is the given $queryRow$ and $m$ is the given $queryGlass$. @@ -250,14 +252,14 @@ class Solution: def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: dp = [[0] * (i + 1) for i in range(query_row + 5)] dp[0][0] += poured - + for row in range(min(99, query_row + 1)): for glass in range(row + 1): excess = (dp[row][glass] - 1.0) / 2.0 if excess > 0: dp[row + 1][glass] += excess dp[row + 1][glass + 1] += excess - + return min(1.0, dp[query_row][query_glass]) ``` @@ -268,9 +270,9 @@ public class Solution { for (int i = 0; i < query_row + 5; i++) { dp[i] = new double[i + 1]; } - + dp[0][0] += poured; - + for (int row = 0; row < Math.min(99, query_row + 1); row++) { for (int glass = 0; glass <= row; glass++) { double excess = (dp[row][glass] - 1.0) / 2.0; @@ -280,7 +282,7 @@ public class Solution { } } } - + return Math.min(1.0, dp[query_row][query_glass]); } } @@ -294,9 +296,9 @@ public: for (int i = 0; i <= query_row + 4; i++) { dp[i].resize(i + 1, 0); } - + dp[0][0] += poured; - + for (int row = 0; row < min(99, query_row + 1); row++) { for (int glass = 0; glass <= row; glass++) { double excess = (dp[row][glass] - 1.0) / 2.0; @@ -306,7 +308,7 @@ public: } } } - + return min(1.0, dp[query_row][query_glass]); } }; @@ -321,7 +323,9 @@ class Solution { * @return {number} */ champagneTower(poured, query_row, query_glass) { - const dp = Array.from({ length: query_row + 5 }, (_, i) => Array(i + 1).fill(0)); + const dp = Array.from({ length: query_row + 5 }, (_, i) => + Array(i + 1).fill(0), + ); dp[0][0] += poured; for (let row = 0; row < Math.min(99, query_row + 1); row++) { @@ -343,8 +347,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n * m)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n * m)$ > Where $n$ is the given $queryRow$ and $m$ is the given $queryGlass$. @@ -375,7 +379,7 @@ class Solution: public class Solution { public double champagneTower(int poured, int query_row, int query_glass) { double[] prev_row = new double[] { poured }; // Flow - + for (int row = 1; row <= query_row; row++) { double[] cur_row = new double[row + 1]; for (int i = 0; i < row; i++) { @@ -387,7 +391,7 @@ public class Solution { } prev_row = cur_row; } - + return Math.min(1.0, prev_row[query_glass]); } } @@ -398,7 +402,7 @@ class Solution { public: double champagneTower(int poured, int query_row, int query_glass) { vector prev_row = {double(poured)}; // Flow - + for (int row = 1; row <= query_row; row++) { vector cur_row(row + 1, 0); for (int i = 0; i < row; i++) { @@ -410,7 +414,7 @@ public: } prev_row = cur_row; } - + return min(1.0, prev_row[query_glass]); } }; @@ -425,8 +429,8 @@ class Solution { * @return {number} */ champagneTower(poured, query_row, query_glass) { - let prev_row = [poured]; // Flow - + let prev_row = [poured]; // Flow + for (let row = 1; row <= query_row; row++) { let cur_row = new Array(row + 1).fill(0); for (let i = 0; i < row; i++) { @@ -438,7 +442,7 @@ class Solution { } prev_row = cur_row; } - + return Math.min(1, prev_row[query_glass]); } } @@ -448,8 +452,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n)$ > Where $n$ is the given $queryRow$ and $m$ is the given $queryGlass$. @@ -463,7 +467,7 @@ class Solution { class Solution: def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float: dp = [poured] + [0] * query_row - + for row in range(1, query_row + 1): for i in range(row - 1, -1, -1): extra = dp[i] - 1 @@ -472,7 +476,7 @@ class Solution: dp[i + 1] += 0.5 * extra else: dp[i] = 0 - + return min(1, dp[query_glass]) ``` @@ -556,7 +560,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n)$ -> Where $n$ is the given $queryRow$ and $m$ is the given $queryGlass$. \ No newline at end of file +> Where $n$ is the given $queryRow$ and $m$ is the given $queryGlass$. diff --git a/articles/cheapest-flight-path.md b/articles/cheapest-flight-path.md index 976640249..7c0b87da3 100644 --- a/articles/cheapest-flight-path.md +++ b/articles/cheapest-flight-path.md @@ -10,7 +10,7 @@ class Solution: dist = [[INF] * (k + 5) for _ in range(n)] for u, v, cst in flights: adj[u].append([v, cst]) - + dist[src][0] = 0 minHeap = [(0, src, -1)] # cost, node, stops while len(minHeap): @@ -35,12 +35,12 @@ public class Solution { List[] adj = new ArrayList[n]; int[][] dist = new int[n][k + 5]; for (int i = 0; i < n; i++) Arrays.fill(dist[i], INF); - + for (int i = 0; i < n; i++) adj[i] = new ArrayList<>(); for (int[] flight : flights) { adj[flight[0]].add(new int[]{flight[1], flight[2]}); } - + dist[src][0] = 0; PriorityQueue minHeap = new PriorityQueue<>( Comparator.comparingInt(a -> a[0]) @@ -74,16 +74,16 @@ public: int INF = 1e9; vector>> adj(n); vector> dist(n, vector(k + 5, INF)); - + for (auto& flight : flights) { adj[flight[0]].emplace_back(flight[1], flight[2]); } - + dist[src][0] = 0; - priority_queue, + priority_queue, vector>, greater<>> minHeap; minHeap.emplace(0, src, -1); - + while (!minHeap.empty()) { auto [cst, node, stops] = minHeap.top(); minHeap.pop(); @@ -116,15 +116,14 @@ class Solution { findCheapestPrice(n, flights, src, dst, k) { const INF = Infinity; const adj = Array.from({ length: n }, () => []); - const dist = Array.from({ length: n }, () => - Array(k + 5).fill(INF)); - + const dist = Array.from({ length: n }, () => Array(k + 5).fill(INF)); + for (let [u, v, cst] of flights) { adj[u].push([v, cst]); } - + dist[src][0] = 0; - const minHeap = new MinPriorityQueue(entry => entry[0]); + const minHeap = new MinPriorityQueue((entry) => entry[0]); minHeap.push([0, src, -1]); // cost, node, stops while (!minHeap.isEmpty()) { const [cst, node, stops] = minHeap.pop(); @@ -150,31 +149,31 @@ public class Solution { int INF = int.MaxValue; List[] adj = new List[n]; int[][] dist = new int[n][]; - + for (int i = 0; i < n; i++) { adj[i] = new List(); dist[i] = new int[k + 2]; Array.Fill(dist[i], INF); } - + foreach (var flight in flights) { adj[flight[0]].Add(new int[] { flight[1], flight[2] }); } - + dist[src][0] = 0; var minHeap = new PriorityQueue<(int cst, int node, int stops), int>(); minHeap.Enqueue((0, src, 0), 0); - + while (minHeap.Count > 0) { var (cst, node, stops) = minHeap.Dequeue(); if (node == dst) return cst; if (stops > k) continue; - + foreach (var neighbor in adj[node]) { int nei = neighbor[0], w = neighbor[1]; int nextCst = cst + w; int nextStops = stops + 1; - + if (dist[nei][nextStops] > nextCst) { dist[nei][nextStops] = nextCst; minHeap.Enqueue((nextCst, nei, nextStops), nextCst); @@ -309,8 +308,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O((n + m) * k)$ -* Space complexity: $O(n * k)$ +- Time complexity: $O((n + m) * k)$ +- Space complexity: $O(n * k)$ > Where $n$ is the number of cities, $m$ is the number of flights and $k$ is the number of stops. @@ -476,7 +475,7 @@ func findCheapestPrice(n int, flights [][]int, src int, dst int, k int) int { for i := 0; i <= k; i++ { tmpPrices := make([]int, n) copy(tmpPrices, prices) - + for _, flight := range flights { s, d, p := flight[0], flight[1], flight[2] if prices[s] == math.MaxInt32 { @@ -488,7 +487,7 @@ func findCheapestPrice(n int, flights [][]int, src int, dst int, k int) int { } prices = tmpPrices } - + if prices[dst] == math.MaxInt32 { return -1 } @@ -547,8 +546,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + (m * k))$ -* Space complexity: $O(n)$ +- Time complexity: $O(n + (m * k))$ +- Space complexity: $O(n)$ > Where $n$ is the number of cities, $m$ is the number of flights and $k$ is the number of stops. @@ -572,7 +571,7 @@ class Solution: cst, node, stops = q.popleft() if stops > k: continue - + for nei, w in adj[node]: nextCost = cst + w if nextCost < prices[nei]: @@ -665,7 +664,7 @@ class Solution { const prices = Array(n).fill(Infinity); prices[src] = 0; const adj = Array.from({ length: n }, () => []); - + for (const [u, v, cst] of flights) { adj[u].push([v, cst]); } @@ -838,7 +837,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * k)$ -* Space complexity: $O(n + m)$ +- Time complexity: $O(n * k)$ +- Space complexity: $O(n + m)$ -> Where $n$ is the number of cities, $m$ is the number of flights and $k$ is the number of stops. \ No newline at end of file +> Where $n$ is the number of cities, $m$ is the number of flights and $k$ is the number of stops. diff --git a/articles/check-completeness-of-a-binary-tree.md b/articles/check-completeness-of-a-binary-tree.md index 90a185822..86acd8fd4 100644 --- a/articles/check-completeness-of-a-binary-tree.md +++ b/articles/check-completeness-of-a-binary-tree.md @@ -142,8 +142,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -285,12 +285,12 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- -## 3. Depth First Search (Two Pass) +## 3. Depth First Search (Two Pass) ::tabs-start @@ -308,11 +308,11 @@ class Solution: return True if index >= n: return False - + left = dfs(node.left, 2 * index + 1, n) right = dfs(node.right, 2 * index + 2, n) return left and right - + def countNodes(node): if not node: return 0 @@ -414,7 +414,10 @@ class Solution { const dfs = (node, index, n) => { if (!node) return true; if (index >= n) return false; - return dfs(node.left, 2 * index + 1, n) && dfs(node.right, 2 * index + 2, n); + return ( + dfs(node.left, 2 * index + 1, n) && + dfs(node.right, 2 * index + 2, n) + ); }; const n = countNodes(root); @@ -427,8 +430,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -447,7 +450,7 @@ class Solution: def isCompleteTree(self, root: Optional[TreeNode]) -> bool: treeHgt = 0 nullSeen = False - + def dfs(node, hgt): nonlocal treeHgt, nullSeen if not node: @@ -458,9 +461,9 @@ class Solution: elif hgt != treeHgt: return False return not (hgt == treeHgt and nullSeen) - + return dfs(node.left, hgt + 1) and dfs(node.right, hgt + 1) - + return dfs(root, 0) ``` @@ -587,5 +590,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. diff --git a/articles/check-if-a-string-contains-all-binary-codes-of-size-k.md b/articles/check-if-a-string-contains-all-binary-codes-of-size-k.md index 917412238..fc0354181 100644 --- a/articles/check-if-a-string-contains-all-binary-codes-of-size-k.md +++ b/articles/check-if-a-string-contains-all-binary-codes-of-size-k.md @@ -67,11 +67,11 @@ class Solution { */ hasAllCodes(s, k) { const n = s.length; - if (n < (1 << k)) { + if (n < 1 << k) { return false; } - for (let num = 0; num < (1 << k); num++) { + for (let num = 0; num < 1 << k; num++) { const binaryCode = num.toString(2).padStart(k, '0'); if (!s.includes(binaryCode)) { return false; @@ -87,8 +87,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 2 ^ k)$ -* Space complexity: $O(k)$ +- Time complexity: $O(n * 2 ^ k)$ +- Space complexity: $O(k)$ > Where $n$ is the length of the string $s$ and $k$ is the length of the binary code. @@ -103,11 +103,11 @@ class Solution: def hasAllCodes(self, s: str, k: int) -> bool: if len(s) < 2 ** k: return False - + codeSet = set() for i in range(len(s) - k + 1): codeSet.add(s[i:i + k]) - + return len(codeSet) == 2 ** k ``` @@ -117,12 +117,12 @@ public class Solution { if (s.length() < (1 << k)) { return false; } - + HashSet codeSet = new HashSet<>(); for (int i = 0; i <= s.length() - k; i++) { codeSet.add(s.substring(i, i + k)); } - + return codeSet.size() == (1 << k); } } @@ -135,12 +135,12 @@ public: if (s.size() < (1 << k)) { return false; } - + std::unordered_set codeSet; for (int i = 0; i <= s.size() - k; i++) { codeSet.insert(s.substr(i, k)); } - + return codeSet.size() == (1 << k); } }; @@ -154,16 +154,16 @@ class Solution { * @return {boolean} */ hasAllCodes(s, k) { - if (s.length < (1 << k)) { + if (s.length < 1 << k) { return false; } - + const codeSet = new Set(); for (let i = 0; i <= s.length - k; i++) { codeSet.add(s.substring(i, i + k)); } - - return codeSet.size === (1 << k); + + return codeSet.size === 1 << k; } } ``` @@ -172,8 +172,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * k)$ -* Space complexity: $O(2 ^ k)$ +- Time complexity: $O(n * k)$ +- Space complexity: $O(2 ^ k)$ > Where $n$ is the length of the string $s$ and $k$ is the length of the binary code. @@ -189,7 +189,7 @@ class Solution: n = len(s) if n < (1 << k): return False - + codeSet = [False] * (1 << k) cur = 0 i = j = 0 @@ -199,7 +199,7 @@ class Solution: cur |= (1 << bit) bit -= 1 j += 1 - + have = 1 codeSet[cur] = True while j < n: @@ -215,7 +215,7 @@ class Solution: if not codeSet[cur]: have += 1 codeSet[cur] = True - + return have == (1 << k) ``` @@ -321,17 +321,19 @@ class Solution { */ hasAllCodes(s, k) { const n = s.length; - if (n < (1 << k)) { + if (n < 1 << k) { return false; } const codeSet = new Array(1 << k).fill(false); let cur = 0; - let i = 0, j = 0, bit = k - 1; + let i = 0, + j = 0, + bit = k - 1; while (j < k) { if (s[j] === '1') { - cur |= (1 << bit); + cur |= 1 << bit; } bit--; j++; @@ -342,7 +344,7 @@ class Solution { while (j < n) { if (s[i] === '1') { - cur ^= (1 << (k - 1)); + cur ^= 1 << (k - 1); } i++; @@ -358,7 +360,7 @@ class Solution { } } - return have === (1 << k); + return have === 1 << k; } } ``` @@ -367,8 +369,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(2 ^ k)$ +- Time complexity: $O(n)$ +- Space complexity: $O(2 ^ k)$ > Where $n$ is the length of the string $s$ and $k$ is the length of the binary code. @@ -384,11 +386,11 @@ class Solution: n = len(s) if n < (1 << k): return False - + codeSet = [False] * (1 << k) cur = 0 have = 0 - + for i in range(n): cur = ((cur << 1) & ((1 << k) - 1)) | (ord(s[i]) - ord('0')) @@ -396,7 +398,7 @@ class Solution: if not codeSet[cur]: codeSet[cur] = True have += 1 - + return have == (1 << k) ``` @@ -464,12 +466,13 @@ class Solution { */ hasAllCodes(s, k) { const n = s.length; - if (n < (1 << k)) { + if (n < 1 << k) { return false; } const codeSet = new Array(1 << k).fill(false); - let cur = 0, have = 0; + let cur = 0, + have = 0; for (let i = 0; i < n; i++) { cur = ((cur << 1) & ((1 << k) - 1)) | (s[i] - '0'); @@ -482,7 +485,7 @@ class Solution { } } - return have === (1 << k); + return have === 1 << k; } } ``` @@ -491,7 +494,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(2 ^ k)$ +- Time complexity: $O(n)$ +- Space complexity: $O(2 ^ k)$ -> Where $n$ is the length of the string $s$ and $k$ is the length of the binary code. \ No newline at end of file +> Where $n$ is the length of the string $s$ and $k$ is the length of the binary code. diff --git a/articles/check-if-array-is-sorted-and-rotated.md b/articles/check-if-array-is-sorted-and-rotated.md index 061da0d48..0b258f9ea 100644 --- a/articles/check-if-array-is-sorted-and-rotated.md +++ b/articles/check-if-array-is-sorted-and-rotated.md @@ -121,8 +121,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -222,8 +222,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -285,7 +285,8 @@ class Solution { * @return {boolean} */ check(nums) { - let count = 0, N = nums.length; + let count = 0, + N = nums.length; for (let i = 0; i < N; i++) { if (nums[i] > nums[(i + 1) % N] && ++count > 1) { @@ -302,5 +303,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/check-if-move-is-legal.md b/articles/check-if-move-is-legal.md index acc1d8b66..c1263c780 100644 --- a/articles/check-if-move-is-legal.md +++ b/articles/check-if-move-is-legal.md @@ -6,7 +6,7 @@ class Solution: def checkMove(self, board: List[List[str]], rMove: int, cMove: int, color: str) -> bool: ROWS, COLS = len(board), len(board[0]) - direction = [[1, 0], [-1, 0], [0, 1], [0, -1], + direction = [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [-1, -1], [1, -1], [-1, 1]] board[rMove][cMove] = color @@ -35,7 +35,7 @@ class Solution: public class Solution { public boolean checkMove(char[][] board, int rMove, int cMove, char color) { int ROWS = board.length, COLS = board[0].length; - int[][] direction = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}, + int[][] direction = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {-1, -1}, {1, -1}, {-1, 1}}; board[rMove][cMove] = color; @@ -76,7 +76,7 @@ class Solution { public: bool checkMove(vector>& board, int rMove, int cMove, char color) { int ROWS = board.size(), COLS = board[0].size(); - vector> direction = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}, + vector> direction = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {-1, -1}, {1, -1}, {-1, 1}}; board[rMove][cMove] = color; @@ -123,9 +123,18 @@ class Solution { * @return {boolean} */ checkMove(board, rMove, cMove, color) { - const ROWS = board.length, COLS = board[0].length; - const direction = [[1, 0], [-1, 0], [0, 1], [0, -1], - [1, 1], [-1, -1], [1, -1], [-1, 1]]; + const ROWS = board.length, + COLS = board[0].length; + const direction = [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + [1, 1], + [-1, -1], + [1, -1], + [-1, 1], + ]; board[rMove][cMove] = color; @@ -136,7 +145,7 @@ class Solution { while (row >= 0 && row < ROWS && col >= 0 && col < COLS) { length++; - if (board[row][col] === ".") { + if (board[row][col] === '.') { return false; } if (board[row][col] === color) { @@ -162,8 +171,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ --- @@ -265,22 +274,29 @@ class Solution { * @return {boolean} */ checkMove(board, rMove, cMove, color) { - const ROWS = board.length, COLS = board[0].length; + const ROWS = board.length, + COLS = board[0].length; const direction = [0, 1, 0, -1, 0, 1, 1, -1, -1, 1]; board[rMove][cMove] = color; for (let d = 0; d < 9; d++) { - let row = rMove, col = cMove; + let row = rMove, + col = cMove; for (let length = 1; ; ++length) { row += direction[d]; col += direction[d + 1]; - if (row < 0 || col < 0 || row >= ROWS || col >= COLS || board[row][col] === '.') + if ( + row < 0 || + col < 0 || + row >= ROWS || + col >= COLS || + board[row][col] === '.' + ) break; if (board[row][col] === color) { - if (length > 1) - return true; + if (length > 1) return true; break; } } @@ -294,5 +310,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ diff --git a/articles/check-if-there-is-a-valid-partition-for-the-array.md b/articles/check-if-there-is-a-valid-partition-for-the-array.md index e855fd84d..fca7ab21e 100644 --- a/articles/check-if-there-is-a-valid-partition-for-the-array.md +++ b/articles/check-if-there-is-a-valid-partition-for-the-array.md @@ -8,17 +8,17 @@ class Solution: def dfs(i): if i == len(nums): return True - + res = False if i < len(nums) - 1 and nums[i] == nums[i + 1]: res = dfs(i + 2) if i < len(nums) - 2: - if ((nums[i] == nums[i + 1] == nums[i + 2]) or + if ((nums[i] == nums[i + 1] == nums[i + 2]) or (nums[i] + 1 == nums[i + 1] and nums[i + 1] + 1 == nums[i + 2]) ): res = res or dfs(i + 3) return res - + return dfs(0) ``` @@ -27,16 +27,16 @@ public class Solution { public boolean validPartition(int[] nums) { return dfs(nums, 0); } - + private boolean dfs(int[] nums, int i) { if (i == nums.length) return true; - + boolean res = false; if (i < nums.length - 1 && nums[i] == nums[i + 1]) { res = dfs(nums, i + 2); } if (i < nums.length - 2) { - if ((nums[i] == nums[i + 1] && nums[i + 1] == nums[i + 2]) || + if ((nums[i] == nums[i + 1] && nums[i + 1] == nums[i + 2]) || (nums[i] + 1 == nums[i + 1] && nums[i + 1] + 1 == nums[i + 2])) { res = res || dfs(nums, i + 3); } @@ -62,7 +62,7 @@ private: res = dfs(nums, i + 2); } if (i < nums.size() - 2) { - if ((nums[i] == nums[i + 1] && nums[i + 1] == nums[i + 2]) || + if ((nums[i] == nums[i + 1] && nums[i + 1] == nums[i + 2]) || (nums[i] + 1 == nums[i + 1] && nums[i + 1] + 1 == nums[i + 2])) { res = res || dfs(nums, i + 3); } @@ -87,8 +87,11 @@ class Solution { res = dfs(i + 2); } if (i < nums.length - 2) { - if ((nums[i] === nums[i + 1] && nums[i + 1] === nums[i + 2]) || - (nums[i] + 1 === nums[i + 1] && nums[i + 1] + 1 === nums[i + 2])) { + if ( + (nums[i] === nums[i + 1] && nums[i + 1] === nums[i + 2]) || + (nums[i] + 1 === nums[i + 1] && + nums[i + 1] + 1 === nums[i + 2]) + ) { res = res || dfs(i + 3); } } @@ -104,8 +107,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ --- @@ -120,19 +123,19 @@ class Solution: def dfs(i): if i in dp: return dp[i] - + res = False if i < len(nums) - 1 and nums[i] == nums[i + 1]: res = dfs(i + 2) if i < len(nums) - 2: - if ((nums[i] == nums[i + 1] == nums[i + 2]) or + if ((nums[i] == nums[i + 1] == nums[i + 2]) or (nums[i] + 1 == nums[i + 1] and nums[i + 1] + 1 == nums[i + 2]) ): res = res or dfs(i + 3) - + dp[i] = res return res - + return dfs(0) ``` @@ -143,22 +146,22 @@ public class Solution { public boolean validPartition(int[] nums) { return dfs(nums, 0); } - + private boolean dfs(int[] nums, int i) { if (i == nums.length) return true; if (memo.containsKey(i)) return memo.get(i); - + boolean res = false; if (i < nums.length - 1 && nums[i] == nums[i + 1]) { res = dfs(nums, i + 2); } if (i < nums.length - 2) { - if ((nums[i] == nums[i + 1] && nums[i + 1] == nums[i + 2]) || + if ((nums[i] == nums[i + 1] && nums[i + 1] == nums[i + 2]) || (nums[i] + 1 == nums[i + 1] && nums[i + 1] + 1 == nums[i + 2])) { res = res || dfs(nums, i + 3); } } - + memo.put(i, res); return res; } @@ -184,7 +187,7 @@ private: res = dfs(nums, i + 2); } if (i < nums.size() - 2) { - if ((nums[i] == nums[i + 1] && nums[i + 1] == nums[i + 2]) || + if ((nums[i] == nums[i + 1] && nums[i + 1] == nums[i + 2]) || (nums[i] + 1 == nums[i + 1] && nums[i + 1] + 1 == nums[i + 2])) { res = res || dfs(nums, i + 3); } @@ -213,8 +216,11 @@ class Solution { res = dfs(i + 2); } if (i < nums.length - 2) { - if ((nums[i] === nums[i + 1] && nums[i + 1] === nums[i + 2]) || - (nums[i] + 1 === nums[i + 1] && nums[i + 1] + 1 === nums[i + 2])) { + if ( + (nums[i] === nums[i + 1] && nums[i + 1] === nums[i + 2]) || + (nums[i] + 1 === nums[i + 1] && + nums[i + 1] + 1 === nums[i + 2]) + ) { res = res || dfs(i + 3); } } @@ -232,8 +238,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -250,7 +256,7 @@ class Solution: for i in range(2, len(nums) + 1): if nums[i - 1] == nums[i - 2]: dp[i] = dp[i] or dp[i - 2] - if i > 2 and ((nums[i - 1] == nums[i - 2] == nums[i - 3]) or + if i > 2 and ((nums[i - 1] == nums[i - 2] == nums[i - 3]) or (nums[i - 3] + 1 == nums[i - 2] and nums[i - 2] + 1 == nums[i - 1])): dp[i] = dp[i] or dp[i - 3] @@ -314,8 +320,12 @@ class Solution { if (nums[i - 1] === nums[i - 2]) { dp[i] = dp[i] || dp[i - 2]; } - if (i > 2 && ((nums[i - 1] === nums[i - 2] && nums[i - 2] === nums[i - 3]) || - (nums[i - 3] + 1 === nums[i - 2] && nums[i - 2] + 1 === nums[i - 1]))) { + if ( + i > 2 && + ((nums[i - 1] === nums[i - 2] && nums[i - 2] === nums[i - 3]) || + (nums[i - 3] + 1 === nums[i - 2] && + nums[i - 2] + 1 === nums[i - 1])) + ) { dp[i] = dp[i] || dp[i - 3]; } } @@ -329,8 +339,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -348,7 +358,7 @@ class Solution: if nums[i] == nums[i + 1] and dp[1]: dp[0] = True elif i < len(nums) - 2 and dp[2] and ( - (nums[i] == nums[i + 1] == nums[i + 2]) or + (nums[i] == nums[i + 1] == nums[i + 2]) or (nums[i] + 1 == nums[i + 1] and nums[i + 1] == nums[i + 2] - 1) ): dp[0] = True @@ -372,8 +382,8 @@ public class Solution { boolean dp1 = dp[0]; if (nums[i] == nums[i + 1] && dp[1]) { dp[0] = true; - } else if (i < nums.length - 2 && dp[2] && - ((nums[i] == nums[i + 1] && nums[i] == nums[i + 2]) || + } else if (i < nums.length - 2 && dp[2] && + ((nums[i] == nums[i + 1] && nums[i] == nums[i + 2]) || (nums[i] + 1 == nums[i + 1] && nums[i + 1] == nums[i + 2] - 1))) { dp[0] = true; } else { @@ -382,7 +392,7 @@ public class Solution { dp[2] = dp[1]; dp[1] = dp1; } - + return dp[0]; } } @@ -398,8 +408,8 @@ public: bool dp1 = dp[0]; if (nums[i] == nums[i + 1] && dp[1]) { dp[0] = true; - } else if (i < nums.size() - 2 && dp[2] && - ((nums[i] == nums[i + 1] && nums[i] == nums[i + 2]) || + } else if (i < nums.size() - 2 && dp[2] && + ((nums[i] == nums[i + 1] && nums[i] == nums[i + 2]) || (nums[i] + 1 == nums[i + 1] && nums[i + 1] == nums[i + 2] - 1))) { dp[0] = true; } else { @@ -427,9 +437,13 @@ class Solution { let dp1 = dp[0]; if (nums[i] === nums[i + 1] && dp[1]) { dp[0] = true; - } else if (i < nums.length - 2 && dp[2] && - ((nums[i] === nums[i + 1] && nums[i] === nums[i + 2]) || - (nums[i] + 1 === nums[i + 1] && nums[i + 1] === nums[i + 2] - 1))) { + } else if ( + i < nums.length - 2 && + dp[2] && + ((nums[i] === nums[i + 1] && nums[i] === nums[i + 2]) || + (nums[i] + 1 === nums[i + 1] && + nums[i + 1] === nums[i + 2] - 1)) + ) { dp[0] = true; } else { dp[0] = false; @@ -447,5 +461,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/check-if-two-string-arrays-are-equivalent.md b/articles/check-if-two-string-arrays-are-equivalent.md index 39805de58..ed6ece7b1 100644 --- a/articles/check-if-two-string-arrays-are-equivalent.md +++ b/articles/check-if-two-string-arrays-are-equivalent.md @@ -35,7 +35,7 @@ class Solution { * @return {boolean} */ arrayStringsAreEqual(word1, word2) { - return word1.join("") === word2.join(""); + return word1.join('') === word2.join(''); } } ``` @@ -44,8 +44,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n + m)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(n + m)$ > Where $n$ and $m$ are the total number of characters in both the arrays $word1$ and $word2$, respectively. @@ -117,7 +117,7 @@ class Solution { * @return {boolean} */ arrayStringsAreEqual(word1, word2) { - let s1 = word1.join(""); + let s1 = word1.join(''); let i = 0; for (let w of word2) { @@ -137,8 +137,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(n)$ > Where $n$ and $m$ are the total number of characters in both the arrays $word1$ and $word2$, respectively. @@ -235,8 +235,10 @@ class Solution { * @return {boolean} */ arrayStringsAreEqual(word1, word2) { - let w1 = 0, w2 = 0; // Index of word - let i = 0, j = 0; // Index of character + let w1 = 0, + w2 = 0; // Index of word + let i = 0, + j = 0; // Index of character while (w1 < word1.length && w2 < word2.length) { if (word1[w1][i] !== word2[w2][j]) { @@ -264,7 +266,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n + m)$ +- Space complexity: $O(1)$ extra space. -> Where $n$ and $m$ are the total number of characters in both the arrays $word1$ and $word2$, respectively. \ No newline at end of file +> Where $n$ and $m$ are the total number of characters in both the arrays $word1$ and $word2$, respectively. diff --git a/articles/cherry-pickup-ii.md b/articles/cherry-pickup-ii.md index cc5ccc3da..7dc14324b 100644 --- a/articles/cherry-pickup-ii.md +++ b/articles/cherry-pickup-ii.md @@ -12,14 +12,14 @@ class Solution: return 0 if r == ROWS - 1: return grid[r][c1] + (grid[r][c2] if c1 != c2 else 0) - + res = 0 for c1_d in [-1, 0, 1]: for c2_d in [-1, 0, 1]: res = max(res, dfs(r + 1, c1 + c1_d, c2 + c2_d)) - + return res + grid[r][c1] + (grid[r][c2] if c1 != c2 else 0) - + return dfs(0, 0, COLS - 1) ``` @@ -85,10 +85,12 @@ class Solution { * @return {number} */ cherryPickup(grid) { - const ROWS = grid.length, COLS = grid[0].length; + const ROWS = grid.length, + COLS = grid[0].length; const dfs = (r, c1, c2) => { - if (c1 < 0 || c2 < 0 || c1 >= COLS || c2 >= COLS || c1 > c2) return 0; + if (c1 < 0 || c2 < 0 || c1 >= COLS || c2 >= COLS || c1 > c2) + return 0; if (r === ROWS - 1) { return grid[r][c1] + (c1 === c2 ? 0 : grid[r][c2]); } @@ -111,8 +113,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * 9 ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(m * 9 ^ n)$ +- Space complexity: $O(n)$ for recursion stack. > Where $n$ is the number of rows and $m$ is the number of columns in the grid. @@ -135,15 +137,15 @@ class Solution: return 0 if r == ROWS - 1: return grid[r][c1] + grid[r][c2] - + res = 0 for c1_d in [-1, 0, 1]: for c2_d in [-1, 0, 1]: res = max(res, dfs(r + 1, c1 + c1_d, c2 + c2_d)) - + cache[(r, c1, c2)] = res + grid[r][c1] + (grid[r][c2] if c1 != c2 else 0) return cache[(r, c1, c2)] - + return dfs(0, 0, COLS - 1) ``` @@ -225,11 +227,10 @@ class Solution { * @return {number} */ cherryPickup(grid) { - const ROWS = grid.length, COLS = grid[0].length; + const ROWS = grid.length, + COLS = grid[0].length; const cache = Array.from({ length: ROWS }, () => - Array.from({ length: COLS }, () => - Array(COLS).fill(-1) - ) + Array.from({ length: COLS }, () => Array(COLS).fill(-1)), ); const dfs = (r, c1, c2) => { @@ -238,7 +239,8 @@ class Solution { } if (cache[r][c1][c2] !== -1) return cache[r][c1][c2]; if (r === ROWS - 1) { - return cache[r][c1][c2] = grid[r][c1] + (c1 === c2 ? 0 : grid[r][c2]); + return (cache[r][c1][c2] = + grid[r][c1] + (c1 === c2 ? 0 : grid[r][c2])); } let res = 0; @@ -247,7 +249,8 @@ class Solution { res = Math.max(res, dfs(r + 1, c1 + c1_d, c2 + c2_d)); } } - return cache[r][c1][c2] = res + grid[r][c1] + (c1 === c2 ? 0 : grid[r][c2]); + return (cache[r][c1][c2] = + res + grid[r][c1] + (c1 === c2 ? 0 : grid[r][c2])); }; return dfs(0, 0, COLS - 1); @@ -259,8 +262,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m ^ 2)$ -* Space complexity: $O(n * m ^ 2)$ +- Time complexity: $O(n * m ^ 2)$ +- Space complexity: $O(n * m ^ 2)$ > Where $n$ is the number of rows and $m$ is the number of columns in the grid. @@ -379,9 +382,10 @@ class Solution { * @return {number} */ cherryPickup(grid) { - const ROWS = grid.length, COLS = grid[0].length; + const ROWS = grid.length, + COLS = grid[0].length; const dp = Array.from({ length: ROWS }, () => - Array.from({ length: COLS }, () => Array(COLS).fill(0)) + Array.from({ length: COLS }, () => Array(COLS).fill(0)), ); for (let r = ROWS - 1; r >= 0; r--) { @@ -396,9 +400,18 @@ class Solution { let maxCherries = 0; for (let d1 = -1; d1 <= 1; d1++) { for (let d2 = -1; d2 <= 1; d2++) { - const nc1 = c1 + d1, nc2 = c2 + d2; - if (nc1 >= 0 && nc1 < COLS && nc2 >= 0 && nc2 < COLS) { - maxCherries = Math.max(maxCherries, dp[r + 1][nc1][nc2]); + const nc1 = c1 + d1, + nc2 = c2 + d2; + if ( + nc1 >= 0 && + nc1 < COLS && + nc2 >= 0 && + nc2 < COLS + ) { + maxCherries = Math.max( + maxCherries, + dp[r + 1][nc1][nc2], + ); } } } @@ -419,8 +432,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m ^ 2)$ -* Space complexity: $O(n * m ^ 2)$ +- Time complexity: $O(n * m ^ 2)$ +- Space complexity: $O(n * m ^ 2)$ > Where $n$ is the number of rows and $m$ is the number of columns in the grid. @@ -521,20 +534,33 @@ class Solution { * @return {number} */ cherryPickup(grid) { - const ROWS = grid.length, COLS = grid[0].length; + const ROWS = grid.length, + COLS = grid[0].length; let dp = Array.from({ length: COLS }, () => Array(COLS).fill(0)); for (let r = ROWS - 1; r >= 0; r--) { - const cur_dp = Array.from({ length: COLS }, () => Array(COLS).fill(0)); + const cur_dp = Array.from({ length: COLS }, () => + Array(COLS).fill(0), + ); for (let c1 = 0; c1 < COLS; c1++) { for (let c2 = c1; c2 < COLS; c2++) { let maxCherries = 0; - const cherries = grid[r][c1] + (c1 === c2 ? 0 : grid[r][c2]); + const cherries = + grid[r][c1] + (c1 === c2 ? 0 : grid[r][c2]); for (let d1 = -1; d1 <= 1; d1++) { for (let d2 = -1; d2 <= 1; d2++) { - const nc1 = c1 + d1, nc2 = c2 + d2; - if (nc1 >= 0 && nc1 < COLS && nc2 >= 0 && nc2 < COLS) { - maxCherries = Math.max(maxCherries, cherries + dp[nc1][nc2]); + const nc1 = c1 + d1, + nc2 = c2 + d2; + if ( + nc1 >= 0 && + nc1 < COLS && + nc2 >= 0 && + nc2 < COLS + ) { + maxCherries = Math.max( + maxCherries, + cherries + dp[nc1][nc2], + ); } } } @@ -553,7 +579,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m ^ 2)$ -* Space complexity: $O(m ^ 2)$ +- Time complexity: $O(n * m ^ 2)$ +- Space complexity: $O(m ^ 2)$ -> Where $n$ is the number of rows and $m$ is the number of columns in the grid. \ No newline at end of file +> Where $n$ is the number of rows and $m$ is the number of columns in the grid. diff --git a/articles/circular-sentence.md b/articles/circular-sentence.md index c4e969dc1..f71c4dfc4 100644 --- a/articles/circular-sentence.md +++ b/articles/circular-sentence.md @@ -65,7 +65,7 @@ class Solution { * @return {boolean} */ isCircularSentence(sentence) { - const w = sentence.split(" "); + const w = sentence.split(' '); for (let i = 0; i < w.length; i++) { const start = w[i][0]; @@ -84,8 +84,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -150,5 +150,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/climbing-stairs.md b/articles/climbing-stairs.md index 126511582..2c4ca3de7 100644 --- a/articles/climbing-stairs.md +++ b/articles/climbing-stairs.md @@ -5,19 +5,19 @@ ```python class Solution: def climbStairs(self, n: int) -> int: - + def dfs(i): if i >= n: return i == n return dfs(i + 1) + dfs(i + 2) - + return dfs(0) ``` ```java public class Solution { public int climbStairs(int n) { - return dfs(n, 0); + return dfs(n, 0); } public int dfs(int n, int i) { @@ -48,11 +48,10 @@ class Solution { * @return {number} */ climbStairs(n) { - const dfs = (i) => { if (i >= n) return i == n; return dfs(i + 1) + dfs(i + 2); - } + }; return dfs(0); } } @@ -60,7 +59,7 @@ class Solution { ```csharp public class Solution { - public int ClimbStairs(int n) { + public int ClimbStairs(int n) { return Dfs(n, 0); } @@ -118,8 +117,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ --- @@ -138,7 +137,7 @@ class Solution: return cache[i] cache[i] = dfs(i + 1) + dfs(i + 2) return cache[i] - + return dfs(0) ``` @@ -150,7 +149,7 @@ public class Solution { for (int i = 0; i < n; i++) { cache[i] = -1; } - return dfs(n, 0); + return dfs(n, 0); } public int dfs(int n, int i) { @@ -189,8 +188,8 @@ class Solution { const dfs = (i) => { if (i >= n) return i == n; if (cache[i] != -1) return cache[i]; - return cache[i] = dfs(i + 1) + dfs(i + 2); - } + return (cache[i] = dfs(i + 1) + dfs(i + 2)); + }; return dfs(0); } } @@ -199,11 +198,11 @@ class Solution { ```csharp public class Solution { int[] cache; - public int ClimbStairs(int n) { + public int ClimbStairs(int n) { cache = new int[n]; for (int i = 0; i < n; i++) { cache[i] = -1; - } + } return Dfs(n, 0); } @@ -259,7 +258,7 @@ class Solution { class Solution { func climbStairs(_ n: Int) -> Int { var cache = Array(repeating: -1, count: n) - + func dfs(_ i: Int) -> Int { if i >= n { return i == n ? 1 : 0 @@ -270,7 +269,7 @@ class Solution { cache[i] = dfs(i + 1) + dfs(i + 2) return cache[i] } - + return dfs(0) } } @@ -280,8 +279,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -425,8 +424,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -443,7 +442,7 @@ class Solution: temp = one one = one + two two = temp - + return one ``` @@ -451,13 +450,13 @@ class Solution: public class Solution { public int climbStairs(int n) { int one = 1, two = 1; - + for (int i = 0; i < n - 1; i++) { int temp = one; one = one + two; two = temp; } - + return one; } } @@ -468,13 +467,13 @@ class Solution { public: int climbStairs(int n) { int one = 1, two = 1; - + for (int i = 0; i < n - 1; i++) { int temp = one; one = one + two; two = temp; } - + return one; } }; @@ -487,14 +486,15 @@ class Solution { * @return {number} */ climbStairs(n) { - let one = 1, two = 1; - + let one = 1, + two = 1; + for (let i = 0; i < n - 1; i++) { let temp = one; one = one + two; two = temp; } - + return one; } } @@ -504,13 +504,13 @@ class Solution { public class Solution { public int ClimbStairs(int n) { int one = 1, two = 1; - + for (int i = 0; i < n - 1; i++) { int temp = one; one = one + two; two = temp; } - + return one; } } @@ -558,7 +558,7 @@ class Solution { one = one + two two = temp } - + return one } } @@ -568,8 +568,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -584,13 +584,13 @@ class Solution: return 1 def matrix_mult(A, B): - return [[A[0][0] * B[0][0] + A[0][1] * B[1][0], + return [[A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0][0] * B[0][1] + A[0][1] * B[1][1]], - [A[1][0] * B[0][0] + A[1][1] * B[1][0], + [A[1][0] * B[0][0] + A[1][1] * B[1][0], A[1][0] * B[0][1] + A[1][1] * B[1][1]]] def matrix_pow(M, p): - result = [[1, 0], [0, 1]] + result = [[1, 0], [0, 1]] base = M while p: @@ -627,7 +627,7 @@ public class Solution { } private int[][] matrixPow(int[][] M, int p) { - int[][] result = {{1, 0}, {0, 1}}; + int[][] result = {{1, 0}, {0, 1}}; int[][] base = M; while (p > 0) { @@ -648,13 +648,13 @@ class Solution { public: int climbStairs(int n) { if (n == 1) return 1; - + vector> M = {{1, 1}, {1, 0}}; vector> result = matrixPow(M, n); return result[0][0]; } - + private: vector> matrixMult(vector>& A, vector>& B) { return {{A[0][0] * B[0][0] + A[0][1] * B[1][0], @@ -664,7 +664,7 @@ private: } vector> matrixPow(vector>& M, int p) { - vector> result = {{1, 0}, {0, 1}}; + vector> result = {{1, 0}, {0, 1}}; vector> base = M; while (p > 0) { @@ -691,15 +691,22 @@ class Solution { const matrixMult = (A, B) => { return [ - [A[0][0] * B[0][0] + A[0][1] * B[1][0], - A[0][0] * B[0][1] + A[0][1] * B[1][1]], - [A[1][0] * B[0][0] + A[1][1] * B[1][0], - A[1][0] * B[0][1] + A[1][1] * B[1][1]] + [ + A[0][0] * B[0][0] + A[0][1] * B[1][0], + A[0][0] * B[0][1] + A[0][1] * B[1][1], + ], + [ + A[1][0] * B[0][0] + A[1][1] * B[1][0], + A[1][0] * B[0][1] + A[1][1] * B[1][1], + ], ]; }; const matrixPow = (M, p) => { - let result = [[1, 0], [0, 1]]; + let result = [ + [1, 0], + [0, 1], + ]; let base = M; while (p > 0) { @@ -713,7 +720,10 @@ class Solution { return result; }; - const M = [[1, 1], [1, 0]]; + const M = [ + [1, 1], + [1, 0], + ]; const result = matrixPow(M, n); return result[0][0]; @@ -742,7 +752,7 @@ public class Solution { } private int[,] MatrixPow(int[,] M, int p) { - int[,] result = new int[,] {{1, 0}, {0, 1}}; + int[,] result = new int[,] {{1, 0}, {0, 1}}; int[,] baseM = M; while (p > 0) { @@ -763,18 +773,18 @@ func climbStairs(n int) int { if n == 1 { return 1 } - + M := [][]int{{1, 1}, {1, 0}} result := matrixPow(M, n) - + return result[0][0] } func matrixMult(A, B [][]int) [][]int { return [][]int{ - {A[0][0]*B[0][0] + A[0][1]*B[1][0], + {A[0][0]*B[0][0] + A[0][1]*B[1][0], A[0][0]*B[0][1] + A[0][1]*B[1][1]}, - {A[1][0]*B[0][0] + A[1][1]*B[1][0], + {A[1][0]*B[0][0] + A[1][1]*B[1][0], A[1][0]*B[0][1] + A[1][1]*B[1][1]}, } } @@ -808,9 +818,9 @@ class Solution { private fun matrixMult(A: Array, B: Array): Array { return arrayOf( - intArrayOf(A[0][0] * B[0][0] + A[0][1] * B[1][0], + intArrayOf(A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0][0] * B[0][1] + A[0][1] * B[1][1]), - intArrayOf(A[1][0] * B[0][0] + A[1][1] * B[1][0], + intArrayOf(A[1][0] * B[0][0] + A[1][1] * B[1][0], A[1][0] * B[0][1] + A[1][1] * B[1][1]) ) } @@ -842,9 +852,9 @@ class Solution { func matrixMult(_ A: [[Int]], _ B: [[Int]]) -> [[Int]] { return [ - [A[0][0] * B[0][0] + A[0][1] * B[1][0], + [A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0][0] * B[0][1] + A[0][1] * B[1][1]], - [A[1][0] * B[0][0] + A[1][1] * B[1][0], + [A[1][0] * B[0][0] + A[1][1] * B[1][0], A[1][0] * B[0][1] + A[1][1] * B[1][1]] ] } @@ -876,8 +886,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ --- @@ -932,15 +942,14 @@ class Solution { let phi = (1 + sqrt5) / 2; let psi = (1 - sqrt5) / 2; n++; - return Math.round((Math.pow(phi, n) - - Math.pow(psi, n)) / sqrt5); + return Math.round((Math.pow(phi, n) - Math.pow(psi, n)) / sqrt5); } } ``` ```csharp public class Solution { - public int ClimbStairs(int n) { + public int ClimbStairs(int n) { double sqrt5 = Math.Sqrt(5); double phi = (1 + sqrt5) / 2; double psi = (1 - sqrt5) / 2; @@ -957,7 +966,7 @@ func climbStairs(n int) int { phi := (1 + sqrt5) / 2 psi := (1 - sqrt5) / 2 n++ - return int(math.Round((math.Pow(phi, float64(n)) - + return int(math.Round((math.Pow(phi, float64(n)) - math.Pow(psi, float64(n))) / sqrt5)) } ``` @@ -989,5 +998,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ diff --git a/articles/clone-graph.md b/articles/clone-graph.md index e71e55184..e04f9c09b 100644 --- a/articles/clone-graph.md +++ b/articles/clone-graph.md @@ -267,24 +267,24 @@ func cloneGraph(node *Node) *Node { class Solution { fun cloneGraph(node: Node?): Node? { if (node == null) return null - + val oldToNew = HashMap() - + fun dfs(node: Node): Node { if (node in oldToNew) { return oldToNew[node]!! } - + val copy = Node(node.`val`) oldToNew[node] = copy - + for (nei in node.neighbors) { nei?.let { copy.neighbors.add(dfs(it)) } } - + return copy } - + return dfs(node) } } @@ -306,26 +306,26 @@ class Solution { class Solution { func cloneGraph(_ node: Node?) -> Node? { var oldToNew = [Node: Node]() - + func dfs(_ node: Node?) -> Node? { guard let node = node else { return nil } - + if let existingCopy = oldToNew[node] { return existingCopy } - + let copy = Node(node.val) oldToNew[node] = copy - + for neighbor in node.neighbors { if let clonedNeighbor = dfs(neighbor) { copy.neighbors.append(clonedNeighbor) } } - + return copy } - + return dfs(node) } } @@ -335,8 +335,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V)$ > Where $V$ is the number of vertices and $E$ is the number of edges. @@ -564,16 +564,16 @@ func cloneGraph(node *Node) *Node { if node == nil { return nil } - + oldToNew := make(map[*Node]*Node) oldToNew[node] = &Node{Val: node.Val, Neighbors: make([]*Node, 0)} queue := make([]*Node, 0) queue = append(queue, node) - + for len(queue) > 0 { cur := queue[0] queue = queue[1:] - + for _, nei := range cur.Neighbors { if _, exists := oldToNew[nei]; !exists { oldToNew[nei] = &Node{Val: nei.Val, Neighbors: make([]*Node, 0)} @@ -582,7 +582,7 @@ func cloneGraph(node *Node) *Node { oldToNew[cur].Neighbors = append(oldToNew[cur].Neighbors, oldToNew[nei]) } } - + return oldToNew[node] } ``` @@ -598,15 +598,15 @@ func cloneGraph(node *Node) *Node { class Solution { fun cloneGraph(node: Node?): Node? { if (node == null) return null - + val oldToNew = HashMap() oldToNew[node] = Node(node.`val`) val queue = ArrayDeque() queue.add(node) - + while (queue.isNotEmpty()) { val cur = queue.removeFirst() - + for (nei in cur.neighbors) { nei?.let { neighbor -> if (neighbor !in oldToNew) { @@ -617,7 +617,7 @@ class Solution { } } } - + return oldToNew[node] } } @@ -670,7 +670,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V)$ -> Where $V$ is the number of vertices and $E$ is the number of edges. \ No newline at end of file +> Where $V$ is the number of vertices and $E$ is the number of edges. diff --git a/articles/coin-change-ii.md b/articles/coin-change-ii.md index 6e4cce788..0aaa6b61c 100644 --- a/articles/coin-change-ii.md +++ b/articles/coin-change-ii.md @@ -84,7 +84,7 @@ class Solution { */ change(amount, coins) { coins.sort((a, b) => a - b); - + const dfs = (i, a) => { if (a === 0) return 1; if (i >= coins.length) return 0; @@ -129,7 +129,7 @@ public class Solution { ```go func change(amount int, coins []int) int { - sort.Ints(coins) + sort.Ints(coins) var dfs func(i, a int) int dfs = func(i, a int) int { @@ -155,7 +155,7 @@ func change(amount int, coins []int) int { ```kotlin class Solution { fun change(amount: Int, coins: IntArray): Int { - coins.sort() + coins.sort() fun dfs(i: Int, a: Int): Int { if (a == 0) { @@ -208,8 +208,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ {max(n, \frac{a}{m})})$ -* Space complexity: $O(max(n, \frac{a}{m}))$ +- Time complexity: $O(2 ^ {max(n, \frac{a}{m})})$ +- Space complexity: $O(max(n, \frac{a}{m}))$ > Where $n$ is the number of coins, $a$ is the given amount and $m$ is the minimum value among all the coins. @@ -232,7 +232,7 @@ class Solution: return 0 if memo[i][a] != -1: return memo[i][a] - + res = 0 if a >= coins[i]: res = dfs(i + 1, a) @@ -277,7 +277,7 @@ class Solution { public: int change(int amount, vector& coins) { sort(coins.begin(), coins.end()); - vector> memo(coins.size() + 1, + vector> memo(coins.size() + 1, vector(amount + 1, -1)); return dfs(0, amount, coins, memo); @@ -309,7 +309,8 @@ class Solution { change(amount, coins) { coins.sort((a, b) => a - b); let memo = Array.from({ length: coins.length + 1 }, () => - Array(amount + 1).fill(-1)); + Array(amount + 1).fill(-1), + ); const dfs = (i, a) => { if (a === 0) return 1; @@ -430,7 +431,7 @@ class Solution { func change(_ amount: Int, _ coins: [Int]) -> Int { let coins = coins.sorted() var memo = Array(repeating: Array(repeating: -1, count: amount + 1), count: coins.count + 1) - + func dfs(_ i: Int, _ a: Int) -> Int { if a == 0 { return 1 @@ -441,17 +442,17 @@ class Solution { if memo[i][a] != -1 { return memo[i][a] } - + var res = 0 if a >= coins[i] { res = dfs(i + 1, a) res += dfs(i, a - coins[i]) } - + memo[i][a] = res return res } - + return dfs(0, amount) } } @@ -461,8 +462,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * a)$ -* Space complexity: $O(n * a)$ +- Time complexity: $O(n * a)$ +- Space complexity: $O(n * a)$ > Where $n$ is the number of coins and $a$ is the given amount. @@ -478,15 +479,15 @@ class Solution: n = len(coins) coins.sort() dp = [[0] * (amount + 1) for _ in range(n + 1)] - + for i in range(n + 1): dp[i][0] = 1 - + for i in range(n - 1, -1, -1): for a in range(amount + 1): if a >= coins[i]: - dp[i][a] = dp[i + 1][a] - dp[i][a] += dp[i][a - coins[i]] + dp[i][a] = dp[i + 1][a] + dp[i][a] += dp[i][a - coins[i]] return dp[0][amount] ``` @@ -552,7 +553,9 @@ class Solution { change(amount, coins) { coins.sort((a, b) => a - b); const n = coins.length; - const dp = Array.from({ length: n + 1 }, () => Array(amount + 1).fill(0)); + const dp = Array.from({ length: n + 1 }, () => + Array(amount + 1).fill(0), + ); for (let i = 0; i <= n; i++) { dp[i][0] = 1; @@ -612,8 +615,8 @@ func change(amount int, coins []int) int { for i := n - 1; i >= 0; i-- { for a := 0; a <= amount; a++ { if a >= coins[i] { - dp[i][a] = dp[i+1][a] - dp[i][a] += dp[i][a-coins[i]] + dp[i][a] = dp[i+1][a] + dp[i][a] += dp[i][a-coins[i]] } else { dp[i][a] = dp[i+1][a] } @@ -637,10 +640,10 @@ class Solution { for (i in n - 1 downTo 0) { for (a in 0..amount) { if (a >= coins[i]) { - dp[i][a] = dp[i + 1][a] - dp[i][a] += dp[i][a - coins[i]] + dp[i][a] = dp[i + 1][a] + dp[i][a] += dp[i][a - coins[i]] } else { - dp[i][a] = dp[i + 1][a] + dp[i][a] = dp[i + 1][a] } } } @@ -659,11 +662,11 @@ class Solution { repeating: Array(repeating: 0, count: amount + 1), count: n + 1 ) - + for i in 0...n { dp[i][0] = 1 } - + for i in stride(from: n - 1, through: 0, by: -1) { for a in 0...amount { let base = dp[i + 1][a] @@ -679,7 +682,7 @@ class Solution { } } } - + return dp[0][amount] } } @@ -689,8 +692,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * a)$ -* Space complexity: $O(n * a)$ +- Time complexity: $O(n * a)$ +- Space complexity: $O(n * a)$ > Where $n$ is the number of coins and $a$ is the given amount. @@ -878,7 +881,7 @@ class Solution { } } } - + dp = nextDP } @@ -891,8 +894,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * a)$ -* Space complexity: $O(a)$ +- Time complexity: $O(n * a)$ +- Space complexity: $O(a)$ > Where $n$ is the number of coins and $a$ is the given amount. @@ -916,12 +919,12 @@ class Solution: ```java public class Solution { public int change(int amount, int[] coins) { - int[] dp = new int[amount + 1]; + int[] dp = new int[amount + 1]; dp[0] = 1; for (int i = coins.length - 1; i >= 0; i--) - for (int a = 1; a <= amount; a++) + for (int a = 1; a <= amount; a++) dp[a] = dp[a] + (coins[i] <= a ? dp[a - coins[i]] : 0); - return dp[amount]; + return dp[amount]; } } ``` @@ -954,7 +957,7 @@ class Solution { dp[0] = 1; for (let i = coins.length - 1; i >= 0; i--) { for (let a = 1; a <= amount; a++) { - dp[a] += (coins[i] <= a ? dp[a - coins[i]] : 0); + dp[a] += coins[i] <= a ? dp[a - coins[i]] : 0; } } return dp[amount]; @@ -1041,7 +1044,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * a)$ -* Space complexity: $O(a)$ +- Time complexity: $O(n * a)$ +- Space complexity: $O(a)$ -> Where $n$ is the number of coins and $a$ is the given amount. \ No newline at end of file +> Where $n$ is the number of coins and $a$ is the given amount. diff --git a/articles/coin-change.md b/articles/coin-change.md index f61f99922..a4a16fa85 100644 --- a/articles/coin-change.md +++ b/articles/coin-change.md @@ -5,11 +5,11 @@ ```python class Solution: def coinChange(self, coins: List[int], amount: int) -> int: - + def dfs(amount): if amount == 0: return 0 - + res = 1e9 for coin in coins: if amount - coin >= 0: @@ -28,7 +28,7 @@ public class Solution { int res = (int) 1e9; for (int coin : coins) { if (amount - coin >= 0) { - res = Math.min(res, + res = Math.min(res, 1 + dfs(coins, amount - coin)); } } @@ -47,11 +47,11 @@ class Solution { public: int dfs(vector& coins, int amount) { if (amount == 0) return 0; - + int res = 1e9; for (int coin : coins) { if (amount - coin >= 0) { - res = min(res, + res = min(res, 1 + dfs(coins, amount - coin)); } } @@ -73,19 +73,17 @@ class Solution { * @return {number} */ coinChange(coins, amount) { - const dfs = (amount) => { if (amount === 0) return 0; let res = Infinity; for (let coin of coins) { if (amount - coin >= 0) { - res = Math.min(res, - 1 + dfs(amount - coin)); + res = Math.min(res, 1 + dfs(amount - coin)); } } return res; - } + }; const minCoins = dfs(amount); return minCoins === Infinity ? -1 : minCoins; @@ -101,7 +99,7 @@ public class Solution { int res = (int)1e9; foreach (var coin in coins) { if (amount - coin >= 0) { - res = Math.Min(res, + res = Math.Min(res, 1 + Dfs(coins, amount - coin)); } } @@ -122,14 +120,14 @@ func coinChange(coins []int, amount int) int { if amt == 0 { return 0 } - + res := math.MaxInt32 for _, coin := range coins { if amt - coin >= 0 { res = min(res, 1 + dfs(amt - coin)) } } - + return res } @@ -197,8 +195,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ t)$ -* Space complexity: $O(t)$ +- Time complexity: $O(n ^ t)$ +- Space complexity: $O(t)$ > Where $n$ is the length of the array $coins$ and $t$ is the given $amount$. @@ -218,15 +216,15 @@ class Solution: return 0 if amount in memo: return memo[amount] - + res = 1e9 for coin in coins: if amount - coin >= 0: res = min(res, 1 + dfs(amount - coin)) - + memo[amount] = res return res - + minCoins = dfs(amount) return -1 if minCoins >= 1e9 else minCoins ``` @@ -237,7 +235,7 @@ public class Solution { public int dfs(int amount, int[] coins) { if (amount == 0) return 0; - if (memo.containsKey(amount)) + if (memo.containsKey(amount)) return memo.get(amount); int res = Integer.MAX_VALUE; @@ -249,7 +247,7 @@ public class Solution { } } } - + memo.put(amount, res); return res; } @@ -267,7 +265,7 @@ public: unordered_map memo; int dfs(int amount, vector& coins) { if (amount == 0) return 0; - if (memo.find(amount) != memo.end()) + if (memo.find(amount) != memo.end()) return memo[amount]; int res = INT_MAX; @@ -279,7 +277,7 @@ public: } } } - + memo[amount] = res; return res; } @@ -303,8 +301,7 @@ class Solution { const dfs = (amount) => { if (amount === 0) return 0; - if (memo[amount] !== undefined) - return memo[amount]; + if (memo[amount] !== undefined) return memo[amount]; let res = Infinity; for (let coin of coins) { @@ -315,7 +312,7 @@ class Solution { memo[amount] = res; return res; - } + }; const minCoins = dfs(amount); return minCoins === Infinity ? -1 : minCoins; @@ -329,7 +326,7 @@ public class Solution { private int Dfs(int amount, int[] coins) { if (amount == 0) return 0; - if (memo.ContainsKey(amount)) + if (memo.ContainsKey(amount)) return memo[amount]; int res = int.MaxValue; @@ -341,7 +338,7 @@ public class Solution { } } } - + memo[amount] = res; return res; } @@ -363,7 +360,7 @@ func coinChange(coins []int, amount int) int { if val, ok := memo[amt]; ok { return val } - + res := math.MaxInt32 for _, coin := range coins { if amt - coin >= 0 { @@ -450,8 +447,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * t)$ -* Space complexity: $O(t)$ +- Time complexity: $O(n * t)$ +- Space complexity: $O(t)$ > Where $n$ is the length of the array $coins$ and $t$ is the given $amount$. @@ -622,8 +619,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * t)$ -* Space complexity: $O(t)$ +- Time complexity: $O(n * t)$ +- Space complexity: $O(t)$ > Where $n$ is the length of the array $coins$ and $t$ is the given $amount$. @@ -642,7 +639,7 @@ class Solution: q = deque([0]) seen = [False] * (amount + 1) seen[0] = True - res = 0 + res = 0 while q: res += 1 @@ -858,7 +855,7 @@ class Solution { var q = Deque([0]) var seen = Array(repeating: false, count: amount + 1) seen[0] = true - var res = 0 + var res = 0 while !q.isEmpty { res += 1 @@ -887,7 +884,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * t)$ -* Space complexity: $O(t)$ +- Time complexity: $O(n * t)$ +- Space complexity: $O(t)$ -> Where $n$ is the length of the array $coins$ and $t$ is the given $amount$. \ No newline at end of file +> Where $n$ is the length of the array $coins$ and $t$ is the given $amount$. diff --git a/articles/combination-sum-iv.md b/articles/combination-sum-iv.md index b2d2c5386..b96dd0b4d 100644 --- a/articles/combination-sum-iv.md +++ b/articles/combination-sum-iv.md @@ -6,18 +6,18 @@ class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: nums.sort() - + def dfs(total): if total == 0: return 1 - + res = 0 for i in range(len(nums)): if total < nums[i]: break res += dfs(total - nums[i]) return res - + return dfs(target) ``` @@ -28,12 +28,12 @@ public class Solution { return dfs(nums, target); } - + private int dfs(int[] nums, int total) { if (total == 0) { return 1; } - + int res = 0; for (int num : nums) { if (total < num) { @@ -53,12 +53,12 @@ public: sort(nums.begin(), nums.end()); return dfs(nums, target); } - + int dfs(vector& nums, int total) { if (total == 0) { return 1; } - + int res = 0; for (int num : nums) { if (total < num) { @@ -80,10 +80,10 @@ class Solution { */ combinationSum4(nums, target) { nums.sort((a, b) => a - b); - + const dfs = (total) => { if (total === 0) return 1; - + let res = 0; for (let num of nums) { if (total < num) break; @@ -126,8 +126,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ t)$ -* Space complexity: $O(t)$ +- Time complexity: $O(n ^ t)$ +- Space complexity: $O(t)$ > Where $n$ is the size of the array $nums$ and $t$ is the given target. @@ -146,7 +146,7 @@ class Solution: def dfs(total): if total in memo: return memo[total] - + res = 0 for num in nums: if total < num: @@ -154,7 +154,7 @@ class Solution: res += dfs(total - num) memo[total] = res return res - + return dfs(target) ``` @@ -168,12 +168,12 @@ public class Solution { memo.put(0, 1); return dfs(nums, target); } - + private int dfs(int[] nums, int total) { if (memo.containsKey(total)) { return memo.get(total); } - + int res = 0; for (int num : nums) { if (total < num) { @@ -226,7 +226,7 @@ class Solution { */ combinationSum4(nums, target) { nums.sort((a, b) => a - b); - const memo = { 0 : 1 }; + const memo = { 0: 1 }; const dfs = (total) => { if (memo[total] !== undefined) { @@ -281,8 +281,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * t)$ -* Space complexity: $O(t)$ +- Time complexity: $O(n * t)$ +- Space complexity: $O(t)$ > Where $n$ is the size of the array $nums$ and $t$ is the given target. @@ -301,7 +301,7 @@ class Solution: dp[total] = 0 for num in nums: dp[total] += dp.get(total - num, 0) - + return dp[target] ``` @@ -310,7 +310,7 @@ public class Solution { public int combinationSum4(int[] nums, int target) { Map dp = new HashMap<>(); dp.put(0, 1); - + for (int total = 1; total <= target; total++) { dp.put(total, 0); for (int num : nums) { @@ -328,7 +328,7 @@ public: int combinationSum4(vector& nums, int target) { unordered_map dp; dp[0] = 1; - + for (int total = 1; total <= target; total++) { dp[total] = 0; for (int num : nums) { @@ -353,7 +353,7 @@ class Solution { * @return {number} */ combinationSum4(nums, target) { - let dp = {0: 1}; + let dp = { 0: 1 }; for (let total = 1; total <= target; total++) { dp[total] = 0; for (let num of nums) { @@ -389,8 +389,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * t)$ -* Space complexity: $O(t)$ +- Time complexity: $O(n * t)$ +- Space complexity: $O(t)$ > Where $n$ is the size of the array $nums$ and $t$ is the given target. @@ -470,7 +470,10 @@ class Solution { for (let total = target; total > 0; total--) { for (const num of nums) { if (total < num) break; - dp.set(total - num, (dp.get(total - num) || 0) + (dp.get(total) || 0)); + dp.set( + total - num, + (dp.get(total - num) || 0) + (dp.get(total) || 0), + ); } } return dp.get(0) || 0; @@ -506,7 +509,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * t)$ -* Space complexity: $O(t)$ +- Time complexity: $O(n * t)$ +- Space complexity: $O(t)$ -> Where $n$ is the size of the array $nums$ and $t$ is the given target. \ No newline at end of file +> Where $n$ is the size of the array $nums$ and $t$ is the given target. diff --git a/articles/combination-target-sum-ii.md b/articles/combination-target-sum-ii.md index 3b35aab6d..da1e85b65 100644 --- a/articles/combination-target-sum-ii.md +++ b/articles/combination-target-sum-ii.md @@ -10,7 +10,7 @@ class Solution: def generate_subsets(i, cur, total): if total == target: - res.add(tuple(cur)) + res.add(tuple(cur)) return if total > target or i == len(candidates): return @@ -22,7 +22,7 @@ class Solution: generate_subsets(i + 1, cur, total) generate_subsets(0, [], 0) - return [list(combination) for combination in res] + return [list(combination) for combination in res] ``` ```java @@ -101,7 +101,7 @@ class Solution { this.res.clear(); candidates.sort((a, b) => a - b); this.generateSubsets(candidates, target, 0, [], 0); - return Array.from(this.res, subset => JSON.parse(subset)); + return Array.from(this.res, (subset) => JSON.parse(subset)); } /** @@ -122,7 +122,13 @@ class Solution { } cur.push(candidates[i]); - this.generateSubsets(candidates, target, i + 1, cur, total + candidates[i]); + this.generateSubsets( + candidates, + target, + i + 1, + cur, + total + candidates[i], + ); cur.pop(); this.generateSubsets(candidates, target, i + 1, cur, total); @@ -249,8 +255,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 2 ^ n)$ -* Space complexity: $O(n * 2 ^ n)$ +- Time complexity: $O(n * 2 ^ n)$ +- Space complexity: $O(n * 2 ^ n)$ --- @@ -270,16 +276,16 @@ class Solution: return if total > target or i == len(candidates): return - + cur.append(candidates[i]) dfs(i + 1, cur, total + candidates[i]) cur.pop() - + while i + 1 < len(candidates) and candidates[i] == candidates[i+1]: i += 1 dfs(i + 1, cur, total) - + dfs(0, [], 0) return res ``` @@ -389,7 +395,10 @@ class Solution { this.dfs(candidates, target, i + 1, cur, total + candidates[i]); cur.pop(); - while (i + 1 < candidates.length && candidates[i] === candidates[i + 1]) { + while ( + i + 1 < candidates.length && + candidates[i] === candidates[i + 1] + ) { i++; } this.dfs(candidates, target, i + 1, cur, total); @@ -530,8 +539,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 2 ^n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * 2 ^n)$ +- Space complexity: $O(n)$ --- @@ -546,7 +555,7 @@ class Solution: self.count = defaultdict(int) cur = [] A = [] - + for num in nums: if self.count[num] == 0: A.append(num) @@ -560,7 +569,7 @@ class Solution: return if target < 0 or i >= len(nums): return - + if self.count[nums[i]] > 0: cur.append(nums[i]) self.count[nums[i]] -= 1 @@ -575,11 +584,11 @@ class Solution: public class Solution { List> res = new ArrayList<>(); Map count = new HashMap<>(); - + public List> combinationSum2(int[] nums, int target) { List cur = new ArrayList<>(); List A = new ArrayList<>(); - + for (int num : nums) { if (!count.containsKey(num)) { A.add(num); @@ -667,7 +676,7 @@ class Solution { combinationSum2(nums, target) { const cur = []; const A = []; - + for (const num of nums) { if (!this.count.has(num)) { A.push(num); @@ -678,7 +687,7 @@ class Solution { return this.res; } - /** + /** * @param {number[]} nums * @param {number} target * @param {number[]} cur @@ -715,7 +724,7 @@ public class Solution { public List> CombinationSum2(int[] nums, int target) { List cur = new List(); List A = new List(); - + foreach (int num in nums) { if (!count.ContainsKey(num)) { A.Add(num); @@ -776,7 +785,7 @@ func combinationSum2(nums []int, target int) [][]int { if target < 0 || i >= len(uniqueNums) { return } - + if count[uniqueNums[i]] > 0 { cur = append(cur, uniqueNums[i]) count[uniqueNums[i]]-- @@ -820,7 +829,7 @@ class Solution { if (target < 0 || i >= nums.size) { return } - + if (count[nums[i]] ?: 0 > 0) { cur.add(nums[i]) count[nums[i]] = count[nums[i]]!! - 1 @@ -879,8 +888,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 2 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * 2 ^ n)$ +- Space complexity: $O(n)$ --- @@ -1148,5 +1157,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 2 ^ n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n * 2 ^ n)$ +- Space complexity: $O(n)$ diff --git a/articles/combination-target-sum.md b/articles/combination-target-sum.md index 46436ad64..562cfac27 100644 --- a/articles/combination-target-sum.md +++ b/articles/combination-target-sum.md @@ -116,7 +116,7 @@ class Solution { ```csharp public class Solution { - + List> res = new List>(); public void backtrack(int i, List cur, int total, int[] nums, int target) { @@ -124,15 +124,15 @@ public class Solution { res.Add(cur.ToList()); return; } - + if(total > target || i >= nums.Length) return; - + cur.Add(nums[i]); backtrack(i, cur, total + nums[i], nums, target); cur.Remove(cur.Last()); backtrack(i + 1, cur, total, nums, target); - + } public List> CombinationSum(int[] nums, int target) { backtrack(0, new List(), 0, nums, target); @@ -225,8 +225,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ \frac{t}{m})$ -* Space complexity: $O(\frac{t}{m})$ +- Time complexity: $O(2 ^ \frac{t}{m})$ +- Space complexity: $O(\frac{t}{m})$ > Where $t$ is the given $target$ and $m$ is the minimum value in $nums$. @@ -246,14 +246,14 @@ class Solution: if total == target: res.append(cur.copy()) return - + for j in range(i, len(nums)): if total + nums[j] > target: return cur.append(nums[j]) dfs(j, cur, total + nums[j]) cur.pop() - + dfs(0, [], 0) return res ``` @@ -264,7 +264,7 @@ public class Solution { public List> combinationSum(int[] nums, int target) { res = new ArrayList<>(); Arrays.sort(nums); - + dfs(0, new ArrayList<>(), 0, nums, target); return res; } @@ -274,7 +274,7 @@ public class Solution { res.add(new ArrayList<>(cur)); return; } - + for (int j = i; j < nums.length; j++) { if (total + nums[j] > target) { return; @@ -302,7 +302,7 @@ public: res.push_back(cur); return; } - + for (int j = i; j < nums.size(); j++) { if (total + nums[j] > target) { return; @@ -325,13 +325,13 @@ class Solution { combinationSum(nums, target) { const res = []; nums.sort((a, b) => a - b); - + const dfs = (i, cur, total) => { if (total === target) { res.push([...cur]); return; } - + for (let j = i; j < nums.length; j++) { if (total + nums[j] > target) { return; @@ -341,7 +341,7 @@ class Solution { cur.pop(); } }; - + dfs(0, [], 0); return res; } @@ -363,7 +363,7 @@ public class Solution { res.Add(new List(cur)); return; } - + for (int j = i; j < nums.Length; j++) { if (total + nums[j] > target) { return; @@ -389,7 +389,7 @@ func combinationSum(nums []int, target int) [][]int { res = append(res, temp) return } - + for j := i; j < len(nums); j++ { if total + nums[j] > target { return @@ -416,7 +416,7 @@ class Solution { res.add(ArrayList(cur)) return } - + for (j in i until nums.size) { if (total + nums[j] > target) { return @@ -466,7 +466,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ \frac{t}{m})$ -* Space complexity: $O(\frac{t}{m})$ +- Time complexity: $O(2 ^ \frac{t}{m})$ +- Space complexity: $O(\frac{t}{m})$ -> Where $t$ is the given $target$ and $m$ is the minimum value in $nums$. \ No newline at end of file +> Where $t$ is the given $target$ and $m$ is the minimum value in $nums$. diff --git a/articles/combinations-of-a-phone-number.md b/articles/combinations-of-a-phone-number.md index 51796e3f7..7953164f9 100644 --- a/articles/combinations-of-a-phone-number.md +++ b/articles/combinations-of-a-phone-number.md @@ -61,7 +61,7 @@ public class Solution { class Solution { public: vector res; - vector digitToChar = {"", "", "abc", "def", "ghi", "jkl", + vector digitToChar = {"", "", "abc", "def", "ghi", "jkl", "mno", "qprs", "tuv", "wxyz"}; vector letterCombinations(string digits) { @@ -93,14 +93,14 @@ class Solution { let res = []; if (digits.length === 0) return res; const digitToChar = { - "2": "abc", - "3": "def", - "4": "ghi", - "5": "jkl", - "6": "mno", - "7": "qprs", - "8": "tuv", - "9": "wxyz" + 2: 'abc', + 3: 'def', + 4: 'ghi', + 5: 'jkl', + 6: 'mno', + 7: 'qprs', + 8: 'tuv', + 9: 'wxyz', }; const backtrack = (i, curStr) => { @@ -111,8 +111,8 @@ class Solution { for (const c of digitToChar[digits[i]]) { backtrack(i + 1, curStr + c); } - } - backtrack(0, ""); + }; + backtrack(0, ''); return res; } } @@ -120,7 +120,7 @@ class Solution { ```csharp public class Solution { - + private List res = new List(); private Dictionary digitToChar = new Dictionary { {'2', "abc"}, {'3', "def"}, {'4', "ghi"}, {'5', "jkl"}, @@ -216,15 +216,15 @@ class Solution { class Solution { func letterCombinations(_ digits: String) -> [String] { guard !digits.isEmpty else { return [] } - + let digitToChar: [Character: String] = [ "2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz" ] - + var res = [String]() let digitsArray = Array(digits) - + func backtrack(_ i: Int, _ curStr: String) { if curStr.count == digits.count { res.append(curStr) @@ -236,7 +236,7 @@ class Solution { } } } - + backtrack(0, "") return res } @@ -247,10 +247,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 4 ^ n)$ -* Space complexity: - * $O(n)$ extra space. - * $O(n * 4 ^ n)$ space for the output list. +- Time complexity: $O(n * 4 ^ n)$ +- Space complexity: + - $O(n)$ extra space. + - $O(n * 4 ^ n)$ space for the output list. --- @@ -287,14 +287,14 @@ class Solution: ```java public class Solution { - + public List letterCombinations(String digits) { if (digits.isEmpty()) return new ArrayList<>(); - + List res = new ArrayList<>(); res.add(""); String[] digitToChar = { - "", "", "abc", "def", "ghi", "jkl", + "", "", "abc", "def", "ghi", "jkl", "mno", "qprs", "tuv", "wxyz" }; @@ -317,7 +317,7 @@ class Solution { public: vector letterCombinations(string digits) { if (digits.empty()) return {}; - + vector res = {""}; vector digitToChar = { "", "", "abc", "def", "ghi", "jkl", @@ -346,17 +346,17 @@ class Solution { */ letterCombinations(digits) { if (digits.length === 0) return []; - - let res = [""]; + + let res = ['']; const digitToChar = { - "2": "abc", - "3": "def", - "4": "ghi", - "5": "jkl", - "6": "mno", - "7": "qprs", - "8": "tuv", - "9": "wxyz" + 2: 'abc', + 3: 'def', + 4: 'ghi', + 5: 'jkl', + 6: 'mno', + 7: 'qprs', + 8: 'tuv', + 9: 'wxyz', }; for (const digit of digits) { @@ -378,7 +378,7 @@ public class Solution { public List LetterCombinations(string digits) { if (digits.Length == 0) return new List(); - + List res = new List { "" }; Dictionary digitToChar = new Dictionary { { '2', "abc" }, { '3', "def" }, { '4', "ghi" }, { '5', "jkl" }, @@ -466,14 +466,14 @@ class Solution { class Solution { func letterCombinations(_ digits: String) -> [String] { guard !digits.isEmpty else { return [] } - + let digitToChar: [Character: String] = [ "2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz" ] - + var res = [""] - + for digit in digits { guard let letters = digitToChar[digit] else { continue } var tmp = [String]() @@ -484,7 +484,7 @@ class Solution { } res = tmp } - + return res } } @@ -494,7 +494,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 4 ^ n)$ -* Space complexity: - * $O(n)$ extra space. - * $O(n * 4 ^ n)$ space for the output list. +- Time complexity: $O(n * 4 ^ n)$ +- Space complexity: + - $O(n)$ extra space. + - $O(n * 4 ^ n)$ space for the output list. diff --git a/articles/combinations.md b/articles/combinations.md index 321ffeab1..4c1594aaf 100644 --- a/articles/combinations.md +++ b/articles/combinations.md @@ -6,18 +6,18 @@ class Solution: def combine(self, n: int, k: int) -> List[List[int]]: res = [] - + def backtrack(i, comb): if i > n: if len(comb) == k: res.append(comb.copy()) return - + comb.append(i) backtrack(i + 1, comb) comb.pop() backtrack(i + 1, comb) - + backtrack(1, []) return res ``` @@ -25,13 +25,13 @@ class Solution: ```java public class Solution { private List> res; - + public List> combine(int n, int k) { res = new ArrayList<>(); backtrack(1, n, k, new ArrayList<>()); return res; } - + private void backtrack(int i, int n, int k, List comb) { if (i > n) { if (comb.size() == k) { @@ -39,7 +39,7 @@ public class Solution { } return; } - + comb.add(i); backtrack(i + 1, n, k, comb); comb.remove(comb.size() - 1); @@ -84,7 +84,7 @@ class Solution { */ combine(n, k) { const res = []; - + const backtrack = (i, comb) => { if (i > n) { if (comb.length === k) { @@ -92,13 +92,13 @@ class Solution { } return; } - + comb.push(i); backtrack(i + 1, comb); comb.pop(); backtrack(i + 1, comb); }; - + backtrack(1, []); return res; } @@ -109,7 +109,7 @@ class Solution { public class Solution { public List> Combine(int n, int k) { List> res = new List>(); - + void Backtrack(int i, List comb) { if (i > n) { if (comb.Count == k) { @@ -134,8 +134,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(k * \frac {n!}{(n - k)! * k!})$ -* Space complexity: $O(k * \frac {n!}{(n - k)! * k!})$ for the output array. +- Time complexity: $O(k * \frac {n!}{(n - k)! * k!})$ +- Space complexity: $O(k * \frac {n!}{(n - k)! * k!})$ for the output array. > Where $n$ is the number of elements and $k$ is the number of elements to be picked. @@ -225,7 +225,7 @@ class Solution { */ combine(n, k) { const res = []; - + const backtrack = (start, comb) => { if (comb.length === k) { res.push([...comb]); @@ -238,7 +238,7 @@ class Solution { comb.pop(); } }; - + backtrack(1, []); return res; } @@ -273,8 +273,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(k * \frac {n!}{(n - k)! * k!})$ -* Space complexity: $O(k * \frac {n!}{(n - k)! * k!})$ for the output array. +- Time complexity: $O(k * \frac {n!}{(n - k)! * k!})$ +- Space complexity: $O(k * \frac {n!}{(n - k)! * k!})$ for the output array. > Where $n$ is the number of elements and $k$ is the number of elements to be picked. @@ -428,8 +428,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(k * \frac {n!}{(n - k)! * k!})$ -* Space complexity: $O(k * \frac {n!}{(n - k)! * k!})$ for the output array. +- Time complexity: $O(k * \frac {n!}{(n - k)! * k!})$ +- Space complexity: $O(k * \frac {n!}{(n - k)! * k!})$ for the output array. > Where $n$ is the number of elements and $k$ is the number of elements to be picked. @@ -448,7 +448,7 @@ class Solution: for bit in range(n): if mask & (1 << bit): comb.append(bit + 1) - + if len(comb) == k: res.append(comb) return res @@ -504,8 +504,8 @@ class Solution { */ combine(n, k) { const res = []; - for (let mask = 0; mask < (1 << n); mask++) { - if (mask.toString(2).split("1").length - 1 !== k) { + for (let mask = 0; mask < 1 << n; mask++) { + if (mask.toString(2).split('1').length - 1 !== k) { continue; } @@ -548,7 +548,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 2 ^ n)$ -* Space complexity: $O(k * \frac {n!}{(n - k)! * k!})$ for the output array. +- Time complexity: $O(n * 2 ^ n)$ +- Space complexity: $O(k * \frac {n!}{(n - k)! * k!})$ for the output array. -> Where $n$ is the number of elements and $k$ is the number of elements to be picked. \ No newline at end of file +> Where $n$ is the number of elements and $k$ is the number of elements to be picked. diff --git a/articles/concatenated-words.md b/articles/concatenated-words.md index 30147ca36..1c1b24cd0 100644 --- a/articles/concatenated-words.md +++ b/articles/concatenated-words.md @@ -132,7 +132,7 @@ class Solution { const dfs = (concatWord, totLen) => { if (concatWord.length > 1) { - let word = concatWord.join(""); + let word = concatWord.join(''); if (wordSet.has(word)) { res.push(word); wordSet.delete(word); @@ -197,8 +197,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n ^ n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n ^ n)$ +- Space complexity: $O(m * n)$ > Where $n$ is the size of the string array $words$ and $m$ is the length of the longest word in the array. @@ -216,7 +216,7 @@ class Solution: def dfs(word): for i in range(1, len(word)): prefix, suffix = word[:i], word[i:] - if ((prefix in wordSet and suffix in wordSet) or + if ((prefix in wordSet and suffix in wordSet) or (prefix in wordSet and dfs(suffix)) ): return True @@ -303,8 +303,10 @@ class Solution { const prefix = word.substring(0, i); const suffix = word.substring(i); - if ((wordSet.has(prefix) && wordSet.has(suffix)) || - (wordSet.has(prefix) && dfs(suffix))) { + if ( + (wordSet.has(prefix) && wordSet.has(suffix)) || + (wordSet.has(prefix) && dfs(suffix)) + ) { return true; } } @@ -355,8 +357,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m ^ 4)$ -* Space complexity: $O(n * m)$ +- Time complexity: $O(n * m ^ 4)$ +- Space complexity: $O(n * m)$ > Where $n$ is the size of the string array $words$ and $m$ is the length of the longest word in the array. @@ -378,7 +380,7 @@ class Solution: for i in range(1, len(word)): prefix, suffix = word[:i], word[i:] - if ((prefix in wordSet and suffix in wordSet) or + if ((prefix in wordSet and suffix in wordSet) or (prefix in wordSet and dfs(suffix)) ): dp[word] = True @@ -489,8 +491,10 @@ class Solution { const prefix = word.substring(0, i); const suffix = word.substring(i); - if ((wordSet.has(prefix) && wordSet.has(suffix)) || - (wordSet.has(prefix) && dfs(suffix))) { + if ( + (wordSet.has(prefix) && wordSet.has(suffix)) || + (wordSet.has(prefix) && dfs(suffix)) + ) { dp.set(word, true); return true; } @@ -550,8 +554,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m ^ 3)$ -* Space complexity: $O(n * m)$ +- Time complexity: $O(n * m ^ 3)$ +- Space complexity: $O(n * m)$ > Where $n$ is the size of the string array $words$ and $m$ is the length of the longest word in the array. @@ -717,7 +721,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m ^ 3)$ -* Space complexity: $O(n * m)$ +- Time complexity: $O(n * m ^ 3)$ +- Space complexity: $O(n * m)$ -> Where $n$ is the size of the string array $words$ and $m$ is the length of the longest word in the array. \ No newline at end of file +> Where $n$ is the size of the string array $words$ and $m$ is the length of the longest word in the array. diff --git a/articles/concatenation-of-array.md b/articles/concatenation-of-array.md index f3740ed68..6c937a1b5 100644 --- a/articles/concatenation-of-array.md +++ b/articles/concatenation-of-array.md @@ -79,8 +79,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for the output array. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for the output array. --- @@ -159,5 +159,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for the output array. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for the output array. diff --git a/articles/constrained-subsequence-sum.md b/articles/constrained-subsequence-sum.md index 1c04624df..5911f55dc 100644 --- a/articles/constrained-subsequence-sum.md +++ b/articles/constrained-subsequence-sum.md @@ -126,8 +126,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * k)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * k)$ +- Space complexity: $O(n)$ --- @@ -213,8 +213,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * k)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * k)$ +- Space complexity: $O(n)$ --- @@ -271,7 +271,7 @@ class Solution: class SegmentTree { int n; int[] tree; - + public SegmentTree(int N) { this.n = N; while ((this.n & (this.n - 1)) != 0) { @@ -282,7 +282,7 @@ class SegmentTree { tree[i] = Integer.MIN_VALUE; } } - + public void update(int i, int val) { i += n; tree[i] = val; @@ -291,7 +291,7 @@ class SegmentTree { tree[i] = Math.max(tree[i << 1], tree[(i << 1) | 1]); } } - + public int query(int l, int r) { int res = Integer.MIN_VALUE; l += n; @@ -318,13 +318,13 @@ public class Solution { SegmentTree maxSegTree = new SegmentTree(n); maxSegTree.update(0, nums[0]); int res = nums[0]; - + for (int i = 1; i < n; i++) { int cur = nums[i] + maxSegTree.query(Math.max(0, i - k), i - 1); maxSegTree.update(i, cur); res = Math.max(res, cur); } - + return res; } } @@ -343,7 +343,7 @@ public: } tree.assign(2 * n, INT_MIN); } - + void update(int i, int val) { i += n; tree[i] = val; @@ -352,7 +352,7 @@ public: tree[i] = max(tree[i << 1], tree[i << 1 | 1]); } } - + int query(int l, int r) { int res = INT_MIN; l += n; @@ -380,13 +380,13 @@ public: SegmentTree maxSegTree(n); maxSegTree.update(0, nums[0]); int res = nums[0]; - + for (int i = 1; i < n; i++) { int cur = nums[i] + maxSegTree.query(max(0, i - k), i - 1); maxSegTree.update(i, cur); res = max(res, cur); } - + return res; } }; @@ -396,7 +396,7 @@ public: class SegmentTree { /** * @constructor - * @param {number} N + * @param {number} N */ constructor(N) { this.n = N; @@ -416,7 +416,7 @@ class SegmentTree { this.tree[i] = val; while (i > 1) { i >>= 1; - this.tree[i] = Math.max(this.tree[i << 1], this.tree[i << 1 | 1]); + this.tree[i] = Math.max(this.tree[i << 1], this.tree[(i << 1) | 1]); } } @@ -472,8 +472,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -555,7 +555,7 @@ class Solution { constrainedSubsetSum(nums, k) { let res = nums[0]; const maxHeap = new PriorityQueue( - (a, b) => b[0] - a[0] // max_sum, index + (a, b) => b[0] - a[0], // max_sum, index ); maxHeap.enqueue([nums[0], 0]); @@ -578,8 +578,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -697,5 +697,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(k)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(k)$ diff --git a/articles/construct-binary-tree-from-inorder-and-postorder-traversal.md b/articles/construct-binary-tree-from-inorder-and-postorder-traversal.md index eb086eacd..5a538b401 100644 --- a/articles/construct-binary-tree-from-inorder-and-postorder-traversal.md +++ b/articles/construct-binary-tree-from-inorder-and-postorder-traversal.md @@ -128,8 +128,14 @@ class Solution { const root = new TreeNode(rootVal); const mid = inorder.indexOf(rootVal); - root.left = this.buildTree(inorder.slice(0, mid), postorder.slice(0, mid)); - root.right = this.buildTree(inorder.slice(mid + 1), postorder.slice(mid, postorder.length - 1)); + root.left = this.buildTree( + inorder.slice(0, mid), + postorder.slice(0, mid), + ); + root.right = this.buildTree( + inorder.slice(mid + 1), + postorder.slice(mid, postorder.length - 1), + ); return root; } @@ -140,8 +146,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -299,8 +305,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -325,7 +331,7 @@ class Solution: if inorder[inIdx] == limit: inIdx -= 1 return None - + root = TreeNode(postorder[postIdx]) postIdx -= 1 root.right = dfs(root.val) @@ -466,5 +472,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. diff --git a/articles/construct-quad-tree.md b/articles/construct-quad-tree.md index 5e2b91594..2b852c4f7 100644 --- a/articles/construct-quad-tree.md +++ b/articles/construct-quad-tree.md @@ -26,15 +26,15 @@ class Solution: break if allSame: return Node(grid[r][c], True) - + n = n // 2 topleft = dfs(n, r, c) topright = dfs(n, r, c + n) bottomleft = dfs(n, r + n, c) bottomright = dfs(n, r + n, c + n) - + return Node(0, False, topleft, topright, bottomleft, bottomright) - + return dfs(len(grid), 0, 0) ``` @@ -49,7 +49,7 @@ class Node { public Node bottomLeft; public Node bottomRight; - + public Node() { this.val = false; this.isLeaf = false; @@ -58,7 +58,7 @@ class Node { this.bottomLeft = null; this.bottomRight = null; } - + public Node(boolean val, boolean isLeaf) { this.val = val; this.isLeaf = isLeaf; @@ -67,7 +67,7 @@ class Node { this.bottomLeft = null; this.bottomRight = null; } - + public Node(boolean val, boolean isLeaf, Node topLeft, Node topRight, Node bottomLeft, Node bottomRight) { this.val = val; this.isLeaf = isLeaf; @@ -122,7 +122,7 @@ public: Node* topRight; Node* bottomLeft; Node* bottomRight; - + Node() { val = false; isLeaf = false; @@ -131,7 +131,7 @@ public: bottomLeft = NULL; bottomRight = NULL; } - + Node(bool _val, bool _isLeaf) { val = _val; isLeaf = _isLeaf; @@ -140,7 +140,7 @@ public: bottomLeft = NULL; bottomRight = NULL; } - + Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) { val = _val; isLeaf = _isLeaf; @@ -229,7 +229,14 @@ class Solution { const bottomLeft = dfs(mid, r + mid, c); const bottomRight = dfs(mid, r + mid, c + mid); - return new Node(false, false, topLeft, topRight, bottomLeft, bottomRight); + return new Node( + false, + false, + topLeft, + topRight, + bottomLeft, + bottomRight, + ); }; return dfs(grid.length, 0, 0); @@ -256,7 +263,7 @@ public class Node { bottomLeft = null; bottomRight = null; } - + public Node(bool _val, bool _isLeaf) { val = _val; isLeaf = _isLeaf; @@ -265,7 +272,7 @@ public class Node { bottomLeft = null; bottomRight = null; } - + public Node(bool _val,bool _isLeaf,Node _topLeft,Node _topRight,Node _bottomLeft,Node _bottomRight) { val = _val; isLeaf = _isLeaf; @@ -311,8 +318,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 \log n)$ -* Space complexity: $O(\log n)$ for recursion stack. +- Time complexity: $O(n ^ 2 \log n)$ +- Space complexity: $O(\log n)$ for recursion stack. --- @@ -345,7 +352,7 @@ class Solution: bottomLeft = dfs(mid, r + mid, c) bottomRight = dfs(mid, r + mid, c + mid) - if (topLeft.isLeaf and topRight.isLeaf and + if (topLeft.isLeaf and topRight.isLeaf and bottomLeft.isLeaf and bottomRight.isLeaf and topLeft.val == topRight.val == bottomLeft.val == bottomRight.val): return Node(topLeft.val, True) @@ -366,7 +373,7 @@ class Node { public Node bottomLeft; public Node bottomRight; - + public Node() { this.val = false; this.isLeaf = false; @@ -375,7 +382,7 @@ class Node { this.bottomLeft = null; this.bottomRight = null; } - + public Node(boolean val, boolean isLeaf) { this.val = val; this.isLeaf = isLeaf; @@ -384,7 +391,7 @@ class Node { this.bottomLeft = null; this.bottomRight = null; } - + public Node(boolean val, boolean isLeaf, Node topLeft, Node topRight, Node bottomLeft, Node bottomRight) { this.val = val; this.isLeaf = isLeaf; @@ -412,10 +419,10 @@ public class Solution { Node bottomLeft = dfs(grid, mid, r + mid, c); Node bottomRight = dfs(grid, mid, r + mid, c + mid); - if (topLeft.isLeaf && topRight.isLeaf && + if (topLeft.isLeaf && topRight.isLeaf && bottomLeft.isLeaf && bottomRight.isLeaf && - topLeft.val == topRight.val && - topLeft.val == bottomLeft.val && + topLeft.val == topRight.val && + topLeft.val == bottomLeft.val && topLeft.val == bottomRight.val) { return new Node(topLeft.val, true); } @@ -436,7 +443,7 @@ public: Node* topRight; Node* bottomLeft; Node* bottomRight; - + Node() { val = false; isLeaf = false; @@ -445,7 +452,7 @@ public: bottomLeft = NULL; bottomRight = NULL; } - + Node(bool _val, bool _isLeaf) { val = _val; isLeaf = _isLeaf; @@ -454,7 +461,7 @@ public: bottomLeft = NULL; bottomRight = NULL; } - + Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) { val = _val; isLeaf = _isLeaf; @@ -529,15 +536,26 @@ class Solution { const bottomLeft = dfs(mid, r + mid, c); const bottomRight = dfs(mid, r + mid, c + mid); - if (topLeft.isLeaf && topRight.isLeaf && - bottomLeft.isLeaf && bottomRight.isLeaf && + if ( + topLeft.isLeaf && + topRight.isLeaf && + bottomLeft.isLeaf && + bottomRight.isLeaf && topLeft.val === topRight.val && topLeft.val === bottomLeft.val && - topLeft.val === bottomRight.val) { + topLeft.val === bottomRight.val + ) { return new Node(topLeft.val, true); } - return new Node(false, false, topLeft, topRight, bottomLeft, bottomRight); + return new Node( + false, + false, + topLeft, + topRight, + bottomLeft, + bottomRight, + ); }; return dfs(grid.length, 0, 0); @@ -564,7 +582,7 @@ public class Node { bottomLeft = null; bottomRight = null; } - + public Node(bool _val, bool _isLeaf) { val = _val; isLeaf = _isLeaf; @@ -573,7 +591,7 @@ public class Node { bottomLeft = null; bottomRight = null; } - + public Node(bool _val,bool _isLeaf,Node _topLeft,Node _topRight,Node _bottomLeft,Node _bottomRight) { val = _val; isLeaf = _isLeaf; @@ -601,7 +619,7 @@ public class Solution { Node bottomLeft = Dfs(grid, mid, r + mid, c); Node bottomRight = Dfs(grid, mid, r + mid, c + mid); - if (topLeft.isLeaf && topRight.isLeaf && + if (topLeft.isLeaf && topRight.isLeaf && bottomLeft.isLeaf && bottomRight.isLeaf && topLeft.val == topRight.val && topRight.val == bottomLeft.val && @@ -618,8 +636,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(\log n)$ for recursion stack. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(\log n)$ for recursion stack. --- @@ -657,7 +675,7 @@ class Solution: bottomLeft = dfs(n, r + n, c) bottomRight = dfs(n, r + n, c + n) - if (topLeft.isLeaf and topRight.isLeaf and + if (topLeft.isLeaf and topRight.isLeaf and bottomLeft.isLeaf and bottomRight.isLeaf and topLeft.val == topRight.val == bottomLeft.val == bottomRight.val): return topLeft @@ -678,7 +696,7 @@ class Node { public Node bottomLeft; public Node bottomRight; - + public Node() { this.val = false; this.isLeaf = false; @@ -687,7 +705,7 @@ class Node { this.bottomLeft = null; this.bottomRight = null; } - + public Node(boolean val, boolean isLeaf) { this.val = val; this.isLeaf = isLeaf; @@ -696,7 +714,7 @@ class Node { this.bottomLeft = null; this.bottomRight = null; } - + public Node(boolean val, boolean isLeaf, Node topLeft, Node topRight, Node bottomLeft, Node bottomRight) { this.val = val; this.isLeaf = isLeaf; @@ -727,9 +745,9 @@ public class Solution { Node bottomLeft = dfs(grid, n, r + n, c); Node bottomRight = dfs(grid, n, r + n, c + n); - if (topLeft.isLeaf && topRight.isLeaf && + if (topLeft.isLeaf && topRight.isLeaf && bottomLeft.isLeaf && bottomRight.isLeaf && - topLeft.val == topRight.val && topLeft.val == bottomLeft.val && + topLeft.val == topRight.val && topLeft.val == bottomLeft.val && topLeft.val == bottomRight.val) { return topLeft; } @@ -750,7 +768,7 @@ public: Node* topRight; Node* bottomLeft; Node* bottomRight; - + Node() { val = false; isLeaf = false; @@ -759,7 +777,7 @@ public: bottomLeft = NULL; bottomRight = NULL; } - + Node(bool _val, bool _isLeaf) { val = _val; isLeaf = _isLeaf; @@ -768,7 +786,7 @@ public: bottomLeft = NULL; bottomRight = NULL; } - + Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) { val = _val; isLeaf = _isLeaf; @@ -849,14 +867,26 @@ class Solution { const bottomLeft = dfs(n, r + n, c); const bottomRight = dfs(n, r + n, c + n); - if (topLeft.isLeaf && topRight.isLeaf && - bottomLeft.isLeaf && bottomRight.isLeaf && - topLeft.val === topRight.val && topLeft.val === bottomLeft.val && - topLeft.val === bottomRight.val) { + if ( + topLeft.isLeaf && + topRight.isLeaf && + bottomLeft.isLeaf && + bottomRight.isLeaf && + topLeft.val === topRight.val && + topLeft.val === bottomLeft.val && + topLeft.val === bottomRight.val + ) { return topLeft; } - return new Node(false, false, topLeft, topRight, bottomLeft, bottomRight); + return new Node( + false, + false, + topLeft, + topRight, + bottomLeft, + bottomRight, + ); }; return dfs(grid.length, 0, 0); @@ -883,7 +913,7 @@ public class Node { bottomLeft = null; bottomRight = null; } - + public Node(bool _val, bool _isLeaf) { val = _val; isLeaf = _isLeaf; @@ -892,7 +922,7 @@ public class Node { bottomLeft = null; bottomRight = null; } - + public Node(bool _val,bool _isLeaf,Node _topLeft,Node _topRight,Node _bottomLeft,Node _bottomRight) { val = _val; isLeaf = _isLeaf; @@ -941,5 +971,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(\log n)$ for recursion stack. \ No newline at end of file +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(\log n)$ for recursion stack. diff --git a/articles/construct-string-from-binary-tree.md b/articles/construct-string-from-binary-tree.md index 98b9da146..56a3a5b84 100644 --- a/articles/construct-string-from-binary-tree.md +++ b/articles/construct-string-from-binary-tree.md @@ -11,22 +11,22 @@ # self.right = right class Solution: def tree2str(self, root: Optional[TreeNode]) -> str: - if not root: + if not root: return "" - + cur = root.val left = self.tree2str(root.left) right = self.tree2str(root.right) - + if left and right: return f"{cur}({left})({right})" - + if right: return f"{cur}()({right})" - + if left: return f"{cur}({left})" - + return str(cur) ``` @@ -131,7 +131,7 @@ class Solution { */ tree2str(root) { if (!root) { - return ""; + return ''; } const cur = root.val.toString(); @@ -159,8 +159,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -289,18 +289,18 @@ class Solution { const preorder = (root) => { if (!root) return; - res.push("("); + res.push('('); res.push(root.val.toString()); if (!root.left && root.right) { - res.push("()"); + res.push('()'); } preorder(root.left); preorder(root.right); - res.push(")"); + res.push(')'); }; preorder(root); - return res.join("").slice(1, -1); + return res.join('').slice(1, -1); } } ``` @@ -309,8 +309,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -476,7 +476,7 @@ class Solution { */ tree2str(root) { if (!root) { - return ""; + return ''; } let res = []; @@ -488,7 +488,7 @@ class Solution { if (cur) { res.push(`(${cur.val}`); if (!cur.left && cur.right) { - res.push("()"); + res.push('()'); } stack.push(cur); @@ -499,13 +499,13 @@ class Solution { cur = top.right; } else { stack.pop(); - res.push(")"); + res.push(')'); lastVisited = top; } } } - return res.join("").slice(1, -1); + return res.join('').slice(1, -1); } } ``` @@ -514,5 +514,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/contains-duplicate-ii.md b/articles/contains-duplicate-ii.md index cc98d9da1..63116d5da 100644 --- a/articles/contains-duplicate-ii.md +++ b/articles/contains-duplicate-ii.md @@ -82,8 +82,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * min(n, k))$ -* Space complexity: $O(1)$ +- Time complexity: $O(n * min(n, k))$ +- Space complexity: $O(1)$ > Where $n$ is the size of the array $nums$ and $k$ is the maximum distance between two equal numbers. @@ -102,22 +102,22 @@ class Solution: if nums[i] in mp and i - mp[nums[i]] <= k: return True mp[nums[i]] = i - - return False + + return False ``` ```java public class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { Map map = new HashMap<>(); - + for (int i = 0; i < nums.length; i++) { if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k) { return true; } map.put(nums[i], i); } - + return false; } } @@ -128,14 +128,14 @@ class Solution { public: bool containsNearbyDuplicate(vector& nums, int k) { unordered_map mp; - + for (int i = 0; i < nums.size(); i++) { if (mp.find(nums[i]) != mp.end() && i - mp[nums[i]] <= k) { return true; } mp[nums[i]] = i; } - + return false; } }; @@ -174,7 +174,7 @@ public class Solution { } mp[nums[i]] = i; } - + return false; } } @@ -184,8 +184,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ > Where $n$ is the size of the array $nums$ and $k$ is the maximum distance between two equal numbers. @@ -208,7 +208,7 @@ class Solution: if nums[R] in window: return True window.add(nums[R]) - + return False ``` @@ -297,7 +297,7 @@ public class Solution { } window.Add(nums[R]); } - + return false; } } @@ -307,7 +307,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(min(n, k))$ +- Time complexity: $O(n)$ +- Space complexity: $O(min(n, k))$ -> Where $n$ is the size of the array $nums$ and $k$ is the maximum distance between two equal numbers. \ No newline at end of file +> Where $n$ is the size of the array $nums$ and $k$ is the maximum distance between two equal numbers. diff --git a/articles/contiguous-array.md b/articles/contiguous-array.md index f13825744..78d3ca5fd 100644 --- a/articles/contiguous-array.md +++ b/articles/contiguous-array.md @@ -14,10 +14,10 @@ class Solution: ones += 1 else: zeros += 1 - + if ones == zeros and res < (j - i + 1): res = j - i + 1 - + return res ``` @@ -77,17 +77,19 @@ class Solution { * @return {number} */ findMaxLength(nums) { - let n = nums.length, res = 0; + let n = nums.length, + res = 0; for (let i = 0; i < n; i++) { - let zeros = 0, ones = 0; + let zeros = 0, + ones = 0; for (let j = i; j < n; j++) { if (nums[j] === 1) { ones++; } else { zeros++; } - if (ones === zeros && res < (j - i + 1)) { + if (ones === zeros && res < j - i + 1) { res = j - i + 1; } } @@ -102,8 +104,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -183,7 +185,8 @@ class Solution { */ findMaxLength(nums) { const n = nums.length; - let res = 0, count = 0; + let res = 0, + count = 0; const diffIndex = new Array(2 * n + 1).fill(-2); diffIndex[n] = -1; @@ -205,8 +208,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -306,7 +309,9 @@ class Solution { * @return {number} */ findMaxLength(nums) { - let zero = 0, one = 0, res = 0; + let zero = 0, + one = 0, + res = 0; const diffIndex = new Map(); for (let i = 0; i < nums.length; i++) { @@ -337,5 +342,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/continuous-subarray-sum.md b/articles/continuous-subarray-sum.md index a6509f498..a55bdad78 100644 --- a/articles/continuous-subarray-sum.md +++ b/articles/continuous-subarray-sum.md @@ -69,8 +69,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -91,7 +91,7 @@ class Solution: remainder[r] = i elif i - remainder[r] > 1: return True - + return False ``` @@ -171,7 +171,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(k)$ +- Time complexity: $O(n)$ +- Space complexity: $O(k)$ -> Where $n$ is the size of the array $nums$ and $k$ is the number that a subarray sum needs to be multiple of. \ No newline at end of file +> Where $n$ is the size of the array $nums$ and $k$ is the number that a subarray sum needs to be multiple of. diff --git a/articles/convert-an-array-into-a-2d-array-with-conditions.md b/articles/convert-an-array-into-a-2d-array-with-conditions.md index 7f5906f0d..671e10b85 100644 --- a/articles/convert-an-array-into-a-2d-array-with-conditions.md +++ b/articles/convert-an-array-into-a-2d-array-with-conditions.md @@ -16,7 +16,7 @@ class Solution: if r == len(res): res.append([]) res[r].append(num) - + return res ``` @@ -38,7 +38,7 @@ public class Solution { } res.get(r).add(num); } - + return res; } } @@ -63,7 +63,7 @@ public: } res[r].push_back(num); } - + return res; } }; @@ -91,7 +91,7 @@ class Solution { } res[r].push(num); } - + return res; } } @@ -101,8 +101,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n)$ for the output array. +- Time complexity: $O(n * m)$ +- Space complexity: $O(n)$ for the output array. > Where $n$ is the size of the array $nums$ and $m$ is the frequency of the most frequent element in the given array. @@ -129,7 +129,7 @@ class Solution: r += 1 j += 1 i = j - + return res ``` @@ -138,7 +138,7 @@ public class Solution { public List> findMatrix(int[] nums) { Arrays.sort(nums); List> res = new ArrayList<>(); - + int i = 0; while (i < nums.length) { int j = i; @@ -153,7 +153,7 @@ public class Solution { } i = j; } - + return res; } } @@ -179,7 +179,7 @@ public: } i = j; } - + return res; } }; @@ -209,7 +209,7 @@ class Solution { } i = j; } - + return res; } } @@ -219,8 +219,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ for the output array. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ for the output array. --- @@ -313,5 +313,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/convert-bst-to-greater-tree.md b/articles/convert-bst-to-greater-tree.md index 9e01d51be..0c528860f 100644 --- a/articles/convert-bst-to-greater-tree.md +++ b/articles/convert-bst-to-greater-tree.md @@ -159,8 +159,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -303,8 +303,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -329,7 +329,7 @@ class Solution: while node: stack.append(node) node = node.right - + node = stack.pop() curSum += node.val node.val = curSum @@ -452,8 +452,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -491,7 +491,7 @@ class Solution: curSum += cur.val cur.val = curSum cur = cur.left - + return root ``` @@ -639,5 +639,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/convert-sorted-array-to-binary-search-tree.md b/articles/convert-sorted-array-to-binary-search-tree.md index dd933b982..366f0e2e7 100644 --- a/articles/convert-sorted-array-to-binary-search-tree.md +++ b/articles/convert-sorted-array-to-binary-search-tree.md @@ -13,7 +13,7 @@ class Solution: def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]: if not nums: return None - + mid = len(nums) // 2 root = TreeNode(nums[mid]) root.left = self.sortedArrayToBST(nums[:mid]) @@ -116,8 +116,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -249,10 +249,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(\log n)$ space for recursion stack. - * $O(n)$ space for the output. +- Time complexity: $O(n)$ +- Space complexity: + - $O(\log n)$ space for recursion stack. + - $O(n)$ space for the output. --- @@ -271,10 +271,10 @@ class Solution: def sortedArrayToBST(self, nums: List[int]) -> TreeNode: if not nums: return None - + root = TreeNode(0) stack = [(root, 0, len(nums) - 1)] - + while stack: node, l, r = stack.pop() m = (l + r) // 2 @@ -285,7 +285,7 @@ class Solution: if m + 1 <= r: node.right = TreeNode(0) stack.append((node.right, m + 1, r)) - + return root ``` @@ -431,7 +431,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(\log n)$ space for the stack. - * $O(n)$ space for the output. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: + - $O(\log n)$ space for the stack. + - $O(n)$ space for the output. diff --git a/articles/copy-linked-list-with-random-pointer.md b/articles/copy-linked-list-with-random-pointer.md index 0b595bf64..c5306458c 100644 --- a/articles/copy-linked-list-with-random-pointer.md +++ b/articles/copy-linked-list-with-random-pointer.md @@ -21,7 +21,7 @@ class Solution: return None if head in self.map: return self.map[head] - + copy = Node(head.val) self.map[head] = copy copy.next = self.copyRandomList(head.next) @@ -69,7 +69,7 @@ public: int val; Node* next; Node* random; - + Node(int _val) { val = _val; next = NULL; @@ -115,7 +115,7 @@ class Solution { copyRandomList(head) { if (head === null) return null; if (this.map.has(head)) return this.map.get(head); - + const copy = new Node(head.val); this.map.set(head, copy); copy.next = this.copyRandomList(head.next); @@ -132,7 +132,7 @@ public class Node { public int val; public Node next; public Node random; - + public Node(int _val) { val = _val; next = null; @@ -151,7 +151,7 @@ public class Solution { Node copy = new Node(head.val); map[head] = copy; copy.next = copyRandomList(head.next); - + if (head.random != null) { copy.random = copyRandomList(head.random); } else { @@ -182,7 +182,7 @@ func copyRandomList(head *Node) *Node { if val, exists := m[head]; exists { return val } - + copy := &Node{Val: head.Val} m[head] = copy copy.Next = copyRandomList(head.Next) @@ -213,7 +213,7 @@ class Solution { if (map.containsKey(head)) { return map[head] } - + val copy = Node(head.`val`) map[head] = copy copy.next = copyRandomList(head.next) @@ -240,22 +240,22 @@ class Solution { class Solution { private var map = [Node: Node]() - + func copyRandomList(_ head: Node?) -> Node? { if head == nil { return nil } - + if let copied = map[head!] { return copied } - + let copy = Node(head!.val) map[head!] = copy - + copy.next = copyRandomList(head!.next) copy.random = copyRandomList(head!.random) - + return copy } } @@ -265,8 +265,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -351,7 +351,7 @@ public: int val; Node* next; Node* random; - + Node(int _val) { val = _val; next = NULL; @@ -431,7 +431,7 @@ public class Node { public int val; public Node next; public Node random; - + public Node(int _val) { val = _val; next = null; @@ -575,8 +575,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -598,7 +598,7 @@ class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': oldToCopy = collections.defaultdict(lambda: Node(0)) oldToCopy[None] = None - + cur = head while cur: oldToCopy[cur].val = cur.val @@ -660,7 +660,7 @@ public: int val; Node* next; Node* random; - + Node(int _val) { val = _val; next = NULL; @@ -742,7 +742,7 @@ public class Node { public int val; public Node next; public Node random; - + public Node(int _val) { val = _val; next = null; @@ -910,8 +910,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -933,22 +933,22 @@ class Solution: def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]': if head is None: return None - + l1 = head while l1 is not None: l2 = Node(l1.val) l2.next = l1.next l1.next = l2 l1 = l2.next - + newHead = head.next - + l1 = head while l1 is not None: if l1.random is not None: l1.next.random = l1.random.next l1 = l1.next.next - + l1 = head while l1 is not None: l2 = l1.next @@ -956,7 +956,7 @@ class Solution: if l2.next is not None: l2.next = l2.next.next l1 = l1.next - + return newHead ``` @@ -981,7 +981,7 @@ public class Solution { if (head == null) { return null; } - + Node l1 = head; while (l1 != null) { Node l2 = new Node(l1.val); @@ -1023,7 +1023,7 @@ public: int val; Node* next; Node* random; - + Node(int _val) { val = _val; next = NULL; @@ -1090,7 +1090,7 @@ class Solution { if (!head) { return null; } - + let l1 = head; while (l1) { const l2 = new Node(l1.val); @@ -1131,7 +1131,7 @@ public class Node { public int val; public Node next; public Node random; - + public Node(int _val) { val = _val; next = null; @@ -1145,7 +1145,7 @@ public class Solution { if (head == null) { return null; } - + Node l1 = head; while (l1 != null) { Node l2 = new Node(l1.val); @@ -1266,7 +1266,7 @@ class Solution { while (l1 != null) { val l2 = l1.next l1.next = l2?.next - val nextL2 = l2?.next + val nextL2 = l2?.next if (nextL2 != null) { l2.next = nextL2.next } @@ -1298,7 +1298,7 @@ class Solution { if head == nil { return nil } - + var l1 = head while l1 != nil { let l2 = Node(l1!.val) @@ -1306,7 +1306,7 @@ class Solution { l1?.next = l2 l1 = l2.next } - + let newHead = head?.next l1 = head while l1 != nil { @@ -1315,7 +1315,7 @@ class Solution { } l1 = l1?.next?.next } - + l1 = head while l1 != nil { let l2 = l1?.next @@ -1325,7 +1325,7 @@ class Solution { } l1 = l1?.next } - + return newHead } } @@ -1335,10 +1335,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ for the output. +- Time complexity: $O(n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ for the output. --- @@ -1367,15 +1367,15 @@ class Solution: l2.next = l1.random l1.random = l2 l1 = l1.next - + newHead = head.random - + l1 = head while l1: l2 = l1.random l2.random = l2.next.random if l2.next else None l1 = l1.next - + l1 = head while l1 is not None: l2 = l1.random @@ -1446,7 +1446,7 @@ public: int val; Node* next; Node* random; - + Node(int _val) { val = _val; next = NULL; @@ -1548,7 +1548,7 @@ public class Node { public int val; public Node next; public Node random; - + public Node(int _val) { val = _val; next = null; @@ -1752,7 +1752,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ for the output. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ for the output. diff --git a/articles/count-all-valid-pickup-and-delivery-options.md b/articles/count-all-valid-pickup-and-delivery-options.md index 78b58d069..cb4cccaaa 100644 --- a/articles/count-all-valid-pickup-and-delivery-options.md +++ b/articles/count-all-valid-pickup-and-delivery-options.md @@ -95,7 +95,9 @@ class Solution { res = (res + (n - picked) * dfs(picked + 1, delivered)) % MOD; } if (delivered < picked) { - res = (res + (picked - delivered) * dfs(picked, delivered + 1)) % MOD; + res = + (res + (picked - delivered) * dfs(picked, delivered + 1)) % + MOD; } return res; @@ -110,8 +112,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -230,7 +232,9 @@ class Solution { res = (res + (n - picked) * dfs(picked + 1, delivered)) % MOD; } if (delivered < picked) { - res = (res + (picked - delivered) * dfs(picked, delivered + 1)) % MOD; + res = + (res + (picked - delivered) * dfs(picked, delivered + 1)) % + MOD; } dp[picked][delivered] = res; @@ -246,8 +250,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -289,11 +293,11 @@ public class Solution { for (int picked = 0; picked <= n; picked++) { for (int delivered = 0; delivered <= n; delivered++) { if (picked < n) { - dp[picked + 1][delivered] = (int) ((dp[picked + 1][delivered] + + dp[picked + 1][delivered] = (int) ((dp[picked + 1][delivered] + (n - picked) * 1L * dp[picked][delivered]) % MOD); } if (delivered < picked) { - dp[picked][delivered + 1] = (int) ((dp[picked][delivered + 1] + + dp[picked][delivered + 1] = (int) ((dp[picked][delivered + 1] + (picked - delivered) * 1L * dp[picked][delivered]) % MOD); } } @@ -315,11 +319,11 @@ public: for (int picked = 0; picked <= n; picked++) { for (int delivered = 0; delivered <= n; delivered++) { if (picked < n) { - dp[picked + 1][delivered] = (dp[picked + 1][delivered] + + dp[picked + 1][delivered] = (dp[picked + 1][delivered] + (n - picked) * 1LL * dp[picked][delivered]) % MOD; } if (delivered < picked) { - dp[picked][delivered + 1] = (dp[picked][delivered + 1] + + dp[picked][delivered + 1] = (dp[picked][delivered + 1] + (picked - delivered) * 1LL * dp[picked][delivered]) % MOD; } } @@ -344,17 +348,17 @@ class Solution { for (let picked = 0; picked <= n; picked++) { for (let delivered = 0; delivered <= n; delivered++) { if (picked < n) { - dp[picked + 1][delivered] = ( + dp[picked + 1][delivered] = (dp[picked + 1][delivered] + - (n - picked) * dp[picked][delivered]) % MOD - ); + (n - picked) * dp[picked][delivered]) % + MOD; } if (delivered < picked) { - dp[picked][delivered + 1] = ( - (dp[picked][delivered + 1] + - (picked - delivered) * dp[picked][delivered]) % MOD - ); + dp[picked][delivered + 1] = + (dp[picked][delivered + 1] + + (picked - delivered) * dp[picked][delivered]) % + MOD; } } } @@ -368,8 +372,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -412,14 +416,14 @@ public class Solution { for (int picked = 0; picked <= n; picked++) { for (int delivered = 0; delivered < picked; delivered++) { - dp[delivered + 1] = (int)((dp[delivered + 1] + + dp[delivered + 1] = (int)((dp[delivered + 1] + (picked - delivered) * 1L * dp[delivered]) % MOD); } if (picked < n) { int[] next_dp = new int[n + 1]; for (int delivered = 0; delivered <= picked; delivered++) { - next_dp[delivered] = (int)((next_dp[delivered] + + next_dp[delivered] = (int)((next_dp[delivered] + (n - picked) * 1L *dp[delivered]) % MOD); } dp = next_dp; @@ -441,13 +445,13 @@ public: for (int picked = 0; picked <= n; picked++) { for (int delivered = 0; delivered < picked; delivered++) { - dp[delivered + 1] = (int)((dp[delivered + 1] + + dp[delivered + 1] = (int)((dp[delivered + 1] + (picked - delivered) * 1LL * dp[delivered]) % MOD); } if (picked < n) { vector next_dp(n + 1); for (int delivered = 0; delivered <= picked; delivered++) { - next_dp[delivered] = (int)((next_dp[delivered] + + next_dp[delivered] = (int)((next_dp[delivered] + (n - picked) * 1LL * dp[delivered]) % MOD); } dp = next_dp; @@ -472,19 +476,17 @@ class Solution { for (let picked = 0; picked <= n; picked++) { for (let delivered = 0; delivered < picked; delivered++) { - dp[delivered + 1] = ( - (dp[delivered + 1] + - (picked - delivered) * dp[delivered]) % MOD - ); + dp[delivered + 1] = + (dp[delivered + 1] + (picked - delivered) * dp[delivered]) % + MOD; } - + if (picked < n) { let next_dp = new Array(n + 1).fill(0); for (let delivered = 0; delivered <= picked; delivered++) { - next_dp[delivered] = ( - (next_dp[delivered] + - (n - picked) * dp[delivered]) % MOD - ); + next_dp[delivered] = + (next_dp[delivered] + (n - picked) * dp[delivered]) % + MOD; } dp = next_dp; } @@ -499,8 +501,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -561,7 +563,8 @@ class Solution { */ countOrders(n) { const MOD = 1000000007; - let slots = 2 * n, res = 1; + let slots = 2 * n, + res = 1; while (slots > 0) { let validChoices = (slots * (slots - 1)) / 2; @@ -577,8 +580,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -664,5 +667,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/count-connected-components.md b/articles/count-connected-components.md index c31580864..6027f2b24 100644 --- a/articles/count-connected-components.md +++ b/articles/count-connected-components.md @@ -16,7 +16,7 @@ class Solution: if not visit[nei]: visit[nei] = True dfs(nei) - + res = 0 for node in range(n): if not visit[node]: @@ -234,13 +234,13 @@ class Solution { func countComponents(_ n: Int, _ edges: [[Int]]) -> Int { var adj = Array(repeating: [Int](), count: n) var visit = Array(repeating: false, count: n) - + for edge in edges { let u = edge[0], v = edge[1] adj[u].append(v) adj[v].append(u) } - + func dfs(_ node: Int) { for nei in adj[node] { if !visit[nei] { @@ -249,7 +249,7 @@ class Solution { } } } - + var res = 0 for node in 0.. Where $V$ is the number of vertices and $E$ is the number of edges in the graph. @@ -297,7 +297,7 @@ class Solution: if not visit[nei]: visit[nei] = True q.append(nei) - + res = 0 for node in range(n): if not visit[node]: @@ -483,11 +483,11 @@ func countComponents(n int, edges [][]int) int { visit[node] = true for len(q) > 0 { cur := q[0] - q = q[1:] + q = q[1:] for _, nei := range adj[cur] { if !visit[nei] { visit[nei] = true - q = append(q, nei) + q = append(q, nei) } } } @@ -551,7 +551,7 @@ class Solution { adj[u].append(v) adj[v].append(u) } - + func bfs(_ node: Int) { var q = Deque() q.append(node) @@ -566,7 +566,7 @@ class Solution { } } } - + var res = 0 for node in 0.. Where $V$ is the number of vertices and $E$ is the number of edges in the graph. @@ -954,12 +954,12 @@ class Solution { class DSU { var parent: [Int] var rank: [Int] - + init(_ n: Int) { parent = Array(0.. Int { var cur = node while cur != parent[cur] { @@ -968,7 +968,7 @@ class DSU { } return cur } - + func union(_ u: Int, _ v: Int) -> Bool { let pu = find(u) let pv = find(v) @@ -1003,7 +1003,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + (E * α(V)))$ -* Space complexity: $O(V)$ +- Time complexity: $O(V + (E * α(V)))$ +- Space complexity: $O(V)$ -> Where $V$ is the number of vertices and $E$ is the number of edges in the graph. $α()$ is used for amortized complexity. \ No newline at end of file +> Where $V$ is the number of vertices and $E$ is the number of edges in the graph. $α()$ is used for amortized complexity. diff --git a/articles/count-good-nodes-in-binary-tree.md b/articles/count-good-nodes-in-binary-tree.md index d9356f32c..f1d78248e 100644 --- a/articles/count-good-nodes-in-binary-tree.md +++ b/articles/count-good-nodes-in-binary-tree.md @@ -44,7 +44,7 @@ class Solution: */ class Solution { - + public int goodNodes(TreeNode root) { return dfs(root, root.val); } @@ -153,7 +153,7 @@ class Solution { */ public class Solution { - + public int GoodNodes(TreeNode root) { return Dfs(root, root.val); } @@ -196,11 +196,11 @@ func goodNodes(root *TreeNode) int { if node.Val >= maxVal { res = 1 } - + maxVal = max(maxVal, node.Val) res += dfs(node.Left, maxVal) res += dfs(node.Right, maxVal) - + return res } @@ -287,8 +287,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -308,20 +308,20 @@ class Solution: def goodNodes(self, root: TreeNode) -> int: res = 0 q = deque() - + q.append((root,-float('inf'))) while q: node,maxval = q.popleft() - if node.val >= maxval: + if node.val >= maxval: res += 1 - - if node.left: + + if node.left: q.append((node.left,max(maxval,node.val))) - + if node.right: q.append((node.right,max(maxval,node.val))) - + return res ``` @@ -627,5 +627,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/count-number-of-bad-pairs.md b/articles/count-number-of-bad-pairs.md index 936e3af7f..7f5cee56e 100644 --- a/articles/count-number-of-bad-pairs.md +++ b/articles/count-number-of-bad-pairs.md @@ -55,7 +55,8 @@ class Solution { * @return {number} */ countBadPairs(nums) { - let n = nums.length, res = 0; + let n = nums.length, + res = 0; for (let i = 0; i < n - 1; i++) { for (let j = i + 1; j < n; j++) { if (j - i !== nums[j] - nums[i]) { @@ -72,8 +73,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -137,7 +138,8 @@ class Solution { */ countBadPairs(nums) { let count = new Map(); - let total = 0, good = 0; + let total = 0, + good = 0; for (let i = 0; i < nums.length; i++) { let key = nums[i] - i; good += count.get(key) || 0; @@ -153,5 +155,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/count-number-of-islands.md b/articles/count-number-of-islands.md index 042d79082..8b5a4322f 100644 --- a/articles/count-number-of-islands.md +++ b/articles/count-number-of-islands.md @@ -10,11 +10,11 @@ class Solution: islands = 0 def dfs(r, c): - if (r < 0 or c < 0 or r >= ROWS or + if (r < 0 or c < 0 or r >= ROWS or c >= COLS or grid[r][c] == "0" ): return - + grid[r][c] = "0" for dr, dc in directions: dfs(r + dr, c + dc) @@ -30,13 +30,13 @@ class Solution: ```java public class Solution { - private static final int[][] directions = {{1, 0}, {-1, 0}, + private static final int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; - + public int numIslands(char[][] grid) { int ROWS = grid.length, COLS = grid[0].length; int islands = 0; - + for (int r = 0; r < ROWS; r++) { for (int c = 0; c < COLS; c++) { if (grid[r][c] == '1') { @@ -45,16 +45,16 @@ public class Solution { } } } - + return islands; } - + private void dfs(char[][] grid, int r, int c) { - if (r < 0 || c < 0 || r >= grid.length || + if (r < 0 || c < 0 || r >= grid.length || c >= grid[0].length || grid[r][c] == '0') { return; } - + grid[r][c] = '0'; for (int[] dir : directions) { dfs(grid, r + dir[0], c + dir[1]); @@ -79,16 +79,16 @@ public: } } } - + return islands; } - + void dfs(vector>& grid, int r, int c) { - if (r < 0 || c < 0 || r >= grid.size() || + if (r < 0 || c < 0 || r >= grid.size() || c >= grid[0].size() || grid[r][c] == '0') { return; } - + grid[r][c] = '0'; for (int i = 0; i < 4; i++) { dfs(grid, r + directions[i][0], c + directions[i][1]); @@ -104,14 +104,20 @@ class Solution { * @return {number} */ numIslands(grid) { - const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; - const ROWS = grid.length, COLS = grid[0].length; + const directions = [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + ]; + const ROWS = grid.length, + COLS = grid[0].length; let islands = 0; const dfs = (r, c) => { - if (r < 0 || c < 0 || r >= ROWS || - c >= COLS || grid[r][c] === '0') return; - + if (r < 0 || c < 0 || r >= ROWS || c >= COLS || grid[r][c] === '0') + return; + grid[r][c] = '0'; for (const [dr, dc] of directions) { dfs(r + dr, c + dc); @@ -135,10 +141,10 @@ class Solution { ```csharp public class Solution { private static readonly int[][] directions = new int[][] { - new int[] {1, 0}, new int[] {-1, 0}, + new int[] {1, 0}, new int[] {-1, 0}, new int[] {0, 1}, new int[] {0, -1} }; - + public int NumIslands(char[][] grid) { int ROWS = grid.Length, COLS = grid[0].Length; int islands = 0; @@ -156,7 +162,7 @@ public class Solution { } private void Dfs(char[][] grid, int r, int c) { - if (r < 0 || c < 0 || r >= grid.Length || + if (r < 0 || c < 0 || r >= grid.Length || c >= grid[0].Length || grid[r][c] == '0') { return; } @@ -177,7 +183,7 @@ func numIslands(grid [][]byte) int { var dfs func(r, c int) dfs = func(r, c int) { - if r < 0 || c < 0 || r >= rows || + if r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] == '0' { return } @@ -203,16 +209,16 @@ func numIslands(grid [][]byte) int { ```kotlin class Solution { fun numIslands(grid: Array): Int { - val directions = arrayOf(intArrayOf(1, 0), - intArrayOf(-1, 0), - intArrayOf(0, 1), + val directions = arrayOf(intArrayOf(1, 0), + intArrayOf(-1, 0), + intArrayOf(0, 1), intArrayOf(0, -1)) val rows = grid.size val cols = grid[0].size var islands = 0 fun dfs(r: Int, c: Int) { - if (r < 0 || c < 0 || r >= rows || + if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] == '0') { return } @@ -274,8 +280,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns in the $grid$. @@ -298,7 +304,7 @@ class Solution: q.append((r, c)) while q: - row, col = q.popleft() + row, col = q.popleft() for dr, dc in directions: nr, nc = dr + row, dc + col if (nr < 0 or nc < 0 or nr >= ROWS or @@ -319,13 +325,13 @@ class Solution: ```java public class Solution { - private static final int[][] directions = {{1, 0}, {-1, 0}, + private static final int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; - + public int numIslands(char[][] grid) { int ROWS = grid.length, COLS = grid[0].length; int islands = 0; - + for (int r = 0; r < ROWS; r++) { for (int c = 0; c < COLS; c++) { if (grid[r][c] == '1') { @@ -334,22 +340,22 @@ public class Solution { } } } - + return islands; } - + private void bfs(char[][] grid, int r, int c) { Queue q = new LinkedList<>(); grid[r][c] = '0'; q.add(new int[]{r, c}); - + while (!q.isEmpty()) { int[] node = q.poll(); int row = node[0], col = node[1]; - + for (int[] dir : directions) { int nr = row + dir[0], nc = col + dir[1]; - if (nr >= 0 && nc >= 0 && nr < grid.length && + if (nr >= 0 && nc >= 0 && nr < grid.length && nc < grid[0].length && grid[nr][nc] == '1') { q.add(new int[]{nr, nc}); grid[nr][nc] = '0'; @@ -362,7 +368,7 @@ public class Solution { ```cpp class Solution { - int directions[4][2] = {{1, 0}, {-1, 0}, + int directions[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; public: int numIslands(vector>& grid) { @@ -392,7 +398,7 @@ public: for (int i = 0; i < 4; i++) { int nr = row + directions[i][0]; int nc = col + directions[i][1]; - if (nr >= 0 && nc >= 0 && nr < grid.size() && + if (nr >= 0 && nc >= 0 && nr < grid.size() && nc < grid[0].size() && grid[nr][nc] == '1') { q.push({nr, nc}); grid[nr][nc] = '0'; @@ -410,21 +416,33 @@ class Solution { * @return {number} */ numIslands(grid) { - const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; - const ROWS = grid.length, COLS = grid[0].length; + const directions = [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + ]; + const ROWS = grid.length, + COLS = grid[0].length; let islands = 0; const bfs = (r, c) => { const q = new Queue(); q.push([r, c]); grid[r][c] = '0'; - + while (!q.isEmpty()) { const [row, col] = q.pop(); for (const [dr, dc] of directions) { - const nr = row + dr, nc = col + dc; - if (nr >= 0 && nc >= 0 && nr < ROWS && - nc < COLS && grid[nr][nc] === '1') { + const nr = row + dr, + nc = col + dc; + if ( + nr >= 0 && + nc >= 0 && + nr < ROWS && + nc < COLS && + grid[nr][nc] === '1' + ) { q.push([nr, nc]); grid[nr][nc] = '0'; } @@ -449,7 +467,7 @@ class Solution { ```csharp public class Solution { private static readonly int[][] directions = new int[][] { - new int[] {1, 0}, new int[] {-1, 0}, + new int[] {1, 0}, new int[] {-1, 0}, new int[] {0, 1}, new int[] {0, -1} }; @@ -480,7 +498,7 @@ public class Solution { foreach (var dir in directions) { int nr = row + dir[0], nc = col + dir[1]; - if (nr >= 0 && nc >= 0 && nr < grid.Length && + if (nr >= 0 && nc >= 0 && nr < grid.Length && nc < grid[0].Length && grid[nr][nc] == '1') { q.Enqueue(new int[] { nr, nc }); grid[nr][nc] = '0'; @@ -508,7 +526,7 @@ func numIslands(grid [][]byte) int { row, col := front[0], front[1] for _, dir := range directions { nr, nc := row+dir[0], col+dir[1] - if nr < 0 || nc < 0 || nr >= rows || + if nr < 0 || nc < 0 || nr >= rows || nc >= cols || grid[nr][nc] == '0' { continue } @@ -534,9 +552,9 @@ func numIslands(grid [][]byte) int { ```kotlin class Solution { fun numIslands(grid: Array): Int { - val directions = arrayOf(intArrayOf(1, 0), - intArrayOf(-1, 0), - intArrayOf(0, 1), + val directions = arrayOf(intArrayOf(1, 0), + intArrayOf(-1, 0), + intArrayOf(0, 1), intArrayOf(0, -1)) val rows = grid.size val cols = grid[0].size @@ -552,7 +570,7 @@ class Solution { for (dir in directions) { val nr = row + dir[0] val nc = col + dir[1] - if (nr < 0 || nc < 0 || nr >= rows || + if (nr < 0 || nc < 0 || nr >= rows || nc >= cols || grid[nr][nc] == '0') { continue } @@ -622,8 +640,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns in the $grid$. @@ -678,7 +696,7 @@ class Solution: nc >= COLS or grid[nr][nc] == "0" ): continue - + if dsu.union(index(r, c), index(nr, nc)): islands -= 1 @@ -736,7 +754,7 @@ public class Solution { for (int[] d : directions) { int nr = r + d[0]; int nc = c + d[1]; - if (nr >= 0 && nc >= 0 && nr < ROWS && + if (nr >= 0 && nc >= 0 && nr < ROWS && nc < COLS && grid[nr][nc] == '1') { if (dsu.union(r * COLS + c, nr * COLS + nc)) { islands--; @@ -808,7 +826,7 @@ public: for (auto& d : directions) { int nr = r + d[0]; int nc = c + d[1]; - if (nr >= 0 && nc >= 0 && nr < ROWS && + if (nr >= 0 && nc >= 0 && nr < ROWS && nc < COLS && grid[nr][nc] == '1') { if (dsu.unionBySize(index(r, c), index(nr, nc))) { islands--; @@ -827,7 +845,9 @@ public: ```javascript class DSU { constructor(n) { - this.Parent = Array(n + 1).fill(0).map((_, i) => i); + this.Parent = Array(n + 1) + .fill(0) + .map((_, i) => i); this.Size = Array(n + 1).fill(1); } @@ -873,7 +893,10 @@ class Solution { const dsu = new DSU(ROWS * COLS); const directions = [ - [1, 0], [-1, 0], [0, 1], [0, -1] + [1, 0], + [-1, 0], + [0, 1], + [0, -1], ]; let islands = 0; @@ -885,9 +908,15 @@ class Solution { if (grid[r][c] === '1') { islands++; for (let [dr, dc] of directions) { - let nr = r + dr, nc = c + dc; - if (nr >= 0 && nc >= 0 && nr < ROWS && - nc < COLS && grid[nr][nc] === '1') { + let nr = r + dr, + nc = c + dc; + if ( + nr >= 0 && + nc >= 0 && + nr < ROWS && + nc < COLS && + grid[nr][nc] === '1' + ) { if (dsu.union(index(r, c), index(nr, nc))) { islands--; } @@ -944,7 +973,7 @@ public class Solution { DSU dsu = new DSU(ROWS * COLS); int[][] directions = new int[][] { - new int[] { 1, 0 }, new int[] { -1, 0 }, + new int[] { 1, 0 }, new int[] { -1, 0 }, new int[] { 0, 1 }, new int[] { 0, -1 } }; int islands = 0; @@ -956,7 +985,7 @@ public class Solution { foreach (var d in directions) { int nr = r + d[0]; int nc = c + d[1]; - if (nr >= 0 && nc >= 0 && nr < ROWS && + if (nr >= 0 && nc >= 0 && nr < ROWS && nc < COLS && grid[nr][nc] == '1') { if (dsu.Union(r * COLS + c, nr * COLS + nc)) { islands--; @@ -1029,7 +1058,7 @@ func numIslands(grid [][]byte) int { islands++ for _, dir := range directions { nr, nc := r+dir[0], c+dir[1] - if nr < 0 || nc < 0 || nr >= rows || + if nr < 0 || nc < 0 || nr >= rows || nc >= cols || grid[nr][nc] == '0' { continue } @@ -1077,9 +1106,9 @@ class Solution { val rows = grid.size val cols = grid[0].size val dsu = DSU(rows * cols) - val directions = arrayOf(intArrayOf(1, 0), - intArrayOf(-1, 0), - intArrayOf(0, 1), + val directions = arrayOf(intArrayOf(1, 0), + intArrayOf(-1, 0), + intArrayOf(0, 1), intArrayOf(0, -1)) var islands = 0 @@ -1094,7 +1123,7 @@ class Solution { for (dir in directions) { val nr = r + dir[0] val nc = c + dir[1] - if (nr < 0 || nc < 0 || nr >= rows || + if (nr < 0 || nc < 0 || nr >= rows || nc >= cols || grid[nr][nc] == '0') { continue } @@ -1186,7 +1215,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ -> Where $m$ is the number of rows and $n$ is the number of columns in the $grid$. \ No newline at end of file +> Where $m$ is the number of rows and $n$ is the number of columns in the $grid$. diff --git a/articles/count-odd-numbers-in-an-interval-range.md b/articles/count-odd-numbers-in-an-interval-range.md index 1cbaf37b8..ffdbd3fbe 100644 --- a/articles/count-odd-numbers-in-an-interval-range.md +++ b/articles/count-odd-numbers-in-an-interval-range.md @@ -64,8 +64,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ > Where $n$ is the number of integers in the given range. @@ -134,8 +134,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ --- @@ -183,5 +183,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ diff --git a/articles/count-of-matches-in-tournament.md b/articles/count-of-matches-in-tournament.md index 2ceeeae80..07623949f 100644 --- a/articles/count-of-matches-in-tournament.md +++ b/articles/count-of-matches-in-tournament.md @@ -68,8 +68,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ --- @@ -116,5 +116,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ diff --git a/articles/count-paths.md b/articles/count-paths.md index 5db166df2..fd59ec46a 100644 --- a/articles/count-paths.md +++ b/articles/count-paths.md @@ -5,14 +5,14 @@ ```python class Solution: def uniquePaths(self, m: int, n: int) -> int: - + def dfs(i, j): if i == (m - 1) and j == (n - 1): return 1 if i >= m or j >= n: return 0 return dfs(i, j + 1) + dfs(i + 1, j) - + return dfs(0, 0) ``` @@ -27,7 +27,7 @@ public class Solution { return 1; } if (i >= m || j >= n) return 0; - return dfs(i, j + 1, m, n) + + return dfs(i, j + 1, m, n) + dfs(i + 1, j, m, n); } } @@ -45,7 +45,7 @@ public: return 1; } if (i >= m || j >= n) return 0; - return dfs(i, j + 1, m, n) + + return dfs(i, j + 1, m, n) + dfs(i + 1, j, m, n); } }; @@ -59,14 +59,13 @@ class Solution { * @return {number} */ uniquePaths(m, n) { - const dfs = (i, j) => { - if (i == (m - 1) && j == (n - 1)) { + if (i == m - 1 && j == n - 1) { return 1; } if (i >= m || j >= n) return 0; return dfs(i, j + 1) + dfs(i + 1, j); - } + }; return dfs(0, 0); } @@ -84,7 +83,7 @@ public class Solution { return 1; } if (i >= m || j >= n) return 0; - return Dfs(i, j + 1, m, n) + + return Dfs(i, j + 1, m, n) + Dfs(i + 1, j, m, n); } } @@ -102,7 +101,7 @@ func uniquePaths(m int, n int) int { } return dfs(i, j+1) + dfs(i+1, j) } - + return dfs(0, 0) } ``` @@ -115,7 +114,7 @@ class Solution { if (i >= m || j >= n) return 0 return dfs(i, j + 1) + dfs(i + 1, j) } - + return dfs(0, 0) } } @@ -143,8 +142,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ {m + n})$ -* Space complexity: $O(m + n)$ +- Time complexity: $O(2 ^ {m + n})$ +- Space complexity: $O(m + n)$ > Where $m$ is the number of rows and $n$ is the number of columns. @@ -165,10 +164,10 @@ class Solution: return 0 if memo[i][j] != -1: return memo[i][j] - + memo[i][j] = dfs(i, j + 1) + dfs(i + 1, j) return memo[i][j] - + return dfs(0, 0) ``` @@ -191,7 +190,7 @@ public class Solution { if (memo[i][j] != -1) { return memo[i][j]; } - return memo[i][j] = dfs(i, j + 1, m, n) + + return memo[i][j] = dfs(i, j + 1, m, n) + dfs(i + 1, j, m, n); } } @@ -214,7 +213,7 @@ public: if (memo[i][j] != -1) { return memo[i][j]; } - return memo[i][j] = dfs(i, j + 1, m, n) + + return memo[i][j] = dfs(i, j + 1, m, n) + dfs(i + 1, j, m, n); } }; @@ -228,10 +227,9 @@ class Solution { * @return {number} */ uniquePaths(m, n) { - const memo = Array.from({ length: m }, () => - Array(n).fill(-1)); + const memo = Array.from({ length: m }, () => Array(n).fill(-1)); const dfs = (i, j) => { - if (i == (m - 1) && j == (n - 1)) { + if (i == m - 1 && j == n - 1) { return 1; } if (i >= m || j >= n) return 0; @@ -240,7 +238,7 @@ class Solution { } memo[i][j] = dfs(i, j + 1) + dfs(i + 1, j); return memo[i][j]; - } + }; return dfs(0, 0); } @@ -267,7 +265,7 @@ public class Solution { if (memo[i, j] != -1) { return memo[i, j]; } - return memo[i, j] = Dfs(i, j + 1, m, n) + + return memo[i, j] = Dfs(i, j + 1, m, n) + Dfs(i + 1, j, m, n); } } @@ -294,11 +292,11 @@ func uniquePaths(m int, n int) int { if memo[i][j] != -1 { return memo[i][j] } - + memo[i][j] = dfs(i, j+1) + dfs(i+1, j) return memo[i][j] } - + return dfs(0, 0) } ``` @@ -351,8 +349,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns. @@ -418,8 +416,7 @@ class Solution { * @return {number} */ uniquePaths(m, n) { - let dp = Array.from({ length: m + 1 }, () => - Array(n + 1).fill(0)); + let dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)); dp[m - 1][n - 1] = 1; for (let i = m - 1; i >= 0; i--) { @@ -506,8 +503,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns. @@ -597,7 +594,7 @@ public class Solution { for (int i = 0; i < m - 1; i++) { var newRow = new int[n]; Array.Fill(newRow, 1); - for (int j = n - 2; j >=0; j--) { + for (int j = n - 2; j >=0; j--) { newRow[j] = newRow[j + 1] + row[j]; } row = newRow; @@ -666,8 +663,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(n)$ > Where $m$ is the number of rows and $n$ is the number of columns. @@ -684,7 +681,7 @@ class Solution: for i in range(m - 2, -1, -1): for j in range(n - 2, -1, -1): dp[j] += dp[j + 1] - + return dp[0] ``` @@ -693,13 +690,13 @@ public class Solution { public int uniquePaths(int m, int n) { int[] dp = new int[n]; Arrays.fill(dp, 1); - + for (int i = m - 2; i >= 0; i--) { for (int j = n - 2; j >= 0; j--) { dp[j] += dp[j + 1]; } } - + return dp[0]; } } @@ -710,13 +707,13 @@ class Solution { public: int uniquePaths(int m, int n) { vector dp(n, 1); - + for (int i = m - 2; i >= 0; i--) { for (int j = n - 2; j >= 0; j--) { dp[j] += dp[j + 1]; } } - + return dp[0]; } }; @@ -731,13 +728,13 @@ class Solution { */ uniquePaths(m, n) { let dp = new Array(n).fill(1); - + for (let i = m - 2; i >= 0; i--) { for (let j = n - 2; j >= 0; j--) { dp[j] += dp[j + 1]; } } - + return dp[0]; } } @@ -748,13 +745,13 @@ public class Solution { public int UniquePaths(int m, int n) { int[] dp = new int[n]; Array.Fill(dp, 1); - + for (int i = m - 2; i >= 0; i--) { for (int j = n - 2; j >= 0; j--) { dp[j] += dp[j + 1]; } } - + return dp[0]; } } @@ -813,8 +810,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(n)$ > Where $m$ is the number of rows and $n$ is the number of columns. @@ -905,7 +902,8 @@ class Solution { [m, n] = [n, m]; } - let res = 1, j = 1; + let res = 1, + j = 1; for (let i = m; i < m + n - 1; i++) { res *= i; res = Math.floor(res / j); @@ -983,7 +981,7 @@ class Solution { res /= j j++ } - + return res.toInt() } } @@ -1017,7 +1015,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(min(m, n))$ -* Space complexity: $O(1)$ +- Time complexity: $O(min(m, n))$ +- Space complexity: $O(1)$ -> Where $m$ is the number of rows and $n$ is the number of columns. \ No newline at end of file +> Where $m$ is the number of rows and $n$ is the number of columns. diff --git a/articles/count-squares.md b/articles/count-squares.md index 1b5defe8c..b1d133d73 100644 --- a/articles/count-squares.md +++ b/articles/count-squares.md @@ -46,7 +46,7 @@ public class CountSquares { if (Math.abs(py - y) != Math.abs(px - x) || x == px || y == py) { continue; } - res += ptsCount.getOrDefault(Arrays.asList(x, py), 0) * + res += ptsCount.getOrDefault(Arrays.asList(x, py), 0) * ptsCount.getOrDefault(Arrays.asList(px, y), 0); } return res; @@ -70,10 +70,10 @@ public: void add(vector point) { long key = getKey(point[0], point[1]); - ptsCount[key]++; - pts.push_back(point); + ptsCount[key]++; + pts.push_back(point); } - + int count(vector point) { int res = 0; int px = point[0], py = point[1]; @@ -139,7 +139,7 @@ public class CountSquares { var tuplePoint = (point[0], point[1]); if (!ptsCount.ContainsKey(tuplePoint)) ptsCount[tuplePoint] = 0; - + ptsCount[tuplePoint]++; pts.Add(point); } @@ -148,7 +148,7 @@ public class CountSquares { int res = 0; int px = point[0]; int py = point[1]; - + foreach (var pt in pts) { int x = pt[0]; int y = pt[1]; @@ -156,7 +156,7 @@ public class CountSquares { if (Math.Abs(py - y) != Math.Abs(px - x) || x == px || y == py) continue; - res += (ptsCount.GetValueOrDefault((x, py)) * + res += (ptsCount.GetValueOrDefault((x, py)) * ptsCount.GetValueOrDefault((px, y))); } return res; @@ -195,13 +195,13 @@ func (this *CountSquares) Count(point []int) int { if abs(py-pt.y) != abs(px-pt.x) || pt.x == px || pt.y == py { continue } - + p1 := Point{pt.x, py} p2 := Point{px, pt.y} - + res += this.ptsCount[p1] * this.ptsCount[p2] } - + return res } @@ -229,7 +229,7 @@ class CountSquares() { val (px, py) = point for ((x, y) in points) { - if (kotlin.math.abs(py - y) != kotlin.math.abs(px - x) || + if (kotlin.math.abs(py - y) != kotlin.math.abs(px - x) || x == px || y == py) { continue } @@ -278,8 +278,8 @@ class CountSquares { ### Time & Space Complexity -* Time complexity: $O(1)$ for $add()$, $O(n)$ for $count()$. -* Space complexity: $O(n)$ +- Time complexity: $O(1)$ for $add()$, $O(n)$ for $count()$. +- Space complexity: $O(n)$ --- @@ -357,7 +357,7 @@ class CountSquares { public: CountSquares() {} - + void add(vector point) { ptsCount[point[0]][point[1]]++; } @@ -414,13 +414,15 @@ class CountSquares { const x3 = x1 + side; const x4 = x1 - side; - res += cnt * - (this.ptsCount.get(x3)?.get(y1) || 0) * - (this.ptsCount.get(x3)?.get(y2) || 0); + res += + cnt * + (this.ptsCount.get(x3)?.get(y1) || 0) * + (this.ptsCount.get(x3)?.get(y2) || 0); - res += cnt * - (this.ptsCount.get(x4)?.get(y1) || 0) * - (this.ptsCount.get(x4)?.get(y2) || 0); + res += + cnt * + (this.ptsCount.get(x4)?.get(y1) || 0) * + (this.ptsCount.get(x4)?.get(y2) || 0); } return res; @@ -459,15 +461,15 @@ public class CountSquares { int x3 = x1 + side, x4 = x1 - side; res += cnt * - (ptsCount.ContainsKey(x3) && + (ptsCount.ContainsKey(x3) && ptsCount[x3].ContainsKey(y1) ? ptsCount[x3][y1] : 0) * - (ptsCount.ContainsKey(x3) && + (ptsCount.ContainsKey(x3) && ptsCount[x3].ContainsKey(y2) ? ptsCount[x3][y2] : 0); res += cnt * - (ptsCount.ContainsKey(x4) && + (ptsCount.ContainsKey(x4) && ptsCount[x4].ContainsKey(y1) ? ptsCount[x4][y1] : 0) * - (ptsCount.ContainsKey(x4) && + (ptsCount.ContainsKey(x4) && ptsCount[x4].ContainsKey(y2) ? ptsCount[x4][y2] : 0); } @@ -522,15 +524,15 @@ func (this *CountSquares) Count(point []int) int { ```kotlin class CountSquares { private val points = HashMap>() - + fun add(point: IntArray) { val x = point[0] val y = point[1] - + if (!points.containsKey(x)) { points[x] = hashMapOf() } - + points[x]?.put(y, (points[x]?.get(y) ?: 0) + 1) } @@ -538,19 +540,19 @@ class CountSquares { var result = 0 val x1 = point[0] val y1 = point[1] - + points[x1]?.forEach { (y2, count1) -> if (y2 == y1) return@forEach - + val side = Math.abs(y2 - y1) - + val x3 = x1 + side if (points.containsKey(x3)) { val count2 = points[x3]?.get(y1) ?: 0 val count3 = points[x3]?.get(y2) ?: 0 result += count1 * count2 * count3 } - + val x4 = x1 - side if (points.containsKey(x4)) { val count2 = points[x4]?.get(y1) ?: 0 @@ -558,7 +560,7 @@ class CountSquares { result += count1 * count2 * count3 } } - + return result } } @@ -567,17 +569,17 @@ class CountSquares { ```swift class CountSquares { var ptsCount: [Int: [Int: Int]] - + init() { ptsCount = [:] } - + func add(_ point: [Int]) { let x = point[0] let y = point[1] ptsCount[x, default: [:]][y, default: 0] += 1 } - + func count(_ point: [Int]) -> Int { var res = 0 let x1 = point[0] @@ -602,5 +604,5 @@ class CountSquares { ### Time & Space Complexity -* Time complexity: $O(1)$ for $add()$, $O(n)$ for $count()$. -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(1)$ for $add()$, $O(n)$ for $count()$. +- Space complexity: $O(n)$ diff --git a/articles/count-sub-islands.md b/articles/count-sub-islands.md index 22a7598f7..7f7357ff6 100644 --- a/articles/count-sub-islands.md +++ b/articles/count-sub-islands.md @@ -9,19 +9,19 @@ class Solution: visit = set() def dfs(r, c): - if (min(r, c) < 0 or r == ROWS or c == COLS or + if (min(r, c) < 0 or r == ROWS or c == COLS or grid2[r][c] == 0 or (r, c) in visit): return True - + visit.add((r, c)) res = grid1[r][c] - + res &= dfs(r - 1, c) res &= dfs(r + 1, c) res &= dfs(r, c - 1) res &= dfs(r, c + 1) return res - + count = 0 for r in range(ROWS): for c in range(COLS): @@ -49,7 +49,7 @@ public class Solution { } private boolean dfs(int r, int c, int[][] grid1, int[][] grid2) { - if (r < 0 || c < 0 || r >= grid1.length || c >= grid1[0].length || + if (r < 0 || c < 0 || r >= grid1.length || c >= grid1[0].length || grid2[r][c] == 0 || visit[r][c]) { return true; } @@ -61,7 +61,7 @@ public class Solution { res &= dfs(r, c + 1, grid1, grid2); return res; } - + } ``` @@ -87,7 +87,7 @@ public: private: bool dfs(int r, int c, vector>& grid1, vector>& grid2) { - if (r < 0 || c < 0 || r >= grid1.size() || c >= grid1[0].size() || + if (r < 0 || c < 0 || r >= grid1.size() || c >= grid1[0].size() || grid2[r][c] == 0 || visit[r][c]) { return true; } @@ -111,11 +111,21 @@ class Solution { * @return {number} */ countSubIslands(grid1, grid2) { - const ROWS = grid1.length, COLS = grid1[0].length; - const visit = Array.from({ length: ROWS }, () => Array(COLS).fill(false)); + const ROWS = grid1.length, + COLS = grid1[0].length; + const visit = Array.from({ length: ROWS }, () => + Array(COLS).fill(false), + ); const dfs = (r, c) => { - if (r < 0 || c < 0 || r >= ROWS || c >= COLS || grid2[r][c] === 0 || visit[r][c]) + if ( + r < 0 || + c < 0 || + r >= ROWS || + c >= COLS || + grid2[r][c] === 0 || + visit[r][c] + ) return true; visit[r][c] = true; let res = grid1[r][c] === 1; @@ -143,8 +153,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns. @@ -291,8 +301,11 @@ class Solution { * @return {number} */ countSubIslands(grid1, grid2) { - const ROWS = grid1.length, COLS = grid1[0].length; - const visit = Array.from({ length: ROWS }, () => Array(COLS).fill(false)); + const ROWS = grid1.length, + COLS = grid1[0].length; + const visit = Array.from({ length: ROWS }, () => + Array(COLS).fill(false), + ); const directions = [1, 0, -1, 0, 1]; let count = 0; @@ -306,9 +319,16 @@ class Solution { if (grid1[r][c] === 0) res = false; for (let i = 0; i < 4; i++) { - const nr = r + directions[i], nc = c + directions[i + 1]; - if (nr >= 0 && nr < ROWS && nc >= 0 && nc < COLS && - grid2[nr][nc] === 1 && !visit[nr][nc]) { + const nr = r + directions[i], + nc = c + directions[i + 1]; + if ( + nr >= 0 && + nr < ROWS && + nc >= 0 && + nc < COLS && + grid2[nr][nc] === 1 && + !visit[nr][nc] + ) { visit[nr][nc] = true; queue.push([nr, nc]); } @@ -333,8 +353,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns. @@ -374,7 +394,7 @@ class Solution: def getId(r, c): return r * COLS + c - + land = unions = 0 for r in range(ROWS): for c in range(COLS): @@ -387,7 +407,7 @@ class Solution: unions += dsu.union(getId(r, c), getId(r, c + 1)) if not grid1[r][c]: unions += dsu.union(getId(r, c), N) - + return land - unions ``` @@ -497,7 +517,7 @@ class DSU { this.Parent = Array.from({ length: n + 1 }, (_, i) => i); this.Size = Array(n + 1).fill(1); } - + /** * @param {number} node * @return {number} @@ -515,7 +535,8 @@ class DSU { * @return {boolean} */ union(u, v) { - let pu = this.find(u), pv = this.find(v); + let pu = this.find(u), + pv = this.find(v); if (pu === pv) return false; if (this.Size[pu] < this.Size[pv]) [pu, pv] = [pv, pu]; this.Size[pu] += this.Size[pv]; @@ -531,12 +552,15 @@ class Solution { * @return {number} */ countSubIslands(grid1, grid2) { - const ROWS = grid1.length, COLS = grid1[0].length, N = ROWS * COLS; + const ROWS = grid1.length, + COLS = grid1[0].length, + N = ROWS * COLS; const dsu = new DSU(N); const getId = (r, c) => r * COLS + c; - let land = 0, unions = 0; + let land = 0, + unions = 0; for (let r = 0; r < ROWS; r++) { for (let c = 0; c < COLS; c++) { if (grid2[r][c] === 0) continue; @@ -545,8 +569,7 @@ class Solution { unions += dsu.union(getId(r, c), getId(r + 1, c)); if (c + 1 < COLS && grid2[r][c + 1] === 1) unions += dsu.union(getId(r, c), getId(r, c + 1)); - if (grid1[r][c] === 0) - unions += dsu.union(getId(r, c), N); + if (grid1[r][c] === 0) unions += dsu.union(getId(r, c), N); } } return land - unions; @@ -558,7 +581,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ -> Where $m$ is the number of rows and $n$ is the number of columns. \ No newline at end of file +> Where $m$ is the number of rows and $n$ is the number of columns. diff --git a/articles/count-subarrays-where-max-element-appears-at-least-k-times.md b/articles/count-subarrays-where-max-element-appears-at-least-k-times.md index c4d2a5914..b57ff83d0 100644 --- a/articles/count-subarrays-where-max-element-appears-at-least-k-times.md +++ b/articles/count-subarrays-where-max-element-appears-at-least-k-times.md @@ -13,10 +13,10 @@ class Solution: for j in range(i, n): if nums[j] == maxi: cnt += 1 - + if cnt >= k: res += 1 - + return res ``` @@ -37,7 +37,7 @@ public class Solution { if (nums[j] == maxi) { cnt++; } - + if (cnt >= k) { res++; } @@ -63,7 +63,7 @@ public: if (nums[j] == maxi) { cnt++; } - + if (cnt >= k) { res++; } @@ -83,7 +83,8 @@ class Solution { * @return {number} */ countSubarrays(nums, k) { - let n = nums.length, res = 0; + let n = nums.length, + res = 0; let maxi = Math.max(...nums); for (let i = 0; i < n; i++) { @@ -92,7 +93,7 @@ class Solution { if (nums[j] === maxi) { cnt++; } - + if (cnt >= k) { res++; } @@ -108,8 +109,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -127,15 +128,15 @@ class Solution: for r in range(len(nums)): if nums[r] == max_n: max_cnt += 1 - + while max_cnt > k or (l <= r and max_cnt == k and nums[l] != max_n): if nums[l] == max_n: max_cnt -= 1 l += 1 - + if max_cnt == k: res += l + 1 - + return res ``` @@ -209,7 +210,9 @@ class Solution { */ countSubarrays(nums, k) { let maxN = Math.max(...nums); - let maxCnt = 0, l = 0, res = 0; + let maxCnt = 0, + l = 0, + res = 0; for (let r = 0; r < nums.length; r++) { if (nums[r] === maxN) { @@ -237,8 +240,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -325,7 +328,10 @@ class Solution { * @return {number} */ countSubarrays(nums, k) { - let max_n = Math.max(...nums), max_cnt = 0, l = 0, res = 0; + let max_n = Math.max(...nums), + max_cnt = 0, + l = 0, + res = 0; for (let r = 0; r < nums.length; r++) { if (nums[r] === max_n) { @@ -349,8 +355,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -367,13 +373,13 @@ class Solution: for i, num in enumerate(nums): if num == max_n: max_indexes.append(i) - + res = 0 for i in range(1, len(max_indexes) - k + 1): cur = (max_indexes[i] - max_indexes[i - 1]) cur *= (n - max_indexes[i + k - 1]) res += cur - + return res ``` @@ -452,7 +458,9 @@ class Solution { let res = 0; for (let i = 1; i <= max_indexes.length - k; i++) { - res += (max_indexes[i] - max_indexes[i - 1]) * (n - max_indexes[i + k - 1]); + res += + (max_indexes[i] - max_indexes[i - 1]) * + (n - max_indexes[i + k - 1]); } return res; @@ -464,8 +472,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -483,13 +491,13 @@ class Solution: for i, num in enumerate(nums): if num == max_n: max_indexes.append(i) - + if len(max_indexes) > k: max_indexes.popleft() - + if len(max_indexes) == k: res += max_indexes[0] + 1 - + return res ``` @@ -500,7 +508,7 @@ public class Solution { for (int num : nums) { maxN = Math.max(maxN, num); } - + Queue maxIndexes = new LinkedList<>(); long res = 0; @@ -508,16 +516,16 @@ public class Solution { if (nums[i] == maxN) { maxIndexes.add(i); } - + if (maxIndexes.size() > k) { maxIndexes.poll(); } - + if (maxIndexes.size() == k) { res += maxIndexes.peek() + 1; } } - + return res; } } @@ -535,16 +543,16 @@ public: if (nums[i] == maxN) { maxIndexes.push(i); } - + if (maxIndexes.size() > k) { maxIndexes.pop(); } - + if (maxIndexes.size() == k) { res += maxIndexes.front() + 1; } } - + return res; } }; @@ -566,16 +574,16 @@ class Solution { if (nums[i] === maxN) { maxIndexes.push(i); } - + if (maxIndexes.size() > k) { maxIndexes.pop(); } - + if (maxIndexes.size() === k) { res += maxIndexes.front() + 1; } } - + return res; } } @@ -585,5 +593,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/count-subsequences.md b/articles/count-subsequences.md index 241876a84..30cd51025 100644 --- a/articles/count-subsequences.md +++ b/articles/count-subsequences.md @@ -7,18 +7,18 @@ class Solution: def numDistinct(self, s: str, t: str) -> int: if len(t) > len(s): return 0 - + def dfs(i, j): if j == len(t): return 1 if i == len(s): return 0 - + res = dfs(i + 1, j) if s[i] == t[j]: res += dfs(i + 1, j + 1) return res - + return dfs(0, 0) ``` @@ -87,7 +87,7 @@ class Solution { if (t.length > s.length) { return 0; } - + const dfs = (i, j) => { if (j === t.length) { return 1; @@ -101,7 +101,7 @@ class Solution { res += dfs(i + 1, j + 1); } return res; - } + }; return dfs(0, 0); } @@ -191,7 +191,7 @@ class Solution { func dfs(_ i: Int, _ j: Int) -> Int { if j == tLen { return 1 } if i == sLen { return 0 } - + var res = dfs(i + 1, j) if sArray[i] == tArray[j] { res += dfs(i + 1, j + 1) @@ -208,8 +208,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ m)$ -* Space complexity: $O(m)$ +- Time complexity: $O(2 ^ m)$ +- Space complexity: $O(m)$ > Where $m$ is the length of the string $s$. @@ -224,7 +224,7 @@ class Solution: def numDistinct(self, s: str, t: str) -> int: if len(t) > len(s): return 0 - + dp = {} def dfs(i, j): if j == len(t): @@ -233,7 +233,7 @@ class Solution: return 0 if (i, j) in dp: return dp[(i, j)] - + res = dfs(i + 1, j) if s[i] == t[j]: res += dfs(i + 1, j + 1) @@ -307,10 +307,12 @@ class Solution { * @return {number} */ numDistinct(s, t) { - let m = s.length, n = t.length; + let m = s.length, + n = t.length; if (n > m) return 0; - let dp = Array(m + 1).fill().map(() => - Array(n + 1).fill(-1)); + let dp = Array(m + 1) + .fill() + .map(() => Array(n + 1).fill(-1)); const dfs = (i, j) => { if (j === n) return 1; @@ -323,7 +325,7 @@ class Solution { } dp[i][j] = res; return res; - } + }; return dfs(0, 0); } @@ -369,7 +371,7 @@ func numDistinct(s string, t string) int { dp[i][j] = -1 } } - + var dfs func(i, j int) int dfs = func(i, j int) int { if j == len(t) { @@ -452,8 +454,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the length of the string $s$ and $n$ is the length of the string $t$. @@ -471,13 +473,13 @@ class Solution: for i in range(m + 1): dp[i][n] = 1 - + for i in range(m - 1, -1, -1): for j in range(n - 1, -1, -1): dp[i][j] = dp[i + 1][j] if s[i] == t[j]: dp[i][j] += dp[i + 1][j + 1] - + return dp[0][0] ``` @@ -538,9 +540,9 @@ class Solution { * @return {number} */ numDistinct(s, t) { - let m = s.length, n = t.length; - let dp = Array.from({ length: m + 1 }, () => - Array(n + 1).fill(0)); + let m = s.length, + n = t.length; + let dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)); for (let i = 0; i <= m; i++) { dp[i][n] = 1; @@ -674,8 +676,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the length of the string $s$ and $n$ is the length of the string $t$. @@ -758,7 +760,8 @@ class Solution { * @return {number} */ numDistinct(s, t) { - let m = s.length, n = t.length; + let m = s.length, + n = t.length; let dp = new Array(n + 1).fill(0); let nextDp = new Array(n + 1).fill(0); @@ -817,7 +820,7 @@ func numDistinct(s string, t string) int { nextDp[j] += dp[j+1] } } - dp = append([]int(nil), nextDp...) + dp = append([]int(nil), nextDp...) } return dp[0] @@ -876,7 +879,7 @@ class Solution { } dp = nextDp } - + return dp[0] } } @@ -886,8 +889,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(n)$ > Where $m$ is the length of the string $s$ and $n$ is the length of the string $t$. @@ -912,8 +915,8 @@ class Solution: res += prev prev = dp[j] - dp[j] = res - + dp[j] = res + return dp[0] ``` @@ -936,7 +939,7 @@ public class Solution { dp[j] = res; } } - + return dp[0]; } } @@ -976,7 +979,8 @@ class Solution { * @return {number} */ numDistinct(s, t) { - let m = s.length, n = t.length; + let m = s.length, + n = t.length; let dp = new Array(n + 1).fill(0); dp[n] = 1; @@ -1105,7 +1109,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(n)$ -> Where $m$ is the length of the string $s$ and $n$ is the length of the string $t$. \ No newline at end of file +> Where $m$ is the length of the string $s$ and $n$ is the length of the string $t$. diff --git a/articles/count-the-number-of-consistent-strings.md b/articles/count-the-number-of-consistent-strings.md index 600698357..abbbc5a2c 100644 --- a/articles/count-the-number-of-consistent-strings.md +++ b/articles/count-the-number-of-consistent-strings.md @@ -91,8 +91,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m * l)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n * m * l)$ +- Space complexity: $O(1)$ > Where $n$ is the number of words, $m$ is the length of the string $allowed$, and $l$ is the length of the longest word. @@ -190,8 +190,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * l + m)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n * l + m)$ +- Space complexity: $O(m)$ > Where $n$ is the number of words, $m$ is the length of the string $allowed$, and $l$ is the length of the longest word. @@ -297,8 +297,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * l + m)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n * l + m)$ +- Space complexity: $O(m)$ > Where $n$ is the number of words, $m$ is the length of the string $allowed$, and $l$ is the length of the longest word. @@ -409,7 +409,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * l + m)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n * l + m)$ +- Space complexity: $O(1)$ -> Where $n$ is the number of words, $m$ is the length of the string $allowed$, and $l$ is the length of the longest word. \ No newline at end of file +> Where $n$ is the number of words, $m$ is the length of the string $allowed$, and $l$ is the length of the longest word. diff --git a/articles/count-triplets-that-can-form-two-arrays-of-equal-xor.md b/articles/count-triplets-that-can-form-two-arrays-of-equal-xor.md index 129c14f82..10c0d16c0 100644 --- a/articles/count-triplets-that-can-form-two-arrays-of-equal-xor.md +++ b/articles/count-triplets-that-can-form-two-arrays-of-equal-xor.md @@ -92,7 +92,8 @@ class Solution { for (let i = 0; i < N - 1; i++) { for (let j = i + 1; j < N; j++) { for (let k = j; k < N; k++) { - let a = 0, b = 0; + let a = 0, + b = 0; for (let idx = i; idx < j; idx++) { a ^= arr[idx]; } @@ -115,8 +116,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 4)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n ^ 4)$ +- Space complexity: $O(1)$ extra space. --- @@ -227,8 +228,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 3)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n ^ 3)$ +- Space complexity: $O(1)$ extra space. --- @@ -324,8 +325,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ extra space. --- @@ -405,7 +406,8 @@ class Solution { */ countTriplets(arr) { const N = arr.length; - let res = 0, prefix = 0; + let res = 0, + prefix = 0; const count = new Map(); // number of prefixes const indexSum = new Map(); // sum of indices with that prefix count.set(0, 1); @@ -428,5 +430,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/count-vowel-strings-in-ranges.md b/articles/count-vowel-strings-in-ranges.md index 22c92a839..5e50ee28a 100644 --- a/articles/count-vowel-strings-in-ranges.md +++ b/articles/count-vowel-strings-in-ranges.md @@ -97,10 +97,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: - * $O(1)$ extra space. - * $O(m)$ space for the output list. +- Time complexity: $O(n * m)$ +- Space complexity: + - $O(1)$ extra space. + - $O(m)$ space for the output list. > Where $n$ is the number of words, and $m$ is the number of queries. @@ -217,10 +217,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: - * $O(n)$ extra space. - * $O(m)$ space for the output list. +- Time complexity: $O(n + m)$ +- Space complexity: + - $O(n)$ extra space. + - $O(m)$ space for the output list. > Where $n$ is the number of words, and $m$ is the number of queries. @@ -307,7 +307,7 @@ class Solution { */ vowelStrings(words, queries) { let vowels = 0; - for (let c of "aeiou") { + for (let c of 'aeiou') { vowels |= 1 << (c.charCodeAt(0) - 97); } @@ -315,7 +315,7 @@ class Solution { for (let w of words) { const f = w.charCodeAt(0) - 97; const l = w.charCodeAt(w.length - 1) - 97; - const isVowel = ((1 << f) & vowels) && ((1 << l) & vowels) ? 1 : 0; + const isVowel = (1 << f) & vowels && (1 << l) & vowels ? 1 : 0; prefix.push(prefix[prefix.length - 1] + isVowel); } @@ -328,9 +328,9 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: - * $O(n)$ extra space. - * $O(m)$ space for the output list. +- Time complexity: $O(n + m)$ +- Space complexity: + - $O(n)$ extra space. + - $O(m)$ space for the output list. -> Where $n$ is the number of words, and $m$ is the number of queries. \ No newline at end of file +> Where $n$ is the number of words, and $m$ is the number of queries. diff --git a/articles/count-vowels-permutation.md b/articles/count-vowels-permutation.md index c2f561f56..51b5027c5 100644 --- a/articles/count-vowels-permutation.md +++ b/articles/count-vowels-permutation.md @@ -17,7 +17,7 @@ class Solution: def dfs(i, v): if i == n: return 1 - + total = 0 for nxt in follows[v]: total = (total + dfs(i + 1, nxt)) % MOD @@ -26,7 +26,7 @@ class Solution: res = 0 for vowel in ['a', 'e', 'i', 'o', 'u']: res = (res + dfs(1, vowel)) % MOD - + return res ``` @@ -53,7 +53,7 @@ public class Solution { if (i == n) { return 1; } - + int total = 0; for (char next : follows.get(v)) { total = (total + dfs(i + 1, next, n)) % MOD; @@ -76,7 +76,7 @@ class Solution { public: int countVowelPermutation(int n) { - + int res = 0; for (char vowel : string("aeiou")) { res = (res + dfs(1, vowel, n)) % MOD; @@ -89,7 +89,7 @@ private: if (i == n) { return 1; } - + int total = 0; for (char& next : follows[v]) { total = (total + dfs(i + 1, next, n)) % MOD; @@ -113,14 +113,14 @@ class Solution { e: ['a', 'i'], i: ['a', 'e', 'o', 'u'], o: ['i', 'u'], - u: ['a'] + u: ['a'], }; const dfs = (i, v) => { if (i === n) { return 1; } - + let total = 0; for (const next of follows[v]) { total = (total + dfs(i + 1, next)) % MOD; @@ -142,8 +142,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(4 ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(4 ^ n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -169,7 +169,7 @@ class Solution: return 1 if (i, v) in cache: return cache[(i, v)] - + total = 0 for nxt in follows[v]: total = (total + dfs(i + 1, nxt)) % MOD @@ -179,7 +179,7 @@ class Solution: res = 0 for vowel in ['a', 'e', 'i', 'o', 'u']: res = (res + dfs(1, vowel)) % MOD - + return res ``` @@ -213,7 +213,7 @@ public class Solution { return 1; } if (dp[i][v] != -1) return dp[i][v]; - + int total = 0; for (int next : follows.get(v)) { total = (total + dfs(i + 1, next, n)) % MOD; @@ -271,11 +271,11 @@ class Solution { const dp = Array.from({ length: n }, () => Array(5).fill(-1)); const follows = { - 0: [1], // 'a' -> 'e' - 1: [0, 2], // 'e' -> 'a', 'i' - 2: [0, 1, 3, 4], // 'i' -> 'a', 'e', 'o', 'u' - 3: [2, 4], // 'o' -> 'i', 'u' - 4: [0], // 'u' -> 'a' + 0: [1], // 'a' -> 'e' + 1: [0, 2], // 'e' -> 'a', 'i' + 2: [0, 1, 3, 4], // 'i' -> 'a', 'e', 'o', 'u' + 3: [2, 4], // 'o' -> 'i', 'u' + 4: [0], // 'u' -> 'a' }; const dfs = (i, v) => { @@ -303,8 +303,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -412,11 +412,11 @@ class Solution { const MOD = 1e9 + 7; const dp = Array.from({ length: n + 1 }, () => Array(5).fill(0)); const follows = [ - [1], // 'a' -> 'e' - [0, 2], // 'e' -> 'a', 'i' + [1], // 'a' -> 'e' + [0, 2], // 'e' -> 'a', 'i' [0, 1, 3, 4], // 'i' -> 'a', 'e', 'o', 'u' - [2, 4], // 'o' -> 'i', 'u' - [0] // 'u' -> 'a' + [2, 4], // 'o' -> 'i', 'u' + [0], // 'u' -> 'a' ]; for (let v = 0; v < 5; v++) { @@ -440,8 +440,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -551,11 +551,11 @@ class Solution { countVowelPermutation(n) { const MOD = 1e9 + 7; const follows = [ - [1], // 'a' -> 'e' - [0, 2], // 'e' -> 'a', 'i' + [1], // 'a' -> 'e' + [0, 2], // 'e' -> 'a', 'i' [0, 1, 3, 4], // 'i' -> 'a', 'e', 'o', 'u' - [2, 4], // 'o' -> 'i', 'u' - [0] // 'u' -> 'a' + [2, 4], // 'o' -> 'i', 'u' + [0], // 'u' -> 'a' ]; let dp = [1, 1, 1, 1, 1]; @@ -579,8 +579,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ since we used array of size $5$. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ since we used array of size $5$. --- @@ -805,7 +805,6 @@ class M { } class Solution { - /** * @param {M} * @param {number} exp @@ -834,11 +833,11 @@ class Solution { countVowelPermutation(n) { const MOD = 1e9 + 7; const follows = [ - [0, 1, 0, 0, 0], // 'a' -> 'e' - [1, 0, 1, 0, 0], // 'e' -> 'a', 'i' - [1, 1, 0, 1, 1], // 'i' -> 'a', 'e', 'o', 'u' - [0, 0, 1, 0, 1], // 'o' -> 'i', 'u' - [1, 0, 0, 0, 0] // 'u' -> 'a' + [0, 1, 0, 0, 0], // 'a' -> 'e' + [1, 0, 1, 0, 0], // 'e' -> 'a', 'i' + [1, 1, 0, 1, 1], // 'i' -> 'a', 'e', 'o', 'u' + [0, 0, 1, 0, 1], // 'o' -> 'i', 'u' + [1, 0, 0, 0, 0], // 'u' -> 'a' ]; const base = new M(5); base.a = follows; @@ -858,7 +857,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m ^ 3 \log n)$ -* Space complexity: $O(m ^ 2)$ +- Time complexity: $O(m ^ 3 \log n)$ +- Space complexity: $O(m ^ 2)$ -> Where $m$ is the size of the matrix used in matrix exponentiation $(5 X 5)$ and $n$ is the length of the permutation. \ No newline at end of file +> Where $m$ is the size of the matrix used in matrix exponentiation $(5 X 5)$ and $n$ is the length of the permutation. diff --git a/articles/count-ways-to-build-good-strings.md b/articles/count-ways-to-build-good-strings.md index a18b90526..5642378ea 100644 --- a/articles/count-ways-to-build-good-strings.md +++ b/articles/count-ways-to-build-good-strings.md @@ -66,7 +66,7 @@ class Solution { countGoodStrings(low, high, zero, one) { const mod = 1e9 + 7; - const dfs = length => { + const dfs = (length) => { if (length > high) return 0; let res = length >= low ? 1 : 0; res = (res + dfs(length + zero)) % mod; @@ -83,8 +83,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ for recursion stack. > Where $n$ is equal to the given $high$ value. @@ -172,7 +172,7 @@ class Solution { const mod = 1e9 + 7; const dp = new Array(high + 1).fill(-1); - const dfs = length => { + const dfs = (length) => { if (length > high) return 0; if (dp[length] !== -1) return dp[length]; dp[length] = length >= low ? 1 : 0; @@ -190,8 +190,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ > Where $n$ is equal to the given $high$ value. @@ -209,7 +209,7 @@ class Solution: for i in range(1, high + 1): dp[i] = (dp.get(i - one, 0) + dp.get(i - zero, 0)) % mod - + return sum(dp[i] for i in range(low, high + 1)) % mod ``` @@ -277,7 +277,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ -> Where $n$ is equal to the given $high$ value. \ No newline at end of file +> Where $n$ is equal to the given $high$ value. diff --git a/articles/counting-bits.md b/articles/counting-bits.md index 66b5db885..67980b8b6 100644 --- a/articles/counting-bits.md +++ b/articles/counting-bits.md @@ -25,7 +25,7 @@ public class Solution { res[num]++; } } - } + } return res; } } @@ -80,7 +80,7 @@ public class Solution { res[num]++; } } - } + } return res; } } @@ -142,10 +142,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ space for the output array. +- Time complexity: $O(n \log n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ space for the output array. --- @@ -210,7 +210,7 @@ class Solution { let num = i; while (num !== 0) { res[i]++; - num &= (num - 1); + num &= num - 1; } } return res; @@ -284,10 +284,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ space for the output array. +- Time complexity: $O(n \log n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ space for the output array. --- @@ -388,10 +388,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ space for the output array. +- Time complexity: $O(n \log n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ space for the output array. --- @@ -538,10 +538,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ space for the output array. +- Time complexity: $O(n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ space for the output array. --- @@ -649,7 +649,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ space for the output array. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ space for the output array. diff --git a/articles/course-schedule-ii.md b/articles/course-schedule-ii.md index 6a3e85924..7f110a71c 100644 --- a/articles/course-schedule-ii.md +++ b/articles/course-schedule-ii.md @@ -38,7 +38,7 @@ public class Solution { public int[] findOrder(int numCourses, int[][] prerequisites) { Map> prereq = new HashMap<>(); for (int[] pair : prerequisites) { - prereq.computeIfAbsent(pair[0], + prereq.computeIfAbsent(pair[0], k -> new ArrayList<>()).add(pair[1]); } @@ -60,7 +60,7 @@ public class Solution { } private boolean dfs(int course, Map> prereq, - Set visit, Set cycle, + Set visit, Set cycle, List output) { if (cycle.contains(course)) { @@ -108,9 +108,9 @@ public: private: bool dfs(int course, const unordered_map>& prereq, - unordered_set& visit, unordered_set& cycle, + unordered_set& visit, unordered_set& cycle, vector& output) { - + if (cycle.count(course)) { return false; } @@ -218,9 +218,9 @@ public class Solution { } private bool Dfs(int course, Dictionary> prereq, - HashSet visit, HashSet cycle, + HashSet visit, HashSet cycle, List output) { - + if (cycle.Contains(course)) { return false; } @@ -285,7 +285,7 @@ func findOrder(numCourses int, prerequisites [][]int) []int { return []int{} } } - + return output } ``` @@ -378,8 +378,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ > Where $V$ is the number of courses and $E$ is the number of prerequisites. @@ -402,7 +402,7 @@ class Solution: for n in range(numCourses): if indegree[n] == 0: q.append(n) - + finish, output = 0, [] while q: node = q.popleft() @@ -412,7 +412,7 @@ class Solution: indegree[nei] -= 1 if indegree[nei] == 0: q.append(nei) - + if finish != numCourses: return [] return output[::-1] @@ -451,7 +451,7 @@ public class Solution { } } } - + if (finish != numCourses) { return new int[0]; } @@ -466,7 +466,7 @@ public: vector findOrder(int numCourses, vector>& prerequisites) { vector indegree(numCourses, 0); vector> adj(numCourses); - + for (auto& pre : prerequisites) { indegree[pre[1]]++; adj[pre[0]].push_back(pre[1]); @@ -635,7 +635,7 @@ class Solution { fun findOrder(numCourses: Int, prerequisites: Array): IntArray { val indegree = IntArray(numCourses) val adj = Array(numCourses) { mutableListOf() } - + for (pair in prerequisites) { val (src, dst) = pair indegree[dst]++ @@ -712,8 +712,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ > Where $V$ is the number of courses and $E$ is the number of prerequisites. @@ -731,7 +731,7 @@ class Solution: for nxt, pre in prerequisites: indegree[nxt] += 1 adj[pre].append(nxt) - + output = [] def dfs(node): @@ -741,11 +741,11 @@ class Solution: indegree[nei] -= 1 if indegree[nei] == 0: dfs(nei) - + for i in range(numCourses): if indegree[i] == 0: dfs(i) - + return output if len(output) == numCourses else [] ``` @@ -754,7 +754,7 @@ public class Solution { private List output = new ArrayList<>(); private int[] indegree; private List> adj; - + private void dfs(int node) { output.add(node); indegree[node]--; @@ -798,7 +798,7 @@ class Solution { vector output; vector indegree; vector> adj; - + void dfs(int node) { output.push_back(node); indegree[node]--; @@ -841,7 +841,7 @@ class Solution { findOrder(numCourses, prerequisites) { let adj = Array.from({ length: numCourses }, () => []); let indegree = Array(numCourses).fill(0); - + for (let [nxt, pre] of prerequisites) { indegree[nxt]++; adj[pre].push(nxt); @@ -1023,7 +1023,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ -> Where $V$ is the number of courses and $E$ is the number of prerequisites. \ No newline at end of file +> Where $V$ is the number of courses and $E$ is the number of prerequisites. diff --git a/articles/course-schedule-iv.md b/articles/course-schedule-iv.md index 0738453e4..19e758112 100644 --- a/articles/course-schedule-iv.md +++ b/articles/course-schedule-iv.md @@ -8,7 +8,7 @@ class Solution: adj = [[] for _ in range(numCourses)] for u, v in prerequisites: adj[u].append(v) - + def dfs(node, target): if node == target: return True @@ -52,7 +52,7 @@ public class Solution { ```cpp class Solution { vector> adj; - + public: vector checkIfPrerequisite(int numCourses, vector>& prerequisites, vector>& queries) { adj.assign(numCourses, vector()); @@ -142,8 +142,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O((V + E) * m)$ -* Space complexity: $O(V + E + m)$ +- Time complexity: $O((V + E) * m)$ +- Space complexity: $O(V + E + m)$ > Where $m$ is the number of queries, $V$ is the number of courses, and $E$ is the number of prerequisites. @@ -266,7 +266,6 @@ class Solution { adj[crs].push(pre); } - const dfs = (crs) => { if (prereqMap.has(crs)) { return prereqMap.get(crs); @@ -332,8 +331,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(V * (V + E) + m)$ -* Space complexity: $O(V ^ 2 + E + m)$ +- Time complexity: $O(V * (V + E) + m)$ +- Space complexity: $O(V ^ 2 + E + m)$ > Where $m$ is the number of queries, $V$ is the number of courses, and $E$ is the number of prerequisites. @@ -351,19 +350,19 @@ class Solution: for prereq, crs in prerequisites: adj[crs].append(prereq) isPrereq[crs][prereq] = True - + def dfs(crs, prereq): if isPrereq[crs][prereq] != -1: return isPrereq[crs][prereq] == 1 - + for pre in adj[crs]: if pre == prereq or dfs(pre, prereq): isPrereq[crs][prereq] = 1 return True - + isPrereq[crs][prereq] = 0 return False - + res = [] for u, v in queries: res.append(dfs(v, u)) @@ -382,7 +381,7 @@ public class Solution { adj[i] = new ArrayList<>(); Arrays.fill(isPrereq[i], -1); } - + for (int[] pre : prerequisites) { adj[pre[1]].add(pre[0]); isPrereq[pre[1]][pre[0]] = 1; @@ -460,7 +459,9 @@ class Solution { */ checkIfPrerequisite(numCourses, prerequisites, queries) { const adj = Array.from({ length: numCourses }, () => []); - const isPrereq = Array.from({ length: numCourses }, () => Array(numCourses).fill(-1)); + const isPrereq = Array.from({ length: numCourses }, () => + Array(numCourses).fill(-1), + ); for (const [prereq, crs] of prerequisites) { adj[crs].push(prereq); isPrereq[crs][prereq] = 1; @@ -536,8 +537,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(V * (V + E) + m)$ -* Space complexity: $O(V ^ 2 + E + m)$ +- Time complexity: $O(V * (V + E) + m)$ +- Space complexity: $O(V ^ 2 + E + m)$ > Where $m$ is the number of queries, $V$ is the number of courses, and $E$ is the number of prerequisites. @@ -553,13 +554,13 @@ class Solution: adj = [set() for _ in range(numCourses)] indegree = [0] * numCourses isPrereq = [set() for _ in range(numCourses)] - + for pre, crs in prerequisites: adj[pre].add(crs) indegree[crs] += 1 - + q = deque([i for i in range(numCourses) if indegree[i] == 0]) - + while q: node = q.popleft() for neighbor in adj[node]: @@ -568,7 +569,7 @@ class Solution: indegree[neighbor] -= 1 if indegree[neighbor] == 0: q.append(neighbor) - + return [u in isPrereq[v] for u, v in queries] ``` @@ -742,8 +743,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(V * (V + E) + m)$ -* Space complexity: $O(V ^ 2 + E + m)$ +- Time complexity: $O(V * (V + E) + m)$ +- Space complexity: $O(V ^ 2 + E + m)$ > Where $m$ is the number of queries, $V$ is the number of courses, and $E$ is the number of prerequisites. @@ -758,18 +759,18 @@ class Solution: def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]: res = [] adj = [[False] * numCourses for _ in range(numCourses)] - + for pre, crs in prerequisites: adj[pre][crs] = True - + for k in range(numCourses): for i in range(numCourses): for j in range(numCourses): adj[i][j] = adj[i][j] or (adj[i][k] and adj[k][j]) - + for u, v in queries: res.append(adj[u][v]) - + return res ``` @@ -778,11 +779,11 @@ public class Solution { public List checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) { boolean[][] adj = new boolean[numCourses][numCourses]; List res = new ArrayList<>(); - + for (int[] pre : prerequisites) { adj[pre[0]][pre[1]] = true; } - + for (int k = 0; k < numCourses; k++) { for (int i = 0; i < numCourses; i++) { for (int j = 0; j < numCourses; j++) { @@ -790,11 +791,11 @@ public class Solution { } } } - + for (int[] q : queries) { res.add(adj[q[0]][q[1]]); } - + return res; } } @@ -806,11 +807,11 @@ public: vector checkIfPrerequisite(int numCourses, vector>& prerequisites, vector>& queries) { vector> adj(numCourses, vector(numCourses, false)); vector res; - + for (auto& pre : prerequisites) { adj[pre[0]][pre[1]] = true; } - + for (int k = 0; k < numCourses; k++) { for (int i = 0; i < numCourses; i++) { for (int j = 0; j < numCourses; j++) { @@ -818,11 +819,11 @@ public: } } } - + for (auto& q : queries) { res.push_back(adj[q[0]][q[1]]); } - + return res; } }; @@ -837,13 +838,15 @@ class Solution { * @return {boolean[]} */ checkIfPrerequisite(numCourses, prerequisites, queries) { - let adj = Array.from({ length: numCourses }, () => Array(numCourses).fill(false)); + let adj = Array.from({ length: numCourses }, () => + Array(numCourses).fill(false), + ); let res = []; - + for (let [pre, crs] of prerequisites) { adj[pre][crs] = true; } - + for (let k = 0; k < numCourses; k++) { for (let i = 0; i < numCourses; i++) { for (let j = 0; j < numCourses; j++) { @@ -851,11 +854,11 @@ class Solution { } } } - + for (let [u, v] of queries) { res.push(adj[u][v]); } - + return res; } } @@ -894,7 +897,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(V ^ 3 + E + m)$ -* Space complexity: $O(V ^ 2 + E + m)$ +- Time complexity: $O(V ^ 3 + E + m)$ +- Space complexity: $O(V ^ 2 + E + m)$ -> Where $m$ is the number of queries, $V$ is the number of courses, and $E$ is the number of prerequisites. \ No newline at end of file +> Where $m$ is the number of queries, $V$ is the number of courses, and $E$ is the number of prerequisites. diff --git a/articles/course-schedule.md b/articles/course-schedule.md index d57ce12c1..2138d1628 100644 --- a/articles/course-schedule.md +++ b/articles/course-schedule.md @@ -160,9 +160,9 @@ class Solution { } } visiting.delete(crs); - preMap.set(crs, []); + preMap.set(crs, []); return true; - } + }; for (let c = 0; c < numCourses; c++) { if (!dfs(c)) { @@ -359,8 +359,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ > Where $V$ is the number of courses and $E$ is the number of prerequisites. @@ -383,7 +383,7 @@ class Solution: for n in range(numCourses): if indegree[n] == 0: q.append(n) - + finish = 0 while q: node = q.popleft() @@ -392,7 +392,7 @@ class Solution: indegree[nei] -= 1 if indegree[nei] == 0: q.append(nei) - + return finish == numCourses ``` @@ -439,7 +439,7 @@ public: bool canFinish(int numCourses, vector>& prerequisites) { vector indegree(numCourses, 0); vector> adj(numCourses); - + for (auto& pre : prerequisites) { indegree[pre[1]]++; adj[pre[0]].push_back(pre[1]); @@ -589,7 +589,7 @@ class Solution { fun canFinish(numCourses: Int, prerequisites: Array): Boolean { val indegree = IntArray(numCourses) { 0 } val adj = Array(numCourses) { mutableListOf() } - + for (prereq in prerequisites) { val (src, dst) = prereq indegree[dst]++ @@ -661,7 +661,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ -> Where $V$ is the number of courses and $E$ is the number of prerequisites. \ No newline at end of file +> Where $V$ is the number of courses and $E$ is the number of prerequisites. diff --git a/articles/daily-temperatures.md b/articles/daily-temperatures.md index f004aac40..2c100dab5 100644 --- a/articles/daily-temperatures.md +++ b/articles/daily-temperatures.md @@ -90,7 +90,7 @@ class Solution { j++; count++; } - count = (j === n) ? 0 : count; + count = j === n ? 0 : count; res[i] = count; } return res; @@ -126,11 +126,11 @@ public class Solution { func dailyTemperatures(temperatures []int) []int { n := len(temperatures) res := make([]int, 0) - + for i := 0; i < n; i++ { count := 1 j := i + 1 - + for j < n { if temperatures[j] > temperatures[i] { break @@ -138,14 +138,14 @@ func dailyTemperatures(temperatures []int) []int { j++ count++ } - + if j == n { count = 0 } - + res = append(res, count) } - + return res } ``` @@ -155,11 +155,11 @@ class Solution { fun dailyTemperatures(temperatures: IntArray): IntArray { val n = temperatures.size val res = mutableListOf() - + for (i in 0 until n) { var count = 1 var j = i + 1 - + while (j < n) { if (temperatures[j] > temperatures[i]) { break @@ -167,11 +167,11 @@ class Solution { j++ count++ } - + count = if (j == n) 0 else count res.add(count) } - + return res.toIntArray() } } @@ -205,10 +205,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ space for the output array. +- Time complexity: $O(n ^ 2)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ space for the output array. --- @@ -334,7 +334,7 @@ func dailyTemperatures(temperatures []int) []int { class Solution { fun dailyTemperatures(temperatures: IntArray): IntArray { val res = IntArray(temperatures.size) { 0 } - val stack = mutableListOf() + val stack = mutableListOf() for (i in temperatures.indices) { while (stack.isNotEmpty() && temperatures[i] > temperatures[stack.last()]) { @@ -371,8 +371,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -393,7 +393,7 @@ class Solution: j = n break j += res[j] - + if j < n: res[i] = j - i return res @@ -518,7 +518,7 @@ func dailyTemperatures(temperatures []int) []int { } j += res[j] } - + if j < n { res[i] = j - i } @@ -542,7 +542,7 @@ class Solution { } j += res[j] } - + if (j < n) { res[i] = j - i } @@ -581,7 +581,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ space for the output array. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ space for the output array. diff --git a/articles/data-stream-as-disjoint-intervals.md b/articles/data-stream-as-disjoint-intervals.md index a39dc70f3..c0aa4b934 100644 --- a/articles/data-stream-as-disjoint-intervals.md +++ b/articles/data-stream-as-disjoint-intervals.md @@ -94,7 +94,7 @@ class SummaryRanges { this.arr = []; } - /** + /** * @param {number} value * @return {void} */ @@ -128,11 +128,11 @@ class SummaryRanges { ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for initialization. - * $O(1)$ time for each $addNum()$ function call. - * $O(n \log n)$ time for each $getIntervals()$ function call. -* Space complexity: $O(n)$ +- Time complexity: + - $O(1)$ time for initialization. + - $O(1)$ time for each $addNum()$ function call. + - $O(n \log n)$ time for each $getIntervals()$ function call. +- Space complexity: $O(n)$ --- @@ -267,11 +267,11 @@ class SummaryRanges { ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for initialization. - * $O(1)$ time for each $addNum()$ function call. - * $O(n \log n)$ time for each $getIntervals()$ function call. -* Space complexity: $O(n)$ +- Time complexity: + - $O(1)$ time for initialization. + - $O(1)$ time for each $addNum()$ function call. + - $O(n \log n)$ time for each $getIntervals()$ function call. +- Space complexity: $O(n)$ --- @@ -355,11 +355,11 @@ public: ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for initialization. - * $O(\log n)$ time for each $addNum()$ function call. - * $O(n)$ time for each $getIntervals()$ function call. -* Space complexity: $O(n)$ +- Time complexity: + - $O(1)$ time for initialization. + - $O(\log n)$ time for each $addNum()$ function call. + - $O(n)$ time for each $getIntervals()$ function call. +- Space complexity: $O(n)$ --- @@ -443,8 +443,8 @@ public: ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for initialization. - * $O(\log n)$ time for each $addNum()$ function call. - * $O(n)$ time for each $getIntervals()$ function call. -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: + - $O(1)$ time for initialization. + - $O(\log n)$ time for each $addNum()$ function call. + - $O(n)$ time for each $getIntervals()$ function call. +- Space complexity: $O(n)$ diff --git a/articles/decode-string.md b/articles/decode-string.md index c86b9b8f1..43b20f525 100644 --- a/articles/decode-string.md +++ b/articles/decode-string.md @@ -6,14 +6,14 @@ class Solution: def decodeString(self, s: str) -> str: self.i = 0 - + def helper(): res = "" k = 0 - + while self.i < len(s): c = s[self.i] - + if c.isdigit(): k = k * 10 + int(c) elif c == "[": @@ -24,28 +24,28 @@ class Solution: return res else: res += c - + self.i += 1 return res - + return helper() ``` ```java public class Solution { private int i = 0; - + public String decodeString(String s) { return helper(s); } - + private String helper(String s) { StringBuilder res = new StringBuilder(); int k = 0; - + while (i < s.length()) { char c = s.charAt(i); - + if (Character.isDigit(c)) { k = k * 10 + (c - '0'); } else if (c == '[') { @@ -58,10 +58,10 @@ public class Solution { } else { res.append(c); } - + i++; } - + return res.toString(); } } @@ -114,7 +114,7 @@ class Solution { let i = 0; const helper = () => { - let res = ""; + let res = ''; let k = 0; while (i < s.length) { @@ -122,11 +122,11 @@ class Solution { if (!isNaN(c)) { k = k * 10 + parseInt(c, 10); - } else if (c === "[") { + } else if (c === '[') { i++; res += helper().repeat(k); k = 0; - } else if (c === "]") { + } else if (c === ']') { return res; } else { res += c; @@ -187,8 +187,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n + N)$ -* Space complexity: $O(n + N)$ +- Time complexity: $O(n + N)$ +- Space complexity: $O(n + N)$ > Where $n$ is the length of the input string and $N$ is the length of the output string. @@ -308,16 +308,16 @@ class Solution { for (let i = 0; i < s.length; i++) { const char = s[i]; - if (char !== "]") { + if (char !== ']') { stack.push(char); } else { - let substr = ""; - while (stack[stack.length - 1] !== "[") { + let substr = ''; + while (stack[stack.length - 1] !== '[') { substr = stack.pop() + substr; } stack.pop(); - let k = ""; + let k = ''; while (stack.length > 0 && !isNaN(stack[stack.length - 1])) { k = stack.pop() + k; } @@ -325,7 +325,7 @@ class Solution { } } - return stack.join(""); + return stack.join(''); } } ``` @@ -369,8 +369,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n + N ^ 2)$ -* Space complexity: $O(n + N)$ +- Time complexity: $O(n + N ^ 2)$ +- Space complexity: $O(n + N)$ > Where $n$ is the length of the input string and $N$ is the length of the output string. @@ -485,18 +485,18 @@ class Solution { decodeString(s) { const stringStack = []; const countStack = []; - let cur = ""; + let cur = ''; let k = 0; for (const c of s) { if (!isNaN(c)) { k = k * 10 + parseInt(c, 10); - } else if (c === "[") { + } else if (c === '[') { stringStack.push(cur); countStack.push(k); - cur = ""; + cur = ''; k = 0; - } else if (c === "]") { + } else if (c === ']') { const temp = cur; cur = stringStack.pop(); const count = countStack.pop(); @@ -548,7 +548,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n + N)$ -* Space complexity: $O(n + N)$ +- Time complexity: $O(n + N)$ +- Space complexity: $O(n + N)$ -> Where $n$ is the length of the input string and $N$ is the length of the output string. \ No newline at end of file +> Where $n$ is the length of the input string and $N$ is the length of the output string. diff --git a/articles/decode-ways.md b/articles/decode-ways.md index c735d1d3f..7d227fcd0 100644 --- a/articles/decode-ways.md +++ b/articles/decode-ways.md @@ -5,7 +5,7 @@ ```python class Solution: def numDecodings(self, s: str) -> int: - + def dfs(i): if i == len(s): return 1 @@ -14,7 +14,7 @@ class Solution: res = dfs(i + 1) if i < len(s) - 1: - if (s[i] == '1' or + if (s[i] == '1' or (s[i] == '2' and s[i + 1] < '7')): res += dfs(i + 2) @@ -31,7 +31,7 @@ public class Solution { int res = dfs(i + 1, s); if (i < s.length() - 1) { - if (s.charAt(i) == '1' || + if (s.charAt(i) == '1' || (s.charAt(i) == '2' && s.charAt(i + 1) < '7')) { res += dfs(i + 2, s); } @@ -51,10 +51,10 @@ public: int dfs(int i, string& s) { if (i == s.size()) return 1; if (s[i] == '0') return 0; - + int res = dfs(i + 1, s); if (i < s.size() - 1) { - if (s[i] == '1' || + if (s[i] == '1' || (s[i] == '2' && s[i + 1] < '7')) { res += dfs(i + 2, s); } @@ -75,15 +75,13 @@ class Solution { * @return {number} */ numDecodings(s) { - const dfs = (i) => { if (i === s.length) return 1; if (s[i] === '0') return 0; let res = dfs(i + 1); if (i < s.length - 1) { - if (s[i] === '1' || - (s[i] === '2' && s[i + 1] < '7')) { + if (s[i] === '1' || (s[i] === '2' && s[i + 1] < '7')) { res += dfs(i + 2); } } @@ -104,7 +102,7 @@ public class Solution { int res = Dfs(i + 1); if (i < s.Length - 1) { - if (s[i] == '1' || + if (s[i] == '1' || (s[i] == '2' && s[i + 1] < '7')) { res += Dfs(i + 2); } @@ -167,7 +165,7 @@ class Solution { class Solution { func numDecodings(_ s: String) -> Int { let chars = Array(s) - + func dfs(_ i: Int) -> Int { if i == chars.count { return 1 @@ -195,8 +193,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ --- @@ -229,7 +227,7 @@ class Solution: ```java public class Solution { - + public int numDecodings(String s) { Map dp = new HashMap<>(); dp.put(s.length(), 1); @@ -246,7 +244,7 @@ public class Solution { } int res = dfs(s, i + 1, dp); - if (i + 1 < s.length() && (s.charAt(i) == '1' || + if (i + 1 < s.length() && (s.charAt(i) == '1' || s.charAt(i) == '2' && s.charAt(i + 1) < '7')) { res += dfs(s, i + 2, dp); } @@ -275,7 +273,7 @@ private: } int res = dfs(s, i + 1, dp); - if (i + 1 < s.size() && (s[i] == '1' || + if (i + 1 < s.size() && (s[i] == '1' || s[i] == '2' && s[i + 1] < '7')) { res += dfs(s, i + 2, dp); } @@ -313,8 +311,11 @@ class Solution { } let res = this.dfs(s, i + 1, dp); - if (i + 1 < s.length && (s.charAt(i) === '1' || - (s.charAt(i) === '2' && s.charAt(i + 1) < '7'))) { + if ( + i + 1 < s.length && + (s.charAt(i) === '1' || + (s.charAt(i) === '2' && s.charAt(i + 1) < '7')) + ) { res += this.dfs(s, i + 2, dp); } dp.set(i, res); @@ -341,7 +342,7 @@ public class Solution { } int res = Dfs(s, i + 1, dp); - if (i + 1 < s.Length && (s[i] == '1' || + if (i + 1 < s.Length && (s[i] == '1' || s[i] == '2' && s[i + 1] < '7')) { res += Dfs(s, i + 2, dp); } @@ -367,7 +368,7 @@ func dfs(s string, i int, dp map[int]int) int { return 0 } res := dfs(s, i+1, dp) - if i+1 < len(s) && (s[i] == '1' || + if i+1 < len(s) && (s[i] == '1' || (s[i] == '2' && s[i+1] <= '6')) { res += dfs(s, i+2, dp) } @@ -393,7 +394,7 @@ class Solution { return 0 } var res = dfs(s, i + 1, dp) - if (i + 1 < s.length && (s[i] == '1' || + if (i + 1 < s.length && (s[i] == '1' || (s[i] == '2' && s[i + 1] <= '6'))) { res += dfs(s, i + 2, dp) } @@ -419,7 +420,7 @@ class Solution { } var res = dfs(i + 1) - if i + 1 < chars.count, + if i + 1 < chars.count, chars[i] == "1" || (chars[i] == "2" && "0123456".contains(chars[i + 1])) { res += dfs(i + 2) } @@ -436,8 +437,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -464,7 +465,7 @@ class Solution: ```java public class Solution { - public int numDecodings(String s) { + public int numDecodings(String s) { int[] dp = new int[s.length() + 1]; dp[s.length()] = 1; for (int i = s.length() - 1; i >= 0; i--) { @@ -472,7 +473,7 @@ public class Solution { dp[i] = 0; } else { dp[i] = dp[i + 1]; - if (i + 1 < s.length() && (s.charAt(i) == '1' || + if (i + 1 < s.length() && (s.charAt(i) == '1' || s.charAt(i) == '2' && s.charAt(i + 1) < '7')) { dp[i] += dp[i + 2]; } @@ -494,7 +495,7 @@ public: dp[i] = 0; } else { dp[i] = dp[i + 1]; - if (i + 1 < s.size() && (s[i] == '1' || + if (i + 1 < s.size() && (s[i] == '1' || s[i] == '2' && s[i + 1] < '7')) { dp[i] += dp[i + 2]; } @@ -519,9 +520,12 @@ class Solution { dp[i] = 0; } else { dp[i] = dp[i + 1]; - if (i + 1 < s.length && (s.charAt(i) === '1' || - (s.charAt(i) === '2' && s.charAt(i + 1) < '7'))) { - dp[i] += dp[i + 2]; + if ( + i + 1 < s.length && + (s.charAt(i) === '1' || + (s.charAt(i) === '2' && s.charAt(i + 1) < '7')) + ) { + dp[i] += dp[i + 2]; } } } @@ -540,7 +544,7 @@ public class Solution { dp[i] = 0; } else { dp[i] = dp[i + 1]; - if (i + 1 < s.Length && (s[i] == '1' || + if (i + 1 < s.Length && (s[i] == '1' || s[i] == '2' && s[i + 1] < '7')) { dp[i] += dp[i + 2]; } @@ -560,7 +564,7 @@ func numDecodings(s string) int { dp[i] = 0 } else { dp[i] = dp[i+1] - if i+1 < len(s) && (s[i] == '1' || + if i+1 < len(s) && (s[i] == '1' || (s[i] == '2' && s[i+1] <= '6')) { dp[i] += dp[i+2] } @@ -579,7 +583,7 @@ class Solution { dp[i] = 0 } else { dp[i] = dp[i + 1] ?: 0 - if (i + 1 < s.length && (s[i] == '1' || + if (i + 1 < s.length && (s[i] == '1' || (s[i] == '2' && s[i + 1] <= '6'))) { dp[i] = dp[i]!! + (dp[i + 2] ?: 0) } @@ -604,7 +608,7 @@ class Solution { dp[i] = dp[i + 1] ?? 0 } - if i + 1 < chars.count, + if i + 1 < chars.count, chars[i] == "1" || (chars[i] == "2" && "0123456".contains(chars[i + 1])) { dp[i]! += dp[i + 2] ?? 0 } @@ -618,8 +622,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -648,7 +652,7 @@ class Solution: ```java public class Solution { - public int numDecodings(String s) { + public int numDecodings(String s) { int dp = 0, dp2 = 0; int dp1 = 1; for (int i = s.length() - 1; i >= 0; i--) { @@ -656,7 +660,7 @@ public class Solution { dp = 0; } else { dp = dp1; - if (i + 1 < s.length() && (s.charAt(i) == '1' || + if (i + 1 < s.length() && (s.charAt(i) == '1' || s.charAt(i) == '2' && s.charAt(i + 1) < '7')) { dp += dp2; } @@ -681,7 +685,7 @@ public: dp = 0; } else { dp = dp1; - if (i + 1 < s.size() && (s[i] == '1' || + if (i + 1 < s.size() && (s[i] == '1' || s[i] == '2' && s[i + 1] < '7')) { dp += dp2; } @@ -702,16 +706,20 @@ class Solution { * @return {number} */ numDecodings(s) { - let dp2 = 0, dp = 0; + let dp2 = 0, + dp = 0; let dp1 = 1; for (let i = s.length - 1; i >= 0; i--) { if (s.charAt(i) === '0') { dp = 0; } else { dp = dp1; - if (i + 1 < s.length && (s.charAt(i) === '1' || - (s.charAt(i) === '2' && s.charAt(i + 1) < '7'))) { - dp += dp2; + if ( + i + 1 < s.length && + (s.charAt(i) === '1' || + (s.charAt(i) === '2' && s.charAt(i + 1) < '7')) + ) { + dp += dp2; } } dp2 = dp1; @@ -732,7 +740,7 @@ public class Solution { dp = 0; } else { dp = dp1; - if (i + 1 < s.Length && (s[i] == '1' || + if (i + 1 < s.Length && (s[i] == '1' || s[i] == '2' && s[i + 1] < '7')) { dp += dp2; } @@ -756,7 +764,7 @@ func numDecodings(s string) int { } else { dp = dp1 } - if i+1 < len(s) && (s[i] == '1' || + if i+1 < len(s) && (s[i] == '1' || s[i] == '2' && s[i+1] <= '6') { dp += dp2 } @@ -780,7 +788,7 @@ class Solution { } else { dp = dp1 } - if (i + 1 < s.length && (s[i] == '1' || + if (i + 1 < s.length && (s[i] == '1' || (s[i] == '2' && s[i + 1] <= '6'))) { dp += dp2 } @@ -805,7 +813,7 @@ class Solution { dp = dp1 } - if i + 1 < chars.count, + if i + 1 < chars.count, chars[i] == "1" || (chars[i] == "2" && "0123456".contains(chars[i + 1])) { dp += dp2 } @@ -820,5 +828,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/delete-and-earn.md b/articles/delete-and-earn.md index ae00ea5db..38521d451 100644 --- a/articles/delete-and-earn.md +++ b/articles/delete-and-earn.md @@ -10,20 +10,20 @@ class Solution: def dfs(i): if i >= len(nums): return 0 - + cur = nums[i] pick = 0 while i < len(nums) and nums[i] == cur: pick += nums[i] i += 1 - + res = dfs(i) while i < len(nums) and nums[i] == 1 + cur: i += 1 - + res = max(res, pick + dfs(i)) return res - + return dfs(0) ``` @@ -94,18 +94,19 @@ class Solution { const dfs = (i) => { if (i >= nums.length) return 0; - - let cur = nums[i], pick = 0; + + let cur = nums[i], + pick = 0; while (i < nums.length && nums[i] === cur) { pick += nums[i]; i++; } - + let res = dfs(i); while (i < nums.length && nums[i] === cur + 1) { i++; } - + res = Math.max(res, pick + dfs(i)); return res; }; @@ -119,8 +120,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ --- @@ -142,17 +143,17 @@ class Solution: return 0 if memo[i] != -1: return memo[i] - + res = val[nums[i]] if i + 1 < len(nums) and nums[i] + 1 == nums[i + 1]: res += dfs(i + 2) else: res += dfs(i + 1) - + res = max(res, dfs(i + 1)) memo[i] = res return res - + return dfs(0) ``` @@ -241,7 +242,7 @@ class Solution { */ deleteAndEarn(nums) { const val = new Map(); - nums.forEach(num => { + nums.forEach((num) => { val.set(num, (val.get(num) || 0) + num); }); const uniqueNums = Array.from(new Set(nums)).sort((a, b) => a - b); @@ -272,8 +273,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -288,7 +289,7 @@ class Solution: for num in nums: val[num] += num nums = sorted(list(set(nums))) - + dp = [0] * (len(nums) + 1) for i in range(len(nums) - 1, -1, -1): take = val[nums[i]] @@ -297,7 +298,7 @@ class Solution: else: take += dp[i + 1] dp[i] = max(dp[i + 1], take) - + return dp[0] ``` @@ -334,7 +335,7 @@ public: vector sortedNums; for (auto& [key, _] : val) sortedNums.push_back(key); sort(sortedNums.begin(), sortedNums.end()); - + vector dp(sortedNums.size() + 1); for (int i = sortedNums.size() - 1; i >= 0; i--) { int take = val[sortedNums[i]]; @@ -345,7 +346,7 @@ public: } dp[i] = max(dp[i + 1], take); } - + return dp[0]; } }; @@ -359,13 +360,16 @@ class Solution { */ deleteAndEarn(nums) { const val = new Map(); - nums.forEach(num => val.set(num, (val.get(num) || 0) + num)); + nums.forEach((num) => val.set(num, (val.get(num) || 0) + num)); const sortedNums = Array.from(val.keys()).sort((a, b) => a - b); const dp = Array(sortedNums.length + 1).fill(0); for (let i = sortedNums.length - 1; i >= 0; i--) { let take = val.get(sortedNums[i]); - if (i + 1 < sortedNums.length && sortedNums[i + 1] === sortedNums[i] + 1) { + if ( + i + 1 < sortedNums.length && + sortedNums[i + 1] === sortedNums[i] + 1 + ) { take += dp[i + 2]; } else { take += dp[i + 1]; @@ -382,8 +386,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -401,7 +405,7 @@ class Solution: dp[num] += num for i in range(m - 1, 0, -1): dp[i] = max(dp[i + 1], dp[i + 2] + dp[i]) - + return dp[1] ``` @@ -430,7 +434,7 @@ public: for (auto& num : nums) { dp[num] += num; } - + for (int i = m - 1; i > 0; i--) { dp[i] = max(dp[i + 1], dp[i + 2] + dp[i]); } @@ -464,8 +468,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n)$ -* Space complexity: $O(m)$ +- Time complexity: $O(m + n)$ +- Space complexity: $O(m)$ > Where $m$ is the maximum element in the array and $n$ is the size of the array. @@ -557,10 +561,11 @@ class Solution { */ deleteAndEarn(nums) { const count = new Map(); - nums.forEach(num => count.set(num, (count.get(num) || 0) + num)); + nums.forEach((num) => count.set(num, (count.get(num) || 0) + num)); const uniqueNums = [...count.keys()].sort((a, b) => a - b); - let earn1 = 0, earn2 = 0; + let earn1 = 0, + earn2 = 0; for (let i = 0; i < uniqueNums.length; i++) { const curEarn = count.get(uniqueNums[i]); if (i > 0 && uniqueNums[i] === uniqueNums[i - 1] + 1) { @@ -582,5 +587,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ diff --git a/articles/delete-leaves-with-a-given-value.md b/articles/delete-leaves-with-a-given-value.md index add3a0494..38471c91d 100644 --- a/articles/delete-leaves-with-a-given-value.md +++ b/articles/delete-leaves-with-a-given-value.md @@ -156,8 +156,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -433,8 +433,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -619,7 +619,8 @@ class Solution { if (!root) return null; const stack = []; - let cur = root, visited = null; + let cur = root, + visited = null; while (stack.length > 0 || cur !== null) { while (cur !== null) { @@ -715,5 +716,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/delete-node-in-a-bst.md b/articles/delete-node-in-a-bst.md index 0a9617193..a84c6e82b 100644 --- a/articles/delete-node-in-a-bst.md +++ b/articles/delete-node-in-a-bst.md @@ -196,8 +196,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(h)$ -* Space complexity: $O(h)$ for the recursion stack. +- Time complexity: $O(h)$ +- Space complexity: $O(h)$ for the recursion stack. > Where $h$ is the height of the given binary search tree. @@ -410,8 +410,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(h)$ -* Space complexity: $O(h)$ for the recursion stack. +- Time complexity: $O(h)$ +- Space complexity: $O(h)$ for the recursion stack. > Where $h$ is the height of the given binary search tree. @@ -432,10 +432,10 @@ class Solution: def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: if not root: return root - + parent = None cur = root - + # Find the node to delete while cur and cur.val != key: parent = cur @@ -443,10 +443,10 @@ class Solution: cur = cur.right else: cur = cur.left - + if not cur: return root - + # Node with only one child or no child if not cur.left or not cur.right: child = cur.left if cur.left else cur.right @@ -464,21 +464,21 @@ class Solution: while cur.left: par = cur cur = cur.left - + if par: # if there was a left traversal par.left = cur.right cur.right = delNode.right - + cur.left = delNode.left - + if not parent: # if we're deleting root return cur - + if parent.left == delNode: parent.left = cur else: parent.right = cur - + return root ``` @@ -501,10 +501,10 @@ class Solution: public class Solution { public TreeNode deleteNode(TreeNode root, int key) { if (root == null) return root; - + TreeNode parent = null; TreeNode cur = root; - + // Find the node to delete while (cur != null && cur.val != key) { parent = cur; @@ -514,9 +514,9 @@ public class Solution { cur = cur.left; } } - + if (cur == null) return root; - + // Node with only one child or no child if (cur.left == null || cur.right == null) { TreeNode child = (cur.left != null) ? cur.left : cur.right; @@ -535,22 +535,22 @@ public class Solution { par = cur; cur = cur.left; } - + if (par != null) { // if there was a left traversal par.left = cur.right; cur.right = delNode.right; } cur.left = delNode.left; - + if (parent == null) return cur; // if deleting root - + if (parent.left == delNode) { parent.left = cur; } else { parent.right = cur; } } - + return root; } } @@ -572,10 +572,10 @@ class Solution { public: TreeNode* deleteNode(TreeNode* root, int key) { if (!root) return root; - + TreeNode* parent = nullptr; TreeNode* cur = root; - + // Find the node to delete while (cur && cur->val != key) { parent = cur; @@ -585,9 +585,9 @@ public: cur = cur->left; } } - + if (!cur) return root; - + // Node with only one child or no child if (!cur->left || !cur->right) { TreeNode* child = cur->left ? cur->left : cur->right; @@ -606,22 +606,22 @@ public: par = cur; cur = cur->left; } - + if (par) { // if there was a left traversal par->left = cur->right; cur->right = delNode->right; } cur->left = delNode->left; - + if (!parent) return cur; // if deleting root - + if (parent->left == delNode) { parent->left = cur; } else { parent->right = cur; } } - + return root; } }; @@ -646,10 +646,10 @@ class Solution { */ deleteNode(root, key) { if (!root) return root; - + let parent = null; let cur = root; - + // Find the node to delete while (cur && cur.val !== key) { parent = cur; @@ -659,9 +659,9 @@ class Solution { cur = cur.left; } } - + if (!cur) return root; - + // Node with only one child or no child if (!cur.left || !cur.right) { const child = cur.left || cur.right; @@ -680,22 +680,23 @@ class Solution { par = cur; cur = cur.left; } - - if (par) { // if there was a left traversal + + if (par) { + // if there was a left traversal par.left = cur.right; cur.right = delNode.right; } cur.left = delNode.left; - + if (!parent) return cur; // if deleting root - + if (parent.left === delNode) { parent.left = cur; } else { parent.right = cur; } } - + return root; } } @@ -784,7 +785,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(h)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(h)$ +- Space complexity: $O(1)$ extra space. -> Where $h$ is the height of the given binary search tree. \ No newline at end of file +> Where $h$ is the height of the given binary search tree. diff --git a/articles/depth-of-binary-tree.md b/articles/depth-of-binary-tree.md index 88a35751d..35876c27c 100644 --- a/articles/depth-of-binary-tree.md +++ b/articles/depth-of-binary-tree.md @@ -199,10 +199,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(h)$ - * Best Case ([balanced tree](https://www.geeksforgeeks.org/balanced-binary-tree/)): $O(log(n))$ - * Worst Case ([degenerate tree](https://www.geeksforgeeks.org/introduction-to-degenerate-binary-tree/)): $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(h)$ + - Best Case ([balanced tree](https://www.geeksforgeeks.org/balanced-binary-tree/)): $O(log(n))$ + - Worst Case ([degenerate tree](https://www.geeksforgeeks.org/introduction-to-degenerate-binary-tree/)): $O(n)$ > Where $n$ is the number of nodes in the tree and $h$ is the height of the tree. @@ -398,25 +398,25 @@ func maxDepth(root *TreeNode) int { if root == nil { return 0 } - + stack := list.New() stack.PushBack([]interface{}{root, 1}) res := 0 - + for stack.Len() > 0 { back := stack.Back() stack.Remove(back) pair := back.Value.([]interface{}) node := pair[0].(*TreeNode) depth := pair[1].(int) - + if node != nil { res = max(res, depth) stack.PushBack([]interface{}{node.Left, depth + 1}) stack.PushBack([]interface{}{node.Right, depth + 1}) } } - + return res } @@ -444,21 +444,21 @@ class Solution { if (root == null) { return 0 } - + val stack = ArrayDeque>() stack.addLast(Pair(root, 1)) var res = 0 - + while (stack.isNotEmpty()) { val (node, depth) = stack.removeLast() - + if (node != null) { res = maxOf(res, depth) stack.addLast(Pair(node.left, depth + 1)) stack.addLast(Pair(node.right, depth + 1)) } } - + return res } } @@ -503,12 +503,12 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- -## 3. Breadth First Search +## 3. Breadth First Search ::tabs-start @@ -718,18 +718,18 @@ func maxDepth(root *TreeNode) int { if root == nil { return 0 } - + q := linkedlistqueue.New() q.Enqueue(root) level := 0 - + for !q.Empty() { size := q.Size() - + for i := 0; i < size; i++ { val, _ := q.Dequeue() node := val.(*TreeNode) - + if node.Left != nil { q.Enqueue(node.Left) } @@ -739,7 +739,7 @@ func maxDepth(root *TreeNode) int { } level++ } - + return level } ``` @@ -760,23 +760,23 @@ class Solution { if (root == null) { return 0 } - + val q = ArrayDeque() q.addLast(root) var level = 0 - + while (q.isNotEmpty()) { val size = q.size - + repeat(size) { val node = q.removeFirst() - + node.left?.let { q.addLast(it) } node.right?.let { q.addLast(it) } } level++ } - + return level } } @@ -827,5 +827,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/design-a-food-rating-system.md b/articles/design-a-food-rating-system.md index 7be2642c1..f94a3a44f 100644 --- a/articles/design-a-food-rating-system.md +++ b/articles/design-a-food-rating-system.md @@ -125,7 +125,8 @@ class FoodRatings { * @return {string} */ highestRated(cuisine) { - let maxR = 0, res = ""; + let maxR = 0, + res = ''; for (let food of this.cuisineToFood.get(cuisine)) { let r = this.foodToRating.get(food); if (r > maxR || (r === maxR && food < res)) { @@ -142,11 +143,11 @@ class FoodRatings { ### Time & Space Complexity -* Time complexity: - * $O(n)$ time for initialization. - * $O(1)$ time for each $changeRating()$ function call. - * $O(n)$ time for each $highestRated()$ function call. -* Space complexity: $O(n)$ +- Time complexity: + - $O(n)$ time for initialization. + - $O(1)$ time for each $changeRating()$ function call. + - $O(n)$ time for each $highestRated()$ function call. +- Space complexity: $O(n)$ --- @@ -288,13 +289,17 @@ class FoodRatings { this.foodToRating.set(foods[i], ratings[i]); this.foodToCuisine.set(foods[i], cuisines[i]); if (!this.cuisineToHeap.has(cuisines[i])) { - this.cuisineToHeap.set(cuisines[i], new PriorityQueue( - (a, b) => b.rating - a.rating || a.name.localeCompare(b.name) - )); + this.cuisineToHeap.set( + cuisines[i], + new PriorityQueue( + (a, b) => + b.rating - a.rating || a.name.localeCompare(b.name), + ), + ); } - this.cuisineToHeap.get(cuisines[i]).enqueue( - { rating: ratings[i], name: foods[i] } - ); + this.cuisineToHeap + .get(cuisines[i]) + .enqueue({ rating: ratings[i], name: foods[i] }); } } @@ -306,9 +311,9 @@ class FoodRatings { changeRating(food, newRating) { let cuisine = this.foodToCuisine.get(food); this.foodToRating.set(food, newRating); - this.cuisineToHeap.get(cuisine).enqueue( - { rating: newRating, name: food } - ); + this.cuisineToHeap + .get(cuisine) + .enqueue({ rating: newRating, name: food }); } /** @@ -324,7 +329,7 @@ class FoodRatings { } heap.dequeue(); } - return ""; + return ''; } } ``` @@ -333,11 +338,11 @@ class FoodRatings { ### Time & Space Complexity -* Time complexity: - * $O(n \log n)$ time for initialization. - * $O(\log n)$ time for each $changeRating()$ function call. - * $O(\log n)$ time for each $highestRated()$ function call. -* Space complexity: $O(n)$ +- Time complexity: + - $O(n \log n)$ time for initialization. + - $O(\log n)$ time for each $changeRating()$ function call. + - $O(\log n)$ time for each $highestRated()$ function call. +- Space complexity: $O(n)$ --- @@ -450,8 +455,8 @@ public: ### Time & Space Complexity -* Time complexity: - * $O(n \log n)$ time for initialization. - * $O(\log n)$ time for each $changeRating()$ function call. - * $O(1)$ in Python and $O(\log n)$ in other languages for each $highestRated()$ function call. -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: + - $O(n \log n)$ time for initialization. + - $O(\log n)$ time for each $changeRating()$ function call. + - $O(1)$ in Python and $O(\log n)$ in other languages for each $highestRated()$ function call. +- Space complexity: $O(n)$ diff --git a/articles/design-browser-history.md b/articles/design-browser-history.md index a557f9151..8035bf24f 100644 --- a/articles/design-browser-history.md +++ b/articles/design-browser-history.md @@ -104,7 +104,7 @@ class BrowserHistory { this.frontHistory = []; } - /** + /** * @param {string} url * @return {void} */ @@ -113,7 +113,7 @@ class BrowserHistory { this.frontHistory = []; } - /** + /** * @param {number} steps * @return {string} */ @@ -124,7 +124,7 @@ class BrowserHistory { return this.backHistory[this.backHistory.length - 1]; } - /** + /** * @param {number} steps * @return {string} */ @@ -141,11 +141,11 @@ class BrowserHistory { ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for initialization. - * $O(1)$ time for each $visit()$ function call. - * $O(min(n, steps))$ time for each $back()$ and $forward()$ function calls. -* Space complexity: $O(m * n)$ +- Time complexity: + - $O(1)$ time for initialization. + - $O(1)$ time for each $visit()$ function call. + - $O(min(n, steps))$ time for each $back()$ and $forward()$ function calls. +- Space complexity: $O(m * n)$ > Where $n$ is the number of visited urls, $m$ is the average length of each url, and $steps$ is the number of steps we go forward or back. @@ -246,7 +246,7 @@ class BrowserHistory { this.cur = 0; } - /** + /** * @param {string} url * @return {void} */ @@ -256,7 +256,7 @@ class BrowserHistory { this.history.push(url); } - /** + /** * @param {number} steps * @return {string} */ @@ -265,7 +265,7 @@ class BrowserHistory { return this.history[this.cur]; } - /** + /** * @param {number} steps * @return {string} */ @@ -280,11 +280,11 @@ class BrowserHistory { ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for initialization. - * $O(n)$ time for each $visit()$ function call. - * $O(1)$ time for each $back()$ and $forward()$ function calls. -* Space complexity: $O(m * n)$ +- Time complexity: + - $O(1)$ time for initialization. + - $O(n)$ time for each $visit()$ function call. + - $O(1)$ time for each $back()$ and $forward()$ function calls. +- Space complexity: $O(m * n)$ > Where $n$ is the number of visited urls and $m$ is the average length of each url. @@ -404,7 +404,7 @@ class BrowserHistory { this.n = 1; } - /** + /** * @param {string} url * @return {void} */ @@ -419,7 +419,7 @@ class BrowserHistory { } } - /** + /** * @param {number} steps * @return {string} */ @@ -428,7 +428,7 @@ class BrowserHistory { return this.history[this.cur]; } - /** + /** * @param {number} steps * @return {string} */ @@ -443,11 +443,11 @@ class BrowserHistory { ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for initialization. - * $O(1)$ time for each $visit()$ function call. - * $O(1)$ time for each $back()$ and $forward()$ function calls. -* Space complexity: $O(m * n)$ +- Time complexity: + - $O(1)$ time for initialization. + - $O(1)$ time for each $visit()$ function call. + - $O(1)$ time for each $back()$ and $forward()$ function calls. +- Space complexity: $O(m * n)$ > Where $n$ is the number of visited urls and $m$ is the average length of each url. @@ -540,7 +540,7 @@ class BrowserHistory { ListNode* prev; ListNode* next; - ListNode(string val, ListNode* prev = nullptr, ListNode* next = nullptr) + ListNode(string val, ListNode* prev = nullptr, ListNode* next = nullptr) : val(val), prev(prev), next(next) {} }; @@ -592,7 +592,7 @@ class BrowserHistory { this.cur = new ListNode(homepage); } - /** + /** * @param {string} url * @return {void} */ @@ -601,7 +601,7 @@ class BrowserHistory { this.cur = this.cur.next; } - /** + /** * @param {number} steps * @return {string} */ @@ -613,7 +613,7 @@ class BrowserHistory { return this.cur.val; } - /** + /** * @param {number} steps * @return {string} */ @@ -631,10 +631,10 @@ class BrowserHistory { ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for initialization. - * $O(1)$ time for each $visit()$ function call. - * $O(min(n, steps))$ time for each $back()$ and $forward()$ function calls. -* Space complexity: $O(m * n)$ +- Time complexity: + - $O(1)$ time for initialization. + - $O(1)$ time for each $visit()$ function call. + - $O(min(n, steps))$ time for each $back()$ and $forward()$ function calls. +- Space complexity: $O(m * n)$ -> Where $n$ is the number of visited urls, $m$ is the average length of each url, and $steps$ is the number of steps we go forward or back. \ No newline at end of file +> Where $n$ is the number of visited urls, $m$ is the average length of each url, and $steps$ is the number of steps we go forward or back. diff --git a/articles/design-circular-queue.md b/articles/design-circular-queue.md index 89aee1a18..9d79a45aa 100644 --- a/articles/design-circular-queue.md +++ b/articles/design-circular-queue.md @@ -236,11 +236,11 @@ public class MyCircularQueue { ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for initialization. - * $O(1)$ time for each $enQueue()$, $Front()$, $Rear()$, $isEmpty()$ and $isFull()$ function calls. - * $O(n)$ time for each $deQueue()$ function call. -* Space complexity: $O(n)$ +- Time complexity: + - $O(1)$ time for initialization. + - $O(1)$ time for each $enQueue()$, $Front()$, $Rear()$, $isEmpty()$ and $isFull()$ function calls. + - $O(n)$ time for each $deQueue()$ function call. +- Space complexity: $O(n)$ > Where $n$ is the size of the queue. @@ -252,14 +252,14 @@ public class MyCircularQueue { ```python class MyCircularQueue: - + def __init__(self, k: int): self.q = [0] * k self.k = k self.front = 0 self.rear = -1 self.size = 0 - + def enQueue(self, value: int) -> bool: if self.isFull(): return False @@ -267,27 +267,27 @@ class MyCircularQueue: self.q[self.rear] = value self.size += 1 return True - + def deQueue(self) -> bool: if self.isEmpty(): return False self.front = (self.front + 1) % self.k self.size -= 1 return True - + def Front(self) -> int: if self.isEmpty(): return -1 return self.q[self.front] - + def Rear(self) -> int: if self.isEmpty(): return -1 return self.q[self.rear] - + def isEmpty(self) -> bool: return self.size == 0 - + def isFull(self) -> bool: return self.size == self.k ``` @@ -522,10 +522,10 @@ public class MyCircularQueue { ### Time & Space Complexity -* Time complexity: - * $O(n)$ time for initialization. - * $O(1)$ time for each $enQueue()$, $deQueue()$, $Front()$, $Rear()$, $isEmpty()$ and $isFull()$ function calls. -* Space complexity: $O(n)$ +- Time complexity: + - $O(n)$ time for initialization. + - $O(1)$ time for each $enQueue()$, $deQueue()$, $Front()$, $Rear()$, $isEmpty()$ and $isFull()$ function calls. +- Space complexity: $O(n)$ > Where $n$ is the size of the queue. @@ -704,9 +704,9 @@ public: ```javascript class ListNode { /** - * @param {number} val - * @param {ListNode} next - * @param {ListNode} prev + * @param {number} val + * @param {ListNode} next + * @param {ListNode} prev */ constructor(val, next = null, prev = null) { this.val = val; @@ -847,10 +847,10 @@ public class MyCircularQueue { ### Time & Space Complexity -* Time complexity: - * $O(n)$ time for initialization. - * $O(1)$ time for each $enQueue()$, $deQueue()$, $Front()$, $Rear()$, $isEmpty()$ and $isFull()$ function calls. -* Space complexity: $O(n)$ +- Time complexity: + - $O(n)$ time for initialization. + - $O(1)$ time for each $enQueue()$, $deQueue()$, $Front()$, $Rear()$, $isEmpty()$ and $isFull()$ function calls. +- Space complexity: $O(n)$ > Where $n$ is the size of the queue. @@ -871,10 +871,10 @@ class MyCircularQueue: self.space = k self.left = ListNode(0) self.right = self.left - + def enQueue(self, value: int) -> bool: if self.isFull(): return False - + cur = ListNode(value) if self.isEmpty(): self.left.next = cur @@ -882,31 +882,31 @@ class MyCircularQueue: else: self.right.next = cur self.right = cur - + self.space -= 1 return True - + def deQueue(self) -> bool: if self.isEmpty(): return False - + self.left.next = self.left.next.next if self.left.next is None: self.right = self.left - + self.space += 1 return True - + def Front(self) -> int: if self.isEmpty(): return -1 return self.left.next.val - + def Rear(self) -> int: if self.isEmpty(): return -1 return self.right.val - + def isEmpty(self) -> bool: return self.left.next is None - + def isFull(self) -> bool: return self.space == 0 ``` @@ -1206,9 +1206,9 @@ public class MyCircularQueue { ### Time & Space Complexity -* Time complexity: - * $O(n)$ time for initialization. - * $O(1)$ time for each $enQueue()$, $deQueue()$, $Front()$, $Rear()$, $isEmpty()$ and $isFull()$ function calls. -* Space complexity: $O(n)$ +- Time complexity: + - $O(n)$ time for initialization. + - $O(1)$ time for each $enQueue()$, $deQueue()$, $Front()$, $Rear()$, $isEmpty()$ and $isFull()$ function calls. +- Space complexity: $O(n)$ -> Where $n$ is the size of the queue. \ No newline at end of file +> Where $n$ is the size of the queue. diff --git a/articles/design-hashmap.md b/articles/design-hashmap.md index b26900e0f..c8ce07de0 100644 --- a/articles/design-hashmap.md +++ b/articles/design-hashmap.md @@ -69,8 +69,8 @@ class MyHashMap { this.map = new Array(1000001).fill(-1); } - /** - * @param {number} key + /** + * @param {number} key * @param {number} value * @return {void} */ @@ -78,7 +78,7 @@ class MyHashMap { this.map[key] = value; } - /** + /** * @param {number} key * @return {number} */ @@ -86,7 +86,7 @@ class MyHashMap { return this.map[key]; } - /** + /** * @param {number} key * @return {void} */ @@ -125,8 +125,8 @@ public class MyHashMap { ### Time & Space Complexity -* Time complexity: $O(1)$ for each function call. -* Space complexity: $O(1000000)$ since the key is in the range $[0, 1000000]$. +- Time complexity: $O(1)$ for each function call. +- Space complexity: $O(1000000)$ since the key is in the range $[0, 1000000]$. --- @@ -145,7 +145,7 @@ class MyHashMap: def __init__(self): self.map = [ListNode() for _ in range(1000)] - + def hash(self, key: int) -> int: return key % len(self.map) @@ -305,8 +305,8 @@ public: ```javascript class ListNode { - /** - * @param {number} key + /** + * @param {number} key * @param {number} val * @param {ListNode} next */ @@ -322,16 +322,16 @@ class MyHashMap { this.map = Array.from({ length: 1000 }, () => new ListNode()); } - /** - * @param {number} key + /** + * @param {number} key * @return {number} */ hash(key) { return key % this.map.length; } - /** - * @param {number} key + /** + * @param {number} key * @param {number} value * @return {void} */ @@ -347,8 +347,8 @@ class MyHashMap { cur.next = new ListNode(key, value); } - /** - * @param {number} key + /** + * @param {number} key * @return {number} */ get(key) { @@ -362,8 +362,8 @@ class MyHashMap { return -1; } - /** - * @param {number} key + /** + * @param {number} key * @return {void} */ remove(key) { @@ -446,7 +446,7 @@ public class MyHashMap { ### Time & Space Complexity -* Time complexity: $O(\frac{n}{k})$ for each function call. -* Space complexity: $O(k + m)$ +- Time complexity: $O(\frac{n}{k})$ for each function call. +- Space complexity: $O(k + m)$ -> Where $n$ is the number of keys, $k$ is the size of the map ($1000$) and $m$ is the number of unique keys. \ No newline at end of file +> Where $n$ is the number of keys, $k$ is the size of the map ($1000$) and $m$ is the number of unique keys. diff --git a/articles/design-hashset.md b/articles/design-hashset.md index 643994b20..79c4e8e33 100644 --- a/articles/design-hashset.md +++ b/articles/design-hashset.md @@ -76,7 +76,7 @@ class MyHashSet { this.data = []; } - /** + /** * @param {number} key * @return {void} */ @@ -86,7 +86,7 @@ class MyHashSet { } } - /** + /** * @param {number} key * @return {void} */ @@ -97,7 +97,7 @@ class MyHashSet { } } - /** + /** * @param {number} key * @return {boolean} */ @@ -137,8 +137,8 @@ public class MyHashSet { ### Time & Space Complexity -* Time complexity: $O(n)$ for each function call. -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ for each function call. +- Space complexity: $O(n)$ --- @@ -211,7 +211,7 @@ class MyHashSet { this.data = new Array(1000001).fill(false); } - /** + /** * @param {number} key * @return {void} */ @@ -219,7 +219,7 @@ class MyHashSet { this.data[key] = true; } - /** + /** * @param {number} key * @return {void} */ @@ -227,7 +227,7 @@ class MyHashSet { this.data[key] = false; } - /** + /** * @param {number} key * @return {boolean} */ @@ -263,8 +263,8 @@ public class MyHashSet { ### Time & Space Complexity -* Time complexity: $O(1)$ for each function call. -* Space complexity: $O(1000000)$ since the key is in the range $[0, 1000000]$. +- Time complexity: $O(1)$ for each function call. +- Space complexity: $O(1000000)$ since the key is in the range $[0, 1000000]$. --- @@ -551,8 +551,8 @@ public class MyHashSet { ### Time & Space Complexity -* Time complexity: $O(\frac{n}{k})$ for each function call. -* Space complexity: $O(k + m)$ +- Time complexity: $O(\frac{n}{k})$ for each function call. +- Space complexity: $O(k + m)$ > Where $n$ is the number of keys, $k$ is the size of the set ($10000$) and $m$ is the number of unique keys. @@ -913,7 +913,7 @@ class BST { return node; } - /** + /** * @param {number} key * @return {boolean} */ @@ -921,7 +921,7 @@ class BST { return this._search(this.root, key); } - /** + /** * @param {TreeNode} node * @param {number} key * @return {boolean} @@ -944,7 +944,7 @@ class MyHashSet { return key % this.size; } - /** + /** * @param {number} key * @return {void} */ @@ -955,7 +955,7 @@ class MyHashSet { } } - /** + /** * @param {number} key * @return {void} */ @@ -964,7 +964,7 @@ class MyHashSet { this.buckets[idx].remove(key); } - /** + /** * @param {number} key * @return {boolean} */ @@ -1080,8 +1080,8 @@ public class MyHashSet { ### Time & Space Complexity -* Time complexity: $O(\log (\frac{n}{k}))$ in average case, $O(\frac{n}{k})$ in worst case for each function call. -* Space complexity: $O(k + m)$ +- Time complexity: $O(\log (\frac{n}{k}))$ in average case, $O(\frac{n}{k})$ in worst case for each function call. +- Space complexity: $O(k + m)$ > Where $n$ is the number of keys, $k$ is the size of the set ($10000$) and $m$ is the number of unique keys. @@ -1183,7 +1183,7 @@ class MyHashSet { this.set = new Array(31251).fill(0); } - /** + /** * @param {number} key * @return {void} */ @@ -1191,7 +1191,7 @@ class MyHashSet { this.set[Math.floor(key / 32)] |= this.getMask(key); } - /** + /** * @param {number} key * @return {void} */ @@ -1201,7 +1201,7 @@ class MyHashSet { } } - /** + /** * @param {number} key * @return {boolean} */ @@ -1209,12 +1209,12 @@ class MyHashSet { return (this.set[Math.floor(key / 32)] & this.getMask(key)) !== 0; } - /** + /** * @param {number} key * @return {number} */ getMask(key) { - return 1 << (key % 32); + return 1 << key % 32; } } ``` @@ -1253,7 +1253,7 @@ public class MyHashSet { ### Time & Space Complexity -* Time complexity: $O(1)$ for each function call. -* Space complexity: $O(k)$ +- Time complexity: $O(1)$ for each function call. +- Space complexity: $O(k)$ -> Where $k$ is the size of the set $(31251)$. \ No newline at end of file +> Where $k$ is the size of the set $(31251)$. diff --git a/articles/design-linked-list.md b/articles/design-linked-list.md index 618c2335c..c0e5df04b 100644 --- a/articles/design-linked-list.md +++ b/articles/design-linked-list.md @@ -275,11 +275,11 @@ class MyLinkedList { ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for initialization. - * $O(1)$ time for $addAtHead()$. - * $O(n)$ time for $get()$, $addAtTail()$, $addAtIndex()$, $deleteAtIndex()$. -* Space complexity: $O(n)$ +- Time complexity: + - $O(1)$ time for initialization. + - $O(1)$ time for $addAtHead()$. + - $O(n)$ time for $get()$, $addAtTail()$, $addAtIndex()$, $deleteAtIndex()$. +- Space complexity: $O(n)$ --- @@ -347,12 +347,12 @@ class ListNode { public class MyLinkedList { ListNode head; int size; - + public MyLinkedList() { head = new ListNode(0, null); size = 0; } - + private ListNode getPrev(int index) { ListNode cur = head; for (int i = 0; i < index; i++) { @@ -360,22 +360,22 @@ public class MyLinkedList { } return cur; } - + public int get(int index) { if (index >= size) { return -1; } return getPrev(index).next.val; } - + public void addAtHead(int val) { addAtIndex(0, val); } - + public void addAtTail(int val) { addAtIndex(size, val); } - + public void addAtIndex(int index, int val) { if (index > size) { return; @@ -385,7 +385,7 @@ public class MyLinkedList { prev.next = node; size++; } - + public void deleteAtIndex(int index) { if (index >= size) { return; @@ -412,20 +412,20 @@ public: head = new ListNode(0, nullptr); size = 0; } - + int get(int index) { if (index >= size) return -1; return getPrev(index)->next->val; } - + void addAtHead(int val) { addAtIndex(0, val); } - + void addAtTail(int val) { addAtIndex(size, val); } - + void addAtIndex(int index, int val) { if (index > size) return; ListNode* prev = getPrev(index); @@ -433,7 +433,7 @@ public: prev->next = node; size++; } - + void deleteAtIndex(int index) { if (index >= size) return; ListNode* prev = getPrev(index); @@ -442,11 +442,11 @@ public: delete toDelete; size--; } - + private: ListNode* head; int size; - + ListNode* getPrev(int index) { ListNode* cur = head; for (int i = 0; i < index; i++) { @@ -459,89 +459,89 @@ private: ```javascript class ListNode { - /** + /** * @constructor - * @param {number} - * @param {ListNode|null} - */ - constructor(val = 0, next = null) { - this.val = val; - this.next = next; - } + * @param {number} + * @param {ListNode|null} + */ + constructor(val = 0, next = null) { + this.val = val; + this.next = next; + } } class MyLinkedList { - constructor() { - this.head = new ListNode(0); - this.size = 0; - } + constructor() { + this.head = new ListNode(0); + this.size = 0; + } - /** - * @param {number} index - * @return {ListNode} - */ - getPrev(index) { - let cur = this.head; - for (let i = 0; i < index; i++) { - cur = cur.next; - } - return cur; - } + /** + * @param {number} index + * @return {ListNode} + */ + getPrev(index) { + let cur = this.head; + for (let i = 0; i < index; i++) { + cur = cur.next; + } + return cur; + } - /** - * @param {number} index - * @return {number} - */ - get(index) { - if (index >= this.size) { - return -1; - } - return this.getPrev(index).next.val; - } + /** + * @param {number} index + * @return {number} + */ + get(index) { + if (index >= this.size) { + return -1; + } + return this.getPrev(index).next.val; + } - /** - * @param {number} val - * @return {void} - */ - addAtHead(val) { - this.addAtIndex(0, val); - } + /** + * @param {number} val + * @return {void} + */ + addAtHead(val) { + this.addAtIndex(0, val); + } - /** - * @param {number} val - * @return {void} - */ - addAtTail(val) { - this.addAtIndex(this.size, val); - } + /** + * @param {number} val + * @return {void} + */ + addAtTail(val) { + this.addAtIndex(this.size, val); + } - /** - * @param {number} index - * @param {number} val - * @return {void} - */ - addAtIndex(index, val) { - if (index > this.size) { - return; - } - let prev = this.getPrev(index); - let node = new ListNode(val, prev.next); - prev.next = node; - this.size++; - } + /** + * @param {number} index + * @param {number} val + * @return {void} + */ + addAtIndex(index, val) { + if (index > this.size) { + return; + } + let prev = this.getPrev(index); + let node = new ListNode(val, prev.next); + prev.next = node; + this.size++; + } - /** - * @param {number} index - * @return {void} - */ - deleteAtIndex(index) { - if (index >= this.size) { - return; - } - let prev = this.getPrev(index); - prev.next = prev.next.next; - this.size--; - } + /** + * @param {number} index + * @return {void} + */ + deleteAtIndex(index) { + if (index >= this.size) { + return; + } + let prev = this.getPrev(index); + prev.next = prev.next.next; + this.size--; + } } ``` @@ -549,11 +549,11 @@ class MyLinkedList { ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for initialization. - * $O(1)$ time for $addAtHead()$. - * $O(n)$ time for $get()$, $addAtTail()$, $addAtIndex()$, $deleteAtIndex()$. -* Space complexity: $O(n)$ +- Time complexity: + - $O(1)$ time for initialization. + - $O(1)$ time for $addAtHead()$. + - $O(n)$ time for $get()$, $addAtTail()$, $addAtIndex()$, $deleteAtIndex()$. +- Space complexity: $O(n)$ --- @@ -799,108 +799,108 @@ public: ```javascript class ListNode { - /** + /** * @constructor - * @param {number} val - */ - constructor(val) { - this.val = val; - this.prev = null; - this.next = null; - } + * @param {number} val + */ + constructor(val) { + this.val = val; + this.prev = null; + this.next = null; + } } class MyLinkedList { - constructor() { - this.head = new ListNode(0); - this.tail = new ListNode(0); - this.head.next = this.tail; - this.tail.prev = this.head; - } + constructor() { + this.head = new ListNode(0); + this.tail = new ListNode(0); + this.head.next = this.tail; + this.tail.prev = this.head; + } - /** - * @param {number} index - * @return {number} - */ - get(index) { - let cur = this.head.next; - while (cur && index > 0) { - cur = cur.next; - index--; - } - if (cur && cur !== this.tail && index === 0) { - return cur.val; - } - return -1; - } + /** + * @param {number} index + * @return {number} + */ + get(index) { + let cur = this.head.next; + while (cur && index > 0) { + cur = cur.next; + index--; + } + if (cur && cur !== this.tail && index === 0) { + return cur.val; + } + return -1; + } - /** - * @param {number} val - * @return {void} - */ - addAtHead(val) { - const node = new ListNode(val); - const next = this.head.next; - const prev = this.head; - prev.next = node; - next.prev = node; - node.next = next; - node.prev = prev; - } + /** + * @param {number} val + * @return {void} + */ + addAtHead(val) { + const node = new ListNode(val); + const next = this.head.next; + const prev = this.head; + prev.next = node; + next.prev = node; + node.next = next; + node.prev = prev; + } - /** - * @param {number} val - * @return {void} - */ - addAtTail(val) { - const node = new ListNode(val); - const next = this.tail; - const prev = this.tail.prev; - prev.next = node; - next.prev = node; - node.next = next; - node.prev = prev; - } + /** + * @param {number} val + * @return {void} + */ + addAtTail(val) { + const node = new ListNode(val); + const next = this.tail; + const prev = this.tail.prev; + prev.next = node; + next.prev = node; + node.next = next; + node.prev = prev; + } - /** - * @param {number} index - * @param {number} val - * @return {void} - */ - addAtIndex(index, val) { - let cur = this.head.next; - while (cur && index > 0) { - cur = cur.next; - index--; - } - if (cur && index === 0) { - const node = new ListNode(val); - const next = cur; - const prev = cur.prev; - prev.next = node; - next.prev = node; - node.next = next; - node.prev = prev; - } - } + /** + * @param {number} index + * @param {number} val + * @return {void} + */ + addAtIndex(index, val) { + let cur = this.head.next; + while (cur && index > 0) { + cur = cur.next; + index--; + } + if (cur && index === 0) { + const node = new ListNode(val); + const next = cur; + const prev = cur.prev; + prev.next = node; + next.prev = node; + node.next = next; + node.prev = prev; + } + } - /** - * @param {number} index - * @return {void} - */ - deleteAtIndex(index) { - let cur = this.head.next; - while (cur && index > 0) { - cur = cur.next; - index--; - } - if (cur && cur !== this.tail && index === 0) { - const next = cur.next; - const prev = cur.prev; - next.prev = prev; - prev.next = next; - } - } + /** + * @param {number} index + * @return {void} + */ + deleteAtIndex(index) { + let cur = this.head.next; + while (cur && index > 0) { + cur = cur.next; + index--; + } + if (cur && cur !== this.tail && index === 0) { + const next = cur.next; + const prev = cur.prev; + next.prev = prev; + prev.next = next; + } + } } ``` @@ -908,11 +908,11 @@ class MyLinkedList { ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for initialization. - * $O(1)$ time for $addAtHead()$, $addAtTail()$. - * $O(n)$ time for $get()$, $addAtIndex()$, $deleteAtIndex()$. -* Space complexity: $O(n)$ +- Time complexity: + - $O(1)$ time for initialization. + - $O(1)$ time for $addAtHead()$, $addAtTail()$. + - $O(n)$ time for $get()$, $addAtIndex()$, $deleteAtIndex()$. +- Space complexity: $O(n)$ --- @@ -985,11 +985,11 @@ class ListNode { int val; ListNode next; ListNode prev; - + ListNode(int val) { this(val, null, null); } - + ListNode(int val, ListNode next, ListNode prev) { this.val = val; this.next = next; @@ -1001,7 +1001,7 @@ public class MyLinkedList { ListNode head; ListNode tail; int size; - + public MyLinkedList() { head = new ListNode(0); tail = new ListNode(0); @@ -1025,20 +1025,20 @@ public class MyLinkedList { return cur; } } - + public int get(int index) { if (index >= size) return -1; return getPrev(index).next.val; } - + public void addAtHead(int val) { addAtIndex(0, val); } - + public void addAtTail(int val) { addAtIndex(size, val); } - + public void addAtIndex(int index, int val) { if (index > size) return; ListNode node = new ListNode(val); @@ -1050,7 +1050,7 @@ public class MyLinkedList { next.prev = node; size++; } - + public void deleteAtIndex(int index) { if (index >= size) return; ListNode prev = getPrev(index); @@ -1075,12 +1075,12 @@ class MyLinkedList { this->prev = prev; } }; - + public: ListNode* head; ListNode* tail; int size; - + MyLinkedList() { head = new ListNode(0); tail = new ListNode(0); @@ -1088,7 +1088,7 @@ public: tail->prev = head; size = 0; } - + ListNode* getPrev(int index) { if (index <= size / 2) { ListNode* cur = head; @@ -1104,20 +1104,20 @@ public: return cur; } } - + int get(int index) { if (index >= size) return -1; return getPrev(index)->next->val; } - + void addAtHead(int val) { addAtIndex(0, val); } - + void addAtTail(int val) { addAtIndex(size, val); } - + void addAtIndex(int index, int val) { if (index > size) return; ListNode* node = new ListNode(val); @@ -1129,7 +1129,7 @@ public: next->prev = node; size++; } - + void deleteAtIndex(int index) { if (index >= size) return; ListNode* prev = getPrev(index); @@ -1151,103 +1151,103 @@ class ListNode { * @param {ListNode|null} * @param {ListNode|null} */ - constructor(val = 0, next = null, prev = null) { - this.val = val; - this.next = next; - this.prev = prev; - } + constructor(val = 0, next = null, prev = null) { + this.val = val; + this.next = next; + this.prev = prev; + } } class MyLinkedList { - constructor() { - this.head = new ListNode(0); - this.tail = new ListNode(0); - this.head.next = this.tail; - this.tail.prev = this.head; - this.size = 0; - } + constructor() { + this.head = new ListNode(0); + this.tail = new ListNode(0); + this.head.next = this.tail; + this.tail.prev = this.head; + this.size = 0; + } - /** - * @param {number} index - * @return {ListNode} - */ - getPrev(index) { - let cur; - if (index <= this.size / 2) { - cur = this.head; - for (let i = 0; i < index; i++) { - cur = cur.next; - } - } else { - cur = this.tail; - for (let i = 0; i < this.size - index + 1; i++) { - cur = cur.prev; - } - } - return cur; - } + /** + * @param {number} index + * @return {ListNode} + */ + getPrev(index) { + let cur; + if (index <= this.size / 2) { + cur = this.head; + for (let i = 0; i < index; i++) { + cur = cur.next; + } + } else { + cur = this.tail; + for (let i = 0; i < this.size - index + 1; i++) { + cur = cur.prev; + } + } + return cur; + } - /** - * @param {number} index - * @return {number} - */ - get(index) { - if (index >= this.size) { - return -1; - } - return this.getPrev(index).next.val; - } + /** + * @param {number} index + * @return {number} + */ + get(index) { + if (index >= this.size) { + return -1; + } + return this.getPrev(index).next.val; + } - /** - * @param {number} val - * @return {void} - */ - addAtHead(val) { - this.addAtIndex(0, val); - } + /** + * @param {number} val + * @return {void} + */ + addAtHead(val) { + this.addAtIndex(0, val); + } - /** - * @param {number} val - * @return {void} - */ - addAtTail(val) { - this.addAtIndex(this.size, val); - } + /** + * @param {number} val + * @return {void} + */ + addAtTail(val) { + this.addAtIndex(this.size, val); + } - /** - * @param {number} index - * @param {number} val - * @return {void} - */ - addAtIndex(index, val) { - if (index > this.size) { - return; - } - const node = new ListNode(val); - const prev = this.getPrev(index); - const next = prev.next; - prev.next = node; - node.prev = prev; - node.next = next; - next.prev = node; - this.size++; - } + /** + * @param {number} index + * @param {number} val + * @return {void} + */ + addAtIndex(index, val) { + if (index > this.size) { + return; + } + const node = new ListNode(val); + const prev = this.getPrev(index); + const next = prev.next; + prev.next = node; + node.prev = prev; + node.next = next; + next.prev = node; + this.size++; + } - /** - * @param {number} index - * @return {void} - */ - deleteAtIndex(index) { - if (index >= this.size) { - return; - } - const prev = this.getPrev(index); - const cur = prev.next; - const next = cur.next; - prev.next = next; - next.prev = prev; - this.size--; - } + /** + * @param {number} index + * @return {void} + */ + deleteAtIndex(index) { + if (index >= this.size) { + return; + } + const prev = this.getPrev(index); + const cur = prev.next; + const next = cur.next; + prev.next = next; + next.prev = prev; + this.size--; + } } ``` @@ -1255,8 +1255,8 @@ class MyLinkedList { ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for initialization. - * $O(1)$ time for $addAtHead()$, $addAtTail()$. - * $O(n)$ time for $get()$, $addAtIndex()$, $deleteAtIndex()$. -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: + - $O(1)$ time for initialization. + - $O(1)$ time for $addAtHead()$, $addAtTail()$. + - $O(n)$ time for $get()$, $addAtIndex()$, $deleteAtIndex()$. +- Space complexity: $O(n)$ diff --git a/articles/design-parking-system.md b/articles/design-parking-system.md index 4abdb9aa3..907eee766 100644 --- a/articles/design-parking-system.md +++ b/articles/design-parking-system.md @@ -84,10 +84,10 @@ class ParkingSystem { ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for initialization. - * $O(1)$ time for each $addCar()$ function call. -* Space complexity: $O(1)$ +- Time complexity: + - $O(1)$ time for initialization. + - $O(1)$ time for each $addCar()$ function call. +- Space complexity: $O(1)$ --- @@ -161,7 +161,7 @@ class ParkingSystem { ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for initialization. - * $O(1)$ time for each $addCar()$ function call. -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: + - $O(1)$ time for initialization. + - $O(1)$ time for each $addCar()$ function call. +- Space complexity: $O(1)$ diff --git a/articles/design-twitter-feed.md b/articles/design-twitter-feed.md index 75eade212..cfc516627 100644 --- a/articles/design-twitter-feed.md +++ b/articles/design-twitter-feed.md @@ -19,7 +19,7 @@ class Twitter: for followeeId in self.followMap[userId]: feed.extend(self.tweetMap[followeeId]) - feed.sort(key=lambda x: -x[0]) + feed.sort(key=lambda x: -x[0]) return [tweetId for _, tweetId in feed[:10]] def follow(self, followerId: int, followeeId: int) -> None: @@ -88,7 +88,7 @@ public: vector getNewsFeed(int userId) { vector> feed = tweetMap[userId]; for (int followeeId : followMap[userId]) { - feed.insert(feed.end(), tweetMap[followeeId].begin(), + feed.insert(feed.end(), tweetMap[followeeId].begin(), tweetMap[followeeId].end()); } sort(feed.begin(), feed.end(), [](auto &a, auto &b) { @@ -137,11 +137,11 @@ class Twitter { */ getNewsFeed(userId) { let feed = [...(this.tweetMap.get(userId) || [])]; - (this.followMap.get(userId) || new Set()).forEach(followeeId => { + (this.followMap.get(userId) || new Set()).forEach((followeeId) => { feed.push(...(this.tweetMap.get(followeeId) || [])); }); feed.sort((a, b) => b[0] - a[0]); - return feed.slice(0, 10).map(x => x[1]); + return feed.slice(0, 10).map((x) => x[1]); } /** @@ -151,7 +151,8 @@ class Twitter { */ follow(followerId, followeeId) { if (followerId !== followeeId) { - if (!this.followMap.has(followerId)) this.followMap.set(followerId, new Set()); + if (!this.followMap.has(followerId)) + this.followMap.set(followerId, new Set()); this.followMap.get(followerId).add(followeeId); } } @@ -246,17 +247,17 @@ func (this *Twitter) PostTweet(userId int, tweetId int) { func (this *Twitter) GetNewsFeed(userId int) []int { feed := make([]Tweet, 0) feed = append(feed, this.tweetMap[userId]...) - + if follows, ok := this.followMap[userId]; ok { for followeeId := range follows { feed = append(feed, this.tweetMap[followeeId]...) } } - + sort.Slice(feed, func(i, j int) bool { return feed[i].time > feed[j].time }) - + result := make([]int, 0) for i := 0; i < len(feed) && i < 10; i++ { result = append(result, feed[i].tweetId) @@ -285,7 +286,7 @@ class Twitter { private var time = 0 private val followMap = HashMap>() private val tweetMap = HashMap>>() - + fun postTweet(userId: Int, tweetId: Int) { if (!tweetMap.containsKey(userId)) { tweetMap[userId] = mutableListOf() @@ -293,19 +294,19 @@ class Twitter { tweetMap[userId]?.add(Pair(time, tweetId)) time++ } - + fun getNewsFeed(userId: Int): List { val feed = mutableListOf>() tweetMap[userId]?.let { feed.addAll(it) } followMap[userId]?.forEach { followeeId -> tweetMap[followeeId]?.let { feed.addAll(it) } } - + return feed.sortedByDescending { it.first } .take(10) .map { it.second } } - + fun follow(followerId: Int, followeeId: Int) { if (followerId != followeeId) { if (!followMap.containsKey(followerId)) { @@ -314,7 +315,7 @@ class Twitter { followMap[followerId]?.add(followeeId) } } - + fun unfollow(followerId: Int, followeeId: Int) { followMap[followerId]?.remove(followeeId) } @@ -370,8 +371,8 @@ class Twitter { ### Time & Space Complexity -* Time complexity: $O(n * m + t\log t)$ for each $getNewsFeed()$ call and $O(1)$ for remaining methods. -* Space complexity: $O(N * m + N * M)$ +- Time complexity: $O(n * m + t\log t)$ for each $getNewsFeed()$ call and $O(1)$ for remaining methods. +- Space complexity: $O(N * m + N * M)$ > Where $n$ is the total number of $followeeIds$ associated with the $userId$, $m$ is the maximum number of tweets by any user, $t$ is the total number of tweets associated with the $userId$ and its $followeeIds$, $N$ is the total number of $userIds$ and $M$ is the maximum number of followees for any user. @@ -421,7 +422,7 @@ class Twitter: ```java public class Twitter { - + private int count; private Map> tweetMap; private Map> followMap; @@ -536,7 +537,7 @@ public: class Twitter { constructor() { - this.count = 0; + this.count = 0; this.tweetMap = new Map(); // userId -> array of [count, tweetId] this.followMap = new Map(); // userId -> set of followeeIds } @@ -564,9 +565,7 @@ class Twitter { this.followMap.set(userId, new Set()); } this.followMap.get(userId).add(userId); - const minHeap = new PriorityQueue( - (a, b) => a[0] - b[0] - ); + const minHeap = new PriorityQueue((a, b) => a[0] - b[0]); for (const followeeId of this.followMap.get(userId)) { if (this.tweetMap.has(followeeId)) { @@ -581,8 +580,14 @@ class Twitter { const [count, tweetId, followeeId, nextIndex] = minHeap.dequeue(); res.push(tweetId); if (nextIndex >= 0) { - const [olderCount, olderTweetId] = this.tweetMap.get(followeeId)[nextIndex]; - minHeap.enqueue([olderCount, olderTweetId, followeeId, nextIndex - 1]); + const [olderCount, olderTweetId] = + this.tweetMap.get(followeeId)[nextIndex]; + minHeap.enqueue([ + olderCount, + olderTweetId, + followeeId, + nextIndex - 1, + ]); } } @@ -704,16 +709,16 @@ func (this *Twitter) PostTweet(userId int, tweetId int) { func (this *Twitter) GetNewsFeed(userId int) []int { res := make([]int, 0) - + minHeap := priorityqueue.NewWith(func(a, b interface{}) int { return a.([]int)[0] - b.([]int)[0] }) - + if this.followMap[userId] == nil { this.followMap[userId] = make(map[int]bool) } this.followMap[userId][userId] = true - + for followeeId := range this.followMap[userId] { tweets := this.tweetMap[followeeId] if len(tweets) > 0 { @@ -722,21 +727,21 @@ func (this *Twitter) GetNewsFeed(userId int) []int { minHeap.Enqueue([]int{count, tweetId, followeeId, index - 1}) } } - + for minHeap.Size() > 0 && len(res) < 10 { item, _ := minHeap.Dequeue() curr := item.([]int) count, tweetId, followeeId, index := curr[0], curr[1], curr[2], curr[3] - + res = append(res, tweetId) - + if index >= 0 { tweets := this.tweetMap[followeeId] count, tweetId = tweets[index][0], tweets[index][1] minHeap.Enqueue([]int{count, tweetId, followeeId, index - 1}) } } - + return res } @@ -759,7 +764,7 @@ class Twitter { private var count = 0 private val tweetMap = HashMap>() // userId -> list of [count, tweetId] private val followMap = HashMap>() // userId -> set of followeeId - + fun postTweet(userId: Int, tweetId: Int) { if (!tweetMap.containsKey(userId)) { tweetMap[userId] = mutableListOf() @@ -767,16 +772,16 @@ class Twitter { tweetMap[userId]?.add(intArrayOf(count, tweetId)) count-- } - + fun getNewsFeed(userId: Int): List { val res = mutableListOf() val minHeap = PriorityQueue(compareBy { it[0] }) - + if (!followMap.containsKey(userId)) { followMap[userId] = HashSet() } followMap[userId]?.add(userId) - + followMap[userId]?.forEach { followeeId -> tweetMap[followeeId]?.let { tweets -> if (tweets.isNotEmpty()) { @@ -786,28 +791,28 @@ class Twitter { } } } - + while (minHeap.isNotEmpty() && res.size < 10) { val (count, tweetId, followeeId, index) = minHeap.poll() res.add(tweetId) - + if (index >= 0) { val tweets = tweetMap[followeeId]!! val (nextCount, nextTweetId) = tweets[index] minHeap.add(intArrayOf(nextCount, nextTweetId, followeeId, index - 1)) } } - + return res } - + fun follow(followerId: Int, followeeId: Int) { if (!followMap.containsKey(followerId)) { followMap[followerId] = HashSet() } followMap[followerId]?.add(followeeId) } - + fun unfollow(followerId: Int, followeeId: Int) { followMap[followerId]?.remove(followeeId) } @@ -819,22 +824,22 @@ class Twitter { private var count: Int private var tweetMap: [Int: [(Int, Int)]] // userId -> list of (count, tweetId) private var followMap: [Int: Set] // userId -> set of followeeId - + init() { self.count = 0 self.tweetMap = [:] self.followMap = [:] } - + func postTweet(_ userId: Int, _ tweetId: Int) { tweetMap[userId, default: []].append((count, tweetId)) count -= 1 } - + func getNewsFeed(_ userId: Int) -> [Int] { var res = [Int]() var minHeap = Heap() - + followMap[userId, default: Set()].insert(userId) if let followees = followMap[userId] { for followee in followees { @@ -850,7 +855,7 @@ class Twitter { } } } - + while !minHeap.isEmpty && res.count < 10 { let entry = minHeap.popMin()! res.append(entry.tweetId) @@ -866,11 +871,11 @@ class Twitter { } return res } - + func follow(_ followerId: Int, _ followeeId: Int) { followMap[followerId, default: Set()].insert(followeeId) } - + func unfollow(_ followerId: Int, _ followeeId: Int) { followMap[followerId]?.remove(followeeId) } @@ -881,11 +886,11 @@ struct Item: Comparable { let tweetId: Int let followeeId: Int let index: Int - + static func < (lhs: Item, rhs: Item) -> Bool { return lhs.count < rhs.count } - + static func == (lhs: Item, rhs: Item) -> Bool { return lhs.count == rhs.count } @@ -896,8 +901,8 @@ struct Item: Comparable { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ for each $getNewsFeed()$ call and $O(1)$ for remaining methods. -* Space complexity: $O(N * m + N * M + n)$ +- Time complexity: $O(n \log n)$ for each $getNewsFeed()$ call and $O(1)$ for remaining methods. +- Space complexity: $O(N * m + N * M + n)$ > Where $n$ is the total number of $followeeIds$ associated with the $userId$, $m$ is the maximum number of tweets by any user, $N$ is the total number of $userIds$ and $M$ is the maximum number of followees for any user. @@ -950,7 +955,7 @@ class Twitter: if index >= 0: count, tweetId = self.tweetMap[followeeId][index] heapq.heappush(minHeap, [count, tweetId, followeeId, index - 1]) - + return res def follow(self, followerId: int, followeeId: int) -> None: @@ -1168,7 +1173,6 @@ class Twitter { const [negCount, tId, fId, idx] = maxHeap.dequeue(); minHeap.enqueue([-negCount, tId, fId, idx]); } - } else { for (const followeeId of this.followMap.get(userId)) { if (!this.tweetMap.has(followeeId)) continue; @@ -1658,7 +1662,7 @@ class Twitter { ### Time & Space Complexity -* Time complexity: $O(n)$ for each $getNewsFeed()$ call and $O(1)$ for remaining methods. -* Space complexity: $O(N * m + N * M + n)$ +- Time complexity: $O(n)$ for each $getNewsFeed()$ call and $O(1)$ for remaining methods. +- Space complexity: $O(N * m + N * M + n)$ -> Where $n$ is the total number of $followeeIds$ associated with the $userId$, $m$ is the maximum number of tweets by any user ($m$ can be at most $10$), $N$ is the total number of $userIds$ and $M$ is the maximum number of followees for any user. \ No newline at end of file +> Where $n$ is the total number of $followeeIds$ associated with the $userId$, $m$ is the maximum number of tweets by any user ($m$ can be at most $10$), $N$ is the total number of $userIds$ and $M$ is the maximum number of followees for any user. diff --git a/articles/design-underground-system.md b/articles/design-underground-system.md index d03c0c9e8..1a3f93bae 100644 --- a/articles/design-underground-system.md +++ b/articles/design-underground-system.md @@ -85,7 +85,7 @@ public: ```javascript class UndergroundSystem { - /** + /** * @constructor */ constructor() { @@ -93,9 +93,9 @@ class UndergroundSystem { this.routeMap = new Map(); } - /** - * @param {number} id - * @param {string} startStation + /** + * @param {number} id + * @param {string} startStation * @param {number} t * @return {void} */ @@ -103,9 +103,9 @@ class UndergroundSystem { this.checkInMap.set(id, [startStation, t]); } - /** - * @param {number} id - * @param {string} endStation + /** + * @param {number} id + * @param {string} endStation * @param {number} t * @return {void} */ @@ -117,13 +117,15 @@ class UndergroundSystem { this.routeMap.get(route)[1] += 1; } - /** - * @param {string} startStation + /** + * @param {string} startStation * @param {string} endStation * @return {number} */ getAverageTime(startStation, endStation) { - const [totalTime, count] = this.routeMap.get(`${startStation},${endStation}`); + const [totalTime, count] = this.routeMap.get( + `${startStation},${endStation}`, + ); return totalTime / count; } } @@ -133,11 +135,11 @@ class UndergroundSystem { ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for initialization. - * $O(1)$ time for each $checkIn()$ function call. - * $O(m)$ time for each $checkOut()$ and $getAverageTime()$ function calls. -* Space complexity: $O(n + N ^ 2)$ +- Time complexity: + - $O(1)$ time for initialization. + - $O(1)$ time for each $checkIn()$ function call. + - $O(m)$ time for each $checkOut()$ and $getAverageTime()$ function calls. +- Space complexity: $O(n + N ^ 2)$ > Where $n$ is the number of passengers, $N$ is the total number of stations, and $m$ is the average length of station name. @@ -273,7 +275,7 @@ public: ```javascript class UndergroundSystem { - /** + /** * @constructor */ constructor() { @@ -285,14 +287,17 @@ class UndergroundSystem { this.routeMap = new Map(); } - /** - * @param {string} s1 + /** + * @param {string} s1 * @param {string} s2 * @return {number} */ getHash(s1, s2) { - let h1 = 0, h2 = 0, p1 = 1, p2 = 1; - let combined = s1 + "," + s2; + let h1 = 0, + h2 = 0, + p1 = 1, + p2 = 1; + let combined = s1 + ',' + s2; for (let i = 0; i < combined.length; i++) { let c = combined.charCodeAt(i) - 96; @@ -301,12 +306,12 @@ class UndergroundSystem { p1 = (p1 * this.BASE1) % this.MOD1; p2 = (p2 * this.BASE2) % this.MOD2; } - return BigInt(h1) << BigInt(32) | BigInt(h2); + return (BigInt(h1) << BigInt(32)) | BigInt(h2); } - /** - * @param {number} id - * @param {string} startStation + /** + * @param {number} id + * @param {string} startStation * @param {number} t * @return {void} */ @@ -314,9 +319,9 @@ class UndergroundSystem { this.checkInMap.set(id, [startStation, t]); } - /** - * @param {number} id - * @param {string} endStation + /** + * @param {number} id + * @param {string} endStation * @param {number} t * @return {void} */ @@ -331,8 +336,8 @@ class UndergroundSystem { data[1]++; } - /** - * @param {string} startStation + /** + * @param {string} startStation * @param {string} endStation * @return {number} */ @@ -348,10 +353,10 @@ class UndergroundSystem { ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for initialization. - * $O(1)$ time for each $checkIn()$ function call. - * $O(m)$ time for each $checkOut()$ and $getAverageTime()$ function calls. -* Space complexity: $O(n + N ^ 2)$ +- Time complexity: + - $O(1)$ time for initialization. + - $O(1)$ time for each $checkIn()$ function call. + - $O(m)$ time for each $checkOut()$ and $getAverageTime()$ function calls. +- Space complexity: $O(n + N ^ 2)$ -> Where $n$ is the number of passengers, $N$ is the total number of stations, and $m$ is the average length of station name. \ No newline at end of file +> Where $n$ is the number of passengers, $N$ is the total number of stations, and $m$ is the average length of station name. diff --git a/articles/design-word-search-data-structure.md b/articles/design-word-search-data-structure.md index 033096234..b6e433175 100644 --- a/articles/design-word-search-data-structure.md +++ b/articles/design-word-search-data-structure.md @@ -44,7 +44,7 @@ public class WordDictionary { if (w.length() != word.length()) continue; int i = 0; while (i < w.length()) { - if (w.charAt(i) == word.charAt(i) || + if (w.charAt(i) == word.charAt(i) || word.charAt(i) == '.') { i++; } else { @@ -104,7 +104,7 @@ class WordDictionary { addWord(word) { this.store.push(word); } - + /** * @param {string} word * @return {boolean} @@ -114,8 +114,7 @@ class WordDictionary { if (w.length !== word.length) continue; let i = 0; while (i < w.length) { - if (w[i] === word[i] || - word[i] === '.') { + if (w[i] === word[i] || word[i] === '.') { i++; } else { break; @@ -262,8 +261,8 @@ class WordDictionary { ### Time & Space Complexity -* Time complexity: $O(1)$ for $addWord()$, $O(m * n)$ for $search()$. -* Space complexity: $O(m * n)$ +- Time complexity: $O(1)$ for $addWord()$, $O(m * n)$ for $search()$. +- Space complexity: $O(m * n)$ > Where $m$ is the number of words added and $n$ is the length of the string. @@ -314,10 +313,10 @@ class WordDictionary: ```java public class TrieNode { - + TrieNode[] children; boolean word; - + public TrieNode() { children = new TrieNode[26]; word = false; @@ -325,7 +324,7 @@ public class TrieNode { } public class WordDictionary { - + private TrieNode root; public WordDictionary() { @@ -438,7 +437,7 @@ class WordDictionary { constructor() { this.root = new TrieNode(); } - + /** * @param {string} c * @return {number} @@ -454,7 +453,7 @@ class WordDictionary { addWord(word) { let cur = this.root; for (const c of word) { - const idx = this.getIndex(c); + const idx = this.getIndex(c); if (cur.children[idx] === null) { cur.children[idx] = new TrieNode(); } @@ -462,8 +461,8 @@ class WordDictionary { } cur.word = true; } - - /** + + /** * @param {string} word * @return {boolean} */ @@ -484,14 +483,13 @@ class WordDictionary { const c = word[i]; if (c === '.') { for (const child of cur.children) { - if (child !== null && - this.dfs(word, i + 1, child)) { + if (child !== null && this.dfs(word, i + 1, child)) { return true; } } return false; } else { - const idx = this.getIndex(c); + const idx = this.getIndex(c); if (cur.children[idx] === null) { return false; } @@ -510,7 +508,7 @@ public class TrieNode { } public class WordDictionary { - + private TrieNode root; public WordDictionary() { @@ -725,7 +723,7 @@ class WordDictionary { ### Time & Space Complexity -* Time complexity: $O(n)$ for $addWord()$, $O(n)$ for $search()$. -* Space complexity: $O(t + n)$ +- Time complexity: $O(n)$ for $addWord()$, $O(n)$ for $search()$. +- Space complexity: $O(t + n)$ -> Where $n$ is the length of the string and $t$ is the total number of TrieNodes created in the Trie. \ No newline at end of file +> Where $n$ is the length of the string and $t$ is the total number of TrieNodes created in the Trie. diff --git a/articles/destination-city.md b/articles/destination-city.md index 0dc585b2b..9cd307442 100644 --- a/articles/destination-city.md +++ b/articles/destination-city.md @@ -76,7 +76,7 @@ class Solution { return paths[i][1]; } } - return ""; + return ''; } } ``` @@ -85,8 +85,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -160,7 +160,7 @@ class Solution { return p[1]; } } - return ""; + return ''; } } ``` @@ -169,8 +169,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -182,7 +182,7 @@ class Solution { class Solution: def destCity(self, paths: List[List[str]]) -> str: mp = {p[0]: p[1] for p in paths} - + start = paths[0][0] while start in mp: start = mp[start] @@ -249,5 +249,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/detonate-the-maximum-bombs.md b/articles/detonate-the-maximum-bombs.md index bc1a75fc9..529a40d0c 100644 --- a/articles/detonate-the-maximum-bombs.md +++ b/articles/detonate-the-maximum-bombs.md @@ -157,8 +157,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 3)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 3)$ +- Space complexity: $O(n ^ 2)$ --- @@ -337,8 +337,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 3)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 3)$ +- Space complexity: $O(n ^ 2)$ --- @@ -518,5 +518,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 3)$ -* Space complexity: $O(n ^ 2)$ \ No newline at end of file +- Time complexity: $O(n ^ 3)$ +- Space complexity: $O(n ^ 2)$ diff --git a/articles/distribute-candies-among-children-ii.md b/articles/distribute-candies-among-children-ii.md index 7cfe42ed0..15096031a 100644 --- a/articles/distribute-candies-among-children-ii.md +++ b/articles/distribute-candies-among-children-ii.md @@ -96,8 +96,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(l ^ 3)$ -* Space complexity: $O(1)$ +- Time complexity: $O(l ^ 3)$ +- Space complexity: $O(1)$ > Where $l$ is the given limit. @@ -200,8 +200,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(min(n, limit) ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(min(n, limit) ^ 2)$ +- Space complexity: $O(1)$ --- @@ -269,7 +269,7 @@ class Solution { const bMax = Math.min(n - a, limit); const bMin = Math.max(0, n - a - limit); if (bMax >= bMin) { - res += (bMax - bMin + 1); + res += bMax - bMin + 1; } } return res; @@ -298,8 +298,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(min(n, limit))$ -* Space complexity: $O(1)$ +- Time complexity: $O(min(n, limit))$ +- Space complexity: $O(1)$ --- @@ -369,7 +369,7 @@ class Solution { if (rem <= 2 * limit) { const hi = Math.min(rem, limit); const lo = Math.max(0, rem - limit); - res += (hi - lo + 1); + res += hi - lo + 1; } } return res; @@ -399,8 +399,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(min(n, limit))$ -* Space complexity: $O(1)$ +- Time complexity: $O(min(n, limit))$ +- Space complexity: $O(1)$ --- @@ -471,8 +471,8 @@ class Solution { for (let j = 0; j < 4; j++) { const m = n - j * (limit + 1); if (m < 0) continue; - const ways = (m + 2) * (m + 1) / 2; - const sign = (j % 2 === 0 ? 1 : -1); + const ways = ((m + 2) * (m + 1)) / 2; + const sign = j % 2 === 0 ? 1 : -1; res += sign * C3[j] * ways; } return res; @@ -501,5 +501,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ diff --git a/articles/distribute-coins-in-binary-tree.md b/articles/distribute-coins-in-binary-tree.md index 4e26d25e9..fd39506bb 100644 --- a/articles/distribute-coins-in-binary-tree.md +++ b/articles/distribute-coins-in-binary-tree.md @@ -156,8 +156,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -311,8 +311,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ fo recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ fo recursion stack. --- @@ -508,8 +508,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -719,5 +719,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/divide-array-into-arrays-with-max-difference.md b/articles/divide-array-into-arrays-with-max-difference.md index d969ca851..13a241fd4 100644 --- a/articles/divide-array-into-arrays-with-max-difference.md +++ b/articles/divide-array-into-arrays-with-max-difference.md @@ -12,7 +12,7 @@ class Solution: if nums[i + 2] - nums[i] > k: return [] res.append(nums[i: i + 3]) - + return res ``` @@ -82,8 +82,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ for the output array. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ for the output array. --- @@ -232,7 +232,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n + m)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(n + m)$ -> Where $n$ is the size of the array $nums$ and $m$ is the maximum element in $nums$. \ No newline at end of file +> Where $n$ is the size of the array $nums$ and $m$ is the maximum element in $nums$. diff --git a/articles/divide-array-into-equal-pairs.md b/articles/divide-array-into-equal-pairs.md index bc8a01fb1..d6a394aec 100644 --- a/articles/divide-array-into-equal-pairs.md +++ b/articles/divide-array-into-equal-pairs.md @@ -106,8 +106,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -200,8 +200,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -286,5 +286,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/dota2-senate.md b/articles/dota2-senate.md index 021619e71..e330b7755 100644 --- a/articles/dota2-senate.md +++ b/articles/dota2-senate.md @@ -37,7 +37,7 @@ public class Solution { for (char c : senate.toCharArray()) { s.add(c); } - + while (true) { int i = 0; while (i < s.size()) { @@ -78,7 +78,7 @@ class Solution { public: string predictPartyVictory(string senate) { vector s(senate.begin(), senate.end()); - + while (true) { int i = 0; while (i < s.size()) { @@ -121,20 +121,20 @@ class Solution { * @return {string} */ predictPartyVictory(senate) { - const s = senate.split(""); - + const s = senate.split(''); + while (true) { let i = 0; while (i < s.length) { - if (!s.includes("R")) { - return "Dire"; + if (!s.includes('R')) { + return 'Dire'; } - if (!s.includes("D")) { - return "Radiant"; + if (!s.includes('D')) { + return 'Radiant'; } - if (s[i] === "R") { + if (s[i] === 'R') { let j = (i + 1) % s.length; - while (s[j] === "R") { + while (s[j] === 'R') { j = (j + 1) % s.length; } s.splice(j, 1); @@ -143,7 +143,7 @@ class Solution { } } else { let j = (i + 1) % s.length; - while (s[j] === "D") { + while (s[j] === 'D') { j = (j + 1) % s.length; } s.splice(j, 1); @@ -194,8 +194,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -301,7 +301,7 @@ class Solution { const n = senate.length; for (let i = 0; i < n; i++) { - if (senate[i] === "R") { + if (senate[i] === 'R') { R.push(i); } else { D.push(i); @@ -319,7 +319,7 @@ class Solution { } } - return !R.isEmpty() ? "Radiant" : "Dire"; + return !R.isEmpty() ? 'Radiant' : 'Dire'; } } ``` @@ -359,8 +359,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -385,7 +385,7 @@ class Solution: senate.append('R') cnt -= 1 i += 1 - + return "Radiant" if cnt > 0 else "Dire" ``` @@ -451,7 +451,8 @@ class Solution { */ predictPartyVictory(senate) { let s = senate.split(''); - let cnt = 0, i = 0; + let cnt = 0, + i = 0; while (i < s.length) { const c = s[i]; @@ -469,7 +470,7 @@ class Solution { i++; } - return cnt > 0 ? "Radiant" : "Dire"; + return cnt > 0 ? 'Radiant' : 'Dire'; } } ``` @@ -505,5 +506,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/duplicate-integer.md b/articles/duplicate-integer.md index 329d2cad4..828d15e2e 100644 --- a/articles/duplicate-integer.md +++ b/articles/duplicate-integer.md @@ -40,7 +40,7 @@ public: } return false; } -}; +}; ``` ```javascript @@ -124,8 +124,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -248,8 +248,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -380,8 +380,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -462,5 +462,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/eating-bananas.md b/articles/eating-bananas.md index 4acd82fb0..938d7b892 100644 --- a/articles/eating-bananas.md +++ b/articles/eating-bananas.md @@ -10,7 +10,7 @@ class Solution: totalTime = 0 for pile in piles: totalTime += math.ceil(pile / speed) - + if totalTime <= h: return speed speed += 1 @@ -44,7 +44,7 @@ public: while (true) { long long totalTime = 0; for (int pile : piles) { - totalTime += (pile + speed - 1) / speed; + totalTime += (pile + speed - 1) / speed; } if (totalTime <= h) { @@ -107,7 +107,7 @@ func minEatingSpeed(piles []int, h int) int { for _, pile := range piles { totalTime += int(math.Ceil(float64(pile) / float64(speed))) } - + if totalTime <= h { return speed } @@ -126,7 +126,7 @@ class Solution { for (pile in piles) { totalTime += Math.ceil(pile.toDouble() / speed).toLong() } - + if (totalTime <= h) { return speed } @@ -141,13 +141,13 @@ class Solution { class Solution { func minEatingSpeed(_ piles: [Int], _ h: Int) -> Int { var speed = 1 - + while true { var totalTime = 0 for pile in piles { totalTime += Int(ceil(Double(pile) / Double(speed))) } - + if totalTime <= h { return speed } @@ -162,8 +162,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(1)$ > Where $n$ is the length of the input array $piles$ and $m$ is the maximum number of bananas in a pile. @@ -312,15 +312,15 @@ func minEatingSpeed(piles []int, h int) int { } } res := r - + for l <= r { k := (l + r) / 2 totalTime := 0 - + for _, p := range piles { totalTime += int(math.Ceil(float64(p) / float64(k))) } - + if totalTime <= h { res = k r = k - 1 @@ -338,15 +338,15 @@ class Solution { var l = 1 var r = piles.max()!! var res = r - + while (l <= r) { val k = (l + r) / 2 var totalTime = 0L - + for (p in piles) { totalTime += Math.ceil(p.toDouble() / k).toLong() } - + if (totalTime <= h) { res = k r = k - 1 @@ -389,7 +389,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * \log m)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n * \log m)$ +- Space complexity: $O(1)$ -> Where $n$ is the length of the input array $piles$ and $m$ is the maximum number of bananas in a pile. \ No newline at end of file +> Where $n$ is the length of the input array $piles$ and $m$ is the maximum number of bananas in a pile. diff --git a/articles/edit-distance.md b/articles/edit-distance.md index 7c4b6bfeb..64e70d7de 100644 --- a/articles/edit-distance.md +++ b/articles/edit-distance.md @@ -17,7 +17,7 @@ class Solution: res = min(dfs(i + 1, j), dfs(i, j + 1)) res = min(res, dfs(i + 1, j + 1)) return res + 1 - + return dfs(0, 0) ``` @@ -37,7 +37,7 @@ public class Solution { return dfs(i + 1, j + 1, word1, word2, m, n); } - int res = Math.min(dfs(i + 1, j, word1, word2, m, n), + int res = Math.min(dfs(i + 1, j, word1, word2, m, n), dfs(i, j + 1, word1, word2, m, n)); res = Math.min(res, dfs(i + 1, j + 1, word1, word2, m, n)); return res + 1; @@ -52,15 +52,15 @@ public: int m = word1.size(), n = word2.size(); return dfs(0, 0, word1, word2, m, n); } - + int dfs(int i, int j, string& word1, string& word2, int m, int n) { if (i == m) return n - j; if (j == n) return m - i; if (word1[i] == word2[j]){ return dfs(i + 1, j + 1, word1, word2, m, n); - } + } - int res = min(dfs(i + 1, j, word1, word2, m, n), + int res = min(dfs(i + 1, j, word1, word2, m, n), dfs(i, j + 1, word1, word2, m, n)); res = min(res, dfs(i + 1, j + 1, word1, word2, m, n)); return res + 1; @@ -76,7 +76,8 @@ class Solution { * @return {number} */ minDistance(word1, word2) { - const m = word1.length, n = word2.length; + const m = word1.length, + n = word2.length; const dfs = (i, j) => { if (i === m) return n - j; @@ -109,7 +110,7 @@ public class Solution { return Dfs(i + 1, j + 1, word1, word2, m, n); } - int res = Math.Min(Dfs(i + 1, j, word1, word2, m, n), + int res = Math.Min(Dfs(i + 1, j, word1, word2, m, n), Dfs(i, j + 1, word1, word2, m, n)); res = Math.Min(res, Dfs(i + 1, j + 1, word1, word2, m, n)); return res + 1; @@ -194,8 +195,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(3 ^ {m + n})$ -* Space complexity: $O(m + n)$ +- Time complexity: $O(3 ^ {m + n})$ +- Space complexity: $O(m + n)$ > Where $m$ is the length of $word1$ and $n$ is the length of $word2$. @@ -218,7 +219,7 @@ class Solution: return m - i if (i, j) in dp: return dp[(i, j)] - + if word1[i] == word2[j]: dp[(i, j)] = dfs(i + 1, j + 1) else: @@ -226,7 +227,7 @@ class Solution: res = min(res, dfs(i + 1, j + 1)) dp[(i, j)] = res + 1 return dp[(i, j)] - + return dfs(0, 0) ``` @@ -252,7 +253,7 @@ public class Solution { if (word1.charAt(i) == word2.charAt(j)) { dp[i][j] = dfs(i + 1, j + 1, word1, word2, m, n); } else { - int res = Math.min(dfs(i + 1, j, word1, word2, m, n), + int res = Math.min(dfs(i + 1, j, word1, word2, m, n), dfs(i, j + 1, word1, word2, m, n)); res = Math.min(res, dfs(i + 1, j + 1, word1, word2, m, n)); dp[i][j] = res + 1; @@ -271,7 +272,7 @@ public: dp = vector>(m, vector(n, -1)); return dfs(0, 0, word1, word2, m, n); } - + int dfs(int i, int j, string& word1, string& word2, int m, int n) { if (i == m) return n - j; if (j == n) return m - i; @@ -279,7 +280,7 @@ public: if (word1[i] == word2[j]){ dp[i][j] = dfs(i + 1, j + 1, word1, word2, m, n); } else { - int res = min(dfs(i + 1, j, word1, word2, m, n), + int res = min(dfs(i + 1, j, word1, word2, m, n), dfs(i, j + 1, word1, word2, m, n)); res = min(res, dfs(i + 1, j + 1, word1, word2, m, n)); dp[i][j] = res + 1; @@ -297,9 +298,9 @@ class Solution { * @return {number} */ minDistance(word1, word2) { - const m = word1.length, n = word2.length; - let dp = Array.from({ length: m + 1 }, () => - Array(n + 1).fill(-1)); + const m = word1.length, + n = word2.length; + let dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(-1)); const dfs = (i, j) => { if (i === m) return n - j; if (j === n) return m - i; @@ -322,31 +323,31 @@ class Solution { ```csharp public class Solution { - private int?[,] dp; + private int?[,] dp; public int MinDistance(string word1, string word2) { int m = word1.Length, n = word2.Length; - dp = new int?[m + 1, n + 1]; + dp = new int?[m + 1, n + 1]; return Dfs(0, 0, word1, word2, m, n); } private int Dfs(int i, int j, string word1, string word2, int m, int n) { - if (i == m) return n - j; - if (j == n) return m - i; + if (i == m) return n - j; + if (j == n) return m - i; - if (dp[i, j].HasValue) { + if (dp[i, j].HasValue) { return dp[i, j].Value; } if (word1[i] == word2[j]) { - dp[i, j] = Dfs(i + 1, j + 1, word1, word2, m, n); + dp[i, j] = Dfs(i + 1, j + 1, word1, word2, m, n); } else { - int res = Math.Min(Dfs(i + 1, j, word1, word2, m, n), + int res = Math.Min(Dfs(i + 1, j, word1, word2, m, n), Dfs(i, j + 1, word1, word2, m, n)); - res = Math.Min(res, Dfs(i + 1, j + 1, word1, word2, m, n)); - dp[i, j] = res + 1; + res = Math.Min(res, Dfs(i + 1, j + 1, word1, word2, m, n)); + dp[i, j] = res + 1; } - return dp[i, j].Value; + return dp[i, j].Value; } } ``` @@ -358,7 +359,7 @@ func minDistance(word1 string, word2 string) int { for i := range dp { dp[i] = make([]int, n+1) for j := range dp[i] { - dp[i][j] = -1 + dp[i][j] = -1 } } @@ -454,8 +455,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the length of $word1$ and $n$ is the length of $word2$. @@ -501,7 +502,7 @@ public class Solution { if (word1.charAt(i) == word2.charAt(j)) { dp[i][j] = dp[i + 1][j + 1]; } else { - dp[i][j] = 1 + Math.min(dp[i + 1][j], + dp[i][j] = 1 + Math.min(dp[i + 1][j], Math.min(dp[i][j + 1], dp[i + 1][j + 1])); } } @@ -515,7 +516,7 @@ public class Solution { class Solution { public: int minDistance(string word1, string word2) { - vector> dp(word1.length() + 1, + vector> dp(word1.length() + 1, vector(word2.length() + 1, 0)); for (int j = 0; j <= word2.length(); j++) { @@ -530,7 +531,7 @@ public: if (word1[i] == word2[j]) { dp[i][j] = dp[i + 1][j + 1]; } else { - dp[i][j] = 1 + min(dp[i + 1][j], + dp[i][j] = 1 + min(dp[i + 1][j], min(dp[i][j + 1], dp[i + 1][j + 1])); } } @@ -595,7 +596,7 @@ public class Solution { if (word1[i] == word2[j]) { dp[i, j] = dp[i + 1, j + 1]; } else { - dp[i, j] = 1 + Math.Min(dp[i + 1, j], + dp[i, j] = 1 + Math.Min(dp[i + 1, j], Math.Min(dp[i, j + 1], dp[i + 1, j + 1])); } } @@ -625,7 +626,7 @@ func minDistance(word1, word2 string) int { if word1[i] == word2[j] { dp[i][j] = dp[i+1][j+1] } else { - dp[i][j] = 1 + min(dp[i+1][j], + dp[i][j] = 1 + min(dp[i+1][j], min(dp[i][j+1], dp[i+1][j+1])) } } @@ -661,7 +662,7 @@ class Solution { if (word1[i] == word2[j]) { dp[i][j] = dp[i + 1][j + 1] } else { - dp[i][j] = 1 + minOf(dp[i + 1][j], + dp[i][j] = 1 + minOf(dp[i + 1][j], minOf(dp[i][j + 1], dp[i + 1][j + 1])) } } @@ -703,8 +704,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the length of $word1$ and $n$ is the length of $word2$. @@ -736,7 +737,7 @@ class Solution: else: nextDp[j] = 1 + min(dp[j], nextDp[j + 1], dp[j + 1]) dp = nextDp[:] - + return dp[0] ``` @@ -755,7 +756,7 @@ class Solution { int[] dp = new int[n + 1]; int[] nextDp = new int[n + 1]; - + for (int j = 0; j <= n; j++) { dp[j] = n - j; } @@ -766,13 +767,13 @@ class Solution { if (word1.charAt(i) == word2.charAt(j)) { nextDp[j] = dp[j + 1]; } else { - nextDp[j] = 1 + Math.min(dp[j], + nextDp[j] = 1 + Math.min(dp[j], Math.min(nextDp[j + 1], dp[j + 1])); } } System.arraycopy(nextDp, 0, dp, 0, n + 1); } - + return dp[0]; } } @@ -789,7 +790,7 @@ public: } vector dp(n + 1), nextDp(n + 1); - + for (int j = 0; j <= n; ++j) { dp[j] = n - j; } @@ -818,7 +819,8 @@ class Solution { * @return {number} */ minDistance(word1, word2) { - let m = word1.length, n = word2.length; + let m = word1.length, + n = word2.length; if (m < n) { [m, n] = [n, m]; [word1, word2] = [word2, word1]; @@ -837,8 +839,8 @@ class Solution { if (word1[i] === word2[j]) { nextDp[j] = dp[j + 1]; } else { - nextDp[j] = 1 + Math.min(dp[j], - Math.min(nextDp[j + 1], dp[j + 1])); + nextDp[j] = + 1 + Math.min(dp[j], Math.min(nextDp[j + 1], dp[j + 1])); } } dp = [...nextDp]; @@ -875,7 +877,7 @@ public class Solution { if (word1[i] == word2[j]) { nextDp[j] = dp[j + 1]; } else { - nextDp[j] = 1 + Math.Min(dp[j], + nextDp[j] = 1 + Math.Min(dp[j], Math.Min(nextDp[j + 1], dp[j + 1])); } } @@ -908,13 +910,13 @@ func minDistance(word1, word2 string) int { if word1[i] == word2[j] { nextDp[j] = dp[j+1] } else { - nextDp[j] = 1 + min(dp[j], + nextDp[j] = 1 + min(dp[j], min(nextDp[j+1], dp[j+1])) } } dp, nextDp = nextDp, dp } - + return dp[0] } @@ -970,7 +972,7 @@ class Solution { func minDistance(_ word1: String, _ word2: String) -> Int { var m = word1.count, n = word2.count var word1Array = Array(word1), word2Array = Array(word2) - + if m < n { swap(&m, &n) swap(&word1Array, &word2Array) @@ -1004,8 +1006,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(min(m, n))$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(min(m, n))$ > Where $m$ is the length of $word1$ and $n$ is the length of $word2$. @@ -1022,7 +1024,7 @@ class Solution: if m < n: m, n = n, m word1, word2 = word2, word1 - + dp = [n - i for i in range(n + 1)] for i in range(m - 1, -1, -1): @@ -1058,7 +1060,7 @@ public class Solution { if (word1.charAt(i) == word2.charAt(j)) { dp[j] = nextDp; } else { - dp[j] = 1 + Math.min(dp[j], + dp[j] = 1 + Math.min(dp[j], Math.min(dp[j + 1], nextDp)); } nextDp = temp; @@ -1108,7 +1110,8 @@ class Solution { * @return {number} */ minDistance(word1, word2) { - let m = word1.length, n = word2.length; + let m = word1.length, + n = word2.length; if (m < n) { [m, n] = [n, m]; [word1, word2] = [word2, word1]; @@ -1158,7 +1161,7 @@ public class Solution { if (word1[i] == word2[j]) { dp[j] = nextDp; } else { - dp[j] = 1 + Math.Min(dp[j], + dp[j] = 1 + Math.Min(dp[j], Math.Min(dp[j + 1], nextDp)); } nextDp = temp; @@ -1190,7 +1193,7 @@ func minDistance(word1, word2 string) int { if word1[i] == word2[j] { dp[j] = nextDp } else { - dp[j] = 1 + min(dp[j], + dp[j] = 1 + min(dp[j], min(dp[j+1], nextDp)) } nextDp = temp @@ -1249,7 +1252,7 @@ class Solution { func minDistance(_ word1: String, _ word2: String) -> Int { var m = word1.count, n = word2.count var word1Array = Array(word1), word2Array = Array(word2) - + if m < n { swap(&m, &n) swap(&word1Array, &word2Array) @@ -1279,7 +1282,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(min(m, n))$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(min(m, n))$ -> Where $m$ is the length of $word1$ and $n$ is the length of $word2$. \ No newline at end of file +> Where $m$ is the length of $word1$ and $n$ is the length of $word2$. diff --git a/articles/eliminate-maximum-number-of-monsters.md b/articles/eliminate-maximum-number-of-monsters.md index 551c82473..a3f9acc21 100644 --- a/articles/eliminate-maximum-number-of-monsters.md +++ b/articles/eliminate-maximum-number-of-monsters.md @@ -102,8 +102,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -195,8 +195,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -294,5 +294,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ diff --git a/articles/encode-and-decode-tinyurl.md b/articles/encode-and-decode-tinyurl.md index 0da60014f..06ca58c8e 100644 --- a/articles/encode-and-decode-tinyurl.md +++ b/articles/encode-and-decode-tinyurl.md @@ -87,8 +87,8 @@ class Codec { ### Time & Space Complexity -* Time complexity: $O(1)$ for $encode()$ and $decode()$. -* Space complexity: $O(n * m)$ +- Time complexity: $O(1)$ for $encode()$ and $decode()$. +- Space complexity: $O(n * m)$ > Where $n$ is the number of $longUrls$, $m$ is the average length of the URLs. @@ -193,8 +193,8 @@ class Codec { ### Time & Space Complexity -* Time complexity: $O(1)$ for $encode()$ and $decode()$. -* Space complexity: $O(n * m)$ +- Time complexity: $O(1)$ for $encode()$ and $decode()$. +- Space complexity: $O(n * m)$ > Where $n$ is the number of $longUrls$, $m$ is the average length of the URLs. @@ -206,7 +206,7 @@ class Codec { ```python class Codec: - + def __init__(self): self.encodeMap = {} self.decodeMap = {} @@ -272,7 +272,7 @@ class Codec { constructor() { this.encodeMap = new Map(); this.decodeMap = new Map(); - this.base = "http://tinyurl.com/"; + this.base = 'http://tinyurl.com/'; } /** @@ -306,7 +306,7 @@ class Codec { ### Time & Space Complexity -* Time complexity: $O(1)$ for $encode()$ and $decode()$. -* Space complexity: $O(n * m)$ +- Time complexity: $O(1)$ for $encode()$ and $decode()$. +- Space complexity: $O(n * m)$ -> Where $n$ is the number of $longUrls$, $m$ is the average length of the URLs. \ No newline at end of file +> Where $n$ is the number of $longUrls$, $m$ is the average length of the URLs. diff --git a/articles/evaluate-boolean-binary-tree.md b/articles/evaluate-boolean-binary-tree.md index 4b8fd67ca..96c0e9ada 100644 --- a/articles/evaluate-boolean-binary-tree.md +++ b/articles/evaluate-boolean-binary-tree.md @@ -110,11 +110,15 @@ class Solution { } if (root.val === 2) { - return this.evaluateTree(root.left) || this.evaluateTree(root.right); + return ( + this.evaluateTree(root.left) || this.evaluateTree(root.right) + ); } if (root.val === 3) { - return this.evaluateTree(root.left) && this.evaluateTree(root.right); + return ( + this.evaluateTree(root.left) && this.evaluateTree(root.right) + ); } return false; @@ -126,8 +130,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -305,5 +309,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/evaluate-division.md b/articles/evaluate-division.md index 9be40ad06..b5a942f01 100644 --- a/articles/evaluate-division.md +++ b/articles/evaluate-division.md @@ -253,8 +253,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(n + m)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(n + m)$ > Where $n$ is the number of unique strings and $m$ is the number of queries. @@ -490,8 +490,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(n + m)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(n + m)$ > Where $n$ is the number of unique strings and $m$ is the number of queries. @@ -506,29 +506,29 @@ class UnionFind: def __init__(self): self.parent = {} self.weight = {} - + def add(self, x): if x not in self.parent: self.parent[x] = x self.weight[x] = 1.0 - + def find(self, x): if x != self.parent[x]: orig_parent = self.parent[x] self.parent[x] = self.find(self.parent[x]) self.weight[x] *= self.weight[orig_parent] return self.parent[x] - + def union(self, x, y, value): self.add(x) self.add(y) root_x = self.find(x) root_y = self.find(y) - + if root_x != root_y: self.parent[root_x] = root_y self.weight[root_x] = value * self.weight[y] / self.weight[x] - + def get_ratio(self, x, y): if x not in self.parent or y not in self.parent or self.find(x) != self.find(y): return -1.0 @@ -537,10 +537,10 @@ class UnionFind: class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: uf = UnionFind() - + for (a, b), value in zip(equations, values): uf.union(a, b, value) - + return [uf.get_ratio(a, b) for a, b in queries] ``` @@ -705,7 +705,10 @@ class UnionFind { if (x !== this.parent.get(x)) { const origParent = this.parent.get(x); this.parent.set(x, this.find(origParent)); - this.weight.set(x, this.weight.get(x) * this.weight.get(origParent)); + this.weight.set( + x, + this.weight.get(x) * this.weight.get(origParent), + ); } return this.parent.get(x); } @@ -724,17 +727,24 @@ class UnionFind { if (rootX !== rootY) { this.parent.set(rootX, rootY); - this.weight.set(rootX, (value * this.weight.get(y)) / this.weight.get(x)); + this.weight.set( + rootX, + (value * this.weight.get(y)) / this.weight.get(x), + ); } } - + /** * @param {string} x * @param {string} y * @return {number} */ getRatio(x, y) { - if (!this.parent.has(x) || !this.parent.has(y) || this.find(x) !== this.find(y)) { + if ( + !this.parent.has(x) || + !this.parent.has(y) || + this.find(x) !== this.find(y) + ) { return -1.0; } return this.weight.get(x) / this.weight.get(y); @@ -805,7 +815,7 @@ public class UnionFind { public class Solution { public double[] CalcEquation(List> equations, double[] values, List> queries) { var uf = new UnionFind(); - + for (int i = 0; i < equations.Count; i++) { string a = equations[i][0]; string b = equations[i][1]; @@ -828,8 +838,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O((m + n)\log n)$ -* Space complexity: $O(n + m)$ +- Time complexity: $O((m + n)\log n)$ +- Space complexity: $O(n + m)$ > Where $n$ is the number of unique strings and $m$ is the number of queries. @@ -967,7 +977,9 @@ class Solution { for (const i of graph.get(k).keys()) { for (const j of graph.get(k).keys()) { if (!graph.get(i).has(j)) { - graph.get(i).set(j, graph.get(i).get(k) * graph.get(k).get(j)); + graph + .get(i) + .set(j, graph.get(i).get(k) * graph.get(k).get(j)); } } } @@ -1031,7 +1043,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n ^ 3)$ -* Space complexity: $O(n ^ 2 + m)$ +- Time complexity: $O(m + n ^ 3)$ +- Space complexity: $O(n ^ 2 + m)$ -> Where $n$ is the number of unique strings and $m$ is the number of queries. \ No newline at end of file +> Where $n$ is the number of unique strings and $m$ is the number of queries. diff --git a/articles/evaluate-reverse-polish-notation.md b/articles/evaluate-reverse-polish-notation.md index 3ad96eff8..f08beec96 100644 --- a/articles/evaluate-reverse-polish-notation.md +++ b/articles/evaluate-reverse-polish-notation.md @@ -27,16 +27,16 @@ class Solution: public class Solution { public int evalRPN(String[] tokens) { List tokenList = new ArrayList<>(Arrays.asList(tokens)); - + while (tokenList.size() > 1) { for (int i = 0; i < tokenList.size(); i++) { String token = tokenList.get(i); - + if ("+-*/".contains(token)) { int a = Integer.parseInt(tokenList.get(i - 2)); int b = Integer.parseInt(tokenList.get(i - 1)); int result = 0; - + if (token.equals("+")) { result = a + b; } else if (token.equals("-")) { @@ -46,10 +46,10 @@ public class Solution { } else if (token.equals("/")) { result = a / b; } - + tokenList.set(i - 2, String.valueOf(result)); - tokenList.remove(i); - tokenList.remove(i - 1); + tokenList.remove(i); + tokenList.remove(i - 1); break; } } @@ -65,10 +65,10 @@ public: int evalRPN(vector& tokens) { while (tokens.size() > 1) { for (int i = 0; i < tokens.size(); i++) { - if (tokens[i] == "+" - || tokens[i] == "-" - || tokens[i] == "*" - || tokens[i] == "/") + if (tokens[i] == "+" + || tokens[i] == "-" + || tokens[i] == "*" + || tokens[i] == "/") { int a = stoi(tokens[i - 2]); int b = stoi(tokens[i - 1]); @@ -77,7 +77,7 @@ public: else if (tokens[i] == "-") result = a - b; else if (tokens[i] == "*") result = a * b; else if (tokens[i] == "/") result = a / b; - + tokens.erase(tokens.begin() + i - 2, tokens.begin() + i + 1); tokens.insert(tokens.begin() + i - 2, to_string(result)); break; @@ -94,15 +94,15 @@ class Solution { evalRPN(tokens) { while (tokens.length > 1) { for (let i = 0; i < tokens.length; i++) { - if ("+-*/".includes(tokens[i])) { + if ('+-*/'.includes(tokens[i])) { const a = parseInt(tokens[i - 2]); const b = parseInt(tokens[i - 1]); let result; - if (tokens[i] === "+") result = a + b; - else if (tokens[i] === "-") result = a - b; - else if (tokens[i] === "*") result = a * b; - else if (tokens[i] === "/") result = Math.trunc(a / b); - + if (tokens[i] === '+') result = a + b; + else if (tokens[i] === '-') result = a - b; + else if (tokens[i] === '*') result = a * b; + else if (tokens[i] === '/') result = Math.trunc(a / b); + tokens.splice(i - 2, 3, result.toString()); break; } @@ -117,7 +117,7 @@ class Solution { public class Solution { public int EvalRPN(string[] tokens) { List tokenList = new List(tokens); - + while (tokenList.Count > 1) { for (int i = 0; i < tokenList.Count; i++) { if ("+-*/".Contains(tokenList[i])) { @@ -157,12 +157,12 @@ func evalRPN(tokens []string) int { a, _ := strconv.Atoi(tokens[i-2]) b, _ := strconv.Atoi(tokens[i-1]) var result int - + switch tokens[i] { case "+": result = a + b case "-": - result = a - b + result = a - b case "*": result = a * b case "/": @@ -178,7 +178,7 @@ func evalRPN(tokens []string) int { } } } - + result, _ := strconv.Atoi(tokens[0]) return result } @@ -188,7 +188,7 @@ func evalRPN(tokens []string) int { class Solution { fun evalRPN(tokens: Array): Int { val A = tokens.toMutableList() - + while (A.size > 1) { for (i in A.indices) { if (A[i] in setOf("+", "-", "*", "/")) { @@ -200,9 +200,9 @@ class Solution { "*" -> a * b else -> a / b } - - val temp = A.slice(0..i-3) + - result.toString() + + + val temp = A.slice(0..i-3) + + result.toString() + A.slice(i+1..A.lastIndex) A.clear() A.addAll(temp) @@ -210,7 +210,7 @@ class Solution { } } } - + return A[0].toInt() } } @@ -227,7 +227,7 @@ class Solution { let a = Int(tokens[i-2])! let b = Int(tokens[i-1])! var result = 0 - + if tokens[i] == "+" { result = a + b } else if tokens[i] == "-" { @@ -237,7 +237,7 @@ class Solution { } else if tokens[i] == "/" { result = Int(a / b) } - + tokens = Array(tokens[0..<(i-2)]) + [String(result)] + Array(tokens[(i+1)...]) break } @@ -253,8 +253,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -364,7 +364,7 @@ public: DoublyLinkedList* next; DoublyLinkedList* prev; - DoublyLinkedList(string val, DoublyLinkedList* next = nullptr, + DoublyLinkedList(string val, DoublyLinkedList* next = nullptr, DoublyLinkedList* prev = nullptr) { this->val = val; this->next = next; @@ -386,9 +386,9 @@ public: int ans = 0; while (head != nullptr) { if (head->val == "+" || - head->val == "-" || - head->val == "*" || - head->val == "/") + head->val == "-" || + head->val == "*" || + head->val == "/") { int l = stoi(head->prev->prev->val); int r = stoi(head->prev->val); @@ -444,15 +444,15 @@ class Solution { let ans = 0; while (head !== null) { - if ("+-*/".includes(head.val)) { + if ('+-*/'.includes(head.val)) { let l = parseInt(head.prev.prev.val); let r = parseInt(head.prev.val); let res = 0; - if (head.val === "+") { + if (head.val === '+') { res = l + r; - } else if (head.val === "-") { + } else if (head.val === '-') { res = l - r; - } else if (head.val === "*") { + } else if (head.val === '*') { res = l * r; } else { res = Math.trunc(l / r); @@ -480,7 +480,7 @@ public class DoublyLinkedList { public DoublyLinkedList next; public DoublyLinkedList prev; - public DoublyLinkedList(string val, DoublyLinkedList next = null, + public DoublyLinkedList(string val, DoublyLinkedList next = null, DoublyLinkedList prev = null) { this.val = val; this.next = next; @@ -540,18 +540,18 @@ type DoublyLinkedList struct { func evalRPN(tokens []string) int { head := &DoublyLinkedList{val: tokens[0]} curr := head - + for i := 1; i < len(tokens); i++ { newNode := &DoublyLinkedList{val: tokens[i], prev: curr} curr.next = newNode curr = curr.next } - + for head != nil { if head.val == "+" || head.val == "-" || head.val == "*" || head.val == "/" { l, _ := strconv.Atoi(head.prev.prev.val) r, _ := strconv.Atoi(head.prev.val) - + var res int switch head.val { case "+": @@ -563,17 +563,17 @@ func evalRPN(tokens []string) int { case "/": res = l / r } - + head.val = strconv.Itoa(res) head.prev = head.prev.prev.prev if head.prev != nil { head.prev.next = head } } - + head = head.next } - + ans, _ := strconv.Atoi(curr.val) return ans } @@ -590,34 +590,34 @@ class Solution { fun evalRPN(tokens: Array): Int { val head = DoublyLinkedList(tokens[0]) var curr = head - + for (i in 1 until tokens.size) { val newNode = DoublyLinkedList(tokens[i], prev = curr) curr.next = newNode curr = newNode } - + var ptr: DoublyLinkedList? = head while (ptr != null) { if (ptr.value in setOf("+", "-", "*", "/")) { val l = ptr.prev!!.prev!!.value.toInt() val r = ptr.prev!!.value.toInt() - + val res = when (ptr.value) { "+" -> l + r "-" -> l - r "*" -> l * r else -> l / r } - + ptr.value = res.toString() ptr.prev = ptr.prev!!.prev!!.prev ptr.prev?.next = ptr } - + ptr = ptr.next } - + return curr.value.toInt() } } @@ -685,8 +685,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -701,10 +701,10 @@ class Solution: token = tokens.pop() if token not in "+-*/": return int(token) - + right = dfs() left = dfs() - + if token == '+': return left + right elif token == '-': @@ -713,7 +713,7 @@ class Solution: return left * right elif token == '/': return int(left / right) - + return dfs() ``` @@ -726,7 +726,7 @@ public class Solution { private int dfs(List tokens) { String token = tokens.remove(tokens.size() - 1); - + if (!"+-*/".contains(token)) { return Integer.parseInt(token); } @@ -756,16 +756,16 @@ public: int dfs(vector& tokens) { string token = tokens.back(); tokens.pop_back(); - + if (token != "+" && token != "-" && - token != "*" && token != "/") + token != "*" && token != "/") { return stoi(token); } int right = dfs(tokens); int left = dfs(tokens); - + if (token == "+") { return left + right; } else if (token == "-") { @@ -790,13 +790,12 @@ class Solution { * @return {number} */ evalRPN(tokens) { - /** * @return {number} */ const dfs = () => { const token = tokens.pop(); - if (!"+-*/".includes(token)) { + if (!'+-*/'.includes(token)) { return parseInt(token); } @@ -854,20 +853,20 @@ public class Solution { ```go func evalRPN(tokens []string) int { index := len(tokens) - 1 - + var dfs func() int dfs = func() int { token := tokens[index] index-- - + if token != "+" && token != "-" && token != "*" && token != "/" { val, _ := strconv.Atoi(token) return val } - + right := dfs() left := dfs() - + switch token { case "+": return left + right @@ -879,7 +878,7 @@ func evalRPN(tokens []string) int { return left / right } } - + return dfs() } ``` @@ -887,21 +886,21 @@ func evalRPN(tokens []string) int { ```kotlin class Solution { private var index = 0 - + fun evalRPN(tokens: Array): Int { index = tokens.size - 1 - + fun dfs(): Int { val token = tokens[index] index-- - + if (token !in setOf("+", "-", "*", "/")) { return token.toInt() } - + val right = dfs() val left = dfs() - + return when (token) { "+" -> left + right "-" -> left - right @@ -909,7 +908,7 @@ class Solution { else -> left / right } } - + return dfs() } } @@ -919,7 +918,7 @@ class Solution { class Solution { func evalRPN(_ tokens: [String]) -> Int { var tokens = tokens - + func dfs() -> Int { let token = tokens.removeLast() if let num = Int(token) { @@ -937,7 +936,7 @@ class Solution { default: return 0 } } - + return dfs() } } @@ -947,8 +946,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -1092,12 +1091,12 @@ public class Solution { ```go func evalRPN(tokens []string) int { stack := make([]int, 0) - + for _, token := range tokens { switch token { case "+": a := stack[len(stack)-1] - b := stack[len(stack)-2] + b := stack[len(stack)-2] stack = stack[:len(stack)-2] stack = append(stack, b+a) case "-": @@ -1120,7 +1119,7 @@ func evalRPN(tokens []string) int { stack = append(stack, num) } } - + return stack[0] } ``` @@ -1129,7 +1128,7 @@ func evalRPN(tokens []string) int { class Solution { fun evalRPN(tokens: Array): Int { val stack = ArrayDeque() - + for (token in tokens) { when (token) { "+" -> { @@ -1155,7 +1154,7 @@ class Solution { else -> stack.addLast(token.toInt()) } } - + return stack.last() } } @@ -1193,5 +1192,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/even-odd-tree.md b/articles/even-odd-tree.md index 4c5b25687..823730263 100644 --- a/articles/even-odd-tree.md +++ b/articles/even-odd-tree.md @@ -142,8 +142,10 @@ class Solution { for (let i = q.size(); i > 0; i--) { let node = q.pop(); - if (even && (node.val % 2 === 0 || node.val <= prev)) return false; - if (!even && (node.val % 2 === 1 || node.val >= prev)) return false; + if (even && (node.val % 2 === 0 || node.val <= prev)) + return false; + if (!even && (node.val % 2 === 1 || node.val >= prev)) + return false; if (node.left) q.push(node.left); if (node.right) q.push(node.right); @@ -161,8 +163,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -186,7 +188,7 @@ class Solution: return True even = level % 2 == 0 - if ((even and node.val % 2 == 0) or + if ((even and node.val % 2 == 0) or (not even and (node.val % 2 == 1)) ): return False @@ -194,7 +196,7 @@ class Solution: if len(levels) == level: levels.append(node.val) else: - if ((even and node.val <= levels[level]) or + if ((even and node.val <= levels[level]) or (not even and node.val >= levels[level]) ): return False @@ -228,7 +230,7 @@ public class Solution { if (node == null) return true; boolean even = level % 2 == 0; - if ((even && node.val % 2 == 0) || + if ((even && node.val % 2 == 0) || (!even && node.val % 2 == 1)) { return false; } @@ -236,7 +238,7 @@ public class Solution { if (levels.size() == level) { levels.add(node.val); } else { - if ((even && node.val <= levels.get(level)) || + if ((even && node.val <= levels.get(level)) || (!even && node.val >= levels.get(level))) { return false; } @@ -272,7 +274,7 @@ public: if (!node) return true; bool even = level % 2 == 0; - if ((even && node->val % 2 == 0) || + if ((even && node->val % 2 == 0) || (!even && node->val % 2 == 1)) { return false; } @@ -280,7 +282,7 @@ public: if (levels.size() == level) { levels.push_back(node->val); } else { - if ((even && node->val <= levels[level]) || + if ((even && node->val <= levels[level]) || (!even && node->val >= levels[level])) { return false; } @@ -319,16 +321,17 @@ class Solution { if (!node) return true; const even = level % 2 === 0; - if ((even && node.val % 2 === 0) || - (!even && node.val % 2 === 1)) { + if ((even && node.val % 2 === 0) || (!even && node.val % 2 === 1)) { return false; } if (levels.length === level) { levels.push(node.val); } else { - if ((even && node.val <= levels[level]) || - (!even && node.val >= levels[level])) { + if ( + (even && node.val <= levels[level]) || + (!even && node.val >= levels[level]) + ) { return false; } levels[level] = node.val; @@ -346,8 +349,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -371,7 +374,7 @@ class Solution: node, level = stack.pop() even = level % 2 == 0 - if ((even and node.val % 2 == 0) or + if ((even and node.val % 2 == 0) or (not even and node.val % 2 == 1) ): return False @@ -379,7 +382,7 @@ class Solution: if len(levels) == level: levels.append(node.val) else: - if ((even and node.val <= levels[level]) or + if ((even and node.val <= levels[level]) or (not even and node.val >= levels[level]) ): return False @@ -421,14 +424,14 @@ public class Solution { int level = pair.getValue(); boolean even = level % 2 == 0; - if ((even && node.val % 2 == 0) || + if ((even && node.val % 2 == 0) || (!even && node.val % 2 == 1)) return false; if (levels.size() == level) { levels.add(node.val); } else { - if ((even && node.val <= levels.get(level)) || + if ((even && node.val <= levels.get(level)) || (!even && node.val >= levels.get(level))) return false; levels.set(level, node.val); @@ -467,14 +470,14 @@ public: stack.pop(); bool even = level % 2 == 0; - if ((even && node->val % 2 == 0) || + if ((even && node->val % 2 == 0) || (!even && node->val % 2 == 1)) return false; if (levels.size() == level) { levels.push_back(node->val); } else { - if ((even && node->val <= levels[level]) || + if ((even && node->val <= levels[level]) || (!even && node->val >= levels[level])) return false; levels[level] = node->val; @@ -513,15 +516,16 @@ class Solution { const [node, level] = stack.pop(); const even = level % 2 === 0; - if ((even && node.val % 2 === 0) || - (!even && node.val % 2 === 1)) + if ((even && node.val % 2 === 0) || (!even && node.val % 2 === 1)) return false; if (levels.length === level) { levels.push(node.val); } else { - if ((even && node.val <= levels[level]) || - (!even && node.val >= levels[level])) + if ( + (even && node.val <= levels[level]) || + (!even && node.val >= levels[level]) + ) return false; levels[level] = node.val; } @@ -539,5 +543,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/excel-sheet-column-title.md b/articles/excel-sheet-column-title.md index c792e6591..c6380ce02 100644 --- a/articles/excel-sheet-column-title.md +++ b/articles/excel-sheet-column-title.md @@ -45,10 +45,13 @@ class Solution { */ convertToTitle(columnNumber) { if (columnNumber === 0) { - return ""; + return ''; } const n = columnNumber - 1; - return this.convertToTitle(Math.floor(n / 26)) + String.fromCharCode('A'.charCodeAt(0) + n % 26); + return ( + this.convertToTitle(Math.floor(n / 26)) + + String.fromCharCode('A'.charCodeAt(0) + (n % 26)) + ); } } ``` @@ -60,7 +63,7 @@ public class Solution { return ""; } - columnNumber--; + columnNumber--; return ConvertToTitle(columnNumber / 26) + (char)('A' + columnNumber % 26); } } @@ -70,8 +73,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(\log n)$ for recursion stack. +- Time complexity: $O(\log n)$ +- Space complexity: $O(\log n)$ for recursion stack. > Where $n$ is the given column number. @@ -90,7 +93,7 @@ class Solution: offset = columnNumber % 26 res += chr(ord('A') + offset) columnNumber //= 26 - + return ''.join(reversed(res)) ``` @@ -165,7 +168,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ extra space. -> Where $n$ is the given column number. \ No newline at end of file +> Where $n$ is the given column number. diff --git a/articles/extra-characters-in-a-string.md b/articles/extra-characters-in-a-string.md index 6b2052693..ca7227405 100644 --- a/articles/extra-characters-in-a-string.md +++ b/articles/extra-characters-in-a-string.md @@ -132,8 +132,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 2 ^ n + m * k)$ -* Space complexity: $O(n + m * k)$ +- Time complexity: $O(n * 2 ^ n + m * k)$ +- Space complexity: $O(n + m * k)$ > Where $n$ is the length of the string $s$, $m$ is the number of words in the dictionary, and $k$ is the average length of a word in the dictionary. @@ -276,8 +276,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 3 + m * k)$ -* Space complexity: $O(n + m * k)$ +- Time complexity: $O(n ^ 3 + m * k)$ +- Space complexity: $O(n + m * k)$ > Where $n$ is the length of the string $s$, $m$ is the number of words in the dictionary, and $k$ is the average length of a word in the dictionary. @@ -393,8 +393,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 3 + m * k)$ -* Space complexity: $O(n + m * k)$ +- Time complexity: $O(n ^ 3 + m * k)$ +- Space complexity: $O(n + m * k)$ > Where $n$ is the length of the string $s$, $m$ is the number of words in the dictionary, and $k$ is the average length of a word in the dictionary. @@ -412,7 +412,7 @@ class Solution: def dfs(i): if i in dp: return dp[i] - + res = 1 + dfs(i + 1) for word in dictionary: if i + len(word) > len(s): @@ -425,11 +425,11 @@ class Solution: break if flag: res = min(res, dfs(i + len(word))) - + dp[i] = res return res - return dfs(0) + return dfs(0) ``` ```java @@ -581,8 +581,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m * k)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * m * k)$ +- Space complexity: $O(n)$ > Where $n$ is the length of the string $s$, $m$ is the number of words in the dictionary, and $k$ is the average length of a word in the dictionary. @@ -597,13 +597,13 @@ class Solution: def minExtraChar(self, s: str, dictionary: List[str]) -> int: n = len(s) dp = [0] * (n + 1) - + for i in range(n - 1, -1, -1): dp[i] = 1 + dp[i + 1] for word in dictionary: if i + len(word) <= n and s[i:i + len(word)] == word: dp[i] = min(dp[i], dp[i + len(word)]) - + return dp[0] ``` @@ -662,7 +662,10 @@ class Solution { for (let i = n - 1; i >= 0; i--) { dp[i] = 1 + dp[i + 1]; for (const word of dictionary) { - if (i + word.length <= n && s.slice(i, i + word.length) === word) { + if ( + i + word.length <= n && + s.slice(i, i + word.length) === word + ) { dp[i] = Math.min(dp[i], dp[i + word.length]); } } @@ -697,8 +700,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m * k)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * m * k)$ +- Space complexity: $O(n)$ > Where $n$ is the length of the string $s$, $m$ is the number of words in the dictionary, and $k$ is the average length of a word in the dictionary. @@ -717,7 +720,7 @@ class TrieNode: class Trie: def __init__(self): self.root = TrieNode() - + def addWord(self, word): curr = self.root for c in word: @@ -898,7 +901,7 @@ class Trie { /** * @param {string} word * @return {void} - */ + */ addWord(word) { let curr = this.root; for (const c of word) { @@ -1010,8 +1013,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 + m * k)$ -* Space complexity: $O(n + m * k)$ +- Time complexity: $O(n ^ 2 + m * k)$ +- Space complexity: $O(n + m * k)$ > Where $n$ is the length of the string $s$, $m$ is the number of words in the dictionary, and $k$ is the average length of a word in the dictionary. @@ -1030,7 +1033,7 @@ class TrieNode: class Trie: def __init__(self): self.root = TrieNode() - + def addWord(self, word): curr = self.root for c in word: @@ -1194,7 +1197,7 @@ class Trie { /** * @param {string} word * @return {void} - */ + */ addWord(word) { let curr = this.root; for (const c of word) { @@ -1294,7 +1297,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 + m * k)$ -* Space complexity: $O(n + m * k)$ +- Time complexity: $O(n ^ 2 + m * k)$ +- Space complexity: $O(n + m * k)$ -> Where $n$ is the length of the string $s$, $m$ is the number of words in the dictionary, and $k$ is the average length of a word in the dictionary. \ No newline at end of file +> Where $n$ is the length of the string $s$, $m$ is the number of words in the dictionary, and $k$ is the average length of a word in the dictionary. diff --git a/articles/find-all-anagrams-in-a-string.md b/articles/find-all-anagrams-in-a-string.md index 4201b94ed..8d7411507 100644 --- a/articles/find-all-anagrams-in-a-string.md +++ b/articles/find-all-anagrams-in-a-string.md @@ -64,12 +64,17 @@ class Solution { * @return {number[]} */ findAnagrams(s, p) { - const n = s.length, m = p.length; + const n = s.length, + m = p.length; const res = []; const sortedP = p.split('').sort().join(''); for (let i = 0; i <= n - m; i++) { - const sub = s.substring(i, i + m).split('').sort().join(''); + const sub = s + .substring(i, i + m) + .split('') + .sort() + .join(''); if (sub === sortedP) { res.push(i); } @@ -83,8 +88,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m \log m)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n * m \log m)$ +- Space complexity: $O(m)$ > Where $n$ is the length of the string $s$ and $m$ is the length of the string $p$. @@ -207,7 +212,8 @@ class Solution { * @return {number[]} */ findAnagrams(s, p) { - const n = s.length, m = p.length; + const n = s.length, + m = p.length; if (m > n) return []; const pCount = Array(26).fill(0); @@ -224,7 +230,8 @@ class Solution { } const res = []; - let i = 0, j = m - 1; + let i = 0, + j = m - 1; while (j < n) { let isValid = true; for (let c = 0; c < 26; c++) { @@ -247,8 +254,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(n)$ > Where $n$ is the length of the string $s$ and $m$ is the length of the string $p$. @@ -285,20 +292,20 @@ class Solution: public class Solution { public List findAnagrams(String s, String p) { if (p.length() > s.length()) return new ArrayList<>(); - + int[] pCount = new int[26]; int[] sCount = new int[26]; - + for (char c : p.toCharArray()) { pCount[c - 'a']++; } for (int i = 0; i < p.length(); i++) { sCount[s.charAt(i) - 'a']++; } - + List res = new ArrayList<>(); if (Arrays.equals(pCount, sCount)) res.add(0); - + int l = 0; for (int r = p.length(); r < s.length(); r++) { sCount[s.charAt(r) - 'a']++; @@ -308,7 +315,7 @@ public class Solution { res.add(l); } } - + return res; } } @@ -358,7 +365,7 @@ class Solution { const pCount = new Array(26).fill(0); const sCount = new Array(26).fill(0); - + for (const char of p) { pCount[char.charCodeAt(0) - 97]++; } @@ -388,8 +395,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(1)$ since we have at most $26$ different characters. +- Time complexity: $O(n + m)$ +- Space complexity: $O(1)$ since we have at most $26$ different characters. > Where $n$ is the length of the string $s$ and $m$ is the length of the string $p$. @@ -531,7 +538,8 @@ class Solution { * @return {number[]} */ findAnagrams(s, p) { - const n = s.length, m = p.length; + const n = s.length, + m = p.length; if (m > n) return []; const pCount = new Array(26).fill(0); @@ -575,7 +583,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(1)$ since we have at most $26$ different characters. +- Time complexity: $O(n + m)$ +- Space complexity: $O(1)$ since we have at most $26$ different characters. -> Where $n$ is the length of the string $s$ and $m$ is the length of the string $p$. \ No newline at end of file +> Where $n$ is the length of the string $s$ and $m$ is the length of the string $p$. diff --git a/articles/find-all-duplicates-in-an-array.md b/articles/find-all-duplicates-in-an-array.md index 3d1f99fde..0e7982b24 100644 --- a/articles/find-all-duplicates-in-an-array.md +++ b/articles/find-all-duplicates-in-an-array.md @@ -86,8 +86,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ extra space. --- @@ -168,8 +168,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -256,8 +256,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -274,7 +274,7 @@ class Solution: for num in count: if count[num] == 2: res.append(num) - + return res ``` @@ -350,8 +350,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -369,7 +369,7 @@ class Solution: if nums[idx] < 0: res.append(abs(num)) nums[idx] = -nums[idx] - + return res ``` @@ -385,7 +385,7 @@ public class Solution { } nums[idx] = -nums[idx]; } - + return res; } } @@ -404,7 +404,7 @@ public: } nums[idx] = -nums[idx]; } - + return res; } }; @@ -426,7 +426,7 @@ class Solution { } nums[idx] = -nums[idx]; } - + return res; } } @@ -436,5 +436,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/find-all-numbers-disappeared-in-an-array.md b/articles/find-all-numbers-disappeared-in-an-array.md index f0462dc4f..4ae4b6150 100644 --- a/articles/find-all-numbers-disappeared-in-an-array.md +++ b/articles/find-all-numbers-disappeared-in-an-array.md @@ -7,10 +7,10 @@ class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: n = len(nums) store = set(range(1, n + 1)) - + for num in nums: store.discard(num) - + return list(store) ``` @@ -20,11 +20,11 @@ public class Solution { int n = nums.length; Set store = new HashSet<>(); for (int i = 1; i <= n; i++) store.add(i); - + for (int num : nums) { store.remove(num); } - + return new ArrayList<>(store); } } @@ -37,11 +37,11 @@ public: int n = nums.size(); unordered_set store; for (int i = 1; i <= n; i++) store.insert(i); - + for (int num : nums) { store.erase(num); } - + vector result(store.begin(), store.end()); return result; } @@ -58,11 +58,11 @@ class Solution { const n = nums.length; const store = new Set(); for (let i = 1; i <= n; i++) store.add(i); - + for (let num of nums) { store.delete(num); } - + return Array.from(store); } } @@ -72,8 +72,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -86,10 +86,10 @@ class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: n = len(nums) mark = [False] * n - + for num in nums: mark[num - 1] = True - + res = [] for i in range(1, n + 1): if not mark[i - 1]: @@ -102,11 +102,11 @@ public class Solution { public List findDisappearedNumbers(int[] nums) { int n = nums.length; boolean[] mark = new boolean[n]; - + for (int num : nums) { mark[num - 1] = true; } - + List res = new ArrayList<>(); for (int i = 1; i <= n; i++) { if (!mark[i - 1]) { @@ -124,11 +124,11 @@ public: vector findDisappearedNumbers(vector& nums) { int n = nums.size(); vector mark(n, false); - + for (int num : nums) { mark[num - 1] = true; } - + vector res; for (int i = 1; i <= n; i++) { if (!mark[i - 1]) { @@ -149,11 +149,11 @@ class Solution { findDisappearedNumbers(nums) { const n = nums.length; const mark = new Array(n).fill(false); - + for (let num of nums) { mark[num - 1] = true; } - + const res = []; for (let i = 1; i <= n; i++) { if (!mark[i - 1]) { @@ -169,8 +169,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -183,7 +183,7 @@ class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: n = len(nums) nums.sort() - + res = [] idx = 0 for num in range(1, n + 1): @@ -199,7 +199,7 @@ public class Solution { public List findDisappearedNumbers(int[] nums) { int n = nums.length; Arrays.sort(nums); - + List res = new ArrayList<>(); int idx = 0; for (int num = 1; num <= n; num++) { @@ -221,7 +221,7 @@ public: vector findDisappearedNumbers(vector& nums) { int n = nums.size(); sort(nums.begin(), nums.end()); - + vector res; int idx = 0; for (int num = 1; num <= n; num++) { @@ -245,7 +245,7 @@ class Solution { */ findDisappearedNumbers(nums) { nums.sort((a, b) => a - b); - + const res = []; let idx = 0; for (let num = 1; num <= nums.length; num++) { @@ -265,8 +265,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -279,13 +279,13 @@ class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: for num in nums: i = abs(num) - 1 - nums[i] = -1 * abs(nums[i]) + nums[i] = -1 * abs(nums[i]) res = [] for i, num in enumerate(nums): if num > 0: res.append(i + 1) - return res + return res ``` ```java @@ -295,7 +295,7 @@ public class Solution { int i = Math.abs(num) - 1; nums[i] = -Math.abs(nums[i]); } - + List res = new ArrayList<>(); for (int i = 0; i < nums.length; i++) { if (nums[i] > 0) { @@ -315,7 +315,7 @@ public: int i = abs(num) - 1; nums[i] = -abs(nums[i]); } - + vector res; for (int i = 0; i < nums.size(); i++) { if (nums[i] > 0) { @@ -338,7 +338,7 @@ class Solution { let i = Math.abs(num) - 1; nums[i] = -Math.abs(nums[i]); } - + const res = []; for (let i = 0; i < nums.length; i++) { if (nums[i] > 0) { @@ -354,5 +354,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ since we modified the input array without using extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ since we modified the input array without using extra space. diff --git a/articles/find-all-people-with-secret.md b/articles/find-all-people-with-secret.md index 1d1b58e20..7158d9b53 100644 --- a/articles/find-all-people-with-secret.md +++ b/articles/find-all-people-with-secret.md @@ -142,7 +142,7 @@ class Solution { if (visit.has(src)) return; visit.add(src); secrets.add(src); - for (let nei of (adj.get(src) || [])) { + for (let nei of adj.get(src) || []) { dfs(nei, adj); } }; @@ -166,8 +166,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m \log m + n)$ -* Space complexity: $O(m + n)$ +- Time complexity: $O(m \log m + n)$ +- Space complexity: $O(m + n)$ > Where $m$ is the number of meetings and $n$ is the number of people. @@ -348,8 +348,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m \log m + n)$ -* Space complexity: $O(m + n)$ +- Time complexity: $O(m \log m + n)$ +- Space complexity: $O(m + n)$ > Where $m$ is the number of meetings and $n$ is the number of people. @@ -496,7 +496,8 @@ class Solution { const secrets = new Array(n).fill(false); secrets[0] = secrets[firstPerson] = true; - let i = 0, m = meetings.length; + let i = 0, + m = meetings.length; while (i < m) { const time = meetings[i][2]; const adj = new Map(); @@ -516,7 +517,7 @@ class Solution { const stack = [...visited]; while (stack.length) { const node = stack.pop(); - for (const nei of (adj.get(node) || [])) { + for (const nei of adj.get(node) || []) { if (!visited.has(nei)) { visited.add(nei); stack.push(nei); @@ -539,8 +540,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m \log m + n)$ -* Space complexity: $O(m + n)$ +- Time complexity: $O(m \log m + n)$ +- Space complexity: $O(m + n)$ > Where $m$ is the number of meetings and $n$ is the number of people. @@ -670,7 +671,7 @@ public class Solution { class DSU { public: vector Parent, Size; - + DSU(int n) { Parent.resize(n + 1); Size.resize(n + 1, 1); @@ -810,14 +811,14 @@ class Solution { group.add(v); } - group.forEach(node => { + group.forEach((node) => { if (dsu.find(node) !== dsu.find(0)) { dsu.reset(node); } }); } - return [...Array(n).keys()].filter(i => dsu.find(i) === dsu.find(0)); + return [...Array(n).keys()].filter((i) => dsu.find(i) === dsu.find(0)); } } ``` @@ -826,9 +827,9 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m \log m + (m * α(n)))$ -* Space complexity: - * $O(n)$ extra space. - * $O(m)$ space depending on the sorting algorithm. +- Time complexity: $O(m \log m + (m * α(n)))$ +- Space complexity: + - $O(n)$ extra space. + - $O(m)$ space depending on the sorting algorithm. -> Where $m$ is the number of meetings and $n$ is the number of people. \ No newline at end of file +> Where $m$ is the number of meetings and $n$ is the number of people. diff --git a/articles/find-bottom-left-tree-value.md b/articles/find-bottom-left-tree-value.md index c04645674..a39ec9ed1 100644 --- a/articles/find-bottom-left-tree-value.md +++ b/articles/find-bottom-left-tree-value.md @@ -119,8 +119,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -144,7 +144,7 @@ class Solution: return if depth > self.maxDepth: self.maxDepth, self.res = depth, node.val - + dfs(node.left, depth + 1) dfs(node.right, depth + 1) @@ -244,7 +244,8 @@ class Solution { * @return {number} */ findBottomLeftValue(root) { - let maxDepth = -1, res = root.val; + let maxDepth = -1, + res = root.val; const dfs = (node, depth) => { if (!node) return; @@ -267,8 +268,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -402,7 +403,8 @@ class Solution { * @return {number} */ findBottomLeftValue(root) { - let res = root.val, maxDepth = -1; + let res = root.val, + maxDepth = -1; const stack = [[root, 0]]; while (stack.length) { @@ -425,8 +427,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -591,7 +593,9 @@ class Solution { * @return {number} */ findBottomLeftValue(root) { - let res = root.val, maxDepth = -1, curDepth = 0; + let res = root.val, + maxDepth = -1, + curDepth = 0; let cur = root; while (cur) { @@ -603,7 +607,8 @@ class Solution { cur = cur.right; curDepth++; } else { - let prev = cur.left, steps = 1; + let prev = cur.left, + steps = 1; while (prev.right && prev.right !== cur) { prev = prev.right; steps++; @@ -629,5 +634,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/find-closest-node-to-given-two-nodes.md b/articles/find-closest-node-to-given-two-nodes.md index 52cb6d365..73f74bcdc 100644 --- a/articles/find-closest-node-to-given-two-nodes.md +++ b/articles/find-closest-node-to-given-two-nodes.md @@ -166,7 +166,8 @@ class Solution { const node1Dist = bfs(node1); const node2Dist = bfs(node2); - let res = -1, resDist = Infinity; + let res = -1, + resDist = Infinity; for (let i = 0; i < n; i++) { if (node1Dist[i] !== -1 && node2Dist[i] !== -1) { let dist = Math.max(node1Dist[i], node2Dist[i]); @@ -185,8 +186,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -344,7 +345,8 @@ class Solution { const node1Dist = bfs(node1); const node2Dist = bfs(node2); - let res = -1, resDist = Infinity; + let res = -1, + resDist = Infinity; for (let i = 0; i < n; i++) { if (node1Dist[i] !== -1 && node2Dist[i] !== -1) { let dist = Math.max(node1Dist[i], node2Dist[i]); @@ -363,8 +365,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -382,7 +384,7 @@ class Solution: if nei != -1 and dist[nei] == -1: dist[nei] = dist[node] + 1 dfs(nei, dist) - + node1Dist = [-1] * n node2Dist = [-1] * n node1Dist[node1] = node2Dist[node2] = 0 @@ -499,7 +501,8 @@ class Solution { dfs(node1, node1Dist); dfs(node2, node2Dist); - let res = -1, resDist = Infinity; + let res = -1, + resDist = Infinity; for (let i = 0; i < n; i++) { if (Math.min(node1Dist[i], node2Dist[i]) !== -1) { const dist = Math.max(node1Dist[i], node2Dist[i]); @@ -518,8 +521,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -646,7 +649,8 @@ class Solution { const node1Dist = dfs(node1); const node2Dist = dfs(node2); - let res = -1, resDist = Infinity; + let res = -1, + resDist = Infinity; for (let i = 0; i < n; i++) { if (Math.min(node1Dist[i], node2Dist[i]) !== -1) { const dist = Math.max(node1Dist[i], node2Dist[i]); @@ -665,5 +669,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/find-common-characters.md b/articles/find-common-characters.md index 4a6cfe1e8..1408e1712 100644 --- a/articles/find-common-characters.md +++ b/articles/find-common-characters.md @@ -114,9 +114,9 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: - * $O(1)$ extra space, since we have at most $26$ different characters. - * $O(n * m)$ space for the output list. +- Time complexity: $O(n * m)$ +- Space complexity: + - $O(1)$ extra space, since we have at most $26$ different characters. + - $O(n * m)$ space for the output list. -> Where $n$ is the number of words and $m$ is the length of the longest word. \ No newline at end of file +> Where $n$ is the number of words and $m$ is the length of the longest word. diff --git a/articles/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.md b/articles/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.md index 63c54ead9..e113e35cf 100644 --- a/articles/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.md +++ b/articles/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.md @@ -263,7 +263,8 @@ class UnionFind { * @return {boolean} */ union(v1, v2) { - const p1 = this.find(v1), p2 = this.find(v2); + const p1 = this.find(v1), + p2 = this.find(v2); if (p1 === p2) return false; if (this.rank[p1] > this.rank[p2]) { this.par[p2] = p1; @@ -306,7 +307,10 @@ class Solution { weightWithout += w; } } - if (Math.max(...ufWithout.rank) !== n || weightWithout > mstWeight) { + if ( + Math.max(...ufWithout.rank) !== n || + weightWithout > mstWeight + ) { critical.push(i); continue; } @@ -427,8 +431,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(E ^ 2)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(E ^ 2)$ +- Space complexity: $O(V + E)$ > Where $V$ is the number of vertices and $E$ is the number of edges. @@ -461,7 +465,7 @@ class UnionFind: self.Size[pu] += self.Size[pv] self.Parent[pv] = pu return True - + def isConnected(self): return self.n == 1 @@ -477,14 +481,14 @@ class Solution: if include: wgt += edges[index][2] uf.union(edges[index][0], edges[index][1]) - + for i, e in enumerate(edges): if i == index: continue if uf.union(e[0], e[1]): wgt += e[2] return wgt if uf.isConnected() else float("inf") - + mst_wgt = findMST(-1, False) critical, pseudo = [], [] for i, e in enumerate(edges): @@ -492,7 +496,7 @@ class Solution: critical.append(e[3]) elif mst_wgt == findMST(i, True): pseudo.append(e[3]) - + return [critical, pseudo] ``` @@ -848,8 +852,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(E ^ 2)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(E ^ 2)$ +- Space complexity: $O(V + E)$ > Where $V$ is the number of vertices and $E$ is the number of edges. @@ -1138,8 +1142,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(E ^ 2 \log V)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(E ^ 2 \log V)$ +- Space complexity: $O(V + E)$ > Where $V$ is the number of vertices and $E$ is the number of edges. @@ -1154,12 +1158,12 @@ class UnionFind: def __init__(self, n): self.Parent = list(range(n + 1)) self.Size = [1] * (n + 1) - + def find(self, node): if self.Parent[node] != node: self.Parent[node] = self.find(self.Parent[node]) return self.Parent[node] - + def union(self, u, v): pu = self.find(u) pv = self.find(v) @@ -1175,17 +1179,17 @@ class Solution: def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]: mst = [[] for _ in range(n)] mstEdge = [] - + edge_list = [(w, u, v, i) for i, (u, v, w) in enumerate(edges)] edge_list.sort() - + uf = UnionFind(n) for w, u, v, i in edge_list: if uf.union(u, v): mst[u].append((v, i)) mst[v].append((u, i)) mstEdge.append(i) - + def dfs(node): for next, ind in mst[node]: if path and ind == path[-1]: @@ -1195,7 +1199,7 @@ class Solution: return True path.pop() return False - + pseudo, mstEdge = set(), set(mstEdge) for ind in range(len(edges)): if ind in mstEdge: @@ -1206,7 +1210,7 @@ class Solution: if edges[i][2] == edges[ind][2]: pseudo.add(i) pseudo.add(ind) - + return [list(mstEdge - pseudo), list(pseudo)] ``` @@ -1466,7 +1470,9 @@ class Solution { const mst = Array.from({ length: n }, () => []); const mstEdges = new Set(); const pseudoCriticalEdges = new Set(); - const edgeList = edges.map((e, i) => [...e, i]).sort((a, b) => a[2] - b[2]); + const edgeList = edges + .map((e, i) => [...e, i]) + .sort((a, b) => a[2] - b[2]); const uf = new UnionFind(n); @@ -1507,7 +1513,9 @@ class Solution { } } - const critical = [...mstEdges].filter(edgeIdx => !pseudoCriticalEdges.has(edgeIdx)); + const critical = [...mstEdges].filter( + (edgeIdx) => !pseudoCriticalEdges.has(edgeIdx), + ); const pseudo = [...pseudoCriticalEdges]; return [critical, pseudo]; @@ -1625,7 +1633,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(E ^ 2)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(E ^ 2)$ +- Space complexity: $O(V + E)$ -> Where $V$ is the number of vertices and $E$ is the number of edges. \ No newline at end of file +> Where $V$ is the number of vertices and $E$ is the number of edges. diff --git a/articles/find-duplicate-integer.md b/articles/find-duplicate-integer.md index ef3317436..f6a4db4e0 100644 --- a/articles/find-duplicate-integer.md +++ b/articles/find-duplicate-integer.md @@ -117,8 +117,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -249,8 +249,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -381,8 +381,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -394,7 +394,7 @@ class Solution { class Solution: def findDuplicate(self, nums: List[int]) -> int: for num in nums : - idx = abs(num) - 1 + idx = abs(num) - 1 if nums[idx] < 0 : return abs(num) nums[idx] *= -1 @@ -521,8 +521,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -609,7 +609,8 @@ class Solution { */ findDuplicate(nums) { let n = nums.length; - let low = 1, high = n - 1; + let low = 1, + high = n - 1; while (low < high) { let mid = Math.floor(low + (high - low) / 2); @@ -741,8 +742,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ --- @@ -761,11 +762,11 @@ class Solution: for num in nums: if num & mask: x += 1 - + for num in range(1, n): if num & mask: y += 1 - + if x > y: res |= mask return res @@ -836,7 +837,8 @@ class Solution { let n = nums.length; let res = 0; for (let b = 0; b < 32; b++) { - let x = 0, y = 0; + let x = 0, + y = 0; let mask = 1 << b; for (let num of nums) { if (num & mask) { @@ -982,8 +984,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(32 * n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(32 * n)$ +- Space complexity: $O(1)$ --- @@ -1193,5 +1195,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/find-duplicate-subtrees.md b/articles/find-duplicate-subtrees.md index bf3d6d7e9..655ad8ce0 100644 --- a/articles/find-duplicate-subtrees.md +++ b/articles/find-duplicate-subtrees.md @@ -19,7 +19,7 @@ class Solution: return (node1.val == node2.val and same(node1.left, node2.left) and same(node1.right, node2.right)) - + subTree = [] def dfs(root): if not root: @@ -27,11 +27,11 @@ class Solution: subTree.append(root) dfs(root.left) dfs(root.right) - + dfs(root) res = [] seen = set() - + for i in range(len(subTree)): if subTree[i] in seen: continue @@ -90,8 +90,8 @@ public class Solution { private boolean same(TreeNode node1, TreeNode node2) { if (node1 == null && node2 == null) return true; if (node1 == null || node2 == null) return false; - return node1.val == node2.val && - same(node1.left, node2.left) && + return node1.val == node2.val && + same(node1.left, node2.left) && same(node1.right, node2.right); } @@ -145,8 +145,8 @@ private: bool same(TreeNode* node1, TreeNode* node2) { if (!node1 && !node2) return true; if (!node1 || !node2) return false; - return node1->val == node2->val && - same(node1->left, node2->left) && + return node1->val == node2->val && + same(node1->left, node2->left) && same(node1->right, node2->right); } @@ -191,12 +191,13 @@ class Solution { const same = (node1, node2) => { if (!node1 && !node2) return true; if (!node1 || !node2) return false; - return node1.val === node2.val && - same(node1.left, node2.left) && - same(node1.right, node2.right); + return ( + node1.val === node2.val && + same(node1.left, node2.left) && + same(node1.right, node2.right) + ); }; - for (let i = 0; i < subTree.length; i++) { if (seen.has(subTree[i])) continue; for (let j = i + 1; j < subTree.length; j++) { @@ -221,8 +222,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 3)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 3)$ +- Space complexity: $O(n)$ --- @@ -351,7 +352,7 @@ class Solution { const res = []; const dfs = (node) => { - if (!node) return "null"; + if (!node) return 'null'; const s = `${node.val},${dfs(node.left)},${dfs(node.right)}`; if (!subtrees.has(s)) { subtrees.set(s, []); @@ -373,8 +374,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -472,7 +473,7 @@ class Solution { unordered_map idMap; unordered_map count; vector res; - + public: vector findDuplicateSubtrees(TreeNode* root) { dfs(root); @@ -482,8 +483,8 @@ public: private: int dfs(TreeNode* node) { if (!node) return -1; - string cur = to_string(dfs(node->left)) + "," + - to_string(node->val) + "," + + string cur = to_string(dfs(node->left)) + "," + + to_string(node->val) + "," + to_string(dfs(node->right)); if (idMap.find(cur) == idMap.end()) { idMap[cur] = idMap.size(); @@ -518,24 +519,24 @@ class Solution { const idMap = new Map(); const count = new Map(); const res = []; - + const dfs = (node) => { if (!node) return -1; - + const cur = `${dfs(node.left)},${node.val},${dfs(node.right)}`; if (!idMap.has(cur)) { idMap.set(cur, idMap.size + 1); } - + const curId = idMap.get(cur); count.set(curId, (count.get(curId) || 0) + 1); if (count.get(curId) === 2) { res.push(node); } - + return curId; }; - + dfs(root); return res; } @@ -546,5 +547,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/find-eventual-safe-states.md b/articles/find-eventual-safe-states.md index df245c8a2..205c80bde 100644 --- a/articles/find-eventual-safe-states.md +++ b/articles/find-eventual-safe-states.md @@ -28,7 +28,7 @@ class Solution: ```java public class Solution { private Boolean[] safe; - + public List eventualSafeNodes(int[][] graph) { int n = graph.length; safe = new Boolean[n]; @@ -45,7 +45,7 @@ public class Solution { if (safe[node] != null) { return safe[node]; } - + safe[node] = false; for (int nei : graph[node]) { if (!dfs(graph, nei)) { @@ -131,8 +131,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ > Where $V$ is the number of vertices and $E$ is the number of edges in the given graph. @@ -178,11 +178,11 @@ public class Solution { int[] outdegree = new int[n]; List[] parents = new ArrayList[n]; Queue queue = new LinkedList<>(); - + for (int i = 0; i < n; i++) { parents[i] = new ArrayList<>(); } - + for (int node = 0; node < n; node++) { outdegree[node] = graph[node].length; if (outdegree[node] == 0) { @@ -192,7 +192,7 @@ public class Solution { parents[nei].add(node); } } - + while (!queue.isEmpty()) { int node = queue.poll(); for (int parent : parents[node]) { @@ -202,7 +202,7 @@ public class Solution { } } } - + List res = new ArrayList<>(); for (int node = 0; node < n; node++) { if (outdegree[node] <= 0) { @@ -266,7 +266,7 @@ class Solution { const outdegree = Array(n).fill(0); const parents = Array.from({ length: n }, () => []); const queue = new Queue(); - + for (let node = 0; node < n; node++) { outdegree[node] = graph[node].length; if (outdegree[node] === 0) { @@ -276,7 +276,7 @@ class Solution { parents[nei].push(node); } } - + while (!queue.isEmpty()) { const node = queue.pop(); for (let parent of parents[node]) { @@ -286,7 +286,7 @@ class Solution { } } } - + const res = []; for (let node = 0; node < n; node++) { if (outdegree[node] <= 0) { @@ -302,7 +302,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ -> Where $V$ is the number of vertices and $E$ is the number of edges in the given graph. \ No newline at end of file +> Where $V$ is the number of vertices and $E$ is the number of edges in the given graph. diff --git a/articles/find-first-and-last-position-of-element-in-sorted-array.md b/articles/find-first-and-last-position-of-element-in-sorted-array.md index 41687585a..c4477cc63 100644 --- a/articles/find-first-and-last-position-of-element-in-sorted-array.md +++ b/articles/find-first-and-last-position-of-element-in-sorted-array.md @@ -106,8 +106,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -222,7 +222,9 @@ class Solution { * @return {number} */ binarySearch(nums, target, leftBias) { - let l = 0, r = nums.length - 1, i = -1; + let l = 0, + r = nums.length - 1, + i = -1; while (l <= r) { let m = Math.floor((l + r) / 2); if (target > nums[m]) { @@ -277,8 +279,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ --- @@ -300,7 +302,7 @@ class Solution: else: l = m + 1 return l - + start = binarySearch(target) if start == n or nums[start] != target: return [-1, -1] @@ -377,7 +379,8 @@ class Solution { const n = nums.length; const binarySearch = (target) => { - let l = 0, r = n; + let l = 0, + r = n; while (l < r) { let m = Math.floor(l + (r - l) / 2); if (nums[m] >= target) { @@ -432,8 +435,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ --- @@ -459,27 +462,27 @@ public class Solution { if (left == -1) { return new int[]{-1, -1}; } - + int right = findRight(nums, target); return new int[]{left, right}; } - + private int findLeft(int[] nums, int target) { // O(n) time in worst case int index = Arrays.binarySearch(nums, target); if (index < 0) return -1; - + while (index > 0 && nums[index - 1] == target) { index--; } return index; } - + private int findRight(int[] nums, int target) { // O(n) time in worst case int index = Arrays.binarySearch(nums, target); if (index < 0) return -1; - + while (index < nums.length - 1 && nums[index + 1] == target) { index++; } @@ -546,5 +549,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ diff --git a/articles/find-first-palindromic-string-in-the-array.md b/articles/find-first-palindromic-string-in-the-array.md index 03dd3683d..b0f3995ea 100644 --- a/articles/find-first-palindromic-string-in-the-array.md +++ b/articles/find-first-palindromic-string-in-the-array.md @@ -52,7 +52,7 @@ class Solution { return w; } } - return ""; + return ''; } } ``` @@ -61,8 +61,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(m)$ > Where $n$ is the size of the string array $words$ and $m$ is the average length of a word in the array. @@ -125,14 +125,15 @@ class Solution { */ firstPalindrome(words) { for (let w of words) { - let l = 0, r = w.length - 1; + let l = 0, + r = w.length - 1; while (w.charAt(l) === w.charAt(r)) { if (l >= r) return w; l++; r--; } } - return ""; + return ''; } } ``` @@ -141,7 +142,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n * m)$ +- Space complexity: $O(1)$ extra space. -> Where $n$ is the size of the string array $words$ and $m$ is the average length of a word in the array. \ No newline at end of file +> Where $n$ is the size of the string array $words$ and $m$ is the average length of a word in the array. diff --git a/articles/find-in-mountain-array.md b/articles/find-in-mountain-array.md index c917a7507..9a12f1c93 100644 --- a/articles/find-in-mountain-array.md +++ b/articles/find-in-mountain-array.md @@ -18,7 +18,7 @@ class Solution: for i in range(n): if mountainArr.get(i) == target: return i - + return -1 ``` @@ -31,7 +31,7 @@ class Solution: * public int length() {} * } */ - + public class Solution { public int findInMountainArray(int target, MountainArray mountainArr) { int n = mountainArr.length(); @@ -41,7 +41,7 @@ public class Solution { return i; } } - + return -1; } } @@ -68,7 +68,7 @@ public: return i; } } - + return -1; } }; @@ -106,7 +106,7 @@ class Solution { return i; } } - + return -1; } } @@ -141,8 +141,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -199,7 +199,7 @@ class Solution: r = m - 1 else: return m - + return -1 ``` @@ -212,7 +212,7 @@ class Solution: * public int length() {} * } */ - + public class Solution { public int findInMountainArray(int target, MountainArray mountainArr) { int length = mountainArr.length(); @@ -365,7 +365,9 @@ class Solution { const length = mountainArr.length(); // Find Peak - let l = 1, r = length - 2, peak = 0; + let l = 1, + r = length - 2, + peak = 0; while (l <= r) { const m = Math.floor((l + r) / 2); const left = mountainArr.get(m - 1); @@ -486,8 +488,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ --- @@ -557,7 +559,7 @@ class Solution: * public int length() {} * } */ - + public class Solution { private Map cache = new HashMap<>(); @@ -727,7 +729,7 @@ class Solution { if (val === target) { return m; } - if (ascending === (val < target)) { + if (ascending === val < target) { l = m + 1; } else { r = m - 1; @@ -739,7 +741,9 @@ class Solution { const length = mountainArr.length(); // Find Peak - let l = 1, r = length - 2, peak = 0; + let l = 1, + r = length - 2, + peak = 0; while (l <= r) { const m = Math.floor((l + r) / 2); const left = get(m - 1); @@ -838,5 +842,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(\log n)$ \ No newline at end of file +- Time complexity: $O(\log n)$ +- Space complexity: $O(\log n)$ diff --git a/articles/find-k-closest-elements.md b/articles/find-k-closest-elements.md index d4a177c89..c48874fcf 100644 --- a/articles/find-k-closest-elements.md +++ b/articles/find-k-closest-elements.md @@ -16,12 +16,12 @@ public class Solution { for (int num : arr) { list.add(num); } - + list.sort((a, b) -> { int diff = Math.abs(a - x) - Math.abs(b - x); return diff == 0 ? Integer.compare(a, b) : diff; }); - + List result = list.subList(0, k); Collections.sort(result); return result; @@ -67,10 +67,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n + k \log k)$ -* Space complexity: - * $O(1)$ or $O(n)$ space depending on the sorting algorithm. - * $O(k)$ space for the output array. +- Time complexity: $O(n \log n + k \log k)$ +- Space complexity: + - $O(1)$ or $O(n)$ space depending on the sorting algorithm. + - $O(k)$ space for the output array. > Where $n$ is the size of the input array and $k$ is the number of closest elements to find. @@ -198,7 +198,8 @@ class Solution { } const res = [arr[idx]]; - let l = idx - 1, r = idx + 1; + let l = idx - 1, + r = idx + 1; while (res.length < k) { if (l >= 0 && r < n) { @@ -223,10 +224,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + k \log k)$ -* Space complexity: - * $O(1)$ or $O(k)$ space depending on the sorting algorithm. - * $O(k)$ space for the output array. +- Time complexity: $O(n + k \log k)$ +- Space complexity: + - $O(1)$ or $O(k)$ space depending on the sorting algorithm. + - $O(k)$ space for the output array. > Where $n$ is the size of the input array and $k$ is the number of closest elements to find. @@ -245,7 +246,7 @@ class Solution: r -= 1 else: l += 1 - + return arr[l: r + 1] ``` @@ -295,7 +296,8 @@ class Solution { * @return {number[]} */ findClosestElements(arr, k, x) { - let l = 0, r = arr.length - 1; + let l = 0, + r = arr.length - 1; while (r - l >= k) { if (Math.abs(x - arr[l]) <= Math.abs(x - arr[r])) { r--; @@ -312,8 +314,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n - k)$ -* Space complexity: $O(k)$ for the output array. +- Time complexity: $O(n - k)$ +- Space complexity: $O(k)$ for the output array. > Where $n$ is the size of the input array and $k$ is the number of closest elements to find. @@ -426,7 +428,8 @@ class Solution { * @return {number[]} */ findClosestElements(arr, k, x) { - let l = 0, r = arr.length - 1; + let l = 0, + r = arr.length - 1; while (l < r) { const mid = Math.floor((l + r) / 2); if (arr[mid] < x) { @@ -459,8 +462,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n + k)$ -* Space complexity: $O(k)$ for the output array. +- Time complexity: $O(\log n + k)$ +- Space complexity: $O(k)$ for the output array. > Where $n$ is the size of the input array and $k$ is the number of closest elements to find. @@ -531,7 +534,8 @@ class Solution { * @return {number[]} */ findClosestElements(arr, k, x) { - let l = 0, r = arr.length - k; + let l = 0, + r = arr.length - k; while (l < r) { const m = Math.floor((l + r) / 2); if (x - arr[m] > arr[m + k] - x) { @@ -549,7 +553,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log (n - k) + k)$ -* Space complexity: $O(k)$ for the output array. +- Time complexity: $O(\log (n - k) + k)$ +- Space complexity: $O(k)$ for the output array. -> Where $n$ is the size of the input array and $k$ is the number of closest elements to find. \ No newline at end of file +> Where $n$ is the size of the input array and $k$ is the number of closest elements to find. diff --git a/articles/find-largest-value-in-each-tree-row.md b/articles/find-largest-value-in-each-tree-row.md index d54ce9dfd..0624297ef 100644 --- a/articles/find-largest-value-in-each-tree-row.md +++ b/articles/find-largest-value-in-each-tree-row.md @@ -149,8 +149,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -299,8 +299,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -458,5 +458,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/find-median-in-a-data-stream.md b/articles/find-median-in-a-data-stream.md index ad27aa749..6d9ae64bc 100644 --- a/articles/find-median-in-a-data-stream.md +++ b/articles/find-median-in-a-data-stream.md @@ -14,7 +14,7 @@ class MedianFinder: def findMedian(self) -> float: self.data.sort() n = len(self.data) - return (self.data[n // 2] if (n & 1) else + return (self.data[n // 2] if (n & 1) else (self.data[n // 2] + self.data[n // 2 - 1]) / 2) ``` @@ -190,8 +190,8 @@ class MedianFinder { ### Time & Space Complexity -* Time complexity: $O(m)$ for $addNum()$, $O(m * n \log n)$ for $findMedian()$. -* Space complexity: $O(n)$ +- Time complexity: $O(m)$ for $addNum()$, $O(m * n \log n)$ for $findMedian()$. +- Space complexity: $O(n)$ > Where $m$ is the number of function calls and $n$ is the length of the array. @@ -206,7 +206,7 @@ class MedianFinder: def __init__(self): # two heaps, large, small, minheap, maxheap # heaps should be equal size - self.small, self.large = [], [] + self.small, self.large = [], [] def addNum(self, num: int) -> None: if self.large and num > self.large[0]: @@ -268,7 +268,7 @@ public class MedianFinder { ```cpp class MedianFinder { - priority_queue, less> smallHeap; + priority_queue, less> smallHeap; priority_queue, greater> largeHeap; public: @@ -355,7 +355,7 @@ public class MedianFinder { small = new PriorityQueue(Comparer.Create((a, b) => b.CompareTo(a))); large = new PriorityQueue(); } - + public void AddNum(int num) { if (large.Count != 0 && num > large.Peek()) { large.Enqueue(num, num); @@ -371,14 +371,14 @@ public class MedianFinder { small.Enqueue(val, val); } } - + public double FindMedian() { if (small.Count > large.Count) { return small.Peek(); } else if (large.Count > small.Count) { return large.Peek(); } - + int smallTop = small.Peek(); return (smallTop + large.Peek()) / 2.0; } @@ -412,7 +412,7 @@ func (this *MedianFinder) AddNum(num int) { } else { this.small.Enqueue(num) } - + // Rebalance if this.small.Size() > this.large.Size()+1 { val, _ := this.small.Dequeue() @@ -444,14 +444,14 @@ class MedianFinder() { // small is maxHeap, large is minHeap private val small = PriorityQueue(compareByDescending { it }) private val large = PriorityQueue() - + fun addNum(num: Int) { if (large.isNotEmpty() && num > large.peek()) { large.add(num) } else { small.add(num) } - + // Rebalance if (small.size > large.size + 1) { large.add(small.poll()) @@ -460,7 +460,7 @@ class MedianFinder() { small.add(large.poll()) } } - + fun findMedian(): Double { return when { small.size > large.size -> small.peek().toDouble() @@ -516,7 +516,7 @@ class MedianFinder { ### Time & Space Complexity -* Time complexity: $O(m * \log n)$ for $addNum()$, $O(m)$ for $findMedian()$. -* Space complexity: $O(n)$ +- Time complexity: $O(m * \log n)$ for $addNum()$, $O(m)$ for $findMedian()$. +- Space complexity: $O(n)$ -> Where $m$ is the number of function calls and $n$ is the length of the array. \ No newline at end of file +> Where $m$ is the number of function calls and $n$ is the length of the array. diff --git a/articles/find-minimum-in-rotated-sorted-array.md b/articles/find-minimum-in-rotated-sorted-array.md index 9443959d2..21dafa7eb 100644 --- a/articles/find-minimum-in-rotated-sorted-array.md +++ b/articles/find-minimum-in-rotated-sorted-array.md @@ -77,8 +77,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -96,7 +96,7 @@ class Solution: if nums[l] < nums[r]: res = min(res, nums[l]) break - + m = (l + r) // 2 res = min(res, nums[m]) if nums[m] >= nums[l]: @@ -149,7 +149,7 @@ public: res = min(res, nums[m]); if (nums[m] >= nums[l]) { - l = m + 1; + l = m + 1; } else { r = m - 1; } @@ -299,8 +299,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ --- @@ -365,7 +365,8 @@ class Solution { * @return {number} */ findMin(nums) { - let l = 0, r = nums.length - 1; + let l = 0, + r = nums.length - 1; while (l < r) { let m = l + Math.floor((r - l) / 2); if (nums[m] < nums[r]) { @@ -451,5 +452,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ diff --git a/articles/find-missing-and-repeated-values.md b/articles/find-missing-and-repeated-values.md index 58753bb0f..6ed3c9841 100644 --- a/articles/find-missing-and-repeated-values.md +++ b/articles/find-missing-and-repeated-values.md @@ -88,7 +88,8 @@ class Solution { */ findMissingAndRepeatedValues(grid) { const n = grid.length; - let doubleVal = 0, missing = 0; + let doubleVal = 0, + missing = 0; for (let num = 1; num <= n * n; num++) { let cnt = 0; @@ -116,8 +117,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 4)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 4)$ +- Space complexity: $O(1)$ --- @@ -214,7 +215,8 @@ class Solution { } } - let doubleVal = 0, missing = 0; + let doubleVal = 0, + missing = 0; for (let num = 1; num <= N * N; num++) { let freq = count[num] || 0; @@ -231,8 +233,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -327,7 +329,8 @@ class Solution { findMissingAndRepeatedValues(grid) { const N = grid.length; const seen = new Set(); - let doubleVal = 0, missing = 0; + let doubleVal = 0, + missing = 0; for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { @@ -355,8 +358,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -468,10 +471,10 @@ class Solution { } } - let totSum = N * N * (N * N + 1) / 2; + let totSum = (N * N * (N * N + 1)) / 2; let diff = gridSum - totSum; // a - b - let totSqSum = N * N * (N * N + 1) * (2 * N * N + 1) / 6; + let totSqSum = (N * N * (N * N + 1) * (2 * N * N + 1)) / 6; let sqDiff = gridSqSum - totSqSum; // (a^2) - (b^2) let sum = sqDiff / diff; // a + b @@ -488,5 +491,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ diff --git a/articles/find-missing-observations.md b/articles/find-missing-observations.md index 218ffed24..4c2ccba24 100644 --- a/articles/find-missing-observations.md +++ b/articles/find-missing-observations.md @@ -73,7 +73,8 @@ class Solution { */ missingRolls(rolls, mean, n) { const m = rolls.length; - let nTotal = (mean * (n + m)) - rolls.reduce((sum, roll) => sum + roll, 0); + let nTotal = + mean * (n + m) - rolls.reduce((sum, roll) => sum + roll, 0); if (nTotal < n || nTotal > n * 6) { return []; @@ -95,10 +96,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ space for the output array. +- Time complexity: $O(m + n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ space for the output array. > Where $m$ is the size of the array $rolls$ and $n$ is the number of missing observations. @@ -185,15 +186,18 @@ class Solution { */ missingRolls(rolls, mean, n) { const m = rolls.length; - const nTotal = (mean * (n + m)) - rolls.reduce((sum, roll) => sum + roll, 0); + const nTotal = + mean * (n + m) - rolls.reduce((sum, roll) => sum + roll, 0); if (nTotal < n || nTotal > n * 6) { return []; } const avg = Math.floor(nTotal / n); - const rem = nTotal - (avg * n); - return Array(n - rem).fill(avg).concat(Array(rem).fill(avg + 1)); + const rem = nTotal - avg * n; + return Array(n - rem) + .fill(avg) + .concat(Array(rem).fill(avg + 1)); } } ``` @@ -202,9 +206,9 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ space for the output array. +- Time complexity: $O(m + n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ space for the output array. -> Where $m$ is the size of the array $rolls$ and $n$ is the number of missing observations. \ No newline at end of file +> Where $m$ is the size of the array $rolls$ and $n$ is the number of missing observations. diff --git a/articles/find-peak-element.md b/articles/find-peak-element.md index 18300495f..4ab856d0b 100644 --- a/articles/find-peak-element.md +++ b/articles/find-peak-element.md @@ -73,8 +73,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -147,7 +147,8 @@ class Solution { * @return {number} */ findPeakElement(nums) { - let l = 0, r = nums.length - 1; + let l = 0, + r = nums.length - 1; while (l <= r) { let m = Math.floor(l + (r - l) / 2); @@ -188,8 +189,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ --- @@ -298,8 +299,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(\log n)$ for recursion stack. +- Time complexity: $O(\log n)$ +- Space complexity: $O(\log n)$ for recursion stack. --- @@ -368,7 +369,8 @@ class Solution { * @return {number} */ findPeakElement(nums) { - let l = 0, r = nums.length - 1; + let l = 0, + r = nums.length - 1; while (l < r) { let m = (l + r) >> 1; @@ -405,5 +407,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ diff --git a/articles/find-pivot-index.md b/articles/find-pivot-index.md index 7e8568d02..0354d06e4 100644 --- a/articles/find-pivot-index.md +++ b/articles/find-pivot-index.md @@ -69,7 +69,8 @@ class Solution { pivotIndex(nums) { const n = nums.length; for (let i = 0; i < n; i++) { - let leftSum = 0, rightSum = 0; + let leftSum = 0, + rightSum = 0; for (let l = 0; l < i; l++) { leftSum += nums[l]; } @@ -89,8 +90,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -105,7 +106,7 @@ class Solution: prefixSum = [0] * (n + 1) for i in range(n): prefixSum[i + 1] = prefixSum[i] + nums[i] - + for i in range(n): leftSum = prefixSum[i] rightSum = prefixSum[n] - prefixSum[i + 1] @@ -117,7 +118,7 @@ class Solution: ```java public class Solution { public int pivotIndex(int[] nums) { - int n = nums.length; + int n = nums.length; int[] prefixSum = new int[n + 1]; for (int i = 0; i < n; i++) { prefixSum[i + 1] = prefixSum[i] + nums[i]; @@ -129,7 +130,7 @@ public class Solution { if (leftSum == rightSum) { return i; } - } + } return -1; } } @@ -139,7 +140,7 @@ public class Solution { class Solution { public: int pivotIndex(vector& nums) { - int n = nums.size(); + int n = nums.size(); vector prefixSum(n + 1, 0); for (int i = 0; i < n; i++) { prefixSum[i + 1] = prefixSum[i] + nums[i]; @@ -151,7 +152,7 @@ public: if (leftSum == rightSum) { return i; } - } + } return -1; } }; @@ -186,8 +187,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -280,5 +281,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/find-polygon-with-the-largest-perimeter.md b/articles/find-polygon-with-the-largest-perimeter.md index f736cb463..f05143240 100644 --- a/articles/find-polygon-with-the-largest-perimeter.md +++ b/articles/find-polygon-with-the-largest-perimeter.md @@ -106,8 +106,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ extra space. --- @@ -194,8 +194,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -270,7 +270,7 @@ class Solution { const maxHeap = new MaxPriorityQueue(); let total = 0; - nums.forEach(num => { + nums.forEach((num) => { total += num; maxHeap.enqueue(num); }); @@ -289,7 +289,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: - * $O(n + (30\log n))$ in Python, C++, JS. - * $O(n \log n)$ in Java. -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: + - $O(n + (30\log n))$ in Python, C++, JS. + - $O(n \log n)$ in Java. +- Space complexity: $O(n)$ diff --git a/articles/find-target-in-rotated-sorted-array.md b/articles/find-target-in-rotated-sorted-array.md index b406838bb..41f7e56bb 100644 --- a/articles/find-target-in-rotated-sorted-array.md +++ b/articles/find-target-in-rotated-sorted-array.md @@ -110,8 +110,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -132,7 +132,7 @@ class Solution: r = m pivot = l - + def binary_search(left: int, right: int) -> int: while left <= right: mid = (left + right) // 2 @@ -147,7 +147,7 @@ class Solution: result = binary_search(0, pivot - 1) if result != -1: return result - + return binary_search(pivot, len(nums) - 1) ``` @@ -450,8 +450,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ --- @@ -580,7 +580,8 @@ class Solution { * @return {number} */ search(nums, target) { - let l = 0, r = nums.length - 1; + let l = 0, + r = nums.length - 1; while (l < r) { let m = Math.floor((l + r) / 2); @@ -779,8 +780,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ --- @@ -803,7 +804,7 @@ class Solution: l = mid + 1 else: r = mid - 1 - + else: if target < nums[mid] or target > nums[r]: r = mid - 1 @@ -886,7 +887,8 @@ class Solution { * @return {number} */ search(nums, target) { - let l = 0, r = nums.length - 1; + let l = 0, + r = nums.length - 1; while (l <= r) { const mid = Math.floor((l + r) / 2); @@ -1036,5 +1038,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ diff --git a/articles/find-the-difference-of-two-arrays.md b/articles/find-the-difference-of-two-arrays.md index 853638267..08f994bbc 100644 --- a/articles/find-the-difference-of-two-arrays.md +++ b/articles/find-the-difference-of-two-arrays.md @@ -100,7 +100,7 @@ public: } } - return {vector(res1.begin(), res1.end()), + return {vector(res1.begin(), res1.end()), vector(res2.begin(), res2.end())}; } }; @@ -152,8 +152,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n + m)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n + m)$ > Where $n$ is the size of the array $nums1$ and $m$ is the size of the array $nums2$. @@ -283,8 +283,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n + m \log m)$ -* Space complexity: $O(1)$ or $O(n + m)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n + m \log m)$ +- Space complexity: $O(1)$ or $O(n + m)$ depending on the sorting algorithm. > Where $n$ is the size of the array $nums1$ and $m$ is the size of the array $nums2$. @@ -386,8 +386,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n + m)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(n + m)$ > Where $n$ is the size of the array $nums1$ and $m$ is the size of the array $nums2$. @@ -429,10 +429,10 @@ public: vector> findDifference(vector& nums1, vector& nums2) { vector res1, res2; set numSet1(begin(nums1), end(nums1)), numSet2(begin(nums2), end(nums2)); - + set_difference(begin(numSet1), end(numSet1), begin(numSet2), end(numSet2), back_inserter(res1)); set_difference(begin(numSet2), end(numSet2), begin(numSet1), end(numSet1), back_inserter(res2)); - + return {res1, res2}; } }; @@ -449,8 +449,8 @@ class Solution { const numSet1 = new Set(nums1); const numSet2 = new Set(nums2); - const res1 = Array.from(numSet1).filter(num => !numSet2.has(num)); - const res2 = Array.from(numSet2).filter(num => !numSet1.has(num)); + const res1 = Array.from(numSet1).filter((num) => !numSet2.has(num)); + const res2 = Array.from(numSet2).filter((num) => !numSet1.has(num)); return [res1, res2]; } @@ -461,7 +461,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n + m)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(n + m)$ -> Where $n$ is the size of the array $nums1$ and $m$ is the size of the array $nums2$. \ No newline at end of file +> Where $n$ is the size of the array $nums1$ and $m$ is the size of the array $nums2$. diff --git a/articles/find-the-difference.md b/articles/find-the-difference.md index b06b2803f..1b3f9f9da 100644 --- a/articles/find-the-difference.md +++ b/articles/find-the-difference.md @@ -77,8 +77,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ since we have at most $26$ different characters. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ since we have at most $26$ different characters. --- @@ -161,8 +161,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ since we have at most $26$ different characters. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ since we have at most $26$ different characters. --- @@ -237,8 +237,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -296,7 +296,8 @@ class Solution { * @return {character} */ findTheDifference(s, t) { - let sumS = 0, sumT = 0; + let sumS = 0, + sumT = 0; for (let char of s) { sumS += char.charCodeAt(0); } @@ -312,8 +313,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -387,8 +388,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -462,5 +463,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/find-the-index-of-the-first-occurrence-in-a-string.md b/articles/find-the-index-of-the-first-occurrence-in-a-string.md index beb5b5893..083991ad6 100644 --- a/articles/find-the-index-of-the-first-occurrence-in-a-string.md +++ b/articles/find-the-index-of-the-first-occurrence-in-a-string.md @@ -64,7 +64,8 @@ class Solution { * @return {number} */ strStr(haystack, needle) { - let n = haystack.length, m = needle.length; + let n = haystack.length, + m = needle.length; for (let i = 0; i < n - m + 1; i++) { let j = 0; while (j < m) { @@ -84,8 +85,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(1)$ > Where $n$ is the length of the string $heystack$ and $m$ is the length of the string $needle$. @@ -112,7 +113,7 @@ class Solution: i += 1 else: prevLPS = lps[prevLPS - 1] - + i = 0 # ptr for haystack j = 0 # ptr for needle while i < len(haystack): @@ -123,10 +124,10 @@ class Solution: i += 1 else: j = lps[j - 1] - + if j == len(needle): return i - len(needle) - + return -1 ``` @@ -231,12 +232,13 @@ class Solution { * @return {number} */ strStr(haystack, needle) { - if (needle === "") return 0; + if (needle === '') return 0; const m = needle.length; const lps = new Array(m).fill(0); - let prevLPS = 0, i = 1; + let prevLPS = 0, + i = 1; while (i < m) { if (needle[i] === needle[prevLPS]) { lps[i] = prevLPS + 1; @@ -250,8 +252,8 @@ class Solution { } } - i = 0; // ptr for haystack - let j = 0; // ptr for needle + i = 0; // ptr for haystack + let j = 0; // ptr for needle while (i < haystack.length) { if (haystack[i] === needle[j]) { i++; @@ -278,8 +280,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(m)$ > Where $n$ is the length of the string $heystack$ and $m$ is the length of the string $needle$. @@ -294,12 +296,12 @@ class Solution: def strStr(self, haystack: str, needle: str) -> int: if not needle: return 0 - + s = needle + "$" + haystack n = len(s) z = [0] * n l, r = 0, 0 - + for i in range(1, n): if i <= r: z[i] = min(r - i + 1, z[i - l]) @@ -307,11 +309,11 @@ class Solution: z[i] += 1 if i + z[i] - 1 > r: l, r = i, i + z[i] - 1 - + for i in range(len(needle) + 1, n): if z[i] == len(needle): return i - len(needle) - 1 - + return -1 ``` @@ -392,12 +394,13 @@ class Solution { * @return {number} */ strStr(haystack, needle) { - if (needle === "") return 0; + if (needle === '') return 0; - const s = needle + "$" + haystack; + const s = needle + '$' + haystack; const n = s.length; const z = new Array(n).fill(0); - let l = 0, r = 0; + let l = 0, + r = 0; for (let i = 1; i < n; i++) { if (i <= r) { @@ -427,8 +430,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n + m)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(n + m)$ > Where $n$ is the length of the string $heystack$ and $m$ is the length of the string $needle$. @@ -443,10 +446,10 @@ class Solution: def strStr(self, haystack: str, needle: str) -> int: if not needle: return 0 - + base1, mod1 = 31, 768258391 base2, mod2 = 37, 685683731 - + n, m = len(haystack), len(needle) if m > n: return -1 @@ -468,7 +471,7 @@ class Solution: for i in range(n - m + 1): if haystack_hash1 == needle_hash1 and haystack_hash2 == needle_hash2: return i - + if i + m < n: haystack_hash1 = (haystack_hash1 * base1 - ord(haystack[i]) * power1 + ord(haystack[i + m])) % mod1 haystack_hash2 = (haystack_hash2 * base2 - ord(haystack[i]) * power2 + ord(haystack[i + m])) % mod2 @@ -580,38 +583,57 @@ class Solution { * @return {number} */ strStr(haystack, needle) { - if (needle === "") return 0; + if (needle === '') return 0; - const base1 = 31, mod1 = 768258391; - const base2 = 37, mod2 = 685683731; + const base1 = 31, + mod1 = 768258391; + const base2 = 37, + mod2 = 685683731; - const n = haystack.length, m = needle.length; + const n = haystack.length, + m = needle.length; if (m > n) return -1; - let power1 = 1, power2 = 1; + let power1 = 1, + power2 = 1; for (let i = 0; i < m; i++) { power1 = (power1 * base1) % mod1; power2 = (power2 * base2) % mod2; } - let needleHash1 = 0, needleHash2 = 0; - let haystackHash1 = 0, haystackHash2 = 0; + let needleHash1 = 0, + needleHash2 = 0; + let haystackHash1 = 0, + haystackHash2 = 0; for (let i = 0; i < m; i++) { needleHash1 = (needleHash1 * base1 + needle.charCodeAt(i)) % mod1; needleHash2 = (needleHash2 * base2 + needle.charCodeAt(i)) % mod2; - haystackHash1 = (haystackHash1 * base1 + haystack.charCodeAt(i)) % mod1; - haystackHash2 = (haystackHash2 * base2 + haystack.charCodeAt(i)) % mod2; + haystackHash1 = + (haystackHash1 * base1 + haystack.charCodeAt(i)) % mod1; + haystackHash2 = + (haystackHash2 * base2 + haystack.charCodeAt(i)) % mod2; } for (let i = 0; i <= n - m; i++) { - if (haystackHash1 === needleHash1 && haystackHash2 === needleHash2) { + if ( + haystackHash1 === needleHash1 && + haystackHash2 === needleHash2 + ) { return i; } if (i + m < n) { - haystackHash1 = (haystackHash1 * base1 - haystack.charCodeAt(i) * power1 + haystack.charCodeAt(i + m)) % mod1; - haystackHash2 = (haystackHash2 * base2 - haystack.charCodeAt(i) * power2 + haystack.charCodeAt(i + m)) % mod2; + haystackHash1 = + (haystackHash1 * base1 - + haystack.charCodeAt(i) * power1 + + haystack.charCodeAt(i + m)) % + mod1; + haystackHash2 = + (haystackHash2 * base2 - + haystack.charCodeAt(i) * power2 + + haystack.charCodeAt(i + m)) % + mod2; if (haystackHash1 < 0) haystackHash1 += mod1; if (haystackHash2 < 0) haystackHash2 += mod2; @@ -627,7 +649,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(1)$ -> Where $n$ is the length of the string $heystack$ and $m$ is the length of the string $needle$. \ No newline at end of file +> Where $n$ is the length of the string $heystack$ and $m$ is the length of the string $needle$. diff --git a/articles/find-the-kth-largest-integer-in-the-array.md b/articles/find-the-kth-largest-integer-in-the-array.md index ba70f2ed8..9c46cfcf2 100644 --- a/articles/find-the-kth-largest-integer-in-the-array.md +++ b/articles/find-the-kth-largest-integer-in-the-array.md @@ -39,8 +39,8 @@ class Solution { * @return {string} */ kthLargestNumber(nums, k) { - nums.sort( - (a, b) => a.length === b.length ? b.localeCompare(a) : b.length - a.length + nums.sort((a, b) => + a.length === b.length ? b.localeCompare(a) : b.length - a.length, ); return nums[k - 1]; } @@ -51,8 +51,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(m * n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. > Where $n$ is the number of strings and $m$ is the average length of a string. @@ -86,7 +86,7 @@ class Solution: ```java public class Solution { public String kthLargestNumber(String[] nums, int k) { - PriorityQueue maxHeap = new PriorityQueue<>((a, b) -> + PriorityQueue maxHeap = new PriorityQueue<>((a, b) -> a.length() == b.length() ? b.compareTo(a) : Integer.compare(b.length(), a.length()) ); @@ -134,8 +134,8 @@ class Solution { * @return {string} */ kthLargestNumber(nums, k) { - const maxHeap = new PriorityQueue( - (a, b) => a.length === b.length ? b.localeCompare(a) : b.length - a.length + const maxHeap = new PriorityQueue((a, b) => + a.length === b.length ? b.localeCompare(a) : b.length - a.length, ); for (const num of nums) { @@ -155,8 +155,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * (n + k) * \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(m * (n + k) * \log n)$ +- Space complexity: $O(n)$ > Where $n$ is the number of strings and $m$ is the average length of a string. @@ -170,7 +170,7 @@ class Solution { class Num: def __init__(self, s: str): self.s = s - + def __lt__(self, other: "Num") -> bool: if len(self.s) != len(other.s): return len(self.s) < len(other.s) @@ -189,7 +189,7 @@ class Solution: ```java public class Solution { public String kthLargestNumber(String[] nums, int k) { - PriorityQueue minHeap = new PriorityQueue<>((a, b) -> + PriorityQueue minHeap = new PriorityQueue<>((a, b) -> a.length() == b.length() ? a.compareTo(b) : Integer.compare(a.length(), b.length()) ); @@ -235,8 +235,8 @@ class Solution { * @return {string} */ kthLargestNumber(nums, k) { - const minHeap = new PriorityQueue( - (a, b) => a.length === b.length ? a.localeCompare(b) : a.length - b.length + const minHeap = new PriorityQueue((a, b) => + a.length === b.length ? a.localeCompare(b) : a.length - b.length, ); for (const num of nums) { @@ -255,8 +255,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n * \log k)$ -* Space complexity: $O(k)$ +- Time complexity: $O(m * n * \log k)$ +- Space complexity: $O(k)$ > Where $n$ is the number of strings and $m$ is the average length of a string. @@ -305,7 +305,7 @@ class Solution: if i > j: break nums[i], nums[j] = nums[j], nums[i] - + nums[left + 1], nums[j] = nums[j], nums[left + 1] return j @@ -487,9 +487,11 @@ class Solution { * @return {string} */ kthLargestNumber(nums, k) { - const greater = (x, y) => x.length !== y.length ? x.length > y.length : x > y; - const less = (x, y) => x.length !== y.length ? x.length < y.length : x < y; - const swap = (arr, i, j) => [arr[i], arr[j]] = [arr[j], arr[i]]; + const greater = (x, y) => + x.length !== y.length ? x.length > y.length : x > y; + const less = (x, y) => + x.length !== y.length ? x.length < y.length : x < y; + const swap = (arr, i, j) => ([arr[i], arr[j]] = [arr[j], arr[i]]); const partition = (nums, left, right) => { const mid = Math.floor((left + right) / 2); @@ -500,7 +502,8 @@ class Solution { if (less(nums[left], nums[left + 1])) swap(nums, left, left + 1); const pivot = nums[left + 1]; - let i = left + 1, j = right; + let i = left + 1, + j = right; while (true) { while (greater(nums[++i], pivot)); @@ -514,11 +517,15 @@ class Solution { }; const quickSelect = (nums, k) => { - let left = 0, right = nums.length - 1; + let left = 0, + right = nums.length - 1; while (true) { if (right <= left + 1) { - if (right === left + 1 && greater(nums[right], nums[left])) { + if ( + right === left + 1 && + greater(nums[right], nums[left]) + ) { swap(nums, left, right); } return nums[k]; @@ -539,5 +546,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ in average case, $O(m * n ^ 2)$ in worst case. -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(m * n)$ in average case, $O(m * n ^ 2)$ in worst case. +- Space complexity: $O(1)$ diff --git a/articles/find-the-longest-valid-obstacle-course-at-each-position.md b/articles/find-the-longest-valid-obstacle-course-at-each-position.md index ff2346555..e4660f452 100644 --- a/articles/find-the-longest-valid-obstacle-course-at-each-position.md +++ b/articles/find-the-longest-valid-obstacle-course-at-each-position.md @@ -139,8 +139,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -225,7 +225,8 @@ class Solution { let dp = new Array(n + 1).fill(1e8); const upperBound = (dp, target) => { - let left = 0, right = dp.length; + let left = 0, + right = dp.length; while (left < right) { let mid = Math.floor((left + right) / 2); if (dp[mid] > target) { @@ -252,8 +253,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -351,7 +352,8 @@ class Solution { let dp = []; const upperBound = (dp, target) => { - let left = 0, right = dp.length; + let left = 0, + right = dp.length; while (left < right) { let mid = Math.floor((left + right) / 2); if (dp[mid] > target) { @@ -383,5 +385,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ diff --git a/articles/find-the-maximum-sum-of-node-values.md b/articles/find-the-maximum-sum-of-node-values.md index d48258892..d37f1846c 100644 --- a/articles/find-the-maximum-sum-of-node-values.md +++ b/articles/find-the-maximum-sum-of-node-values.md @@ -45,7 +45,7 @@ public class Solution { long[] res = { nums[node], nums[node] ^ k }; for (int child : adj[node]) { if (child == parent) continue; - + long[] cur = dfs(child, node, nums, k, adj); long[] tmp = new long[2]; tmp[0] = Math.max(res[0] + cur[0], res[1] + cur[1]); @@ -132,8 +132,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -231,7 +231,7 @@ class Solution { let res = nums[i] + dfs(i + 1, xorCnt); res = Math.max(res, (nums[i] ^ k) + dfs(i + 1, xorCnt ^ 1)); - return dp[i][xorCnt] = res; + return (dp[i][xorCnt] = res); }; return dfs(0, 0); @@ -243,8 +243,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -315,8 +315,14 @@ class Solution { dp[n][1] = -Infinity; for (let i = n - 1; i >= 0; i--) { - dp[i][0] = Math.max(nums[i] + dp[i + 1][0], (nums[i] ^ k) + dp[i + 1][1]); - dp[i][1] = Math.max(nums[i] + dp[i + 1][1], (nums[i] ^ k) + dp[i + 1][0]); + dp[i][0] = Math.max( + nums[i] + dp[i + 1][0], + (nums[i] ^ k) + dp[i + 1][1], + ); + dp[i][1] = Math.max( + nums[i] + dp[i + 1][1], + (nums[i] ^ k) + dp[i + 1][0], + ); } return dp[0][0]; @@ -328,8 +334,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -416,8 +422,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -530,8 +536,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -611,7 +617,9 @@ class Solution { * @return {number} */ maximumValueSum(nums, k, edges) { - let xorCnt = 0, res = 0, minDiff = 1 << 30; + let xorCnt = 0, + res = 0, + minDiff = 1 << 30; for (let num of nums) { let xorNum = num ^ k; @@ -624,7 +632,7 @@ class Solution { minDiff = Math.min(minDiff, Math.abs(xorNum - num)); } - return res - (xorCnt * minDiff); + return res - xorCnt * minDiff; } } ``` @@ -633,5 +641,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/find-the-safest-path-in-a-grid.md b/articles/find-the-safest-path-in-a-grid.md index f547fa423..a6a4bb7dc 100644 --- a/articles/find-the-safest-path-in-a-grid.md +++ b/articles/find-the-safest-path-in-a-grid.md @@ -189,7 +189,12 @@ class Solution { */ maximumSafenessFactor(grid) { const N = grid.length; - const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; + const directions = [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + ]; const inBounds = (r, c) => { return r >= 0 && c >= 0 && r < N && c < N; @@ -212,7 +217,8 @@ class Solution { let [r, c, dist] = q.pop(); for (let [dr, dc] of directions) { - let r2 = r + dr, c2 = c + dc; + let r2 = r + dr, + c2 = c + dc; if (inBounds(r2, c2) && minDist[r2][c2] === -1) { minDist[r2][c2] = dist + 1; q.push([r2, c2, dist + 1]); @@ -223,7 +229,7 @@ class Solution { }; const minDist = precompute(); - const maxHeap = new MaxPriorityQueue({ priority: x => x[0] }); + const maxHeap = new MaxPriorityQueue({ priority: (x) => x[0] }); const visit = Array.from({ length: N }, () => Array(N).fill(false)); maxHeap.enqueue([minDist[0][0], 0, 0]); @@ -237,7 +243,8 @@ class Solution { } for (let [dr, dc] of directions) { - let r2 = r + dr, c2 = c + dc; + let r2 = r + dr, + c2 = c + dc; if (inBounds(r2, c2) && !visit[r2][c2]) { visit[r2][c2] = true; let dist2 = Math.min(dist, minDist[r2][c2]); @@ -254,8 +261,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 \log n)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2 \log n)$ +- Space complexity: $O(n ^ 2)$ --- @@ -466,24 +473,33 @@ class Solution { while (!q.isEmpty()) { let node = q.pop(); - let r = Math.floor(node / N), c = node % N; + let r = Math.floor(node / N), + c = node % N; for (let i = 0; i < 4; i++) { - let r2 = r + directions[i], c2 = c + directions[i + 1]; - if (r2 >= 0 && c2 >= 0 && r2 < N && c2 < N && minDist[r2][c2] === -1) { + let r2 = r + directions[i], + c2 = c + directions[i + 1]; + if ( + r2 >= 0 && + c2 >= 0 && + r2 < N && + c2 < N && + minDist[r2][c2] === -1 + ) { minDist[r2][c2] = minDist[r][c] + 1; q.push(r2 * N + c2); } } } - let maxHeap = new MaxPriorityQueue({ priority: x => x[0] }); + let maxHeap = new MaxPriorityQueue({ priority: (x) => x[0] }); let safeFactor = new Array(N * N).fill(0); safeFactor[0] = minDist[0][0]; maxHeap.enqueue([safeFactor[0], 0]); while (!maxHeap.isEmpty()) { let [dist, node] = maxHeap.dequeue().element; - let r = Math.floor(node / N), c = node % N; + let r = Math.floor(node / N), + c = node % N; if (r === N - 1 && c === N - 1) { return dist; } @@ -492,7 +508,9 @@ class Solution { } for (let i = 0; i < 4; i++) { - let r2 = r + directions[i], c2 = c + directions[i + 1], node2 = r2 * N + c2; + let r2 = r + directions[i], + c2 = c + directions[i + 1], + node2 = r2 * N + c2; if (r2 >= 0 && c2 >= 0 && r2 < N && c2 < N) { let dist2 = Math.min(dist, minDist[r2][c2]); if (dist2 > safeFactor[node2]) { @@ -511,8 +529,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 \log n)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2 \log n)$ +- Space complexity: $O(n ^ 2)$ --- @@ -559,7 +577,7 @@ class Solution: for i in range(4): r2, c2 = r + directions[i], c + directions[i + 1] node2 = r2 * N + c2 - if (0 <= r2 < N and 0 <= c2 < N and not visited[node2] and + if (0 <= r2 < N and 0 <= c2 < N and not visited[node2] and minDist[r2][c2] >= threshold ): visited[node2] = True @@ -638,7 +656,7 @@ public class Solution { for (int i = 0; i < 4; i++) { int r2 = r + directions[i], c2 = c + directions[i + 1]; int node2 = r2 * N + c2; - if (r2 >= 0 && c2 >= 0 && r2 < N && c2 < N && !visited[node2] && + if (r2 >= 0 && c2 >= 0 && r2 < N && c2 < N && !visited[node2] && minDist[r2][c2] >= threshold) { visited[node2] = true; q.offer(node2); @@ -711,7 +729,7 @@ private: for (int i = 0; i < 4; i++) { int r2 = r + directions[i], c2 = c + directions[i + 1], node2 = r2 * N + c2; - if (r2 >= 0 && c2 >= 0 && r2 < N && c2 < N && !visited[node2] && + if (r2 >= 0 && c2 >= 0 && r2 < N && c2 < N && !visited[node2] && minDist[r2][c2] >= threshold) { visited[node2] = true; q.push(node2); @@ -748,10 +766,18 @@ class Solution { while (!q.isEmpty()) { let node = q.pop(); - let r = Math.floor(node / N), c = node % N; + let r = Math.floor(node / N), + c = node % N; for (let i = 0; i < 4; i++) { - let r2 = r + directions[i], c2 = c + directions[i + 1]; - if (r2 >= 0 && c2 >= 0 && r2 < N && c2 < N && minDist[r2][c2] === -1) { + let r2 = r + directions[i], + c2 = c + directions[i + 1]; + if ( + r2 >= 0 && + c2 >= 0 && + r2 < N && + c2 < N && + minDist[r2][c2] === -1 + ) { minDist[r2][c2] = minDist[r][c] + 1; q.push(r2 * N + c2); } @@ -765,13 +791,22 @@ class Solution { while (!q.isEmpty()) { let node = q.pop(); - let r = Math.floor(node / N), c = node % N; + let r = Math.floor(node / N), + c = node % N; if (r === N - 1 && c === N - 1) return true; for (let i = 0; i < 4; i++) { - let r2 = r + directions[i], c2 = c + directions[i + 1], node2 = r2 * N + c2; - if (r2 >= 0 && c2 >= 0 && r2 < N && c2 < N && !visited[node2] && - minDist[r2][c2] >= threshold) { + let r2 = r + directions[i], + c2 = c + directions[i + 1], + node2 = r2 * N + c2; + if ( + r2 >= 0 && + c2 >= 0 && + r2 < N && + c2 < N && + !visited[node2] && + minDist[r2][c2] >= threshold + ) { visited[node2] = true; q.push(node2); } @@ -780,7 +815,8 @@ class Solution { return false; }; - let l = 0, r = Math.min(minDist[0][0], minDist[N - 1][N - 1]); + let l = 0, + r = Math.min(minDist[0][0], minDist[N - 1][N - 1]); while (l <= r) { let mid = Math.floor((l + r) / 2); if (canReach(mid)) { @@ -798,8 +834,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 \log n)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2 \log n)$ +- Space complexity: $O(n ^ 2)$ --- @@ -1006,10 +1042,18 @@ class Solution { while (!q.isEmpty()) { let node = q.popFront(); - let r = Math.floor(node / N), c = node % N; + let r = Math.floor(node / N), + c = node % N; for (let i = 0; i < 4; i++) { - let r2 = r + directions[i], c2 = c + directions[i + 1]; - if (r2 >= 0 && c2 >= 0 && r2 < N && c2 < N && minDist[r2][c2] === -1) { + let r2 = r + directions[i], + c2 = c + directions[i + 1]; + if ( + r2 >= 0 && + c2 >= 0 && + r2 < N && + c2 < N && + minDist[r2][c2] === -1 + ) { minDist[r2][c2] = minDist[r][c] + 1; q.pushBack(r2 * N + c2); } @@ -1017,21 +1061,36 @@ class Solution { } let safeFactor = new Array(N * N).fill(-1); - let res = safeFactor[0] = Math.min(minDist[N - 1][N - 1], minDist[0][0]); + let res = (safeFactor[0] = Math.min( + minDist[N - 1][N - 1], + minDist[0][0], + )); q.pushBack(0); while (!q.isEmpty()) { let node = q.popFront(); - let r = Math.floor(node / N), c = node % N; + let r = Math.floor(node / N), + c = node % N; res = Math.min(res, safeFactor[node]); if (r === N - 1 && c === N - 1) { break; } for (let i = 0; i < 4; i++) { - let r2 = r + directions[i], c2 = c + directions[i + 1], node2 = r2 * N + c2; - if (r2 >= 0 && c2 >= 0 && r2 < N && c2 < N && safeFactor[node2] === -1) { - safeFactor[node2] = Math.min(safeFactor[node], minDist[r2][c2]); + let r2 = r + directions[i], + c2 = c + directions[i + 1], + node2 = r2 * N + c2; + if ( + r2 >= 0 && + c2 >= 0 && + r2 < N && + c2 < N && + safeFactor[node2] === -1 + ) { + safeFactor[node2] = Math.min( + safeFactor[node], + minDist[r2][c2], + ); if (safeFactor[node2] < res) { q.pushBack(node2); } else { @@ -1050,5 +1109,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ \ No newline at end of file +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ diff --git a/articles/find-the-town-judge.md b/articles/find-the-town-judge.md index a1343bd35..092eed3dc 100644 --- a/articles/find-the-town-judge.md +++ b/articles/find-the-town-judge.md @@ -11,11 +11,11 @@ class Solution: for src, dst in trust: outgoing[src] += 1 incoming[dst] += 1 - + for i in range(1, n + 1): if outgoing[i] == 0 and incoming[i] == n - 1: return i - + return -1 ``` @@ -24,18 +24,18 @@ public class Solution { public int findJudge(int n, int[][] trust) { int[] incoming = new int[n + 1]; int[] outgoing = new int[n + 1]; - + for (int[] t : trust) { outgoing[t[0]]++; incoming[t[1]]++; } - + for (int i = 1; i <= n; i++) { if (outgoing[i] == 0 && incoming[i] == n - 1) { return i; } } - + return -1; } } @@ -46,17 +46,17 @@ class Solution { public: int findJudge(int n, vector>& trust) { vector incoming(n + 1, 0), outgoing(n + 1, 0); - + for (auto& t : trust) { outgoing[t[0]]++; incoming[t[1]]++; } - + for (int i = 1; i <= n; i++) { if (outgoing[i] == 0 && incoming[i] == n - 1) return i; } - + return -1; } }; @@ -72,18 +72,18 @@ class Solution { findJudge(n, trust) { let incoming = new Array(n + 1).fill(0); let outgoing = new Array(n + 1).fill(0); - + for (let [src, dst] of trust) { outgoing[src]++; incoming[dst]++; } - + for (let i = 1; i <= n; i++) { if (outgoing[i] === 0 && incoming[i] === n - 1) { return i; } } - + return -1; } } @@ -117,8 +117,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V)$ > Where $V$ is the number of vertices and $E$ is the number of edges. @@ -136,11 +136,11 @@ class Solution: for src, dst in trust: delta[src] -= 1 delta[dst] += 1 - + for i in range(1, n + 1): if delta[i] == n - 1: return i - + return -1 ``` @@ -153,13 +153,13 @@ public class Solution { delta[t[0]] -= 1; delta[t[1]] += 1; } - + for (int i = 1; i <= n; i++) { if (delta[i] == n - 1) { return i; } } - + return -1; } } @@ -170,18 +170,18 @@ class Solution { public: int findJudge(int n, vector>& trust) { vector delta(n + 1, 0); - + for (auto& t : trust) { delta[t[0]]--; delta[t[1]]++; } - + for (int i = 1; i <= n; i++) { if (delta[i] == n - 1) { return i; } } - + return -1; } }; @@ -196,18 +196,18 @@ class Solution { */ findJudge(n, trust) { let delta = new Array(n + 1).fill(0); - + for (let [src, dst] of trust) { delta[src]--; delta[dst]++; } - + for (let i = 1; i <= n; i++) { if (delta[i] === n - 1) { return i; } } - + return -1; } } @@ -239,7 +239,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V)$ -> Where $V$ is the number of vertices and $E$ is the number of edges. \ No newline at end of file +> Where $V$ is the number of vertices and $E$ is the number of edges. diff --git a/articles/find-unique-binary-string.md b/articles/find-unique-binary-string.md index ea24db9f9..33c9097f0 100644 --- a/articles/find-unique-binary-string.md +++ b/articles/find-unique-binary-string.md @@ -83,18 +83,18 @@ class Solution { const backtrack = (i, cur) => { if (i === n) { - const res = cur.join(""); + const res = cur.join(''); return strSet.has(res) ? null : res; } let res = backtrack(i + 1, cur); if (res) return res; - cur[i] = "1"; + cur[i] = '1'; return backtrack(i + 1, cur); }; - return backtrack(0, Array(n).fill("0")); + return backtrack(0, Array(n).fill('0')); } } ``` @@ -103,8 +103,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -118,8 +118,8 @@ class Solution: strSet = set(nums) n = len(nums) - for num in range(1 << n): - res = bin(num)[2:].zfill(n) + for num in range(1 << n): + res = bin(num)[2:].zfill(n) if res not in strSet: return res @@ -136,7 +136,7 @@ public class Solution { int n = nums.length; for (int num = 0; num < (n + 1); num++) { - String res = String.format("%" + n + "s", + String res = String.format("%" + n + "s", Integer.toBinaryString(num)).replace(' ', '0'); if (!strSet.contains(res)) { return res; @@ -186,14 +186,14 @@ class Solution { const strSet = new Set(nums); const n = nums.length; - for (let num = 0; num < (n + 1); num++) { + for (let num = 0; num < n + 1; num++) { let res = num.toString(2).padStart(n, '0'); if (!strSet.has(res)) { return res; } } - return ""; + return ''; } } ``` @@ -202,8 +202,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -259,7 +259,7 @@ class Solution { for (let i = 0; i < nums.length; i++) { res.push(nums[i][i] === '0' ? '1' : '0'); } - return res.join(""); + return res.join(''); } } ``` @@ -268,10 +268,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ space for the output string. +- Time complexity: $O(n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ space for the output string. --- @@ -346,8 +346,9 @@ class Solution { const n = nums.length; while (true) { - let res = Array.from({ length: n }, () => - Math.random() < 0.5 ? '0' : '1').join(""); + let res = Array.from({ length: n }, () => + Math.random() < 0.5 ? '0' : '1', + ).join(''); if (!strSet.has(res)) { return res; } @@ -360,8 +361,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(∞)$ in worst case. -* Space complexity: $O(n)$ +- Time complexity: $O(∞)$ in worst case. +- Space complexity: $O(n)$ --- @@ -672,7 +673,7 @@ class Solution { res.push('1'); } - return res.join(""); + return res.join(''); } } ``` @@ -681,5 +682,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ \ No newline at end of file +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ diff --git a/articles/find-words-that-can-be-formed-by-characters.md b/articles/find-words-that-can-be-formed-by-characters.md index 4dfdf7b44..b343dac24 100644 --- a/articles/find-words-that-can-be-formed-by-characters.md +++ b/articles/find-words-that-can-be-formed-by-characters.md @@ -7,7 +7,7 @@ class Solution: def countCharacters(self, words: List[str], chars: str) -> int: count = Counter(chars) res = 0 - + for w in words: cur_word = Counter(w) good = True @@ -117,8 +117,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + (m * k))$ -* Space complexity: $O(1)$ since we have at most $26$ different characters. +- Time complexity: $O(n + (m * k))$ +- Space complexity: $O(1)$ since we have at most $26$ different characters. > Where $n$ is the length of $chars$, $m$ is the number of words and $k$ is the average length of each word. @@ -133,7 +133,7 @@ class Solution: def countCharacters(self, words: List[str], chars: str) -> int: count = Counter(chars) res = 0 - + for w in words: cur_word = defaultdict(int) good = True @@ -238,8 +238,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + (m * k))$ -* Space complexity: $O(1)$ since we have at most $26$ different characters. +- Time complexity: $O(n + (m * k))$ +- Space complexity: $O(1)$ since we have at most $26$ different characters. > Where $n$ is the length of $chars$, $m$ is the number of words and $k$ is the average length of each word. @@ -255,10 +255,10 @@ class Solution: count = [0] * 26 for c in chars: count[ord(c) - ord('a')] += 1 - + org = count[:] res = 0 - + for w in words: good = True for c in w: @@ -282,10 +282,10 @@ public class Solution { for (char c : chars.toCharArray()) { count[c - 'a']++; } - + int[] org = count.clone(); int res = 0; - + for (String w : words) { boolean good = true; for (int i = 0; i < w.length(); i++) { @@ -316,10 +316,10 @@ public: for (char c : chars) { count[c - 'a']++; } - + vector org = count; int res = 0; - + for (string& w : words) { bool good = true; for (char& c : w) { @@ -354,10 +354,10 @@ class Solution { for (let c of chars) { count[c.charCodeAt(0) - 'a'.charCodeAt(0)]++; } - + const org = [...count]; let res = 0; - + for (let w of words) { let good = true; for (let c of w) { @@ -368,7 +368,7 @@ class Solution { break; } } - + if (good) { res += w.length; } @@ -385,7 +385,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + (m * k))$ -* Space complexity: $O(1)$ since we have at most $26$ different characters. +- Time complexity: $O(n + (m * k))$ +- Space complexity: $O(1)$ since we have at most $26$ different characters. -> Where $n$ is the length of $chars$, $m$ is the number of words and $k$ is the average length of each word. \ No newline at end of file +> Where $n$ is the length of $chars$, $m$ is the number of words and $k$ is the average length of each word. diff --git a/articles/first-bad-version.md b/articles/first-bad-version.md index 12305c833..40a7ff574 100644 --- a/articles/first-bad-version.md +++ b/articles/first-bad-version.md @@ -71,8 +71,8 @@ class Solution extends VersionControl { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -94,7 +94,7 @@ class Solution: return helper(l, m - 1) else: return helper(m + 1, r) - + return helper(1, n) ``` @@ -176,8 +176,8 @@ class Solution extends VersionControl { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(\log n)$ for recursion stack. +- Time complexity: $O(\log n)$ +- Space complexity: $O(\log n)$ for recursion stack. --- @@ -256,7 +256,9 @@ class Solution extends VersionControl { * @return {number} The first bad version */ firstBadVersion(n) { - let l = 1, r = n, res = -1; + let l = 1, + r = n, + res = -1; while (l <= r) { const m = Math.floor(l + (r - l) / 2); if (this.isBadVersion(m)) { @@ -275,8 +277,8 @@ class Solution extends VersionControl { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ --- @@ -351,7 +353,8 @@ class Solution extends VersionControl { * @return {number} The first bad version */ firstBadVersion(n) { - let l = 1, r = n; + let l = 1, + r = n; while (l < r) { const m = Math.floor(l + (r - l) / 2); if (this.isBadVersion(m)) { @@ -369,5 +372,5 @@ class Solution extends VersionControl { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ diff --git a/articles/first-missing-positive.md b/articles/first-missing-positive.md index 09f5f9678..d9b2c5fc2 100644 --- a/articles/first-missing-positive.md +++ b/articles/first-missing-positive.md @@ -15,7 +15,7 @@ class Solution: if flag: return missing - missing += 1 + missing += 1 ``` ```java @@ -84,10 +84,10 @@ class Solution { public class Solution { public int FirstMissingPositive(int[] nums) { int missing = 1; - + while (true) { bool found = false; - + foreach (int num in nums) { if (num == missing) { found = true; @@ -109,8 +109,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -126,11 +126,11 @@ class Solution: for num in nums: if num > 0 and num <= n: seen[num - 1] = True - + for num in range(1, n + 1): if not seen[num - 1]: return num - + return n + 1 ``` @@ -139,19 +139,19 @@ public class Solution { public int firstMissingPositive(int[] nums) { int n = nums.length; boolean[] seen = new boolean[n]; - + for (int num : nums) { if (num > 0 && num <= n) { seen[num - 1] = true; } } - + for (int i = 0; i < n; i++) { if (!seen[i]) { return i + 1; } } - + return n + 1; } } @@ -163,19 +163,19 @@ public: int firstMissingPositive(vector& nums) { int n = nums.size(); vector seen(n, false); - + for (int num : nums) { if (num > 0 && num <= n) { seen[num - 1] = true; } } - + for (int i = 0; i < n; i++) { if (!seen[i]) { return i + 1; } } - + return n + 1; } }; @@ -190,19 +190,19 @@ class Solution { firstMissingPositive(nums) { const n = nums.length; const seen = new Array(n).fill(false); - + for (const num of nums) { if (num > 0 && num <= n) { seen[num - 1] = true; } } - + for (let i = 0; i < n; i++) { if (!seen[i]) { return i + 1; } } - + return n + 1; } } @@ -235,8 +235,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -326,8 +326,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -498,8 +498,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -516,7 +516,7 @@ class Solution: if nums[i] <= 0 or nums[i] > n: i += 1 continue - + index = nums[i] - 1 if nums[i] != nums[index]: nums[i], nums[index] = nums[index], nums[i] @@ -663,5 +663,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/first-unique-character-in-a-string.md b/articles/first-unique-character-in-a-string.md index b60c2e4f6..7fbb67baa 100644 --- a/articles/first-unique-character-in-a-string.md +++ b/articles/first-unique-character-in-a-string.md @@ -84,8 +84,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -99,7 +99,7 @@ class Solution: count = defaultdict(int) for c in s: count[c] += 1 - + for i, c in enumerate(s): if count[c] == 1: return i @@ -132,7 +132,7 @@ public: for (char c : s) { count[c]++; } - + for (int i = 0; i < s.size(); i++) { if (count[s[i]] == 1) { return i; @@ -169,8 +169,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ since we have at most $26$ different characters. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ since we have at most $26$ different characters. --- @@ -188,7 +188,7 @@ class Solution: count[c] = i else: count[c] = n - + res = n for c in count: res = min(res, count[c]) @@ -201,7 +201,7 @@ public class Solution { public int firstUniqChar(String s) { int n = s.length(); Map count = new HashMap<>(); - + for (int i = 0; i < n; i++) { char c = s.charAt(i); if (!count.containsKey(c)) { @@ -210,12 +210,12 @@ public class Solution { count.put(c, n); } } - + int res = n; for (int index : count.values()) { res = Math.min(res, index); } - + return res == n ? -1 : res; } } @@ -235,12 +235,12 @@ public: count[s[i]] = n; } } - + int res = n; for (auto& [key, index] : count) { res = min(res, index); } - + return res == n ? -1 : res; } }; @@ -279,8 +279,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ since we have at most $26$ different characters. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ since we have at most $26$ different characters. --- @@ -361,5 +361,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(26 * n)$ since we have at most $26$ different characters. -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(26 * n)$ since we have at most $26$ different characters. +- Space complexity: $O(1)$ diff --git a/articles/flatten-nested-list-iterator.md b/articles/flatten-nested-list-iterator.md index 6ac2342a2..8a02655a7 100644 --- a/articles/flatten-nested-list-iterator.md +++ b/articles/flatten-nested-list-iterator.md @@ -104,7 +104,7 @@ class NestedIterator { } /** - * @param {NestedInteger[]} nestedArr + * @param {NestedInteger[]} nestedArr */ dfs(nestedArr) { for (let num of nestedArr) { @@ -138,8 +138,8 @@ class NestedIterator { ### Time & Space Complexity -* Time complexity: $O(n + d)$ -* Space complexity: $O(n + d)$ +- Time complexity: $O(n + d)$ +- Space complexity: $O(n + d)$ > Where $n$ is the number of integers and $d$ is the nesting depth. @@ -254,7 +254,7 @@ class NestedIterator { } /** - * @param {NestedInteger[]} nestedArr + * @param {NestedInteger[]} nestedArr */ dfs(nestedArr) { let res = []; @@ -290,8 +290,8 @@ class NestedIterator { ### Time & Space Complexity -* Time complexity: $O(n + d)$ -* Space complexity: $O(n + d)$ +- Time complexity: $O(n + d)$ +- Space complexity: $O(n + d)$ > Where $n$ is the number of integers and $d$ is the nesting depth. @@ -399,7 +399,7 @@ class NestedIterator { this.stack.reverse(); } - /** + /** * @param {NestedInteger[]} nested */ dfs(nested) { @@ -434,8 +434,8 @@ class NestedIterator { ### Time & Space Complexity -* Time complexity: $O(n + d)$ -* Space complexity: $O(n + d)$ +- Time complexity: $O(n + d)$ +- Space complexity: $O(n + d)$ > Where $n$ is the number of integers and $d$ is the nesting depth. @@ -459,7 +459,7 @@ class NestedIterator: top = self.stack[-1] if top.isInteger(): return True - + self.stack.pop() self.stack.extend(reversed(top.getList())) return False @@ -573,7 +573,7 @@ class NestedIterator { ### Time & Space Complexity -* Time complexity: $O(n + d)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n + d)$ +- Space complexity: $O(n)$ -> Where $n$ is the number of integers and $d$ is the nesting depth. \ No newline at end of file +> Where $n$ is the number of integers and $d$ is the nesting depth. diff --git a/articles/flip-equivalent-binary-trees.md b/articles/flip-equivalent-binary-trees.md index 2a2549798..39f315bc3 100644 --- a/articles/flip-equivalent-binary-trees.md +++ b/articles/flip-equivalent-binary-trees.md @@ -17,9 +17,9 @@ class Solution: return False return ( - self.flipEquiv(root1.left, root2.left) and + self.flipEquiv(root1.left, root2.left) and self.flipEquiv(root1.right, root2.right) or - self.flipEquiv(root1.left, root2.right) and + self.flipEquiv(root1.left, root2.right) and self.flipEquiv(root1.right, root2.left) ) ``` @@ -42,14 +42,14 @@ class Solution: */ public class Solution { public boolean flipEquiv(TreeNode root1, TreeNode root2) { - if (root1 == null || root2 == null) + if (root1 == null || root2 == null) return root1 == null && root2 == null; - if (root1.val != root2.val) + if (root1.val != root2.val) return false; - - return (flipEquiv(root1.left, root2.left) && + + return (flipEquiv(root1.left, root2.left) && flipEquiv(root1.right, root2.right) || - flipEquiv(root1.left, root2.right) && + flipEquiv(root1.left, root2.right) && flipEquiv(root1.right, root2.left)); } } @@ -70,14 +70,14 @@ public class Solution { class Solution { public: bool flipEquiv(TreeNode* root1, TreeNode* root2) { - if (!root1 || !root2) + if (!root1 || !root2) return !root1 && !root2; - if (root1->val != root2->val) + if (root1->val != root2->val) return false; - - return (flipEquiv(root1->left, root2->left) && + + return (flipEquiv(root1->left, root2->left) && flipEquiv(root1->right, root2->right) || - flipEquiv(root1->left, root2->right) && + flipEquiv(root1->left, root2->right) && flipEquiv(root1->right, root2->left)); } }; @@ -101,15 +101,15 @@ class Solution { * @return {boolean} */ flipEquiv(root1, root2) { - if (!root1 || !root2) - return !root1 && !root2; - if (root1.val !== root2.val) - return false; - - return (this.flipEquiv(root1.left, root2.left) && - this.flipEquiv(root1.right, root2.right) || - this.flipEquiv(root1.left, root2.right) && - this.flipEquiv(root1.right, root2.left)); + if (!root1 || !root2) return !root1 && !root2; + if (root1.val !== root2.val) return false; + + return ( + (this.flipEquiv(root1.left, root2.left) && + this.flipEquiv(root1.right, root2.right)) || + (this.flipEquiv(root1.left, root2.right) && + this.flipEquiv(root1.right, root2.left)) + ); } } ``` @@ -118,8 +118,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -144,12 +144,12 @@ class Solution: if node1 != node2: return False continue - + if node1.val != node2.val: return False - if ((node1.right and node2.right and - node1.right.val == node2.right.val) or + if ((node1.right and node2.right and + node1.right.val == node2.right.val) or (not node1.right and not node2.right) ): q.append((node1.left, node2.left)) @@ -193,8 +193,8 @@ public class Solution { if (node1.val != node2.val) return false; - if ((node1.left != null && node2.left != null && - node1.left.val == node2.left.val) || + if ((node1.left != null && node2.left != null && + node1.left.val == node2.left.val) || (node1.left == null && node2.left == null)) { q.offer(new TreeNode[]{node1.left, node2.left}); q.offer(new TreeNode[]{node1.right, node2.right}); @@ -238,7 +238,7 @@ public: if (node1->val != node2->val) return false; - if ((node1->left && node2->left && node1->left->val == node2->left->val) || + if ((node1->left && node2->left && node1->left->val == node2->left->val) || (!node1->left && !node2->left)) { q.push({node1->left, node2->left}); q.push({node1->right, node2->right}); @@ -283,9 +283,12 @@ class Solution { if (node1.val !== node2.val) return false; - if ((node1.left && node2.left && - node1.left.val === node2.left.val) || - (!node1.left && !node2.left)) { + if ( + (node1.left && + node2.left && + node1.left.val === node2.left.val) || + (!node1.left && !node2.left) + ) { q.push([node1.left, node2.left]); q.push([node1.right, node2.right]); } else { @@ -303,8 +306,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -334,8 +337,8 @@ class Solution: if node1.val != node2.val: return False - if ((node1.left and node2.left and - node1.left.val == node2.left.val) or + if ((node1.left and node2.left and + node1.left.val == node2.left.val) or (not node1.left and not node2.left) ): stack.append((node1.left, node2.left)) @@ -379,8 +382,8 @@ public class Solution { if (node1.val != node2.val) return false; - if ((node1.left != null && node2.left != null && - node1.left.val == node2.left.val) || + if ((node1.left != null && node2.left != null && + node1.left.val == node2.left.val) || (node1.left == null && node2.left == null)) { stack.push(new TreeNode[]{node1.left, node2.left}); stack.push(new TreeNode[]{node1.right, node2.right}); @@ -423,7 +426,7 @@ public: if (node1->val != node2->val) return false; - if ((node1->left && node2->left && node1->left->val == node2->left->val) || + if ((node1->left && node2->left && node1->left->val == node2->left->val) || (!node1->left && !node2->left)) { stk.push({node1->left, node2->left}); stk.push({node1->right, node2->right}); @@ -468,9 +471,12 @@ class Solution { if (node1.val !== node2.val) return false; - if ((node1.left && node2.left && - node1.left.val === node2.left.val) || - (!node1.left && !node2.left)) { + if ( + (node1.left && + node2.left && + node1.left.val === node2.left.val) || + (!node1.left && !node2.left) + ) { stack.push([node1.left, node2.left]); stack.push([node1.right, node2.right]); } else { @@ -488,5 +494,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/flip-string-to-monotone-increasing.md b/articles/flip-string-to-monotone-increasing.md index 74c357f57..255bc354e 100644 --- a/articles/flip-string-to-monotone-increasing.md +++ b/articles/flip-string-to-monotone-increasing.md @@ -12,7 +12,7 @@ class Solution: return dp[(i, mono)] if i == len(s): return 0 - + if mono and s[i] == "0": dp[(i, mono)] = min(1 + dfs(i + 1, False), dfs(i + 1, mono)) elif mono and s[i] == "1": @@ -21,7 +21,7 @@ class Solution: dp[(i, mono)] = dfs(i + 1, mono) else: dp[(i, mono)] = 1 + dfs(i + 1, mono) - + return dp[(i, mono)] return dfs(0, True) @@ -121,8 +121,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -204,7 +204,8 @@ class Solution { if (s[i] === '0') { dp[i][1] = Math.min(1 + dp[i + 1][0], dp[i + 1][1]); dp[i][0] = 1 + dp[i + 1][0]; - } else { // s[i] === '1' + } else { + // s[i] === '1' dp[i][1] = Math.min(1 + dp[i + 1][1], dp[i + 1][0]); dp[i][0] = dp[i + 1][0]; } @@ -219,8 +220,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -241,7 +242,7 @@ class Solution: else: # s[i] == '1' new_dp_1 = min(dp[1] + 1, dp[0]) new_dp_0 = dp[0] - + dp[1] = new_dp_1 dp[0] = new_dp_0 @@ -311,7 +312,8 @@ class Solution { if (s[i] === '0') { newDp1 = Math.min(1 + dp[0], dp[1]); newDp0 = dp[0] + 1; - } else { // s[i] === '1' + } else { + // s[i] === '1' newDp1 = Math.min(1 + dp[1], dp[0]); newDp0 = dp[0]; } @@ -329,8 +331,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -347,10 +349,10 @@ class Solution: for i in range(n): left_ones[i + 1] = left_ones[i] + (1 if s[i] == '1' else 0) - + for i in range(n - 1, -1, -1): right_zeros[i] = right_zeros[i + 1] + (1 if s[i] == '0' else 0) - + res = float('inf') for i in range(n + 1): res = min(res, left_ones[i] + right_zeros[i]) @@ -441,8 +443,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -502,7 +504,8 @@ class Solution { * @return {number} */ minFlipsMonoIncr(s) { - let res = 0, cntOne = 0; + let res = 0, + cntOne = 0; for (let c of s) { if (c === '1') { cntOne++; @@ -519,5 +522,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/foreign-dictionary.md b/articles/foreign-dictionary.md index 1bb32e486..89a4620fb 100644 --- a/articles/foreign-dictionary.md +++ b/articles/foreign-dictionary.md @@ -58,7 +58,7 @@ public class Solution { for (int i = 0; i < words.length - 1; i++) { String w1 = words[i], w2 = words[i + 1]; int minLen = Math.min(w1.length(), w2.length()); - if (w1.length() > w2.length() && + if (w1.length() > w2.length() && w1.substring(0, minLen).equals(w2.substring(0, minLen))) { return ""; } @@ -121,7 +121,7 @@ public: for (size_t i = 0; i < words.size() - 1; ++i) { const string& w1 = words[i], & w2 = words[i + 1]; size_t minLen = min(w1.length(), w2.length()); - if (w1.length() > w2.length() && + if (w1.length() > w2.length() && w1.substr(0, minLen) == w2.substr(0, minLen)) { return ""; } @@ -179,9 +179,11 @@ class Solution { const w1 = words[i]; const w2 = words[i + 1]; const minLen = Math.min(w1.length, w2.length); - if (w1.length > w2.length && - w1.slice(0, minLen) === w2.slice(0, minLen)) { - return ""; + if ( + w1.length > w2.length && + w1.slice(0, minLen) === w2.slice(0, minLen) + ) { + return ''; } for (let j = 0; j < minLen; j++) { if (w1[j] !== w2[j]) { @@ -208,11 +210,11 @@ class Solution { }; for (const char in adj) { - if (dfs(char)) return ""; + if (dfs(char)) return ''; } res.reverse(); - return res.join(""); + return res.join(''); } } ``` @@ -361,7 +363,7 @@ class Solution { val w1 = words[i] val w2 = words[i + 1] val minLen = minOf(w1.length, w2.length) - if (w1.length > w2.length && + if (w1.length > w2.length && w1.substring(0, minLen) == w2.substring(0, minLen)) { return "" } @@ -416,7 +418,7 @@ class Solution { } } } - + for i in 0.. Bool { if let flag = visited[char] { return flag @@ -451,13 +453,13 @@ class Solution { res.append(char) return false } - + for char in adj.keys { if dfs(char) { return "" } } - + res.reverse() return String(res) } @@ -468,8 +470,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(N + V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(N + V + E)$ +- Space complexity: $O(V + E)$ > Where $V$ is the number of unique characters, $E$ is the number of edges and $N$ is the sum of lengths of all the strings. @@ -484,7 +486,7 @@ class Solution: def foreignDictionary(self, words): adj = {c: set() for w in words for c in w} indegree = {c: 0 for c in adj} - + for i in range(len(words) - 1): w1, w2 = words[i], words[i + 1] minLen = min(len(w1), len(w2)) @@ -496,10 +498,10 @@ class Solution: adj[w1[j]].add(w2[j]) indegree[w2[j]] += 1 break - + q = deque([c for c in indegree if indegree[c] == 0]) res = [] - + while q: char = q.popleft() res.append(char) @@ -507,10 +509,10 @@ class Solution: indegree[neighbor] -= 1 if indegree[neighbor] == 0: q.append(neighbor) - + if len(res) != len(indegree): return "" - + return "".join(res) ``` @@ -519,7 +521,7 @@ public class Solution { public String foreignDictionary(String[] words) { Map> adj = new HashMap<>(); Map indegree = new HashMap<>(); - + for (String word : words) { for (char c : word.toCharArray()) { adj.putIfAbsent(c, new HashSet<>()); @@ -531,7 +533,7 @@ public class Solution { String w1 = words[i]; String w2 = words[i + 1]; int minLen = Math.min(w1.length(), w2.length()); - if (w1.length() > w2.length() && + if (w1.length() > w2.length() && w1.substring(0, minLen).equals(w2.substring(0, minLen))) { return ""; } @@ -539,7 +541,7 @@ public class Solution { if (w1.charAt(j) != w2.charAt(j)) { if (!adj.get(w1.charAt(j)).contains(w2.charAt(j))) { adj.get(w1.charAt(j)).add(w2.charAt(j)); - indegree.put(w2.charAt(j), + indegree.put(w2.charAt(j), indegree.get(w2.charAt(j)) + 1); } break; @@ -587,11 +589,11 @@ public: indegree[c] = 0; } } - + for (int i = 0; i < words.size() - 1; i++) { string w1 = words[i], w2 = words[i + 1]; int minLen = min(w1.size(), w2.size()); - if (w1.size() > w2.size() && + if (w1.size() > w2.size() && w1.substr(0, minLen) == w2.substr(0, minLen)) { return ""; } @@ -605,14 +607,14 @@ public: } } } - + queue q; for (auto &[c, deg] : indegree) { if (deg == 0) { q.push(c); } } - + string res; while (!q.empty()) { char char_ = q.front(); @@ -625,7 +627,7 @@ public: } } } - + return res.size() == indegree.size() ? res : ""; } }; @@ -646,13 +648,16 @@ class Solution { indegree[c] = 0; } } - + for (let i = 0; i < words.length - 1; i++) { - let w1 = words[i], w2 = words[i + 1]; + let w1 = words[i], + w2 = words[i + 1]; let minLen = Math.min(w1.length, w2.length); - if (w1.length > w2.length && - w1.slice(0, minLen) === w2.slice(0, minLen)) { - return ""; + if ( + w1.length > w2.length && + w1.slice(0, minLen) === w2.slice(0, minLen) + ) { + return ''; } for (let j = 0; j < minLen; j++) { if (w1[j] !== w2[j]) { @@ -664,14 +669,14 @@ class Solution { } } } - + let q = new Queue(); for (let c in indegree) { if (indegree[c] === 0) { q.push(c); } } - + let res = []; while (!q.isEmpty()) { let char = q.pop(); @@ -683,12 +688,12 @@ class Solution { } } } - + if (res.length !== Object.keys(indegree).length) { - return ""; + return ''; } - - return res.join(""); + + return res.join(''); } } ``` @@ -714,7 +719,7 @@ public class Solution { var w1 = words[i]; var w2 = words[i + 1]; int minLen = Math.Min(w1.Length, w2.Length); - if (w1.Length > w2.Length && + if (w1.Length > w2.Length && w1.Substring(0, minLen) == w2.Substring(0, minLen)) { return ""; } @@ -761,7 +766,7 @@ public class Solution { func foreignDictionary(words []string) string { adj := make(map[byte]map[byte]struct{}) indegree := make(map[byte]int) - + for _, word := range words { for i := 0; i < len(word); i++ { char := word[i] @@ -771,18 +776,18 @@ func foreignDictionary(words []string) string { indegree[char] = 0 } } - + for i := 0; i < len(words)-1; i++ { w1, w2 := words[i], words[i+1] minLen := len(w1) if len(w2) < minLen { minLen = len(w2) } - + if len(w1) > len(w2) && w1[:minLen] == w2[:minLen] { return "" } - + for j := 0; j < minLen; j++ { if w1[j] != w2[j] { if _, exists := adj[w1[j]][w2[j]]; !exists { @@ -793,20 +798,20 @@ func foreignDictionary(words []string) string { } } } - + q := []byte{} for char := range indegree { if indegree[char] == 0 { q = append(q, char) } } - + res := []byte{} for len(q) > 0 { char := q[0] q = q[1:] res = append(res, char) - + for neighbor := range adj[char] { indegree[neighbor]-- if indegree[neighbor] == 0 { @@ -814,11 +819,11 @@ func foreignDictionary(words []string) string { } } } - + if len(res) != len(indegree) { return "" } - + return string(res) } ``` @@ -828,24 +833,24 @@ class Solution { fun foreignDictionary(words: Array): String { val adj = HashMap>() val indegree = HashMap() - + for (word in words) { for (c in word) { adj.computeIfAbsent(c) { hashSetOf() } indegree[c] = 0 } } - + for (i in 0 until words.size - 1) { val w1 = words[i] val w2 = words[i + 1] val minLen = minOf(w1.length, w2.length) - - if (w1.length > w2.length && + + if (w1.length > w2.length && w1.substring(0, minLen) == w2.substring(0, minLen)) { return "" } - + for (j in 0 until minLen) { if (w1[j] != w2[j]) { if (w2[j] !in adj[w1[j]]!!) { @@ -856,19 +861,19 @@ class Solution { } } } - + val q: Queue = LinkedList() for ((char, degree) in indegree) { if (degree == 0) { q.add(char) } } - + val res = StringBuilder() while (q.isNotEmpty()) { val char = q.poll() res.append(char) - + for (neighbor in adj[char]!!) { indegree[neighbor] = indegree[neighbor]!! - 1 if (indegree[neighbor] == 0) { @@ -876,7 +881,7 @@ class Solution { } } } - + return if (res.length != indegree.size) "" else res.toString() } } @@ -891,12 +896,12 @@ class Solution { adj[char] = Set() } } - + var indegree = [Character: Int]() for key in adj.keys { indegree[key] = 0 } - + for i in 0..() for (c, deg) in indegree { if deg == 0 { q.append(c) } } - + var res = [Character]() while !q.isEmpty { let char = q.removeFirst() @@ -935,11 +940,11 @@ class Solution { } } } - + if res.count != indegree.count { return "" } - + return String(res) } } @@ -949,7 +954,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(N + V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(N + V + E)$ +- Space complexity: $O(V + E)$ -> Where $V$ is the number of unique characters, $E$ is the number of edges and $N$ is the sum of lengths of all the strings. \ No newline at end of file +> Where $V$ is the number of unique characters, $E$ is the number of edges and $N$ is the sum of lengths of all the strings. diff --git a/articles/freedom-trail.md b/articles/freedom-trail.md index 9c7ef1c89..e7803e7f9 100644 --- a/articles/freedom-trail.md +++ b/articles/freedom-trail.md @@ -79,7 +79,7 @@ class Solution { if (ring[i] === key[k]) { const minDist = Math.min( Math.abs(r - i), - ring.length - Math.abs(r - i) + ring.length - Math.abs(r - i), ); res = Math.min(res, minDist + 1 + dfs(i, k + 1)); } @@ -96,8 +96,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ m)$ -* Space complexity: $O(m)$ for recursion stack. +- Time complexity: $O(n ^ m)$ +- Space complexity: $O(m)$ for recursion stack. > Where $n$ is the length of the $ring$ and $m$ is the length of the $key$. @@ -215,7 +215,7 @@ class Solution { if (ring[i] === key[k]) { const minDist = Math.min( Math.abs(r - i), - ring.length - Math.abs(r - i) + ring.length - Math.abs(r - i), ); res = Math.min(res, minDist + 1 + dfs(i, k + 1)); } @@ -234,8 +234,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 * m)$ -* Space complexity: $O(n * m)$ +- Time complexity: $O(n ^ 2 * m)$ +- Space complexity: $O(n * m)$ > Where $n$ is the length of the $ring$ and $m$ is the length of the $key$. @@ -333,9 +333,7 @@ class Solution { findRotateSteps(ring, key) { const n = ring.length; const m = key.length; - const dp = Array.from({ length: m + 1 }, () => - Array(n).fill(Infinity) - ); + const dp = Array.from({ length: m + 1 }, () => Array(n).fill(Infinity)); for (let i = 0; i < n; i++) { dp[m][i] = 0; @@ -345,8 +343,14 @@ class Solution { for (let r = 0; r < n; r++) { for (let i = 0; i < n; i++) { if (ring[i] === key[k]) { - const minDist = Math.min(Math.abs(r - i), n - Math.abs(r - i)); - dp[k][r] = Math.min(dp[k][r], minDist + 1 + dp[k + 1][i]); + const minDist = Math.min( + Math.abs(r - i), + n - Math.abs(r - i), + ); + dp[k][r] = Math.min( + dp[k][r], + minDist + 1 + dp[k + 1][i], + ); } } } @@ -360,8 +364,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 * m)$ -* Space complexity: $O(n * m)$ +- Time complexity: $O(n ^ 2 * m)$ +- Space complexity: $O(n * m)$ > Where $n$ is the length of the $ring$ and $m$ is the length of the $key$. @@ -475,7 +479,10 @@ class Solution { const nextDp = new Array(n).fill(Infinity); for (let r = 0; r < n; r++) { for (const i of adj[key.charCodeAt(k) - 97]) { - const minDist = Math.min(Math.abs(r - i), n - Math.abs(r - i)); + const minDist = Math.min( + Math.abs(r - i), + n - Math.abs(r - i), + ); nextDp[r] = Math.min(nextDp[r], minDist + 1 + dp[i]); } } @@ -491,8 +498,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 * m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2 * m)$ +- Space complexity: $O(n)$ > Where $n$ is the length of the $ring$ and $m$ is the length of the $key$. @@ -550,7 +557,7 @@ public class Solution { for (int r : adj[key.charAt(k) - 'a']) { int minDist = Integer.MAX_VALUE; for (int i : adj[key.charAt(k - 1) - 'a']) { - minDist = Math.min(minDist, + minDist = Math.min(minDist, Math.min(Math.abs(r - i), n - Math.abs(r - i)) + dp[i] ); } @@ -614,7 +621,9 @@ class Solution { findRotateSteps(ring, key) { const n = ring.length; const m = key.length; - const dp = Array(n).fill(0).map((_, i) => Math.min(i, n - i)); + const dp = Array(n) + .fill(0) + .map((_, i) => Math.min(i, n - i)); const adj = Array.from({ length: 26 }, () => []); for (let i = 0; i < n; i++) { @@ -625,15 +634,18 @@ class Solution { for (let r of adj[key.charCodeAt(k) - 97]) { let minDist = Infinity; for (let i of adj[key.charCodeAt(k - 1) - 97]) { - minDist = Math.min(minDist, - Math.min(Math.abs(r - i), n - Math.abs(r - i)) + dp[i] + minDist = Math.min( + minDist, + Math.min(Math.abs(r - i), n - Math.abs(r - i)) + dp[i], ); } dp[r] = minDist; } } - return Math.min(...adj[key.charCodeAt(m - 1) - 97].map(i => dp[i])) + m; + return ( + Math.min(...adj[key.charCodeAt(m - 1) - 97].map((i) => dp[i])) + m + ); } } ``` @@ -642,8 +654,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 * m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2 * m)$ +- Space complexity: $O(n)$ > Where $n$ is the length of the $ring$ and $m$ is the length of the $key$. @@ -658,14 +670,14 @@ class Solution: def findRotateSteps(self, ring: str, key: str) -> int: n = len(ring) m = len(key) - + dp = [0] * n next_dp = [0] * n - + adj = [[] for _ in range(26)] for i, c in enumerate(ring): adj[ord(c) - ord('a')].append(i) - + for k in range(m - 1, -1, -1): c = ord(key[k]) - ord('a') it, N = 0, len(adj[c]) @@ -675,19 +687,19 @@ class Solution: next_dp[r] = float('inf') while it < N and adj[c][it] < r: it += 1 - + nextIdx = adj[c][it] if it < N else adj[c][0] prevIdx = adj[c][it - 1] if it > 0 else adj[c][-1] - + next_dp[r] = min( (r - prevIdx if r > prevIdx else n - (prevIdx - r)) + dp[prevIdx], (nextIdx - r if nextIdx > r else n - (r - nextIdx)) + dp[nextIdx] ) else: next_dp[r] = dp[r] - + dp, next_dp = next_dp, dp - + return dp[0] + m ``` @@ -696,32 +708,32 @@ public class Solution { public int findRotateSteps(String ring, String key) { int n = ring.length(); int m = key.length(); - + int[] dp = new int[n]; int[] nextDp = new int[n]; List[] adj = new ArrayList[26]; - + for (int i = 0; i < 26; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < n; i++) { adj[ring.charAt(i) - 'a'].add(i); } - + for (int k = m - 1; k >= 0; k--) { int c = key.charAt(k) - 'a'; int it = 0, N = adj[c].size(); - + for (int r = 0; r < n; r++) { if (ring.charAt(r) - 'a' != c) { nextDp[r] = Integer.MAX_VALUE; while (it < N && adj[c].get(it) < r) { it++; } - + int nextIdx = it < N ? adj[c].get(it) : adj[c].get(0); int prevIdx = it > 0 ? adj[c].get(it - 1) : adj[c].get(N - 1); - + nextDp[r] = Math.min( (r > prevIdx ? r - prevIdx : n - (prevIdx - r)) + dp[prevIdx], (nextIdx > r ? nextIdx - r : n - (r - nextIdx)) + dp[nextIdx] @@ -730,12 +742,12 @@ public class Solution { nextDp[r] = dp[r]; } } - + int[] temp = dp; dp = nextDp; nextDp = temp; } - + return dp[0] + m; } } @@ -746,29 +758,29 @@ class Solution { public: int findRotateSteps(string ring, string key) { int n = ring.size(), m = key.size(); - + vector dp(n, 0); vector nextDp(n, 0); vector> adj(26); - + for (int i = 0; i < n; i++) { adj[ring[i] - 'a'].push_back(i); } - + for (int k = m - 1; k >= 0; k--) { int c = key[k] - 'a'; int it = 0, N = adj[c].size(); - + for (int r = 0; r < n; r++) { if (ring[r] - 'a' != c) { nextDp[r] = INT_MAX; while (it < N && adj[c][it] < r) { it++; } - + int nextIdx = it < N ? adj[c][it] : adj[c][0]; int prevIdx = it > 0 ? adj[c][it - 1] : adj[c][N - 1]; - + nextDp[r] = min( (r > prevIdx ? r - prevIdx : n - (prevIdx - r)) + dp[prevIdx], (nextIdx > r ? nextIdx - r : n - (r - nextIdx)) + dp[nextIdx] @@ -777,10 +789,10 @@ public: nextDp[r] = dp[r]; } } - + dp.swap(nextDp); } - + return dp[0] + m; } }; @@ -794,42 +806,46 @@ class Solution { * @return {number} */ findRotateSteps(ring, key) { - const n = ring.length, m = key.length; - + const n = ring.length, + m = key.length; + let dp = Array(n).fill(0); let nextDp = Array(n).fill(0); const adj = Array.from({ length: 26 }, () => []); - + for (let i = 0; i < n; i++) { adj[ring.charCodeAt(i) - 97].push(i); } - + for (let k = m - 1; k >= 0; k--) { const c = key.charCodeAt(k) - 97; - let it = 0, N = adj[c].length; - + let it = 0, + N = adj[c].length; + for (let r = 0; r < n; r++) { if (ring.charCodeAt(r) - 97 !== c) { nextDp[r] = Infinity; while (it < N && adj[c][it] < r) { it++; } - + const nextIdx = it < N ? adj[c][it] : adj[c][0]; const prevIdx = it > 0 ? adj[c][it - 1] : adj[c][N - 1]; - + nextDp[r] = Math.min( - (r > prevIdx ? r - prevIdx : n - (prevIdx - r)) + dp[prevIdx], - (nextIdx > r ? nextIdx - r : n - (r - nextIdx)) + dp[nextIdx] + (r > prevIdx ? r - prevIdx : n - (prevIdx - r)) + + dp[prevIdx], + (nextIdx > r ? nextIdx - r : n - (r - nextIdx)) + + dp[nextIdx], ); } else { nextDp[r] = dp[r]; } } - + [dp, nextDp] = [nextDp, dp]; } - + return dp[0] + m; } } @@ -839,7 +855,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n)$ -> Where $n$ is the length of the $ring$ and $m$ is the length of the $key$. \ No newline at end of file +> Where $n$ is the length of the $ring$ and $m$ is the length of the $key$. diff --git a/articles/frequency-of-the-most-frequent-element.md b/articles/frequency-of-the-most-frequent-element.md index 51c727d97..0b65c878b 100644 --- a/articles/frequency-of-the-most-frequent-element.md +++ b/articles/frequency-of-the-most-frequent-element.md @@ -75,8 +75,8 @@ class Solution { let j = i - 1; let tmpK = k; - while (j >= 0 && (tmpK - (nums[i] - nums[j])) >= 0) { - tmpK -= (nums[i] - nums[j]); + while (j >= 0 && tmpK - (nums[i] - nums[j]) >= 0) { + tmpK -= nums[i] - nums[j]; j--; } res = Math.max(res, i - j); @@ -90,8 +90,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 + n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n ^ 2 + n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -200,7 +200,8 @@ class Solution { let res = 1; for (let i = 0; i < nums.length; i++) { - let left = 0, right = i; + let left = 0, + right = i; while (left <= right) { const mid = Math.floor((left + right) / 2); const curSum = prefixSum[i + 1] - prefixSum[mid]; @@ -222,8 +223,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -301,7 +302,9 @@ class Solution { */ maxFrequency(nums, k) { nums.sort((a, b) => a - b); - let total = 0, res = 0, l = 0; + let total = 0, + res = 0, + l = 0; for (let r = 0; r < nums.length; r++) { total += nums[r]; @@ -321,8 +324,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -336,10 +339,10 @@ class Solution: nums.sort() l = 0 total = 0 - + for r in range(len(nums)): total += nums[r] - + if (r - l + 1) * nums[r] > total + k: total -= nums[l] l += 1 @@ -397,7 +400,8 @@ class Solution { */ maxFrequency(nums, k) { nums.sort((a, b) => a - b); - let total = 0, l = 0; + let total = 0, + l = 0; for (let r = 0; r < nums.length; r++) { total += nums[r]; @@ -416,5 +420,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. diff --git a/articles/fruit-into-baskets.md b/articles/fruit-into-baskets.md index 7aa1b5bbe..9869c7d83 100644 --- a/articles/fruit-into-baskets.md +++ b/articles/fruit-into-baskets.md @@ -67,7 +67,8 @@ class Solution { * @return {number} */ totalFruit(fruits) { - let n = fruits.length, res = 0; + let n = fruits.length, + res = 0; for (let i = 0; i < n; i++) { let types = new Set(); @@ -89,8 +90,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -103,7 +104,7 @@ class Solution: def totalFruit(self, fruits: List[int]) -> int: count = defaultdict(int) l, total, res = 0, 0, 0 - + for r in range(len(fruits)): count[fruits[r]] += 1 total += 1 @@ -115,7 +116,7 @@ class Solution: l += 1 if not count[f]: count.pop(f) - + res = max(res, total) return res @@ -182,7 +183,9 @@ class Solution { */ totalFruit(fruits) { let count = new Map(); - let l = 0, total = 0, res = 0; + let l = 0, + total = 0, + res = 0; for (let r = 0; r < fruits.length; r++) { count.set(fruits[r], (count.get(fruits[r]) || 0) + 1); @@ -208,8 +211,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -231,7 +234,7 @@ class Solution: if count[fruits[l]] == 0: count.pop(fruits[l]) l += 1 - + return len(fruits) - l ``` @@ -313,8 +316,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -431,8 +434,13 @@ class Solution { * @return {number} */ totalFruit(fruits) { - let l = 0, fruit1_lastIdx = 0, fruit2_lastIdx = -1; - let fruit1 = fruits[0], fruit2 = -1, total = 1, res = 1; + let l = 0, + fruit1_lastIdx = 0, + fruit2_lastIdx = -1; + let fruit1 = fruits[0], + fruit2 = -1, + total = 1, + res = 1; for (let r = 0; r < fruits.length; r++) { let f = fruits[r]; @@ -444,11 +452,16 @@ class Solution { fruit2_lastIdx = r; fruit2 = f; } else { - if (fruit2_lastIdx === Math.min(fruit1_lastIdx, fruit2_lastIdx)) { - [fruit1_lastIdx, fruit2_lastIdx] = [fruit2_lastIdx, fruit1_lastIdx]; + if ( + fruit2_lastIdx === Math.min(fruit1_lastIdx, fruit2_lastIdx) + ) { + [fruit1_lastIdx, fruit2_lastIdx] = [ + fruit2_lastIdx, + fruit1_lastIdx, + ]; [fruit1, fruit2] = [fruit2, fruit1]; } - total -= (fruit1_lastIdx - l + 1); + total -= fruit1_lastIdx - l + 1; l = fruit1_lastIdx + 1; fruit1 = f; fruit1_lastIdx = r; @@ -464,5 +477,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/furthest-building-you-can-reach.md b/articles/furthest-building-you-can-reach.md index 24ca0ef3b..fe46cae9f 100644 --- a/articles/furthest-building-you-can-reach.md +++ b/articles/furthest-building-you-can-reach.md @@ -137,8 +137,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2 \log n)$ +- Space complexity: $O(n)$ --- @@ -268,7 +268,8 @@ class Solution { * @return {number} */ furthestBuilding(heights, bricks, ladders) { - let l = ladders - 1, r = heights.length - 1; + let l = ladders - 1, + r = heights.length - 1; const canReach = (mid) => { let diffs = []; @@ -309,8 +310,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log ^ 2 n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log ^ 2 n)$ +- Space complexity: $O(n)$ --- @@ -467,7 +468,8 @@ class Solution { diffs.sort((a, b) => b[0] - a[0]); const canReach = (index) => { - let useLadders = 0, useBricks = 0; + let useLadders = 0, + useBricks = 0; for (let [diff, i] of diffs) { if (i > index) continue; @@ -483,7 +485,8 @@ class Solution { return true; }; - let l = 1, r = heights.length - 1; + let l = 1, + r = heights.length - 1; while (l <= r) { let mid = (l + r) >> 1; if (canReach(mid)) { @@ -502,8 +505,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -617,8 +620,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -719,5 +722,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ diff --git a/articles/gas-station.md b/articles/gas-station.md index 9e779b1d8..9f49089c7 100644 --- a/articles/gas-station.md +++ b/articles/gas-station.md @@ -217,8 +217,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -292,7 +292,8 @@ class Solution { */ canCompleteCircuit(gas, cost) { const n = gas.length; - let start = n - 1, end = 0; + let start = n - 1, + end = 0; let tank = gas[start] - cost[start]; while (start > end) { if (tank < 0) { @@ -401,8 +402,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -424,7 +425,7 @@ class Solution: if total < 0: total = 0 res = i + 1 - + return res ``` @@ -455,7 +456,7 @@ public class Solution { class Solution { public: int canCompleteCircuit(vector& gas, vector& cost) { - if (accumulate(gas.begin(), gas.end(), 0) < + if (accumulate(gas.begin(), gas.end(), 0) < accumulate(cost.begin(), cost.end(), 0)) { return -1; } @@ -484,8 +485,10 @@ class Solution { * @return {number} */ canCompleteCircuit(gas, cost) { - if (gas.reduce((acc, val) => acc + val, 0) < - cost.reduce((acc, val) => acc + val, 0)) { + if ( + gas.reduce((acc, val) => acc + val, 0) < + cost.reduce((acc, val) => acc + val, 0) + ) { return -1; } @@ -607,5 +610,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/generate-parentheses.md b/articles/generate-parentheses.md index 635ef1af4..8af8dfdcf 100644 --- a/articles/generate-parentheses.md +++ b/articles/generate-parentheses.md @@ -20,10 +20,10 @@ class Solution: if valid(s): res.append(s) return - + dfs(s + '(') dfs(s + ')') - + dfs("") return res ``` @@ -103,7 +103,7 @@ class Solution { /** * @param {string} s * @param {string[]} - * @param {number} n + * @param {number} n */ dfs(s, res, n) { if (s.length === 2 * n) { @@ -120,7 +120,7 @@ class Solution { */ generateParenthesis(n) { const res = []; - this.dfs("", res, n); + this.dfs('', res, n); return res; } } @@ -157,7 +157,7 @@ public class Solution { ```go func generateParenthesis(n int) []string { res := make([]string, 0) - + var valid func(string) bool valid = func(s string) bool { open := 0 @@ -173,7 +173,7 @@ func generateParenthesis(n int) []string { } return open == 0 } - + var dfs func(string) dfs = func(s string) { if len(s) == n*2 { @@ -182,11 +182,11 @@ func generateParenthesis(n int) []string { } return } - + dfs(s + "(") dfs(s + ")") } - + dfs("") return res } @@ -196,7 +196,7 @@ func generateParenthesis(n int) []string { class Solution { fun generateParenthesis(n: Int): List { val res = mutableListOf() - + fun valid(s: String): Boolean { var open = 0 for (c in s) { @@ -205,7 +205,7 @@ class Solution { } return open == 0 } - + fun dfs(s: String) { if (s.length == n * 2) { if (valid(s)) { @@ -213,11 +213,11 @@ class Solution { } return } - + dfs(s + "(") dfs(s + ")") } - + dfs("") return res } @@ -261,8 +261,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ {2n} * n)$ -* Space complexity: $O(2 ^ {2n} * n)$ +- Time complexity: $O(2 ^ {2n} * n)$ +- Space complexity: $O(2 ^ {2n} * n)$ --- @@ -407,9 +407,9 @@ public class Solution { public List GenerateParenthesis(int n) { List res = new List(); - string stack = ""; + string stack = ""; Backtrack(0, 0, n, res, stack); - return res; + return res; } } ``` @@ -418,27 +418,27 @@ public class Solution { func generateParenthesis(n int) []string { stack := make([]string, 0) res := make([]string, 0) - + var backtrack func(int, int) backtrack = func(openN, closedN int) { if openN == n && closedN == n { res = append(res, strings.Join(stack, "")) return } - + if openN < n { stack = append(stack, "(") backtrack(openN+1, closedN) stack = stack[:len(stack)-1] } - + if closedN < openN { stack = append(stack, ")") backtrack(openN, closedN+1) stack = stack[:len(stack)-1] } } - + backtrack(0, 0) return res } @@ -449,26 +449,26 @@ class Solution { fun generateParenthesis(n: Int): List { val stack = mutableListOf() val res = mutableListOf() - + fun backtrack(openN: Int, closedN: Int) { if (openN == n && closedN == n) { res.add(stack.joinToString("")) return } - + if (openN < n) { stack.add("(") backtrack(openN + 1, closedN) stack.removeAt(stack.lastIndex) } - + if (closedN < openN) { stack.add(")") backtrack(openN, closedN + 1) stack.removeAt(stack.lastIndex) } } - + backtrack(0, 0) return res } @@ -510,8 +510,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\frac{4^n}{\sqrt{n}})$ -* Space complexity: $O(n)$ +- Time complexity: $O(\frac{4^n}{\sqrt{n}})$ +- Space complexity: $O(n)$ --- @@ -524,13 +524,13 @@ class Solution: def generateParenthesis(self, n): res = [[] for _ in range(n+1)] res[0] = [""] - + for k in range(n + 1): for i in range(k): for left in res[i]: for right in res[k-i-1]: res[k].append("(" + left + ")" + right) - + return res[-1] ``` @@ -588,13 +588,13 @@ class Solution { */ generateParenthesis(n) { const res = Array.from({ length: n + 1 }, () => []); - res[0] = [""]; + res[0] = ['']; for (let k = 0; k <= n; k++) { for (let i = 0; i < k; i++) { for (const left of res[i]) { for (const right of res[k - i - 1]) { - res[k].push("(" + left + ")" + right); + res[k].push('(' + left + ')' + right); } } } @@ -633,7 +633,7 @@ public class Solution { func generateParenthesis(n int) []string { res := make([][]string, n+1) res[0] = []string{""} - + for k := 1; k <= n; k++ { res[k] = make([]string, 0) for i := 0; i < k; i++ { @@ -644,7 +644,7 @@ func generateParenthesis(n int) []string { } } } - + return res[n] } ``` @@ -654,7 +654,7 @@ class Solution { fun generateParenthesis(n: Int): List { val res = Array(n + 1) { mutableListOf() } res[0] = mutableListOf("") - + for (k in 1..n) { for (i in 0 until k) { for (left in res[i]) { @@ -664,7 +664,7 @@ class Solution { } } } - + return res[n] } } @@ -695,5 +695,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\frac{4^n}{\sqrt{n}})$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(\frac{4^n}{\sqrt{n}})$ +- Space complexity: $O(n)$ diff --git a/articles/get-equal-substrings-within-budget.md b/articles/get-equal-substrings-within-budget.md index 078230575..6a5ffa330 100644 --- a/articles/get-equal-substrings-within-budget.md +++ b/articles/get-equal-substrings-within-budget.md @@ -96,8 +96,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -170,7 +170,9 @@ class Solution { * @return {number} */ equalSubstring(s, t, maxCost) { - let curCost = 0, l = 0, res = 0; + let curCost = 0, + l = 0, + res = 0; for (let r = 0; r < s.length; r++) { curCost += Math.abs(s.charCodeAt(r) - t.charCodeAt(r)); @@ -190,8 +192,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -270,5 +272,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/greatest-common-divisor-of-strings.md b/articles/greatest-common-divisor-of-strings.md index f8fb01a35..482894ee9 100644 --- a/articles/greatest-common-divisor-of-strings.md +++ b/articles/greatest-common-divisor-of-strings.md @@ -82,14 +82,16 @@ class Solution { * @return {string} */ gcdOfStrings(str1, str2) { - const len1 = str1.length, len2 = str2.length; + const len1 = str1.length, + len2 = str2.length; const isDivisor = (l) => { if (len1 % l !== 0 || len2 % l !== 0) { return false; } const sub = str1.slice(0, l); - const f1 = len1 / l, f2 = len2 / l; + const f1 = len1 / l, + f2 = len2 / l; return sub.repeat(f1) === str1 && sub.repeat(f2) === str2; }; @@ -99,7 +101,7 @@ class Solution { } } - return ""; + return ''; } } ``` @@ -133,8 +135,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(min(m, n) * (m + n))$ -* Space complexity: $O(m + n)$ +- Time complexity: $O(min(m, n) * (m + n))$ +- Space complexity: $O(m + n)$ > Where $m$ and $n$ are the lengths of the strings $str1$ and $str2$ respectively. @@ -151,11 +153,11 @@ class Solution: if m < n: m, n = n, m str1, str2 = str2, str1 - + for l in range(n, 0, -1): if m % l != 0 or n % l != 0: continue - + valid = True for i in range(m): if str1[i] != str2[i % l]: @@ -263,7 +265,8 @@ class Solution { * @return {string} */ gcdOfStrings(str1, str2) { - let m = str1.length, n = str2.length; + let m = str1.length, + n = str2.length; if (m < n) { [m, n] = [n, m]; [str1, str2] = [str2, str1]; @@ -294,7 +297,7 @@ class Solution { } } - return ""; + return ''; } } ``` @@ -339,8 +342,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(min(m, n) * (m + n))$ -* Space complexity: $O(g)$ for the output string. +- Time complexity: $O(min(m, n) * (m + n))$ +- Space complexity: $O(g)$ for the output string. > Where $m$ is the length of the string $str1$, $n$ is the length of the string $str2$, and $g$ is the length of the output string. @@ -398,7 +401,7 @@ class Solution { */ gcdOfStrings(str1, str2) { if (str1 + str2 !== str2 + str1) { - return ""; + return ''; } const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b)); const g = gcd(str1.length, str2.length); @@ -433,8 +436,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n)$ -* Space complexity: $O(m + n)$. +- Time complexity: $O(m + n)$ +- Space complexity: $O(m + n)$. > Where $m$ and $n$ are the lengths of the strings $str1$ and $str2$ respectively. @@ -448,7 +451,7 @@ public class Solution { class Solution: def gcdOfStrings(self, str1: str, str2: str) -> str: g = gcd(len(str1), len(str2)) - + if all(str1[i] == str1[i % g] for i in range(len(str1))) and \ all(str2[i] == str1[i % g] for i in range(len(str2))): return str1[:g] @@ -517,13 +520,13 @@ class Solution { for (let i = 0; i < str1.length; i++) { if (str1[i] !== str1[i % g]) { - return ""; + return ''; } } for (let i = 0; i < str2.length; i++) { if (str2[i] !== str1[i % g]) { - return ""; + return ''; } } @@ -567,7 +570,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n)$ -* Space complexity: $O(g)$ for the output string. +- Time complexity: $O(m + n)$ +- Space complexity: $O(g)$ for the output string. -> Where $m$ is the length of the string $str1$, $n$ is the length of the string $str2$, and $g$ is the GCD of $m$ and $n$. \ No newline at end of file +> Where $m$ is the length of the string $str1$, $n$ is the length of the string $str2$, and $g$ is the GCD of $m$ and $n$. diff --git a/articles/greatest-common-divisor-traversal.md b/articles/greatest-common-divisor-traversal.md index 57628c98a..e68cd2095 100644 --- a/articles/greatest-common-divisor-traversal.md +++ b/articles/greatest-common-divisor-traversal.md @@ -13,13 +13,13 @@ class Solution: if gcd(nums[i], nums[j]) > 1: adj[i].append(j) adj[j].append(i) - + def dfs(node): visit[node] = True for nei in adj[node]: if not visit[nei]: dfs(nei) - + dfs(0) for node in visit: if not node: @@ -195,8 +195,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 \log n)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2 \log n)$ +- Space complexity: $O(n ^ 2)$ --- @@ -227,7 +227,7 @@ class UnionFind: self.Size[pu] += self.Size[pv] self.Parent[pv] = pu return True - + def isConnected(self): return self.n == 1 @@ -252,7 +252,7 @@ class Solution: uf.union(i, factor_index[n]) else: factor_index[n] = i - + return uf.isConnected() ``` @@ -584,8 +584,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n\sqrt {m})$ -* Space complexity: $O(n \log m)$ +- Time complexity: $O(m + n\sqrt {m})$ +- Space complexity: $O(n \log m)$ > Where $n$ is the size of the array $nums$ and $m$ is the maximum value in the array. @@ -893,7 +893,8 @@ class Solution { const uf = new UnionFind(N + MAX + 1); for (let i = 0; i < N; i++) { let num = nums[i]; - if (sieve[num] === 0) { // num is prime + if (sieve[num] === 0) { + // num is prime uf.union(i, N + num); continue; } @@ -1002,8 +1003,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n \log m)$ -* Space complexity: $O(n + m)$ +- Time complexity: $O(m + n \log m)$ +- Space complexity: $O(n + m)$ > Where $n$ is the size of the array $nums$ and $m$ is the maximum value in the array. @@ -1030,7 +1031,7 @@ class Solution: for composite in range(p * p, MAX + 1, p): sieve[composite] = p p += 1 - + adj = defaultdict(list) for i in range(N): num = nums[i] @@ -1305,8 +1306,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n \log m)$ -* Space complexity: $O(n + m)$ +- Time complexity: $O(m + n \log m)$ +- Space complexity: $O(n + m)$ > Where $n$ is the size of the array $nums$ and $m$ is the maximum value in the array. @@ -1521,7 +1522,8 @@ class Solution { const adj = new Map(); for (let i = 0; i < N; i++) { let num = nums[i]; - if (sieve[num] === 0) { // num is prime + if (sieve[num] === 0) { + // num is prime if (!adj.has(i)) adj.set(i, []); if (!adj.has(N + num)) adj.set(N + num, []); adj.get(i).push(N + num); @@ -1639,7 +1641,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n \log m)$ -* Space complexity: $O(n + m)$ +- Time complexity: $O(m + n \log m)$ +- Space complexity: $O(n + m)$ -> Where $n$ is the size of the array $nums$ and $m$ is the maximum value in the array. \ No newline at end of file +> Where $n$ is the size of the array $nums$ and $m$ is the maximum value in the array. diff --git a/articles/grid-game.md b/articles/grid-game.md index 236f53012..fc232c649 100644 --- a/articles/grid-game.md +++ b/articles/grid-game.md @@ -14,7 +14,7 @@ class Solution: bottom1 = 0 for j in range(i, cols): bottom1 += grid[1][j] - + top2 = robot2 = 0 for j in range(cols): if j > i: @@ -24,9 +24,9 @@ class Solution: for k in range(j, i): bottom2 += grid[1][k] robot2 = max(robot2, top2 + bottom2) - + res = min(res, robot2) - + return res ``` @@ -43,20 +43,20 @@ public class Solution { for (int j = i; j < cols; j++) { bottom1 += grid[1][j]; } - + long top2 = 0, robot2 = 0; for (int j = 0; j < cols; j++) { if (j > i) { top2 += grid[0][j]; } - + long bottom2 = 0; for (int k = j; k < i; k++) { bottom2 += grid[1][k]; } robot2 = Math.max(robot2, top2 + bottom2); } - + res = Math.min(res, robot2); } @@ -119,7 +119,8 @@ class Solution { bottom1 += grid[1][j]; } - let top2 = 0, robot2 = 0; + let top2 = 0, + robot2 = 0; for (let j = 0; j < cols; j++) { if (j > i) { top2 += grid[0][j]; @@ -144,8 +145,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 3)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 3)$ +- Space complexity: $O(1)$ --- @@ -260,8 +261,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -350,5 +351,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/guess-number-higher-or-lower.md b/articles/guess-number-higher-or-lower.md index 4946e4968..66c5800d9 100644 --- a/articles/guess-number-higher-or-lower.md +++ b/articles/guess-number-higher-or-lower.md @@ -18,7 +18,7 @@ class Solution: ``` ```java -/** +/** * Forward declaration of guess API. * @param num your guess * @return -1 if num is higher than the picked number @@ -38,7 +38,7 @@ public class Solution extends GuessGame { ``` ```cpp -/** +/** * Forward declaration of guess API. * @param num your guess * @return -1 if num is higher than the picked number @@ -59,7 +59,7 @@ public: ``` ```javascript -/** +/** * Forward declaration of guess API. * @param {number} num your guess * @return -1 if num is higher than the picked number @@ -83,7 +83,7 @@ class Solution { ``` ```csharp -/** +/** * Forward declaration of guess API. * @param num your guess * @return -1 if num is higher than the picked number @@ -106,8 +106,8 @@ public class Solution : GuessGame { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -138,7 +138,7 @@ class Solution: ``` ```java -/** +/** * Forward declaration of guess API. * @param num your guess * @return -1 if num is higher than the picked number @@ -166,7 +166,7 @@ public class Solution extends GuessGame { ``` ```cpp -/** +/** * Forward declaration of guess API. * @param num your guess * @return -1 if num is higher than the picked number @@ -195,7 +195,7 @@ public: ``` ```javascript -/** +/** * Forward declaration of guess API. * @param {number} num your guess * @return -1 if num is higher than the picked number @@ -210,7 +210,8 @@ class Solution { * @return {number} */ guessNumber(n) { - let l = 1, r = n; + let l = 1, + r = n; while (true) { let m = Math.floor((l + r) / 2); let res = guess(m); @@ -227,7 +228,7 @@ class Solution { ``` ```csharp -/** +/** * Forward declaration of guess API. * @param num your guess * @return -1 if num is higher than the picked number @@ -250,8 +251,8 @@ public class Solution : GuessGame { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ --- @@ -287,7 +288,7 @@ class Solution: ``` ```java -/** +/** * Forward declaration of guess API. * @param num your guess * @return -1 if num is higher than the picked number @@ -318,7 +319,7 @@ public class Solution extends GuessGame { ``` ```cpp -/** +/** * Forward declaration of guess API. * @param num your guess * @return -1 if num is higher than the picked number @@ -350,7 +351,7 @@ public: ``` ```javascript -/** +/** * Forward declaration of guess API. * @param {number} num your guess * @return -1 if num is higher than the picked number @@ -365,7 +366,8 @@ class Solution { * @return {number} */ guessNumber(n) { - let l = 1, r = n; + let l = 1, + r = n; while (true) { let m1 = l + Math.floor((r - l) / 3); let m2 = r - Math.floor((r - l) / 3); @@ -385,7 +387,7 @@ class Solution { ``` ```csharp -/** +/** * Forward declaration of guess API. * @param num your guess * @return -1 if num is higher than the picked number @@ -423,5 +425,5 @@ public class Solution : GuessGame { ### Time & Space Complexity -* Time complexity: $O(\log_3 n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(\log_3 n)$ +- Space complexity: $O(1)$ diff --git a/articles/hand-of-straights.md b/articles/hand-of-straights.md index 773278b86..b38a27e84 100644 --- a/articles/hand-of-straights.md +++ b/articles/hand-of-straights.md @@ -157,7 +157,7 @@ class Solution { val count = HashMap() hand.forEach { count[it] = count.getOrDefault(it, 0) + 1 } hand.sort() - + for (num in hand) { if (count[num]!! > 0) { for (i in num until num + groupSize) { @@ -207,8 +207,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -372,7 +372,7 @@ public class Solution { for (int i = first; i < first + groupSize; i++) { if (!count.ContainsKey(i) || count[i] == 0) return false; - + count[i]--; if (count[i] == 0) { if (i != minH.Peek()) @@ -487,8 +487,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -507,7 +507,7 @@ class Solution: last_num, open_groups = -1, 0 for num in sorted(count): - if ((open_groups > 0 and num > last_num + 1) or + if ((open_groups > 0 and num > last_num + 1) or open_groups > count[num] ): return False @@ -536,7 +536,7 @@ public class Solution { int lastNum = -1, openGroups = 0; for (int num : count.keySet()) { - if ((openGroups > 0 && num > lastNum + 1) || + if ((openGroups > 0 && num > lastNum + 1) || openGroups > count.get(num)) { return false; } @@ -562,13 +562,13 @@ public: map count; for (int num : hand) count[num]++; - + queue q; int lastNum = -1, openGroups = 0; for (auto& entry : count) { int num = entry.first; - if ((openGroups > 0 && num > lastNum + 1) || + if ((openGroups > 0 && num > lastNum + 1) || openGroups > count[num]) { return false; } @@ -598,25 +598,30 @@ class Solution { if (hand.length % groupSize !== 0) return false; let count = new Map(); - hand.forEach(num => count.set(num, (count.get(num) || 0) + 1)); + hand.forEach((num) => count.set(num, (count.get(num) || 0) + 1)); let q = new Queue(); - let lastNum = -1, openGroups = 0; + let lastNum = -1, + openGroups = 0; + + Array.from(count.keys()) + .sort((a, b) => a - b) + .forEach((num) => { + if ( + (openGroups > 0 && num > lastNum + 1) || + openGroups > count.get(num) + ) { + return false; + } - Array.from(count.keys()).sort((a, b) => a - b).forEach(num => { - if ((openGroups > 0 && num > lastNum + 1) || - openGroups > count.get(num)) { - return false; - } + q.push(count.get(num) - openGroups); + lastNum = num; + openGroups = count.get(num); - q.push(count.get(num) - openGroups); - lastNum = num; - openGroups = count.get(num); - - if (q.size() === groupSize) { - openGroups -= q.pop(); - } - }); + if (q.size() === groupSize) { + openGroups -= q.pop(); + } + }); return openGroups === 0; } @@ -638,7 +643,7 @@ public class Solution { int lastNum = -1, openGroups = 0; foreach (int num in count.Keys) { - if ((openGroups > 0 && num > lastNum + 1) || + if ((openGroups > 0 && num > lastNum + 1) || openGroups > count[num]) { return false; } @@ -677,7 +682,7 @@ func isNStraightHand(hand []int, groupSize int) bool { lastNum, openGroups := -1, 0 for _, num := range keys { - if (openGroups > 0 && num > lastNum+1) || + if (openGroups > 0 && num > lastNum+1) || openGroups > count[num] { return false } @@ -710,7 +715,7 @@ class Solution { var openGroups = 0 for (num in count.keys) { - if ((openGroups > 0 && num > lastNum + 1) || + if ((openGroups > 0 && num > lastNum + 1) || openGroups > count[num]!!) { return false } @@ -766,8 +771,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -805,7 +810,7 @@ public class Solution { for (int num : hand) { count.put(num, count.getOrDefault(num, 0) + 1); } - + for (int num : hand) { int start = num; while (count.getOrDefault(start - 1, 0) > 0) start--; @@ -832,7 +837,7 @@ public: unordered_map count; for (int num : hand) count[num]++; - + for (int num : hand) { int start = num; while (count[start - 1] > 0) start--; @@ -862,8 +867,8 @@ class Solution { if (hand.length % groupSize !== 0) return false; const count = new Map(); - hand.forEach(num => count.set(num, (count.get(num) || 0) + 1)); - + hand.forEach((num) => count.set(num, (count.get(num) || 0) + 1)); + for (const num of hand) { let start = num; while (count.get(start - 1) > 0) start--; @@ -931,7 +936,7 @@ func isNStraightHand(hand []int, groupSize int) bool { for count[start-1] > 0 { start-- } - + for start <= num { for count[start] > 0 { for i := start; i < start+groupSize; i++ { @@ -1018,5 +1023,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/height-checker.md b/articles/height-checker.md index 1e0919676..14b3e474b 100644 --- a/articles/height-checker.md +++ b/articles/height-checker.md @@ -77,8 +77,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -200,7 +200,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + k)$ -* Space complexity: $O(n + k)$ +- Time complexity: $O(n + k)$ +- Space complexity: $O(n + k)$ -> Where $n$ is the size of the input array, and $k$ is the range of numbers. \ No newline at end of file +> Where $n$ is the size of the input array, and $k$ is the range of numbers. diff --git a/articles/house-robber-ii.md b/articles/house-robber-ii.md index 0469d73df..17cd92a3e 100644 --- a/articles/house-robber-ii.md +++ b/articles/house-robber-ii.md @@ -10,8 +10,8 @@ class Solution: def dfs(i, flag): if i >= len(nums) or (flag and i == len(nums) - 1): return 0 - - return max(dfs(i + 1, flag), + + return max(dfs(i + 1, flag), nums[i] + dfs(i + 2, flag or i == 0)) return max(dfs(0, True), dfs(1, False)) ``` @@ -22,12 +22,12 @@ public class Solution { if (nums.length == 1) return nums[0]; return Math.max(dfs(0, true, nums), dfs(1, false, nums)); } - + private int dfs(int i, boolean flag, int[] nums) { - if (i >= nums.length || (flag && i == nums.length - 1)) + if (i >= nums.length || (flag && i == nums.length - 1)) return 0; - return Math.max(dfs(i + 1, flag, nums), + return Math.max(dfs(i + 1, flag, nums), nums[i] + dfs(i + 2, flag || i == 0, nums)); } } @@ -43,10 +43,10 @@ public: private: int dfs(int i, bool flag, vector& nums) { - if (i >= nums.size() || (flag && i == nums.size() - 1)) + if (i >= nums.size() || (flag && i == nums.size() - 1)) return 0; - return max(dfs(i + 1, flag, nums), + return max(dfs(i + 1, flag, nums), nums[i] + dfs(i + 2, flag || i == 0, nums)); } }; @@ -62,13 +62,14 @@ class Solution { if (nums.length === 1) return nums[0]; const dfs = (i, flag) => { - if (i >= nums.length || (flag && i === nums.length - 1)) - return 0; + if (i >= nums.length || (flag && i === nums.length - 1)) return 0; + + return Math.max( + dfs(i + 1, flag), + nums[i] + dfs(i + 2, flag || i === 0), + ); + }; - return Math.max(dfs(i + 1, flag), - nums[i] + dfs(i + 2, flag || i === 0)); - } - return Math.max(dfs(0, true), dfs(1, false)); } } @@ -80,12 +81,12 @@ public class Solution { if (nums.Length == 1) return nums[0]; return Math.Max(Dfs(0, true, nums), Dfs(1, false, nums)); } - + private int Dfs(int i, bool flag, int[] nums) { - if (i >= nums.Length || (flag && i == nums.Length - 1)) + if (i >= nums.Length || (flag && i == nums.Length - 1)) return 0; - return Math.Max(Dfs(i + 1, flag, nums), + return Math.Max(Dfs(i + 1, flag, nums), nums[i] + Dfs(i + 2, flag || i == 0, nums)); } } @@ -123,7 +124,7 @@ class Solution { if (i >= nums.size || (flag && i == nums.size - 1)) { return 0 } - return maxOf(dfs(i + 1, flag), + return maxOf(dfs(i + 1, flag), nums[i] + dfs(i + 2, flag || i == 0)) } return maxOf(dfs(0, true), dfs(1, false)) @@ -154,8 +155,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ --- @@ -176,7 +177,7 @@ class Solution: return 0 if memo[i][flag] != -1: return memo[i][flag] - memo[i][flag] = max(dfs(i + 1, flag), + memo[i][flag] = max(dfs(i + 1, flag), nums[i] + dfs(i + 2, flag or (i == 0))) return memo[i][flag] @@ -186,25 +187,25 @@ class Solution: ```java public class Solution { private int[][] memo; - + public int rob(int[] nums) { if (nums.length == 1) return nums[0]; - + memo = new int[nums.length][2]; for (int i = 0; i < nums.length; i++) { memo[i][0] = -1; memo[i][1] = -1; } - + return Math.max(dfs(0, 1, nums), dfs(1, 0, nums)); } - + private int dfs(int i, int flag, int[] nums) { - if (i >= nums.length || (flag == 1 && i == nums.length - 1)) + if (i >= nums.length || (flag == 1 && i == nums.length - 1)) return 0; if (memo[i][flag] != -1) return memo[i][flag]; - memo[i][flag] = Math.max(dfs(i + 1, flag, nums), + memo[i][flag] = Math.max(dfs(i + 1, flag, nums), nums[i] + dfs(i + 2, flag | (i == 0 ? 1 : 0), nums)); return memo[i][flag]; } @@ -214,22 +215,22 @@ public class Solution { ```cpp class Solution { vector> memo; - + public: int rob(vector& nums) { if (nums.size() == 1) return nums[0]; - + memo.resize(nums.size(), vector(2, -1)); return max(dfs(0, 1, nums), dfs(1, 0, nums)); } private: int dfs(int i, int flag, vector& nums) { - if (i >= nums.size() || (flag == 1 && i == nums.size() - 1)) + if (i >= nums.size() || (flag == 1 && i == nums.size() - 1)) return 0; - if (memo[i][flag] != -1) + if (memo[i][flag] != -1) return memo[i][flag]; - memo[i][flag] = max(dfs(i + 1, flag, nums), + memo[i][flag] = max(dfs(i + 1, flag, nums), nums[i] + dfs(i + 2, flag | (i == 0 ? 1 : 0), nums)); return memo[i][flag]; } @@ -249,17 +250,15 @@ class Solution { const memo = Array.from({ length: n }, () => Array(2).fill(-1)); const dfs = (i, flag) => { - if (i >= n || (flag && (i === n - 1))) - return 0; - if (memo[i][flag] !== -1) - return memo[i][flag]; + if (i >= n || (flag && i === n - 1)) return 0; + if (memo[i][flag] !== -1) return memo[i][flag]; memo[i][flag] = Math.max( - dfs(i + 1, flag), - nums[i] + dfs(i + 2, flag | (i === 0)) + dfs(i + 1, flag), + nums[i] + dfs(i + 2, flag | (i === 0)), ); return memo[i][flag]; - } + }; return Math.max(dfs(0, 1), dfs(1, 0)); } @@ -272,21 +271,21 @@ public class Solution { public int Rob(int[] nums) { if (nums.Length == 1) return nums[0]; - + memo = new int[nums.Length][]; for (int i = 0; i < nums.Length; i++) { memo[i] = new int[] { -1, -1 }; } - + return Math.Max(Dfs(0, 1, nums), Dfs(1, 0, nums)); } private int Dfs(int i, int flag, int[] nums) { - if (i >= nums.Length || (flag == 1 && i == nums.Length - 1)) + if (i >= nums.Length || (flag == 1 && i == nums.Length - 1)) return 0; - if (memo[i][flag] != -1) + if (memo[i][flag] != -1) return memo[i][flag]; - memo[i][flag] = Math.Max(Dfs(i + 1, flag, nums), + memo[i][flag] = Math.Max(Dfs(i + 1, flag, nums), nums[i] + Dfs(i + 2, flag | (i == 0 ? 1 : 0), nums)); return memo[i][flag]; } @@ -345,7 +344,7 @@ class Solution { if (memo[i][flag] != -1) { return memo[i][flag] } - memo[i][flag] = maxOf(dfs(i + 1, flag), + memo[i][flag] = maxOf(dfs(i + 1, flag), nums[i] + dfs(i + 2, flag or if (i == 0) 1 else 0)) return memo[i][flag] } @@ -388,8 +387,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -402,22 +401,22 @@ class Solution: def rob(self, nums: List[int]) -> int: if len(nums) == 1: return nums[0] - return max(self.helper(nums[1:]), + return max(self.helper(nums[1:]), self.helper(nums[:-1])) - + def helper(self, nums: List[int]) -> int: if not nums: return 0 if len(nums) == 1: return nums[0] - + dp = [0] * len(nums) dp[0] = nums[0] dp[1] = max(nums[0], nums[1]) - + for i in range(2, len(nums)): dp[i] = max(dp[i - 1], nums[i] + dp[i - 2]) - + return dp[-1] ``` @@ -484,8 +483,10 @@ class Solution { if (nums.length === 0) return 0; if (nums.length === 1) return nums[0]; - return Math.max(this.helper(nums.slice(1)), - this.helper(nums.slice(0, -1))); + return Math.max( + this.helper(nums.slice(1)), + this.helper(nums.slice(0, -1)), + ); } /** @@ -576,7 +577,7 @@ class Solution { if (nums.size == 1) { return nums[0] } - return max(helper(nums.copyOfRange(1, nums.size)), + return max(helper(nums.copyOfRange(1, nums.size)), helper(nums.copyOfRange(0, nums.size - 1))) } @@ -609,7 +610,7 @@ class Solution { } return max(helper(Array(nums[1...])), helper(Array(nums[..<(nums.count - 1)]))) } - + func helper(_ nums: [Int]) -> Int { if nums.isEmpty { return 0 @@ -617,15 +618,15 @@ class Solution { if nums.count == 1 { return nums[0] } - + var dp = [Int](repeating: 0, count: nums.count) dp[0] = nums[0] dp[1] = max(nums[0], nums[1]) - + for i in 2.. int: - return max(nums[0], self.helper(nums[1:]), + return max(nums[0], self.helper(nums[1:]), self.helper(nums[:-1])) def helper(self, nums): @@ -663,10 +664,10 @@ class Solution: ```java public class Solution { - + public int rob(int[] nums) { - return Math.max(nums[0], - Math.max(helper(Arrays.copyOfRange(nums, 1, nums.length)), + return Math.max(nums[0], + Math.max(helper(Arrays.copyOfRange(nums, 1, nums.length)), helper(Arrays.copyOfRange(nums, 0, nums.length - 1)))); } @@ -741,12 +742,12 @@ class Solution { ```csharp public class Solution { - + public int Rob(int[] nums) { - if (nums.Length == 1) + if (nums.Length == 1) return nums[0]; - return Math.Max(Helper(nums[1..]), + return Math.Max(Helper(nums[1..]), Helper(nums[..^1])); } @@ -767,7 +768,7 @@ func rob(nums []int) int { if len(nums) == 0 { return 0 } - return max(nums[0], max(helper(nums[1:]), + return max(nums[0], max(helper(nums[1:]), helper(nums[:len(nums)-1]))) } @@ -793,8 +794,8 @@ func max(a, b int) int { ```kotlin class Solution { fun rob(nums: IntArray): Int { - return maxOf(nums[0], - maxOf(helper(nums.copyOfRange(1, nums.size)), + return maxOf(nums[0], + maxOf(helper(nums.copyOfRange(1, nums.size)), helper(nums.copyOfRange(0, nums.size - 1)))) } @@ -821,24 +822,24 @@ class Solution { if nums.count == 1 { return nums[0] } - + let candidate1 = nums[0] let candidate2 = helper(Array(nums[1.. Int { var rob1 = 0 var rob2 = 0 - + for num in nums { let newRob = max(rob1 + num, rob2) rob1 = rob2 rob2 = newRob } - + return rob2 } } @@ -848,5 +849,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/house-robber-iii.md b/articles/house-robber-iii.md index a09238c6b..a0e24cb96 100644 --- a/articles/house-robber-iii.md +++ b/articles/house-robber-iii.md @@ -13,13 +13,13 @@ class Solution: def rob(self, root: Optional[TreeNode]) -> int: if not root: return 0 - + res = root.val if root.left: res += self.rob(root.left.left) + self.rob(root.left.right) if root.right: res += self.rob(root.right.left) + self.rob(root.right.right) - + res = max(res, self.rob(root.left) + self.rob(root.right)) return res ``` @@ -164,8 +164,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -187,16 +187,16 @@ class Solution: def dfs(root): if root in cache: return cache[root] - + cache[root] = root.val if root.left: cache[root] += dfs(root.left.left) + dfs(root.left.right) if root.right: cache[root] += dfs(root.right.left) + dfs(root.right.right) - + cache[root] = max(cache[root], dfs(root.left) + dfs(root.right)) return cache[root] - + return dfs(root) ``` @@ -375,8 +375,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -439,7 +439,7 @@ public class Solution { int[] rightPair = dfs(root.right); int withRoot = root.val + leftPair[1] + rightPair[1]; - int withoutRoot = Math.max(leftPair[0], leftPair[1]) + + int withoutRoot = Math.max(leftPair[0], leftPair[1]) + Math.max(rightPair[0], rightPair[1]); return new int[]{withRoot, withoutRoot}; @@ -476,7 +476,7 @@ private: auto rightPair = dfs(root->right); int withRoot = root->val + leftPair.second + rightPair.second; - int withoutRoot = max(leftPair.first, leftPair.second) + + int withoutRoot = max(leftPair.first, leftPair.second) + max(rightPair.first, rightPair.second); return {withRoot, withoutRoot}; @@ -559,5 +559,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. diff --git a/articles/house-robber.md b/articles/house-robber.md index 22be9ba02..e8d9ca34e 100644 --- a/articles/house-robber.md +++ b/articles/house-robber.md @@ -5,13 +5,13 @@ ```python class Solution: def rob(self, nums: List[int]) -> int: - + def dfs(i): if i >= len(nums): return 0 return max(dfs(i + 1), nums[i] + dfs(i + 2)) - + return dfs(0) ``` @@ -55,14 +55,12 @@ class Solution { * @return {number} */ rob(nums) { - const dfs = (i) => { if (i >= nums.length) { return 0; } - return Math.max(dfs(i + 1), - nums[i] + dfs(i + 2)); - } + return Math.max(dfs(i + 1), nums[i] + dfs(i + 2)); + }; return dfs(0); } } @@ -137,8 +135,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ --- @@ -158,7 +156,7 @@ class Solution: return memo[i] memo[i] = max(dfs(i + 1), nums[i] + dfs(i + 2)) return memo[i] - + return dfs(0) ``` @@ -179,7 +177,7 @@ public class Solution { if (memo[i] != -1) { return memo[i]; } - memo[i] = Math.max(dfs(nums, i + 1), + memo[i] = Math.max(dfs(nums, i + 1), nums[i] + dfs(nums, i + 2)); return memo[i]; } @@ -190,7 +188,7 @@ public class Solution { class Solution { public: vector memo; - + int rob(vector& nums) { memo.resize(nums.size(), -1); return dfs(nums, 0); @@ -225,9 +223,8 @@ class Solution { if (memo[i] !== -1) { return memo[i]; } - return memo[i] = Math.max(dfs(i + 1), - nums[i] + dfs(i + 2)); - } + return (memo[i] = Math.max(dfs(i + 1), nums[i] + dfs(i + 2))); + }; return dfs(0); } } @@ -331,8 +328,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -347,14 +344,14 @@ class Solution: return 0 if len(nums) == 1: return nums[0] - + dp = [0] * len(nums) dp[0] = nums[0] dp[1] = max(nums[0], nums[1]) - + for i in range(2, len(nums)): dp[i] = max(dp[i - 1], nums[i] + dp[i - 2]) - + return dp[-1] ``` @@ -518,8 +515,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -659,5 +656,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/image-smoother.md b/articles/image-smoother.md index 767d82e16..00b007e79 100644 --- a/articles/image-smoother.md +++ b/articles/image-smoother.md @@ -81,12 +81,14 @@ class Solution { * @return {number[][]} */ imageSmoother(img) { - const ROWS = img.length, COLS = img[0].length; + const ROWS = img.length, + COLS = img[0].length; const res = Array.from({ length: ROWS }, () => Array(COLS).fill(0)); for (let r = 0; r < ROWS; r++) { for (let c = 0; c < COLS; c++) { - let total = 0, count = 0; + let total = 0, + count = 0; for (let i = r - 1; i <= r + 1; i++) { for (let j = c - 1; j <= c + 1; j++) { if (i >= 0 && i < ROWS && j >= 0 && j < COLS) { @@ -108,8 +110,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n * m)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n * m)$ > Where $n$ is the number of rows and $m$ is the number of columns of the matrix. @@ -222,16 +224,26 @@ class Solution { * @return {number[][]} */ imageSmoother(img) { - const ROWS = img.length, COLS = img[0].length; + const ROWS = img.length, + COLS = img[0].length; let prevRow = [...img[0]]; for (let r = 0; r < ROWS; r++) { let currRow = [...img[r]]; for (let c = 0; c < COLS; c++) { - let total = 0, count = 0; - for (let i = Math.max(0, r - 1); i < Math.min(ROWS, r + 2); i++) { - for (let j = Math.max(0, c - 1); j < Math.min(COLS, c + 2); j++) { + let total = 0, + count = 0; + for ( + let i = Math.max(0, r - 1); + i < Math.min(ROWS, r + 2); + i++ + ) { + for ( + let j = Math.max(0, c - 1); + j < Math.min(COLS, c + 2); + j++ + ) { if (i === r) { total += currRow[j]; } else if (i === r - 1) { @@ -257,8 +269,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n)$ extra space. +- Time complexity: $O(n * m)$ +- Space complexity: $O(n)$ extra space. > Where $n$ is the number of rows and $m$ is the number of columns of the matrix. @@ -358,14 +370,24 @@ class Solution { * @return {number[][]} */ imageSmoother(img) { - const ROWS = img.length, COLS = img[0].length; + const ROWS = img.length, + COLS = img[0].length; const LIMIT = 256; for (let r = 0; r < ROWS; r++) { for (let c = 0; c < COLS; c++) { - let total = 0, count = 0; - for (let i = Math.max(0, r - 1); i < Math.min(ROWS, r + 2); i++) { - for (let j = Math.max(0, c - 1); j < Math.min(COLS, c + 2); j++) { + let total = 0, + count = 0; + for ( + let i = Math.max(0, r - 1); + i < Math.min(ROWS, r + 2); + i++ + ) { + for ( + let j = Math.max(0, c - 1); + j < Math.min(COLS, c + 2); + j++ + ) { total += img[i][j] % LIMIT; count++; } @@ -389,8 +411,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n * m)$ +- Space complexity: $O(1)$ extra space. > Where $n$ is the number of rows and $m$ is the number of columns of the matrix. @@ -442,7 +464,7 @@ public class Solution { img[r][c] ^= ((total / cnt) << 8); } } - + for (int r = 0; r < ROWS; r++) { for (int c = 0; c < COLS; c++) { img[r][c] >>= 8; @@ -458,7 +480,7 @@ class Solution { public: vector> imageSmoother(vector>& img) { int ROWS = img.size(), COLS = img[0].size(); - + for (int r = 0; r < ROWS; r++) { for (int c = 0; c < COLS; c++) { int total = 0, cnt = 0; @@ -492,11 +514,13 @@ class Solution { * @return {number[][]} */ imageSmoother(img) { - const ROWS = img.length, COLS = img[0].length; + const ROWS = img.length, + COLS = img[0].length; for (let r = 0; r < ROWS; r++) { for (let c = 0; c < COLS; c++) { - let total = 0, cnt = 0; + let total = 0, + cnt = 0; for (let i = r - 1; i <= r + 1; i++) { for (let j = c - 1; j <= c + 1; j++) { if (i < 0 || i >= ROWS || j < 0 || j >= COLS) { @@ -506,7 +530,7 @@ class Solution { cnt++; } } - img[r][c] ^= ((total / cnt) << 8); + img[r][c] ^= (total / cnt) << 8; } } @@ -524,7 +548,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n * m)$ +- Space complexity: $O(1)$ extra space. -> Where $n$ is the number of rows and $m$ is the number of columns of the matrix. \ No newline at end of file +> Where $n$ is the number of rows and $m$ is the number of columns of the matrix. diff --git a/articles/implement-prefix-tree.md b/articles/implement-prefix-tree.md index 3e4a303f2..cbfc89383 100644 --- a/articles/implement-prefix-tree.md +++ b/articles/implement-prefix-tree.md @@ -96,18 +96,18 @@ class TrieNode { public: TrieNode* children[26]; bool endOfWord; - + TrieNode() { for (int i = 0; i < 26; i++) { children[i] = nullptr; - } + } endOfWord = false; } }; class PrefixTree { TrieNode* root; - + public: PrefixTree() { root = new TrieNode(); @@ -423,8 +423,8 @@ class PrefixTree { ### Time & Space Complexity -* Time complexity: $O(n)$ for each function call. -* Space complexity: $O(t)$ +- Time complexity: $O(n)$ for each function call. +- Space complexity: $O(t)$ > Where $n$ is the length of the string and $t$ is the total number of TrieNodes created in the Trie. @@ -577,7 +577,7 @@ class PrefixTree { constructor() { this.root = new TrieNode(); } - + /** * @param {string} word * @return {void} @@ -627,7 +627,7 @@ class PrefixTree { ```csharp public class TrieNode { - public Dictionary children = + public Dictionary children = new Dictionary(); public bool endOfWord = false; } @@ -821,7 +821,7 @@ class PrefixTree { ### Time & Space Complexity -* Time complexity: $O(n)$ for each function call. -* Space complexity: $O(t)$ +- Time complexity: $O(n)$ for each function call. +- Space complexity: $O(t)$ -> Where $n$ is the length of the string and $t$ is the total number of TrieNodes created in the Trie. \ No newline at end of file +> Where $n$ is the length of the string and $t$ is the total number of TrieNodes created in the Trie. diff --git a/articles/implement-queue-using-stacks.md b/articles/implement-queue-using-stacks.md index e6d33a121..770f0cb0a 100644 --- a/articles/implement-queue-using-stacks.md +++ b/articles/implement-queue-using-stacks.md @@ -127,7 +127,7 @@ class MyQueue { this.stack2 = []; } - /** + /** * @param {number} x * @return {void} */ @@ -218,11 +218,11 @@ public class MyQueue { ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for initialization. - * $O(1)$ time for each $push()$ and $empty()$ function calls. - * $O(n)$ time for each $pop()$ and $peek()$ function calls. -* Space complexity: $O(n)$ +- Time complexity: + - $O(1)$ time for initialization. + - $O(1)$ time for each $push()$ and $empty()$ function calls. + - $O(n)$ time for each $pop()$ and $peek()$ function calls. +- Space complexity: $O(n)$ --- @@ -232,7 +232,7 @@ public class MyQueue { ```python class MyQueue: - + def __init__(self): self.s1 = [] self.s2 = [] @@ -341,7 +341,7 @@ class MyQueue { this.s2 = []; } - /** + /** * @param {number} x * @return {void} */ @@ -424,8 +424,8 @@ public class MyQueue { ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for initialization. - * $O(1)$ time for each $push()$ and $empty()$ function calls. - * $O(1)$ amortized time for each $pop()$ and $peek()$ function calls. -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: + - $O(1)$ time for initialization. + - $O(1)$ time for each $push()$ and $empty()$ function calls. + - $O(1)$ amortized time for each $pop()$ and $peek()$ function calls. +- Space complexity: $O(n)$ diff --git a/articles/implement-stack-using-queues.md b/articles/implement-stack-using-queues.md index 16887f069..6d1114f6e 100644 --- a/articles/implement-stack-using-queues.md +++ b/articles/implement-stack-using-queues.md @@ -13,7 +13,7 @@ class MyStack: self.q2.append(x) while self.q1: self.q2.append(self.q1.popleft()) - + self.q1, self.q2 = self.q2, self.q1 def pop(self) -> int: @@ -107,11 +107,11 @@ class MyStack { */ push(x) { this.q2.push(x); - + while (!this.q1.isEmpty()) { this.q2.push(this.q1.pop()); } - + [this.q1, this.q2] = [this.q2, this.q1]; } @@ -176,11 +176,11 @@ public class MyStack { ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for initialization. - * $O(n)$ time for each $push()$ function call. - * $O(1)$ time for each $pop()$ function call. -* Space complexity: $O(n)$ +- Time complexity: + - $O(1)$ time for initialization. + - $O(n)$ time for each $push()$ function call. + - $O(1)$ time for each $pop()$ function call. +- Space complexity: $O(n)$ --- @@ -281,7 +281,7 @@ class MyStack { */ push(x) { this.q.push(x); - + for (let i = this.q.size() - 1; i > 0; i--) { this.q.push(this.q.pop()); } @@ -343,11 +343,11 @@ public class MyStack { ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for initialization. - * $O(n)$ time for each $push()$ function call. - * $O(1)$ time for each $pop()$ function call. -* Space complexity: $O(n)$ +- Time complexity: + - $O(1)$ time for initialization. + - $O(n)$ time for each $push()$ function call. + - $O(1)$ time for each $pop()$ function call. +- Space complexity: $O(n)$ --- @@ -528,8 +528,8 @@ public class MyStack { ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for initialization. - * $O(1)$ time for each $push()$ function call. - * $O(1)$ time for each $pop()$ function call. -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: + - $O(1)$ time for initialization. + - $O(1)$ time for each $push()$ function call. + - $O(1)$ time for each $pop()$ function call. +- Space complexity: $O(n)$ diff --git a/articles/insert-delete-getrandom-o1.md b/articles/insert-delete-getrandom-o1.md index 000979641..caa9b8f0c 100644 --- a/articles/insert-delete-getrandom-o1.md +++ b/articles/insert-delete-getrandom-o1.md @@ -4,7 +4,7 @@ ```python class RandomizedSet: - + def __init__(self): self.numMap = {} self.size = 0 @@ -106,7 +106,7 @@ class RandomizedSet { this.size = 0; } - /** + /** * @param {number} val * @return {boolean} */ @@ -117,7 +117,7 @@ class RandomizedSet { return true; } - /** + /** * @param {number} val * @return {boolean} */ @@ -143,8 +143,8 @@ class RandomizedSet { ### Time & Space Complexity -* Time complexity: $O(n)$ for $getRandom()$, $O(1)$ for other function calls. -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ for $getRandom()$, $O(1)$ for other function calls. +- Space complexity: $O(n)$ --- @@ -154,7 +154,7 @@ class RandomizedSet { ```python class RandomizedSet: - + def __init__(self): self.numMap = {} self.nums = [] @@ -257,7 +257,7 @@ class RandomizedSet { this.nums = []; } - /** + /** * @param {number} val * @return {boolean} */ @@ -268,7 +268,7 @@ class RandomizedSet { return true; } - /** + /** * @param {number} val * @return {boolean} */ @@ -296,5 +296,5 @@ class RandomizedSet { ### Time & Space Complexity -* Time complexity: $O(1)$ for each function call. -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(1)$ for each function call. +- Space complexity: $O(n)$ diff --git a/articles/insert-greatest-common-divisors-in-linked-list.md b/articles/insert-greatest-common-divisors-in-linked-list.md index 6bef838d6..05fa7c7e5 100644 --- a/articles/insert-greatest-common-divisors-in-linked-list.md +++ b/articles/insert-greatest-common-divisors-in-linked-list.md @@ -131,7 +131,8 @@ class Solution { let cur = head; while (cur.next) { - const n1 = cur.val, n2 = cur.next.val; + const n1 = cur.val, + n2 = cur.next.val; const gcdValue = gcd(n1, n2); const newNode = new ListNode(gcdValue, cur.next); cur.next = newNode; @@ -184,9 +185,9 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * \log (min(a, b)))$ -* Space complexity: - * $O(n)$ space for the gcd ListNodes. - * $O(1)$ extra space. +- Time complexity: $O(n * \log (min(a, b)))$ +- Space complexity: + - $O(n)$ space for the gcd ListNodes. + - $O(1)$ extra space. -> Where $n$ is the length of the given list, and $a$ and $b$ are two numbers passed to the $gcd()$ function. \ No newline at end of file +> Where $n$ is the length of the given list, and $a$ and $b$ are two numbers passed to the $gcd()$ function. diff --git a/articles/insert-into-a-binary-search-tree.md b/articles/insert-into-a-binary-search-tree.md index fe0604c3a..b74eb1d2b 100644 --- a/articles/insert-into-a-binary-search-tree.md +++ b/articles/insert-into-a-binary-search-tree.md @@ -153,8 +153,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(h)$ -* Space complexity: $O(h)$ for the recursion stack. +- Time complexity: $O(h)$ +- Space complexity: $O(h)$ for the recursion stack. > Where $h$ is the height of the given binary search tree. @@ -357,7 +357,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(h)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(h)$ +- Space complexity: $O(1)$ extra space. -> Where $h$ is the height of the given binary search tree. \ No newline at end of file +> Where $h$ is the height of the given binary search tree. diff --git a/articles/insert-new-interval.md b/articles/insert-new-interval.md index 14c62d591..b06111133 100644 --- a/articles/insert-new-interval.md +++ b/articles/insert-new-interval.md @@ -91,8 +91,8 @@ class Solution { */ insert(intervals, newInterval) { let n = intervals.length, - i = 0, - res = []; + i = 0, + res = []; while (i < n && intervals[i][1] < newInterval[0]) { res.push(intervals[i]); @@ -120,13 +120,13 @@ class Solution { public class Solution { public int[][] Insert(int[][] intervals, int[] newInterval) { var result = new List(); - + for(var i = 0; i < intervals.Length; i++) { if(newInterval[1] < intervals[i][0]) { result.Add(newInterval); result.AddRange( intervals.AsEnumerable().Skip(i).ToArray()); - + return result.ToArray(); } else if(newInterval[0] > intervals[i][1]) { @@ -136,9 +136,9 @@ public class Solution { newInterval[1] = Math.Max(intervals[i][1], newInterval[1]); } } - + result.Add(newInterval); - + return result.ToArray(); } } @@ -251,10 +251,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ space for the output list. +- Time complexity: $O(n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ space for the output list. --- @@ -404,8 +404,7 @@ class Solution { let res = []; for (let interval of intervals) { - if (res.length === 0 || - res[res.length - 1][1] < interval[0]) { + if (res.length === 0 || res[res.length - 1][1] < interval[0]) { res.push(interval); } else { res[res.length - 1][1] = Math.max( @@ -582,10 +581,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ space for the output list. +- Time complexity: $O(n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ space for the output list. --- @@ -692,7 +691,7 @@ class Solution { public class Solution { public int[][] Insert(int[][] intervals, int[] newInterval) { var result = new List(); - + for(var i = 0; i < intervals.Length; i++) { if(newInterval[1] < intervals[i][0]) { result.Add(newInterval); @@ -705,7 +704,7 @@ public class Solution { newInterval[1] = Math.Max(intervals[i][1], newInterval[1]); } } - + result.Add(newInterval); return result.ToArray(); } @@ -756,7 +755,7 @@ class Solution { for (interval in intervals) { if (newInterval[1] < interval[0]) { res.add(newInterval) - return (res + + return (res + intervals.sliceArray( intervals.indexOf(interval) until intervals.size )).toTypedArray() @@ -802,7 +801,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ space for the output list. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ space for the output list. diff --git a/articles/insertion-sort-list.md b/articles/insertion-sort-list.md index a567be9b0..d729a6b95 100644 --- a/articles/insertion-sort-list.md +++ b/articles/insertion-sort-list.md @@ -131,8 +131,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -244,8 +244,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ extra space. --- @@ -268,11 +268,11 @@ class Solution: if cur.val >= prev.val: prev, cur = cur, cur.next continue - + tmp = dummy while cur.val > tmp.next.val: tmp = tmp.next - + prev.next = cur.next cur.next = tmp.next tmp.next = cur @@ -378,7 +378,8 @@ class Solution { */ insertionSortList(head) { let dummy = new ListNode(0, head); - let prev = head, cur = head.next; + let prev = head, + cur = head.next; while (cur) { if (cur.val >= prev.val) { @@ -407,5 +408,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/integer-break.md b/articles/integer-break.md index 2330d8828..2ef7a83a2 100644 --- a/articles/integer-break.md +++ b/articles/integer-break.md @@ -66,7 +66,7 @@ class Solution { const dfs = (num) => { if (num === 1) return 1; - let res = (num === n) ? 0 : num; + let res = num === n ? 0 : num; for (let i = 1; i < num; i++) { const val = dfs(i) * dfs(num - i); res = Math.max(res, val); @@ -105,8 +105,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n ^ n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -120,12 +120,12 @@ class Solution: def dfs(num, i): if min(num, i) == 0: return 1 - + if i > num: return dfs(num, num) - + return max(i * dfs(num - i, i), dfs(num, i - 1)) - + return dfs(n, n - 1) ``` @@ -139,11 +139,11 @@ public class Solution { if (Math.min(num, i) == 0) { return 1; } - + if (i > num) { return dfs(num, num); } - + return Math.max(i * dfs(num - i, i), dfs(num, i - 1)); } } @@ -161,11 +161,11 @@ private: if (min(num, i) == 0) { return 1; } - + if (i > num) { return dfs(num, num); } - + return max(i * dfs(num - i, i), dfs(num, i - 1)); } }; @@ -182,11 +182,11 @@ class Solution { if (Math.min(num, i) === 0) { return 1; } - + if (i > num) { return dfs(num, num); } - + return Math.max(i * dfs(num - i, i), dfs(num, i - 1)); }; @@ -219,8 +219,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -242,7 +242,7 @@ class Solution: val = dfs(i) * dfs(num - i) dp[num] = max(dp[num], val) return dp[num] - + return dfs(n) ``` @@ -316,7 +316,7 @@ class Solution { return dp.get(num); } - let res = (num === n) ? 0 : num; + let res = num === n ? 0 : num; for (let i = 1; i < num; i++) { const val = dfs(i) * dfs(num - i); res = Math.max(res, val); @@ -360,8 +360,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -381,10 +381,10 @@ class Solution: if i > num: dp[(num, i)] = dfs(num, num) return dp[(num, i)] - + dp[(num, i)] = max(i * dfs(num - i, i), dfs(num, i - 1)) return dp[(num, i)] - + return dfs(n, n - 1) ``` @@ -504,8 +504,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -575,7 +575,7 @@ class Solution { dp[1] = 1; for (let num = 2; num <= n; num++) { - dp[num] = (num === n) ? 0 : num; + dp[num] = num === n ? 0 : num; for (let i = 1; i < num; i++) { dp[num] = Math.max(dp[num], dp[i] * dp[num - i]); } @@ -608,8 +608,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -622,7 +622,7 @@ class Solution: def integerBreak(self, n: int) -> int: if n <= 3: return n - 1 - + res = 1 while n > 4: res *= 3 @@ -702,8 +702,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -802,5 +802,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ diff --git a/articles/integer-to-roman.md b/articles/integer-to-roman.md index bce76d0ae..2a8a85dc1 100644 --- a/articles/integer-to-roman.md +++ b/articles/integer-to-roman.md @@ -84,13 +84,22 @@ class Solution { */ intToRoman(num) { const symList = [ - ["I", 1], ["IV", 4], ["V", 5], ["IX", 9], - ["X", 10], ["XL", 40], ["L", 50], ["XC", 90], - ["C", 100], ["CD", 400], ["D", 500], ["CM", 900], - ["M", 1000] + ['I', 1], + ['IV', 4], + ['V', 5], + ['IX', 9], + ['X', 10], + ['XL', 40], + ['L', 50], + ['XC', 90], + ['C', 100], + ['CD', 400], + ['D', 500], + ['CM', 900], + ['M', 1000], ]; - let res = ""; + let res = ''; for (let i = symList.length - 1; i >= 0; i--) { const [sym, val] = symList[i]; let count = Math.floor(num / val); @@ -138,8 +147,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ --- @@ -188,9 +197,9 @@ public: string tens[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; string ones[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; - return thousands[num / 1000] + - hundreds[(num % 1000) / 100] + - tens[(num % 100) / 10] + + return thousands[num / 1000] + + hundreds[(num % 1000) / 100] + + tens[(num % 100) / 10] + ones[num % 10]; } }; @@ -203,15 +212,50 @@ class Solution { * @return {string} */ intToRoman(num) { - const thousands = ["", "M", "MM", "MMM"]; - const hundreds = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"]; - const tens = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"]; - const ones = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]; - - return thousands[Math.floor(num / 1000)] + - hundreds[Math.floor((num % 1000) / 100)] + - tens[Math.floor((num % 100) / 10)] + - ones[num % 10]; + const thousands = ['', 'M', 'MM', 'MMM']; + const hundreds = [ + '', + 'C', + 'CC', + 'CCC', + 'CD', + 'D', + 'DC', + 'DCC', + 'DCCC', + 'CM', + ]; + const tens = [ + '', + 'X', + 'XX', + 'XXX', + 'XL', + 'L', + 'LX', + 'LXX', + 'LXXX', + 'XC', + ]; + const ones = [ + '', + 'I', + 'II', + 'III', + 'IV', + 'V', + 'VI', + 'VII', + 'VIII', + 'IX', + ]; + + return ( + thousands[Math.floor(num / 1000)] + + hundreds[Math.floor((num % 1000) / 100)] + + tens[Math.floor((num % 100) / 10)] + + ones[num % 10] + ); } } ``` @@ -236,5 +280,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ diff --git a/articles/interleaving-string.md b/articles/interleaving-string.md index 3d124cd01..5bcffb088 100644 --- a/articles/interleaving-string.md +++ b/articles/interleaving-string.md @@ -5,48 +5,48 @@ ```python class Solution: def isInterleave(self, s1: str, s2: str, s3: str) -> bool: - + def dfs(i, j, k): if k == len(s3): return (i == len(s1)) and (j == len(s2)) - + if i < len(s1) and s1[i] == s3[k]: if dfs(i + 1, j, k + 1): return True - + if j < len(s2) and s2[j] == s3[k]: if dfs(i, j + 1, k + 1): return True - + return False - + return dfs(0, 0, 0) ``` ```java public class Solution { public boolean isInterleave(String s1, String s2, String s3) { - + return dfs(0, 0, 0, s1, s2, s3); } - + private boolean dfs(int i, int j, int k, String s1, String s2, String s3) { if (k == s3.length()) { return (i == s1.length()) && (j == s2.length()); } - + if (i < s1.length() && s1.charAt(i) == s3.charAt(k)) { if (dfs(i + 1, j, k + 1, s1, s2, s3)) { return true; } } - + if (j < s2.length() && s2.charAt(j) == s3.charAt(k)) { if (dfs(i, j + 1, k + 1, s1, s2, s3)) { return true; } } - + return false; } } @@ -58,24 +58,24 @@ public: bool isInterleave(string s1, string s2, string s3) { return dfs(0, 0, 0, s1, s2, s3); } - + bool dfs(int i, int j, int k, string& s1, string& s2, string& s3) { if (k == s3.length()) { return (i == s1.length()) && (j == s2.length()); } - + if (i < s1.length() && s1[i] == s3[k]) { if (dfs(i + 1, j, k + 1, s1, s2, s3)) { return true; } } - + if (j < s2.length() && s2[j] == s3[k]) { if (dfs(i, j + 1, k + 1, s1, s2, s3)) { return true; } } - + return false; } }; @@ -90,26 +90,25 @@ class Solution { * @return {boolean} */ isInterleave(s1, s2, s3) { - const dfs = (i, j, k) => { if (k === s3.length) { - return (i === s1.length) && (j === s2.length); + return i === s1.length && j === s2.length; } - + if (i < s1.length && s1[i] === s3[k]) { if (dfs(i + 1, j, k + 1)) { return true; } } - + if (j < s2.length && s2[j] === s3[k]) { if (dfs(i, j + 1, k + 1)) { return true; } } - + return false; - } + }; return dfs(0, 0, 0); } @@ -121,24 +120,24 @@ public class Solution { public bool IsInterleave(string s1, string s2, string s3) { return dfs(0, 0, 0, s1, s2, s3); } - + private bool dfs(int i, int j, int k, string s1, string s2, string s3) { if (k == s3.Length) { return (i == s1.Length) && (j == s2.Length); } - + if (i < s1.Length && s1[i] == s3[k]) { if (dfs(i + 1, j, k + 1, s1, s2, s3)) { return true; } } - + if (j < s2.Length && s2[j] == s3[k]) { if (dfs(i, j + 1, k + 1, s1, s2, s3)) { return true; } } - + return false; } } @@ -204,29 +203,29 @@ class Solution { func isInterleave(_ s1: String, _ s2: String, _ s3: String) -> Bool { let n1 = s1.count, n2 = s2.count, n3 = s3.count if n1 + n2 != n3 { return false } - + let s1 = Array(s1), s2 = Array(s2), s3 = Array(s3) - + func dfs(_ i: Int, _ j: Int, _ k: Int) -> Bool { if k == n3 { return i == n1 && j == n2 } - + if i < n1 && s1[i] == s3[k] { if dfs(i + 1, j, k + 1) { return true } } - + if j < n2 && s2[j] == s3[k] { if dfs(i, j + 1, k + 1) { return true } } - + return false } - + return dfs(0, 0, 0) } } @@ -236,8 +235,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ {m + n})$ -* Space complexity: $O(m + n)$ +- Time complexity: $O(2 ^ {m + n})$ +- Space complexity: $O(m + n)$ > Where $m$ is the length of the string $s1$ and $n$ is the length of the string $s2$. @@ -259,16 +258,16 @@ class Solution: return (i == len(s1)) and (j == len(s2)) if (i, j) in dp: return dp[(i, j)] - + res = False if i < len(s1) and s1[i] == s3[k]: res = dfs(i + 1, j, k + 1) if not res and j < len(s2) and s2[j] == s3[k]: res = dfs(i, j + 1, k + 1) - + dp[(i, j)] = res return res - + return dfs(0, 0, 0) ``` @@ -282,7 +281,7 @@ public class Solution { dp = new Boolean[m + 1][n + 1]; return dfs(0, 0, 0, s1, s2, s3); } - + private boolean dfs(int i, int j, int k, String s1, String s2, String s3) { if (k == s3.length()) { return (i == s1.length()) && (j == s2.length()); @@ -316,7 +315,7 @@ public: dp = vector>(m + 1, vector(n + 1, -1)); return dfs(0, 0, 0, s1, s2, s3); } - + bool dfs(int i, int j, int k, string& s1, string& s2, string& s3) { if (k == s3.length()) { return (i == s1.length()) && (j == s2.length()); @@ -348,14 +347,14 @@ class Solution { * @return {boolean} */ isInterleave(s1, s2, s3) { - const m = s1.length, n = s2.length; + const m = s1.length, + n = s2.length; if (m + n !== s3.length) return false; - - const dp = Array.from({ length: m + 1 }, () => - Array(n + 1).fill(-1)); + + const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(-1)); const dfs = (i, j, k) => { if (k === s3.length) { - return (i === s1.length) && (j === s2.length); + return i === s1.length && j === s2.length; } if (dp[i][j] !== -1) { return dp[i][j]; @@ -365,13 +364,13 @@ class Solution { if (i < s1.length && s1[i] === s3[k]) { res = dfs(i + 1, j, k + 1); } - + if (!res && j < s2.length && s2[j] === s3[k]) { res = dfs(i, j + 1, k + 1); } dp[i][j] = res; return res; - } + }; return dfs(0, 0, 0); } @@ -388,7 +387,7 @@ public class Solution { dp = new bool?[m + 1, n + 1]; return dfs(0, 0, 0, s1, s2, s3); } - + private bool dfs(int i, int j, int k, string s1, string s2, string s3) { if (k == s3.Length) { return (i == s1.Length) && (j == s2.Length); @@ -445,9 +444,9 @@ func isInterleave(s1, s2, s3 string) bool { } if res { - dp[i][j] = 1 + dp[i][j] = 1 } else { - dp[i][j] = 0 + dp[i][j] = 0 } return res @@ -485,7 +484,7 @@ class Solution { res = dfs(i, j + 1, k + 1) } - dp[i][j] = if (res) 1 else 0 + dp[i][j] = if (res) 1 else 0 return res } @@ -500,7 +499,7 @@ class Solution { func isInterleave(_ s1: String, _ s2: String, _ s3: String) -> Bool { let m = s1.count, n = s2.count, l = s3.count if m + n != l { return false } - + let s1 = Array(s1), s2 = Array(s2), s3 = Array(s3) var dp = Array(repeating: Array(repeating: nil as Bool?, count: n + 1), count: m + 1) @@ -533,8 +532,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the length of the string $s1$ and $n$ is the length of the string $s2$. @@ -624,13 +623,15 @@ class Solution { * @return {boolean} */ isInterleave(s1, s2, s3) { - let m = s1.length, n = s2.length; + let m = s1.length, + n = s2.length; if (m + n !== s3.length) { return false; } const dp = Array.from({ length: m + 1 }, () => - Array(n + 1).fill(false)); + Array(n + 1).fill(false), + ); dp[m][n] = true; for (let i = m; i >= 0; i--) { @@ -756,8 +757,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the length of the string $s1$ and $n$ is the length of the string $s2$. @@ -776,7 +777,7 @@ class Solution: if n < m: s1, s2 = s2, s1 m, n = n, m - + dp = [False for _ in range(n + 1)] dp[n] = True for i in range(m, -1, -1): @@ -804,7 +805,7 @@ public class Solution { m = n; n = tempLength; } - + boolean[] dp = new boolean[n + 1]; dp[n] = true; for (int i = m; i >= 0; i--) { @@ -835,7 +836,7 @@ public: swap(s1, s2); swap(m, n); } - + vector dp(n + 1); dp[n] = true; for (int i = m; i >= 0; --i) { @@ -865,13 +866,14 @@ class Solution { * @return {boolean} */ isInterleave(s1, s2, s3) { - let m = s1.length, n = s2.length; + let m = s1.length, + n = s2.length; if (m + n !== s3.length) return false; if (n < m) { [s1, s2] = [s2, s1]; [m, n] = [n, m]; } - + let dp = Array(n + 1).fill(false); dp[n] = true; for (let i = m; i >= 0; i--) { @@ -905,7 +907,7 @@ public class Solution { m = n; n = tempLength; } - + bool[] dp = new bool[n + 1]; dp[n] = true; for (int i = m; i >= 0; i--) { @@ -1032,8 +1034,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(min(m, n))$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(min(m, n))$ > Where $m$ is the length of the string $s1$ and $n$ is the length of the string $s2$. @@ -1052,7 +1054,7 @@ class Solution: if n < m: s1, s2 = s2, s1 m, n = n, m - + dp = [False for _ in range(n + 1)] dp[n] = True for i in range(m, -1, -1): @@ -1144,7 +1146,8 @@ class Solution { * @return {boolean} */ isInterleave(s1, s2, s3) { - let m = s1.length, n = s2.length; + let m = s1.length, + n = s2.length; if (m + n !== s3.length) return false; if (n < m) { [s1, s2] = [s2, s1]; @@ -1316,7 +1319,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(min(m, n))$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(min(m, n))$ -> Where $m$ is the length of the string $s1$ and $n$ is the length of the string $s2$. \ No newline at end of file +> Where $m$ is the length of the string $s1$ and $n$ is the length of the string $s2$. diff --git a/articles/intersection-of-two-arrays.md b/articles/intersection-of-two-arrays.md index 5892704ec..33326dadb 100644 --- a/articles/intersection-of-two-arrays.md +++ b/articles/intersection-of-two-arrays.md @@ -80,8 +80,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n)$ > Where $n$ is the size of the array $nums1$ and $m$ is the size of the array $nums2$. @@ -109,7 +109,7 @@ class Solution: i += 1 while i < n and nums1[i] == nums1[i - 1]: i += 1 - + return res ``` @@ -184,7 +184,8 @@ class Solution { nums2.sort((a, b) => a - b); const res = []; - let i = 0, j = 0; + let i = 0, + j = 0; while (i < nums1.length && j < nums2.length) { while (j < nums2.length && nums2[j] < nums1[i]) { @@ -210,8 +211,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n + m \log m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n + m \log m)$ +- Space complexity: $O(n)$ > Where $n$ is the size of the array $nums1$ and $m$ is the size of the array $nums2$. @@ -303,8 +304,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n + m)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(n + m)$ > Where $n$ is the size of the array $nums1$ and $m$ is the size of the array $nums2$. @@ -320,7 +321,7 @@ class Solution: seen = defaultdict(int) for num in nums1: seen[num] = 1 - + res = [] for num in nums2: if seen[num] == 1: @@ -400,8 +401,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(n)$ > Where $n$ is the size of the array $nums1$ and $m$ is the size of the array $nums2$. @@ -489,8 +490,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(n)$ > Where $n$ is the size of the array $nums1$ and $m$ is the size of the array $nums2$. @@ -518,7 +519,7 @@ public class Solution { for (Integer n : nums2) { set2.add(n); } - + set1.retainAll(set2); int[] res= new int[set1.size()]; int idx = 0; @@ -551,7 +552,7 @@ class Solution { */ intersection(nums1, nums2) { const set2 = new Set(nums2); - return [...new Set(nums1)].filter(num => set2.has(num)); + return [...new Set(nums1)].filter((num) => set2.has(num)); } } ``` @@ -560,7 +561,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ in average case, $O(n * m)$ in worst case. -* Space complexity: $O(n + m)$ +- Time complexity: $O(n + m)$ in average case, $O(n * m)$ in worst case. +- Space complexity: $O(n + m)$ -> Where $n$ is the size of the array $nums1$ and $m$ is the size of the array $nums2$. \ No newline at end of file +> Where $n$ is the size of the array $nums1$ and $m$ is the size of the array $nums2$. diff --git a/articles/intersection-of-two-linked-lists.md b/articles/intersection-of-two-linked-lists.md index 855f2a43f..689323ad8 100644 --- a/articles/intersection-of-two-linked-lists.md +++ b/articles/intersection-of-two-linked-lists.md @@ -112,8 +112,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(m * n)$ +- Space complexity: $O(1)$ extra space. > Where $m$ is the length of the first list and $n$ is the length of the second list. @@ -136,13 +136,13 @@ class Solution: while cur: nodeSet.add(cur) cur = cur.next - + cur = headB while cur: if cur in nodeSet: return cur cur = cur.next - + return None ``` @@ -161,13 +161,13 @@ class Solution: public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { HashSet nodeSet = new HashSet<>(); - + ListNode cur = headA; while (cur != null) { nodeSet.add(cur); cur = cur.next; } - + cur = headB; while (cur != null) { if (nodeSet.contains(cur)) { @@ -175,7 +175,7 @@ public class Solution { } cur = cur.next; } - + return null; } } @@ -194,13 +194,13 @@ class Solution { public: ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) { unordered_set nodeSet; - + ListNode* cur = headA; while (cur) { nodeSet.insert(cur); cur = cur->next; } - + cur = headB; while (cur) { if (nodeSet.find(cur) != nodeSet.end()) { @@ -208,7 +208,7 @@ public: } cur = cur->next; } - + return nullptr; } }; @@ -232,13 +232,13 @@ class Solution { */ getIntersectionNode(headA, headB) { const nodeSet = new Set(); - + let cur = headA; while (cur) { nodeSet.add(cur); cur = cur.next; } - + cur = headB; while (cur) { if (nodeSet.has(cur)) { @@ -246,7 +246,7 @@ class Solution { } cur = cur.next; } - + return null; } } @@ -256,8 +256,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n)$ -* Space complexity: $O(m)$ +- Time complexity: $O(m + n)$ +- Space complexity: $O(m)$ > Where $m$ is the length of the first list and $n$ is the length of the second list. @@ -281,7 +281,7 @@ class Solution: length += 1 cur = cur.next return length - + m = getLength(headA) n = getLength(headB) l1, l2 = headA, headB @@ -289,15 +289,15 @@ class Solution: if m < n: m, n = n, m l1, l2 = headB, headA - + while m - n: m -= 1 l1 = l1.next - + while l1 != l2: l1 = l1.next l2 = l2.next - + return l1 ``` @@ -322,7 +322,7 @@ public class Solution { } return length; } - + public ListNode getIntersectionNode(ListNode headA, ListNode headB) { int m = getLength(headA); int n = getLength(headB); @@ -366,26 +366,26 @@ class Solution { } return length; } - + public: ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) { int m = getLength(headA), n = getLength(headB); ListNode* l1 = headA, *l2 = headB; - + if (m < n) { swap(m, n); swap(l1, l2); } - + while (m-- > n) { l1 = l1->next; } - + while (l1 && l1 != l2) { l1 = l1->next; l2 = l2->next; } - + return l1; } }; @@ -409,7 +409,8 @@ class Solution { */ getIntersectionNode(headA, headB) { const getLength = (head) => { - let length = 0, cur = head; + let length = 0, + cur = head; while (cur) { length++; cur = cur.next; @@ -419,7 +420,8 @@ class Solution { let m = getLength(headA); let n = getLength(headB); - let l1 = headA, l2 = headB; + let l1 = headA, + l2 = headB; if (m < n) { [m, n] = [n, m]; @@ -444,8 +446,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(m + n)$ +- Space complexity: $O(1)$ extra space. > Where $m$ is the length of the first list and $n$ is the length of the second list. @@ -534,7 +536,8 @@ class Solution { * @return {ListNode} */ getIntersectionNode(headA, headB) { - let l1 = headA, l2 = headB; + let l1 = headA, + l2 = headB; while (l1 !== l2) { l1 = l1 ? l1.next : headB; l2 = l2 ? l2.next : headA; @@ -548,7 +551,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(m + n)$ +- Space complexity: $O(1)$ extra space. -> Where $m$ is the length of the first list and $n$ is the length of the second list. \ No newline at end of file +> Where $m$ is the length of the first list and $n$ is the length of the second list. diff --git a/articles/invert-a-binary-tree.md b/articles/invert-a-binary-tree.md index 33ee15f84..25a529652 100644 --- a/articles/invert-a-binary-tree.md +++ b/articles/invert-a-binary-tree.md @@ -252,7 +252,7 @@ class Solution { while !queue.isEmpty { let node = queue.removeFirst() (node.left, node.right) = (node.right, node.left) - + if let left = node.left { queue.append(left) } @@ -269,12 +269,12 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- -## 2. Depth First Search +## 2. Depth First Search ::tabs-start @@ -452,7 +452,7 @@ func invertTree(root *TreeNode) *TreeNode { * var right: TreeNode? = null * } */ - + class Solution { fun invertTree(root: TreeNode?): TreeNode? { if (root == null) return null @@ -503,8 +503,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -737,7 +737,7 @@ class Solution { while !stack.isEmpty { let node = stack.removeLast() (node.left, node.right) = (node.right, node.left) - + if let left = node.left { stack.append(left) } @@ -754,5 +754,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/ipo.md b/articles/ipo.md index 87670000f..63fc51b1a 100644 --- a/articles/ipo.md +++ b/articles/ipo.md @@ -13,10 +13,10 @@ class Solution: while minCapital and minCapital[0][0] <= w: c, p = heapq.heappop(minCapital) heapq.heappush(maxProfit, -p) - + if not maxProfit: break - + w += -heapq.heappop(maxProfit) return w @@ -27,21 +27,21 @@ public class Solution { public int findMaximizedCapital(int k, int w, int[] profits, int[] capital) { PriorityQueue minCapital = new PriorityQueue<>((a, b) -> a[0] - b[0]); // Min heap PriorityQueue maxProfit = new PriorityQueue<>((a, b) -> b - a); // Max heap - + for (int i = 0; i < capital.length; i++) { minCapital.offer(new int[]{capital[i], profits[i]}); } - + for (int i = 0; i < k; i++) { while (!minCapital.isEmpty() && minCapital.peek()[0] <= w) { maxProfit.offer(minCapital.poll()[1]); } if (maxProfit.isEmpty()) { break; - } + } w += maxProfit.poll(); } - + return w; } } @@ -53,11 +53,11 @@ public: int findMaximizedCapital(int k, int w, vector& profits, vector& capital) { priority_queue maxProfit; // Max heap priority_queue, vector>, greater<>> minCapital; // Min heap - + for (int i = 0; i < capital.size(); i++) { minCapital.emplace(capital[i], profits[i]); } - + for (int i = 0; i < k; i++) { while (!minCapital.empty() && minCapital.top().first <= w) { maxProfit.push(minCapital.top().second); @@ -69,7 +69,7 @@ public: w += maxProfit.top(); maxProfit.pop(); } - + return w; } }; @@ -86,12 +86,12 @@ class Solution { */ findMaximizedCapital(k, w, profits, capital) { const minCapital = new PriorityQueue((a, b) => a[0] - b[0]); // Min heap - const maxProfit = new PriorityQueue((a, b) => b - a); // Max heap - + const maxProfit = new PriorityQueue((a, b) => b - a); // Max heap + for (let i = 0; i < capital.length; i++) { minCapital.enqueue([capital[i], profits[i]]); } - + for (let i = 0; i < k; i++) { while (!minCapital.isEmpty() && minCapital.front()[0] <= w) { maxProfit.enqueue(minCapital.dequeue()[1]); @@ -101,7 +101,7 @@ class Solution { } w += maxProfit.dequeue(); } - + return w; } } @@ -144,8 +144,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -159,7 +159,7 @@ class Solution: class Node: def __init__(self, idx): self.idx = idx - + def __lt__(self, other): if capital[self.idx] != capital[other.idx]: return capital[self.idx] < capital[other.idx] @@ -174,7 +174,7 @@ class Solution: while minCapital and capital[minCapital[0].idx] <= w: idx = heapq.heappop(minCapital).idx heapq.heappush(maxProfit, -profits[idx]) - + if not maxProfit: break w += -heapq.heappop(maxProfit) @@ -248,12 +248,8 @@ class Solution { * @return {number} */ findMaximizedCapital(k, w, profits, capital) { - const minCapital = new PriorityQueue( - (a, b) => capital[a] - capital[b], - ); - const maxProfit = new PriorityQueue( - (a, b) => profits[b] - profits[a], - ); + const minCapital = new PriorityQueue((a, b) => capital[a] - capital[b]); + const maxProfit = new PriorityQueue((a, b) => profits[b] - profits[a]); for (let i = 0; i < capital.length; i++) { minCapital.enqueue(i); @@ -306,8 +302,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -321,17 +317,17 @@ class Solution: n = len(profits) indices = list(range(n)) indices.sort(key=lambda i: capital[i]) - + maxProfit, idx = [], 0 for _ in range(k): while idx < n and capital[indices[idx]] <= w: heapq.heappush(maxProfit, -profits[indices[idx]]) idx += 1 - + if not maxProfit: break w += -heapq.heappop(maxProfit) - + return w ``` @@ -344,20 +340,20 @@ public class Solution { indices[i] = i; } Arrays.sort(indices, (a, b) -> Integer.compare(capital[a], capital[b])); - + PriorityQueue maxProfit = new PriorityQueue<>(Collections.reverseOrder()); int idx = 0; for (int i = 0; i < k; i++) { while (idx < n && capital[indices[idx]] <= w) { maxProfit.add(profits[indices[idx]]); idx++; - } + } if (maxProfit.isEmpty()) { break; } w += maxProfit.poll(); } - + return w; } } @@ -375,7 +371,7 @@ public: sort(indices.begin(), indices.end(), [&](int a, int b) { return capital[a] < capital[b]; }); - + priority_queue maxProfit; int idx = 0; for (int i = 0; i < k; i++) { @@ -385,7 +381,7 @@ public: } if (maxProfit.empty()) { break; - } + } w += maxProfit.top(); maxProfit.pop(); } @@ -408,7 +404,7 @@ class Solution { const n = profits.length; const indices = Array.from({ length: n }, (_, i) => i); indices.sort((a, b) => capital[a] - capital[b]); - + const maxProfit = new MaxPriorityQueue(); let idx = 0; for (let i = 0; i < k; i++) { @@ -421,7 +417,7 @@ class Solution { } w += maxProfit.dequeue(); } - + return w; } } @@ -463,5 +459,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ diff --git a/articles/is-anagram.md b/articles/is-anagram.md index eb996634a..9cef09353 100644 --- a/articles/is-anagram.md +++ b/articles/is-anagram.md @@ -7,7 +7,7 @@ class Solution: def isAnagram(self, s: str, t: str) -> bool: if len(s) != len(t): return False - + return sorted(s) == sorted(t) ``` @@ -54,9 +54,9 @@ class Solution { return false; } - let sSort = s.split("").sort().join(); - let tSort = t.split("").sort().join(); - return sSort == tSort + let sSort = s.split('').sort().join(); + let tSort = t.split('').sort().join(); + return sSort == tSort; } } ``` @@ -82,15 +82,15 @@ func isAnagram(s string, t string) bool { if len(s) != len(t) { return false } - + sRunes, tRunes := []rune(s), []rune(t) - sort.Slice(sRunes, func(i, j int) bool { - return sRunes[i] < sRunes[j] + sort.Slice(sRunes, func(i, j int) bool { + return sRunes[i] < sRunes[j] }) - sort.Slice(tRunes, func(i, j int) bool { - return tRunes[i] < tRunes[j] + sort.Slice(tRunes, func(i, j int) bool { + return tRunes[i] < tRunes[j] }) - + for i := range sRunes { if sRunes[i] != tRunes[i] { return false @@ -106,7 +106,7 @@ class Solution { if (s.length != t.length) { return false } - + return s.toCharArray().sorted() == t.toCharArray().sorted() } } @@ -124,10 +124,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n + m \log m)$ -* Space complexity: $O(1)$ or $O(n + m)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n + m \log m)$ +- Space complexity: $O(1)$ or $O(n + m)$ depending on the sorting algorithm. -> Where $n$ is the length of string $s$ and $m$ is the length of string $t$. +> Where $n$ is the length of string $s$ and $m$ is the length of string $t$. --- @@ -301,10 +301,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(1)$ since we have at most $26$ different characters. +- Time complexity: $O(n + m)$ +- Space complexity: $O(1)$ since we have at most $26$ different characters. -> Where $n$ is the length of string $s$ and $m$ is the length of string $t$. +> Where $n$ is the length of string $s$ and $m$ is the length of string $t$. --- @@ -393,7 +393,7 @@ class Solution { count[s.charCodeAt(i) - 'a'.charCodeAt(0)]++; count[t.charCodeAt(i) - 'a'.charCodeAt(0)]--; } - return count.every(val => val === 0); + return count.every((val) => val === 0); } } ``` @@ -495,7 +495,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(1)$ since we have at most $26$ different characters. +- Time complexity: $O(n + m)$ +- Space complexity: $O(1)$ since we have at most $26$ different characters. -> Where $n$ is the length of string $s$ and $m$ is the length of string $t$. \ No newline at end of file +> Where $n$ is the length of string $s$ and $m$ is the length of string $t$. diff --git a/articles/is-graph-bipartite.md b/articles/is-graph-bipartite.md index 2db1c9d94..1a441c806 100644 --- a/articles/is-graph-bipartite.md +++ b/articles/is-graph-bipartite.md @@ -123,8 +123,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V)$ > Where $V$ is the number of vertices and $E$ is the number of edges. @@ -256,8 +256,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V)$ > Where $V$ is the number of vertices and $E$ is the number of edges. @@ -381,8 +381,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V)$ > Where $V$ is the number of vertices and $E$ is the number of edges. @@ -487,7 +487,7 @@ class Solution { class DSU { private: vector Parent, Size; - + public: DSU(int n) { Parent.resize(n); @@ -566,7 +566,8 @@ class DSU { * @return {boolean} */ union(u, v) { - let pu = this.find(u), pv = this.find(v); + let pu = this.find(u), + pv = this.find(v); if (pu === pv) return false; if (this.size[pu] >= this.size[pv]) { this.size[pu] += this.size[pv]; @@ -605,7 +606,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + (E * α(V)))$ -* Space complexity: $O(V)$ +- Time complexity: $O(V + (E * α(V)))$ +- Space complexity: $O(V)$ -> Where $V$ is the number of vertices and $E$ is the number of edges. $α()$ is used for amortized complexity. \ No newline at end of file +> Where $V$ is the number of vertices and $E$ is the number of edges. $α()$ is used for amortized complexity. diff --git a/articles/is-palindrome.md b/articles/is-palindrome.md index 9aea0c833..76910a13a 100644 --- a/articles/is-palindrome.md +++ b/articles/is-palindrome.md @@ -49,9 +49,11 @@ class Solution { * @return {boolean} */ isAlphanumeric(char) { - return (char >= 'a' && char <= 'z') || - (char >= 'A' && char <= 'Z') || - (char >= '0' && char <= '9'); + return ( + (char >= 'a' && char <= 'z') || + (char >= 'A' && char <= 'Z') || + (char >= '0' && char <= '9') + ); } /** @@ -61,7 +63,7 @@ class Solution { isPalindrome(s) { let newStr = ''; for (let c of s) { - if (this.isAlphanumeric(c)) { + if (this.isAlphanumeric(c)) { newStr += c.toLowerCase(); } } @@ -143,8 +145,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -166,10 +168,10 @@ class Solution: return False l, r = l + 1, r - 1 return True - + def alphaNum(self, c): - return (ord('A') <= ord(c) <= ord('Z') or - ord('a') <= ord(c) <= ord('z') or + return (ord('A') <= ord(c) <= ord('Z') or + ord('a') <= ord(c) <= ord('z') or ord('0') <= ord(c) <= ord('9')) ``` @@ -194,8 +196,8 @@ public class Solution { } public boolean alphaNum(char c) { - return (c >= 'A' && c <= 'Z' || - c >= 'a' && c <= 'z' || + return (c >= 'A' && c <= 'Z' || + c >= 'a' && c <= 'z' || c >= '0' && c <= '9'); } } @@ -223,8 +225,8 @@ public: } bool alphaNum(char c) { - return (c >= 'A' && c <= 'Z' || - c >= 'a' && c <= 'z' || + return (c >= 'A' && c <= 'Z' || + c >= 'a' && c <= 'z' || c >= '0' && c <= '9'); } }; @@ -237,7 +239,8 @@ class Solution { * @return {boolean} */ isPalindrome(s) { - let l = 0, r = s.length - 1; + let l = 0, + r = s.length - 1; while (l < r) { while (l < r && !this.alphaNum(s[l])) { @@ -249,7 +252,8 @@ class Solution { if (s[l].toLowerCase() !== s[r].toLowerCase()) { return false; } - l++; r--; + l++; + r--; } return true; } @@ -259,9 +263,11 @@ class Solution { * @return {boolean} */ alphaNum(c) { - return (c >= 'A' && c <= 'Z' || - c >= 'a' && c <= 'z' || - c >= '0' && c <= '9'); + return ( + (c >= 'A' && c <= 'Z') || + (c >= 'a' && c <= 'z') || + (c >= '0' && c <= '9') + ); } } ``` @@ -287,8 +293,8 @@ public class Solution { } public bool AlphaNum(char c) { - return (c >= 'A' && c <= 'Z' || - c >= 'a' && c <= 'z' || + return (c >= 'A' && c <= 'Z' || + c >= 'a' && c <= 'z' || c >= '0' && c <= '9'); } } @@ -375,5 +381,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/is-subsequence.md b/articles/is-subsequence.md index fde7628a6..84927a6c9 100644 --- a/articles/is-subsequence.md +++ b/articles/is-subsequence.md @@ -10,7 +10,7 @@ class Solution: return True if j == len(t): return False - + if s[i] == t[j]: return rec(i + 1, j + 1) return rec(i, j + 1) @@ -76,8 +76,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n)$ > Where $n$ is the length of the string $s$ and $m$ is the length of the string $t$. @@ -166,7 +166,8 @@ class Solution { * @return {boolean} */ isSubsequence(s, t) { - const n = s.length, m = t.length; + const n = s.length, + m = t.length; const memo = Array.from({ length: n }, () => Array(m).fill(-1)); const rec = (i, j) => { @@ -190,8 +191,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n * m)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n * m)$ > Where $n$ is the length of the string $s$ and $m$ is the length of the string $t$. @@ -206,17 +207,17 @@ class Solution: def isSubsequence(self, s: str, t: str) -> bool: n, m = len(s), len(t) dp = [[False] * (m + 1) for _ in range(n + 1)] - + for j in range(m + 1): dp[n][j] = True - + for i in range(n - 1, -1, -1): for j in range(m - 1, -1, -1): if s[i] == t[j]: dp[i][j] = dp[i + 1][j + 1] else: dp[i][j] = dp[i][j + 1] - + return dp[0][0] ``` @@ -225,11 +226,11 @@ public class Solution { public boolean isSubsequence(String s, String t) { int n = s.length(), m = t.length(); boolean[][] dp = new boolean[n + 1][m + 1]; - + for (int j = 0; j <= m; j++) { dp[n][j] = true; } - + for (int i = n - 1; i >= 0; i--) { for (int j = m - 1; j >= 0; j--) { if (s.charAt(i) == t.charAt(j)) { @@ -239,7 +240,7 @@ public class Solution { } } } - + return dp[0][0]; } } @@ -251,11 +252,11 @@ public: bool isSubsequence(string s, string t) { int n = s.size(), m = t.size(); vector> dp(n + 1, vector(m + 1, false)); - + for (int j = 0; j <= m; ++j) { dp[n][j] = true; } - + for (int i = n - 1; i >= 0; --i) { for (int j = m - 1; j >= 0; --j) { if (s[i] == t[j]) { @@ -265,7 +266,7 @@ public: } } } - + return dp[0][0]; } }; @@ -279,13 +280,16 @@ class Solution { * @return {boolean} */ isSubsequence(s, t) { - const n = s.length, m = t.length; - const dp = Array.from({ length: n + 1 }, () => Array(m + 1).fill(false)); - + const n = s.length, + m = t.length; + const dp = Array.from({ length: n + 1 }, () => + Array(m + 1).fill(false), + ); + for (let j = 0; j <= m; j++) { dp[n][j] = true; } - + for (let i = n - 1; i >= 0; i--) { for (let j = m - 1; j >= 0; j--) { if (s[i] === t[j]) { @@ -295,7 +299,7 @@ class Solution { } } } - + return dp[0][0]; } } @@ -305,8 +309,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n * m)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n * m)$ > Where $n$ is the length of the string $s$ and $m$ is the length of the string $t$. @@ -366,7 +370,8 @@ class Solution { * @return {boolean} */ isSubsequence(s, t) { - let i = 0, j = 0; + let i = 0, + j = 0; while (i < s.length && j < t.length) { if (s.charAt(i) == t.charAt(j)) { i++; @@ -382,8 +387,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(1)$ > Where $n$ is the length of the string $s$ and $m$ is the length of the string $t$. @@ -397,21 +402,21 @@ class Solution: n, m = len(s), len(t) if m == 0: return n == 0 - + store = [[m + 1] * 26 for _ in range(m)] store[m - 1][ord(t[m - 1]) - ord('a')] = m - 1 - + for i in range(m - 2, -1, -1): store[i] = store[i + 1][:] store[i][ord(t[i]) - ord('a')] = i - + i, j = 0, 0 while i < n and j < m: j = store[j][ord(s[i]) - ord('a')] + 1 if j > m: return False i += 1 - + return i == n ``` @@ -439,7 +444,7 @@ public class Solution { if (j > m) return false; i++; } - + return i == n; } } @@ -454,7 +459,7 @@ public: vector> store(m, vector(26, m + 1)); store[m - 1][t[m - 1] - 'a'] = m - 1; - + for (int i = m - 2; i >= 0; i--) { store[i] = store[i + 1]; store[i][t[i] - 'a'] = i; @@ -480,7 +485,8 @@ class Solution { * @return {boolean} */ isSubsequence(s, t) { - const n = s.length, m = t.length; + const n = s.length, + m = t.length; if (m === 0) return n === 0; const store = Array.from({ length: m }, () => Array(26).fill(m + 1)); @@ -491,7 +497,8 @@ class Solution { store[i][t.charCodeAt(i) - 'a'.charCodeAt(0)] = i; } - let i = 0, j = 0; + let i = 0, + j = 0; while (i < n && j < m) { j = store[j][s.charCodeAt(i) - 'a'.charCodeAt(0)] + 1; if (j > m) return false; @@ -507,7 +514,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(m)$ -> Where $n$ is the length of the string $s$ and $m$ is the length of the string $t$. \ No newline at end of file +> Where $n$ is the length of the string $s$ and $m$ is the length of the string $t$. diff --git a/articles/island-perimeter.md b/articles/island-perimeter.md index bb87939fe..5a29dba4a 100644 --- a/articles/island-perimeter.md +++ b/articles/island-perimeter.md @@ -13,11 +13,11 @@ class Solution: return 1 if (i, j) in visit: return 0 - + visit.add((i, j)) perim = dfs(i, j + 1) + dfs(i + 1, j) + dfs(i, j - 1) + dfs(i - 1, j) return perim - + for i in range(rows): for j in range(cols): if grid[i][j]: @@ -48,7 +48,7 @@ public class Solution { } private int dfs(int i, int j) { - if (i < 0 || j < 0 || i >= rows || + if (i < 0 || j < 0 || i >= rows || j >= cols || grid[i][j] == 0) { return 1; } @@ -57,7 +57,7 @@ public class Solution { } visited[i][j] = true; - return dfs(i, j + 1) + dfs(i + 1, j) + + return dfs(i, j + 1) + dfs(i + 1, j) + dfs(i, j - 1) + dfs(i - 1, j); } } @@ -71,7 +71,7 @@ private: int rows, cols; int dfs(int i, int j) { - if (i < 0 || j < 0 || i >= rows || + if (i < 0 || j < 0 || i >= rows || j >= cols || grid[i][j] == 0) { return 1; } @@ -80,7 +80,7 @@ private: } visited[i][j] = true; - return dfs(i, j + 1) + dfs(i + 1, j) + + return dfs(i, j + 1) + dfs(i + 1, j) + dfs(i, j - 1) + dfs(i - 1, j); } @@ -110,8 +110,11 @@ class Solution { * @return {number} */ islandPerimeter(grid) { - const rows = grid.length, cols = grid[0].length; - const visited = Array.from({ length: rows }, () => Array(cols).fill(false)); + const rows = grid.length, + cols = grid[0].length; + const visited = Array.from({ length: rows }, () => + Array(cols).fill(false), + ); const dfs = (i, j) => { if (i < 0 || j < 0 || i >= rows || j >= cols || grid[i][j] === 0) { @@ -122,8 +125,9 @@ class Solution { } visited[i][j] = true; - return dfs(i, j + 1) + dfs(i + 1, j) + - dfs(i, j - 1) + dfs(i - 1, j); + return ( + dfs(i, j + 1) + dfs(i + 1, j) + dfs(i, j - 1) + dfs(i - 1, j) + ); }; for (let i = 0; i < rows; i++) { @@ -178,8 +182,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns in the grid. @@ -195,17 +199,17 @@ class Solution: rows, cols = len(grid), len(grid[0]) visited = set() directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] - + def bfs(r, c): queue = deque([(r, c)]) visited.add((r, c)) perimeter = 0 - + while queue: x, y = queue.popleft() for dx, dy in directions: nx, ny = x + dx, y + dy - if (nx < 0 or ny < 0 or nx >= rows or + if (nx < 0 or ny < 0 or nx >= rows or ny >= cols or grid[nx][ny] == 0 ): perimeter += 1 @@ -213,7 +217,7 @@ class Solution: visited.add((nx, ny)) queue.append((nx, ny)) return perimeter - + for i in range(rows): for j in range(cols): if grid[i][j] == 1: @@ -227,7 +231,7 @@ public class Solution { int rows = grid.length, cols = grid[0].length; boolean[][] visited = new boolean[rows][cols]; int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; - + for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (grid[i][j] == 1) { @@ -235,14 +239,14 @@ public class Solution { queue.offer(new int[]{i, j}); visited[i][j] = true; int perimeter = 0; - + while (!queue.isEmpty()) { int[] cell = queue.poll(); int x = cell[0], y = cell[1]; - + for (int[] dir : directions) { int nx = x + dir[0], ny = y + dir[1]; - if (nx < 0 || ny < 0 || nx >= rows || + if (nx < 0 || ny < 0 || nx >= rows || ny >= cols || grid[nx][ny] == 0) { perimeter++; } else if (!visited[nx][ny]) { @@ -282,7 +286,7 @@ public: for (auto& dir : directions) { int nx = x + dir[0], ny = y + dir[1]; - if (nx < 0 || ny < 0 || nx >= rows || + if (nx < 0 || ny < 0 || nx >= rows || ny >= cols || grid[nx][ny] == 0) { perimeter++; } else if (!visited[nx][ny]) { @@ -307,10 +311,18 @@ class Solution { * @return {number} */ islandPerimeter(grid) { - const rows = grid.length, cols = grid[0].length; - const visited = Array.from({ length: rows }, () => Array(cols).fill(false)); - const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; - + const rows = grid.length, + cols = grid[0].length; + const visited = Array.from({ length: rows }, () => + Array(cols).fill(false), + ); + const directions = [ + [0, 1], + [1, 0], + [0, -1], + [-1, 0], + ]; + const bfs = (r, c) => { const queue = new Queue([[r, c]]); visited[r][c] = true; @@ -319,10 +331,16 @@ class Solution { const [x, y] = queue.pop(); for (const [dx, dy] of directions) { - const nx = x + dx, ny = y + dy; - - if (nx < 0 || ny < 0 || nx >= rows || - ny >= cols || grid[nx][ny] === 0) { + const nx = x + dx, + ny = y + dy; + + if ( + nx < 0 || + ny < 0 || + nx >= rows || + ny >= cols || + grid[nx][ny] === 0 + ) { perimeter++; } else if (!visited[nx][ny]) { visited[nx][ny] = true; @@ -399,8 +417,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns in the grid. @@ -470,15 +488,16 @@ class Solution { * @return {number} */ islandPerimeter(grid) { - const m = grid.length, n = grid[0].length; + const m = grid.length, + n = grid[0].length; let res = 0; for (let i = 0; i < m; i++) { for (let j = 0; j < n; j++) { if (grid[i][j] === 1) { - res += (i + 1 >= m || grid[i + 1][j] === 0) ? 1 : 0; - res += (j + 1 >= n || grid[i][j + 1] === 0) ? 1 : 0; - res += (i - 1 < 0 || grid[i - 1][j] === 0) ? 1 : 0; - res += (j - 1 < 0 || grid[i][j - 1] === 0) ? 1 : 0; + res += i + 1 >= m || grid[i + 1][j] === 0 ? 1 : 0; + res += j + 1 >= n || grid[i][j + 1] === 0 ? 1 : 0; + res += i - 1 < 0 || grid[i - 1][j] === 0 ? 1 : 0; + res += j - 1 < 0 || grid[i][j - 1] === 0 ? 1 : 0; } } } @@ -514,8 +533,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(m * n)$ +- Space complexity: $O(1)$ extra space. > Where $m$ is the number of rows and $n$ is the number of columns in the grid. @@ -595,7 +614,8 @@ class Solution { * @return {number} */ islandPerimeter(grid) { - const m = grid.length, n = grid[0].length; + const m = grid.length, + n = grid[0].length; let res = 0; for (let r = 0; r < m; r++) { for (let c = 0; c < n; c++) { @@ -645,7 +665,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(m * n)$ +- Space complexity: $O(1)$ extra space. -> Where $m$ is the number of rows and $n$ is the number of columns in the grid. \ No newline at end of file +> Where $m$ is the number of rows and $n$ is the number of columns in the grid. diff --git a/articles/islands-and-treasure.md b/articles/islands-and-treasure.md index 86e92192f..2e4ad2806 100644 --- a/articles/islands-and-treasure.md +++ b/articles/islands-and-treasure.md @@ -33,14 +33,14 @@ class Solution: ```java public class Solution { - private int[][] directions = {{1, 0}, {-1, 0}, + private int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; private int INF = 2147483647; private boolean[][] visit; private int ROWS, COLS; private int dfs(int[][] grid, int r, int c) { - if (r < 0 || c < 0 || r >= ROWS || + if (r < 0 || c < 0 || r >= ROWS || c >= COLS || grid[r][c] == -1 || visit[r][c]) { return INF; } @@ -78,14 +78,14 @@ public class Solution { ```cpp class Solution { public: - vector> directions = {{1, 0}, {-1, 0}, + vector> directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; int INF = 2147483647; vector> visit; int ROWS, COLS; int dfs(vector>& grid, int r, int c) { - if (r < 0 || c < 0 || r >= ROWS || + if (r < 0 || c < 0 || r >= ROWS || c >= COLS || grid[r][c] == -1 || visit[r][c]) { return INF; } @@ -129,14 +129,24 @@ class Solution { islandsAndTreasure(grid) { let ROWS = grid.length; let COLS = grid[0].length; - const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; + const directions = [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + ]; const INF = 2147483647; - let visit = Array.from({ length: ROWS }, () => - Array(COLS).fill(false)); + let visit = Array.from({ length: ROWS }, () => Array(COLS).fill(false)); const dfs = (r, c) => { - if (r < 0 || c < 0 || r >= ROWS || - c >= COLS || grid[r][c] === -1 || visit[r][c]) { + if ( + r < 0 || + c < 0 || + r >= ROWS || + c >= COLS || + grid[r][c] === -1 || + visit[r][c] + ) { return INF; } if (grid[r][c] === 0) { @@ -165,7 +175,7 @@ class Solution { ```csharp public class Solution { private int[][] directions = new int[][] { - new int[] {1, 0}, new int[] {-1, 0}, + new int[] {1, 0}, new int[] {-1, 0}, new int[] {0, 1}, new int[] {0, -1} }; private int INF = 2147483647; @@ -173,7 +183,7 @@ public class Solution { private int ROWS, COLS; private int Dfs(int[][] grid, int r, int c) { - if (r < 0 || c < 0 || r >= ROWS || + if (r < 0 || c < 0 || r >= ROWS || c >= COLS || grid[r][c] == -1 || visit[r, c]) { return INF; } @@ -220,7 +230,7 @@ func islandsAndTreasure(grid [][]int) { var dfs func(r, c int) int dfs = func(r, c int) int { - if r < 0 || c < 0 || r >= rows || c >= cols || + if r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] == -1 || visit[r][c] { return INF } @@ -267,7 +277,7 @@ class Solution { private var cols = 0 private fun dfs(grid: Array, r: Int, c: Int): Int { - if (r < 0 || c < 0 || r >= rows || c >= cols || + if (r < 0 || c < 0 || r >= rows || c >= cols || grid[r][c] == -1 || visit[r][c]) { return INF } @@ -310,7 +320,7 @@ class Solution { let INF = 2147483647 let directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] var visit = Array(repeating: Array(repeating: false, count: COLS), count: ROWS) - + func dfs(_ r: Int, _ c: Int) -> Int { if r < 0 || c < 0 || r >= ROWS || c >= COLS || grid[r][c] == -1 || visit[r][c] { return INF @@ -318,7 +328,7 @@ class Solution { if grid[r][c] == 0 { return 0 } - + visit[r][c] = true var res = INF for (dx, dy) in directions { @@ -327,7 +337,7 @@ class Solution { visit[r][c] = false return res } - + for r in 0.. Where $m$ is the number of rows and $n$ is the number of columns in the $grid$. @@ -373,7 +383,7 @@ class Solution: return steps for dr, dc in directions: nr, nc = row + dr, col + dc - if (0 <= nr < ROWS and 0 <= nc < COLS and + if (0 <= nr < ROWS and 0 <= nc < COLS and not visit[nr][nc] and grid[nr][nc] != -1 ): visit[nr][nc] = True @@ -389,7 +399,7 @@ class Solution: ```java public class Solution { - private int[][] directions = {{1, 0}, {-1, 0}, + private int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; private int INF = 2147483647; private int ROWS, COLS; @@ -409,7 +419,7 @@ public class Solution { if (grid[row][col] == 0) return steps; for (int[] dir : directions) { int nr = row + dir[0], nc = col + dir[1]; - if (nr >= 0 && nr < ROWS && nc >= 0 && nc < COLS && + if (nr >= 0 && nr < ROWS && nc >= 0 && nc < COLS && !visit[nr][nc] && grid[nr][nc] != -1) { visit[nr][nc] = true; q.add(new int[]{nr, nc}); @@ -440,7 +450,7 @@ public class Solution { class Solution { public: int ROWS, COLS; - vector> directions = {{1, 0}, {-1, 0}, + vector> directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; int INF = INT_MAX; @@ -459,7 +469,7 @@ public: if (grid[row][col] == 0) return steps; for (auto& dir : directions) { int nr = row + dir[0], nc = col + dir[1]; - if (nr >= 0 && nr < ROWS && nc >= 0 && nc < COLS && + if (nr >= 0 && nr < ROWS && nc >= 0 && nc < COLS && !visit[nr][nc] && grid[nr][nc] != -1) { visit[nr][nc] = true; q.push({nr, nc}); @@ -495,15 +505,20 @@ class Solution { islandsAndTreasure(grid) { let ROWS = grid.length; let COLS = grid[0].length; - const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; + const directions = [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + ]; const INF = 2147483647; - let visit = Array.from({ length: ROWS }, () => - Array(COLS).fill(false)); + let visit = Array.from({ length: ROWS }, () => Array(COLS).fill(false)); const bfs = (r, c) => { const q = new Queue([[r, c]]); - const visit = Array.from({ length: ROWS }, () => - Array(COLS).fill(false)); + const visit = Array.from({ length: ROWS }, () => + Array(COLS).fill(false), + ); visit[r][c] = true; let steps = 0; @@ -513,9 +528,16 @@ class Solution { const [row, col] = q.pop(); if (grid[row][col] === 0) return steps; for (let [dr, dc] of directions) { - const nr = row + dr, nc = col + dc; - if (nr >= 0 && nr < ROWS && nc >= 0 && nc < COLS && - !visit[nr][nc] && grid[nr][nc] !== -1) { + const nr = row + dr, + nc = col + dc; + if ( + nr >= 0 && + nr < ROWS && + nc >= 0 && + nc < COLS && + !visit[nr][nc] && + grid[nr][nc] !== -1 + ) { visit[nr][nc] = true; q.push([nr, nc]); } @@ -562,7 +584,7 @@ public class Solution { if (grid[row][col] == 0) return steps; foreach (var dir in directions) { int nr = row + dir[0], nc = col + dir[1]; - if (nr >= 0 && nr < ROWS && nc >= 0 && nc < COLS && + if (nr >= 0 && nr < ROWS && nc >= 0 && nc < COLS && !visit[nr][nc] && grid[nr][nc] != -1) { visit[nr][nc] = true; q.Enqueue(new int[] { nr, nc }); @@ -615,7 +637,7 @@ func islandsAndTreasure(grid [][]int) { } for _, dir := range directions { nr, nc := row+dir[0], col+dir[1] - if nr >= 0 && nc >= 0 && nr < rows && nc < cols && + if nr >= 0 && nc >= 0 && nr < rows && nc < cols && !visit[nr][nc] && grid[nr][nc] != -1 { visit[nr][nc] = true q = append(q, [2]int{nr, nc}) @@ -640,7 +662,7 @@ func islandsAndTreasure(grid [][]int) { ```kotlin class Solution { private val directions = arrayOf( - intArrayOf(1, 0), intArrayOf(-1, 0), + intArrayOf(1, 0), intArrayOf(-1, 0), intArrayOf(0, 1), intArrayOf(0, -1) ) private val INF = 2147483647 @@ -665,7 +687,7 @@ class Solution { for (dir in directions) { val nr = row + dir[0] val nc = col + dir[1] - if (nr in 0 until rows && nc in 0 until cols && + if (nr in 0 until rows && nc in 0 until cols && !visit[nr][nc] && grid[nr][nc] != -1) { visit[nr][nc] = true q.add(Pair(nr, nc)) @@ -695,7 +717,7 @@ class Solution { let COLS = grid[0].count let directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] let INF = 2147483647 - + func bfs(_ r: Int, _ c: Int) -> Int { var q = Deque<(Int, Int)>() q.append((r, c)) @@ -722,7 +744,7 @@ class Solution { } return INF } - + for r in 0.. Where $m$ is the number of rows and $n$ is the number of columns in the $grid$. @@ -797,7 +819,7 @@ public class Solution { } if (q.size() == 0) return; - int[][] dirs = { { -1, 0 }, { 0, -1 }, + int[][] dirs = { { -1, 0 }, { 0, -1 }, { 1, 0 }, { 0, 1 } }; while (!q.isEmpty()) { int[] node = q.poll(); @@ -825,7 +847,7 @@ public: void islandsAndTreasure(vector>& grid) { int m = grid.size(); int n = grid[0].size(); - + queue> q; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { @@ -834,23 +856,23 @@ public: } } } - - vector> dirs = {{-1, 0}, {1, 0}, + + vector> dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; while (!q.empty()) { int row = q.front().first; int col = q.front().second; q.pop(); - + for (int i = 0; i < 4; i++) { int r = row + dirs[i][0]; int c = col + dirs[i][1]; - - if (r < 0 || r >= m || c < 0 || + + if (r < 0 || r >= m || c < 0 || c >= n || grid[r][c] != INT_MAX) { continue; } - + grid[r][c] = grid[row][col] + 1; q.push({r, c}); } @@ -875,8 +897,12 @@ class Solution { * @param {number} c */ function addCell(r, c) { - if (Math.min(r, c) < 0 || r === ROWS || c === COLS || - visit.has(r + ',' + c) || grid[r][c] === -1 + if ( + Math.min(r, c) < 0 || + r === ROWS || + c === COLS || + visit.has(r + ',' + c) || + grid[r][c] === -1 ) { return; } @@ -922,10 +948,10 @@ public class Solution { } if (q.Count == 0) return; - - int[][] dirs = { - new int[] { -1, 0 }, new int[] { 0, -1 }, - new int[] { 1, 0 }, new int[] { 0, 1 } + + int[][] dirs = { + new int[] { -1, 0 }, new int[] { 0, -1 }, + new int[] { 1, 0 }, new int[] { 0, 1 } }; while (q.Count > 0) { int[] cur = q.Dequeue(); @@ -936,7 +962,7 @@ public class Solution { int c = col + dir[1]; if (r >= m || c >= n || r < 0 || c < 0 || grid[r][c] != int.MaxValue) { - continue; + continue; } q.Enqueue(new int[] { r, c }); @@ -972,7 +998,7 @@ func islandsAndTreasure(grid [][]int) { for _, dir := range dirs { r, c := row+dir[0], col+dir[1] - if r >= m || c >= n || r < 0 || c < 0 || + if r >= m || c >= n || r < 0 || c < 0 || grid[r][c] != 2147483647 { continue } @@ -1000,7 +1026,7 @@ class Solution { if (q.isEmpty()) return val dirs = arrayOf( - intArrayOf(-1, 0), intArrayOf(0, -1), + intArrayOf(-1, 0), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(0, 1) ) @@ -1009,7 +1035,7 @@ class Solution { for (dir in dirs) { val r = row + dir[0] val c = col + dir[1] - if (r !in 0 until m || c !in 0 until n || + if (r !in 0 until m || c !in 0 until n || grid[r][c] != Int.MAX_VALUE) { continue } @@ -1033,7 +1059,7 @@ class Solution { let COLS = grid[0].count var visit = Set() var q = Deque() - + func addCell(_ r: Int, _ c: Int) { if r < 0 || c < 0 || r >= ROWS || c >= COLS { return } let item = Item(r: r, c: c) @@ -1041,7 +1067,7 @@ class Solution { visit.insert(item) q.append(item) } - + for r in 0.. Where $m$ is the number of rows and $n$ is the number of columns in the $grid$. \ No newline at end of file +> Where $m$ is the number of rows and $n$ is the number of columns in the $grid$. diff --git a/articles/isomorphic-strings.md b/articles/isomorphic-strings.md index afbaa6c10..b65759396 100644 --- a/articles/isomorphic-strings.md +++ b/articles/isomorphic-strings.md @@ -91,8 +91,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n)$ +- Space complexity: $O(m)$ > Where $n$ is the length of the input string and $m$ is the number of unique characters in the strings. @@ -114,7 +114,7 @@ class Solution: return False mapST[c1] = c2 mapTS[c2] = c1 - + return True ``` @@ -135,7 +135,7 @@ public class Solution { mapST.put(c1, c2); mapTS.put(c2, c1); } - + return true; } } @@ -158,7 +158,7 @@ public: mapST[c1] = c2; mapTS[c2] = c1; } - + return true; } }; @@ -175,10 +175,13 @@ class Solution { const mapTS = new Map(); for (let i = 0; i < s.length; i++) { - const c1 = s[i], c2 = t[i]; + const c1 = s[i], + c2 = t[i]; - if ((mapST.has(c1) && mapST.get(c1) !== c2) || - (mapTS.has(c2) && mapTS.get(c2) !== c1)) { + if ( + (mapST.has(c1) && mapST.get(c1) !== c2) || + (mapTS.has(c2) && mapTS.get(c2) !== c1) + ) { return false; } @@ -195,7 +198,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n)$ +- Space complexity: $O(m)$ -> Where $n$ is the length of the input string and $m$ is the number of unique characters in the strings. \ No newline at end of file +> Where $n$ is the length of the input string and $m$ is the number of unique characters in the strings. diff --git a/articles/jump-game-ii.md b/articles/jump-game-ii.md index db4a1b445..2a9738d34 100644 --- a/articles/jump-game-ii.md +++ b/articles/jump-game-ii.md @@ -88,7 +88,7 @@ class Solution { res = Math.min(res, 1 + dfs(j)); } return res; - } + }; return dfs(0); } @@ -185,7 +185,7 @@ class Solution { return res } - + return dfs(0) } } @@ -195,8 +195,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n!)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n!)$ +- Space complexity: $O(n)$ --- @@ -216,7 +216,7 @@ class Solution: return 0 if nums[i] == 0: return 1000000 - + res = 1000000 end = min(len(nums), i + nums[i] + 1) for j in range(i + 1, end): @@ -244,7 +244,7 @@ public class Solution { if (nums[i] == 0) { return 1000000; } - + int res = 1000000; int end = Math.min(nums.length, i + nums[i] + 1); for (int j = i + 1; j < end; j++) { @@ -275,7 +275,7 @@ private: if (nums[i] == 0) { return 1000000; } - + int res = 1000000; int end = min((int)nums.size(), i + nums[i] + 1); for (int j = i + 1; j < end; j++) { @@ -312,7 +312,7 @@ class Solution { } memo.set(i, res); return res; - } + }; return dfs(0); } @@ -336,7 +336,7 @@ public class Solution { if (nums[i] == 0) { return 1000000; } - + int res = 1000000; int end = Math.Min(nums.Length, i + nums[i] + 1); for (int j = i + 1; j < end; j++) { @@ -446,8 +446,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -615,8 +615,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -686,7 +686,9 @@ class Solution { * @return {number} */ jump(nums) { - let res = 0, l = 0, r = 0; + let res = 0, + l = 0, + r = 0; while (r < nums.length - 1) { let farthest = 0; @@ -795,5 +797,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/jump-game-vii.md b/articles/jump-game-vii.md index c11c1c9dc..b034aa727 100644 --- a/articles/jump-game-vii.md +++ b/articles/jump-game-vii.md @@ -168,8 +168,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n)$ > Where $n$ is the length of the string $s$ and $m$ is the given range of the jump $(maxJump - minJump + 1)$. @@ -184,7 +184,7 @@ class Solution: def canReach(self, s: str, minJump: int, maxJump: int) -> bool: q = deque([0]) farthest = 0 - + while q: i = q.popleft() start = max(i + minJump, farthest + 1) @@ -194,7 +194,7 @@ class Solution: if j == len(s) - 1: return True farthest = i + maxJump - + return False ``` @@ -220,7 +220,7 @@ public class Solution { } farthest = i + maxJump; } - + return false; } } @@ -250,7 +250,7 @@ public: } farthest = i + maxJump; } - + return false; } }; @@ -318,8 +318,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -333,7 +333,7 @@ class Solution: n = len(s) if s[n - 1] == '1': return False - + dp = [False] * n dp[0] = True cnt = 0 @@ -344,7 +344,7 @@ class Solution: cnt -= 1 if cnt > 0 and s[i] == '0': dp[i] = True - + return dp[n - 1] ``` @@ -475,8 +475,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -490,7 +490,7 @@ class Solution: n = len(s) if s[n - 1] == '1': return False - + dp = [False] * n dp[0] = True j = 0 @@ -503,7 +503,7 @@ class Solution: if s[j] == '0': dp[j] = True j += 1 - + return dp[n - 1] ``` @@ -637,5 +637,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/jump-game.md b/articles/jump-game.md index c5048055e..7ed6d6111 100644 --- a/articles/jump-game.md +++ b/articles/jump-game.md @@ -22,7 +22,7 @@ public class Solution { public boolean canJump(int[] nums) { return dfs(nums, 0); } - + private boolean dfs(int[] nums, int i) { if (i == nums.length - 1) { return true; @@ -79,7 +79,7 @@ class Solution { } } return false; - } + }; return dfs(0); } @@ -114,7 +114,7 @@ func canJump(nums []int) bool { if i == len(nums)-1 { return true } - + end := min(len(nums)-1, i+nums[i]) for j := i + 1; j <= end; j++ { if dfs(j) { @@ -123,7 +123,7 @@ func canJump(nums []int) bool { } return false } - + return dfs(0) } @@ -142,7 +142,7 @@ class Solution { if (i == nums.size - 1) { return true } - + val end = minOf(nums.size - 1, i + nums[i]) for (j in (i + 1)..end) { if (dfs(j)) { @@ -151,7 +151,7 @@ class Solution { } return false } - + return dfs(0) } } @@ -184,8 +184,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n!)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n!)$ +- Space complexity: $O(n)$ --- @@ -205,7 +205,7 @@ class Solution: return True if nums[i] == 0: return False - + end = min(len(nums), i + nums[i] + 1) for j in range(i + 1, end): if dfs(j): @@ -234,7 +234,7 @@ public class Solution { if (nums[i] == 0) { return false; } - + int end = Math.min(nums.length, i + nums[i] + 1); for (int j = i + 1; j < end; j++) { if (dfs(nums, j, memo)) { @@ -267,7 +267,7 @@ private: if (nums[i] == 0) { return false; } - + int end = min((int)nums.size(), i + nums[i] + 1); for (int j = i + 1; j < end; j++) { if (dfs(nums, j, memo)) { @@ -308,7 +308,7 @@ class Solution { } memo.set(i, false); return false; - } + }; return dfs(0); } @@ -332,7 +332,7 @@ public class Solution { if (nums[i] == 0) { return false; } - + int end = Math.Min(nums.Length, i + nums[i] + 1); for (int j = i + 1; j < end; j++) { if (Dfs(nums, j, memo)) { @@ -349,13 +349,13 @@ public class Solution { ```go func canJump(nums []int) bool { memo := make(map[int]bool) - + var dfs func(i int) bool dfs = func(i int) bool { if result, exists := memo[i]; exists { return result } - + if i == len(nums)-1 { return true } @@ -363,7 +363,7 @@ func canJump(nums []int) bool { memo[i] = false return false } - + end := min(len(nums), i+nums[i]+1) for j := i + 1; j < end; j++ { if dfs(j) { @@ -371,11 +371,11 @@ func canJump(nums []int) bool { return true } } - + memo[i] = false return false } - + return dfs(0) } @@ -391,10 +391,10 @@ func min(a, b int) int { class Solution { fun canJump(nums: IntArray): Boolean { val memo = HashMap() - + fun dfs(i: Int): Boolean { memo[i]?.let { return it } - + if (i == nums.size - 1) { return true } @@ -402,7 +402,7 @@ class Solution { memo[i] = false return false } - + val end = minOf(nums.size, i + nums[i] + 1) for (j in (i + 1) until end) { if (dfs(j)) { @@ -410,11 +410,11 @@ class Solution { return true } } - + memo[i] = false return false } - + return dfs(0) } } @@ -457,8 +457,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -576,7 +576,7 @@ func canJump(nums []int) bool { n := len(nums) dp := make([]bool, n) dp[n-1] = true - + for i := n - 2; i >= 0; i-- { end := min(n, i + nums[i] + 1) for j := i + 1; j < end; j++ { @@ -603,7 +603,7 @@ class Solution { val n = nums.size val dp = BooleanArray(n) dp[n - 1] = true - + for (i in n - 2 downTo 0) { val end = minOf(n, i + nums[i] + 1) for (j in i + 1 until end) { @@ -643,8 +643,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -735,7 +735,7 @@ public class Solution { ```go func canJump(nums []int) bool { goal := len(nums) - 1 - + for i := len(nums) - 2; i >= 0; i-- { if i + nums[i] >= goal { goal = i @@ -749,7 +749,7 @@ func canJump(nums []int) bool { class Solution { fun canJump(nums: IntArray): Boolean { var goal = nums.size - 1 - + for (i in nums.size - 2 downTo 0) { if (i + nums[i] >= goal) { goal = i @@ -780,5 +780,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/k-closest-points-to-origin.md b/articles/k-closest-points-to-origin.md index 7882e7c18..950ee2098 100644 --- a/articles/k-closest-points-to-origin.md +++ b/articles/k-closest-points-to-origin.md @@ -12,7 +12,7 @@ class Solution: ```java public class Solution { public int[][] kClosest(int[][] points, int k) { - Arrays.sort(points, (a, b) -> (a[0] * a[0] + a[1] * a[1]) - + Arrays.sort(points, (a, b) -> (a[0] * a[0] + a[1] * a[1]) - (b[0] * b[0] + b[1] * b[1])); return Arrays.copyOfRange(points, 0, k); } @@ -39,8 +39,7 @@ class Solution { * @return {number[][]} */ kClosest(points, k) { - points.sort((a, b) => (a[0] ** 2 + a[1] ** 2) - - (b[0] ** 2 + b[1] ** 2)); + points.sort((a, b) => a[0] ** 2 + a[1] ** 2 - (b[0] ** 2 + b[1] ** 2)); return points.slice(0, k); } } @@ -49,7 +48,7 @@ class Solution { ```csharp public class Solution { public int[][] KClosest(int[][] points, int k) { - Array.Sort(points, (a, b) => + Array.Sort(points, (a, b) => (a[0] * a[0] + a[1] * a[1]).CompareTo(b[0] * b[0] + b[1] * b[1])); return points[..k]; } @@ -59,7 +58,7 @@ public class Solution { ```go func kClosest(points [][]int, k int) [][]int { sort.Slice(points, func(i, j int) bool { - return points[i][0]*points[i][0] + points[i][1]*points[i][1] < + return points[i][0]*points[i][0] + points[i][1]*points[i][1] < points[j][0]*points[j][0] + points[j][1]*points[j][1] }) return points[:k] @@ -89,8 +88,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -105,14 +104,14 @@ class Solution: for x, y in points: dist = (x ** 2) + (y ** 2) minHeap.append([dist, x, y]) - + heapq.heapify(minHeap) res = [] while k > 0: dist, x, y = heapq.heappop(minHeap) res.append([x, y]) k -= 1 - + return res ``` @@ -142,7 +141,7 @@ public: auto comp = [](const vector& a, const vector& b) { return a[0]*a[0] + a[1]*a[1] > b[0]*b[0] + b[1]*b[1]; }; - + priority_queue, vector>, decltype(comp)> minHeap(comp); for (const auto& point : points) { @@ -171,7 +170,7 @@ class Solution { * @return {number[][]} */ kClosest(points, k) { - const minHeap = new MinPriorityQueue(point => point[0]); + const minHeap = new MinPriorityQueue((point) => point[0]); for (const [x, y] of points) { const dist = x ** 2 + y ** 2; @@ -289,8 +288,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(k * \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(k * \log n)$ +- Space complexity: $O(n)$ > Where $n$ is the length of the array $points$. @@ -309,7 +308,7 @@ class Solution: heapq.heappush(maxHeap, [dist, x, y]) if len(maxHeap) > k: heapq.heappop(maxHeap) - + res = [] while maxHeap: dist, x, y = heapq.heappop(maxHeap) @@ -321,7 +320,7 @@ class Solution: public class Solution { public int[][] kClosest(int[][] points, int k) { PriorityQueue maxHeap = new PriorityQueue<>( - (a, b) -> Integer.compare(b[0] * b[0] + b[1] * b[1], + (a, b) -> Integer.compare(b[0] * b[0] + b[1] * b[1], a[0] * a[0] + a[1] * a[1]) ); @@ -354,10 +353,10 @@ public: maxHeap.pop(); } } - + vector> res; while (!maxHeap.empty()) { - res.push_back({maxHeap.top().second.first, + res.push_back({maxHeap.top().second.first, maxHeap.top().second.second}); maxHeap.pop(); } @@ -402,7 +401,7 @@ class Solution { public class Solution { public int[][] KClosest(int[][] points, int K) { PriorityQueue maxHeap = new(); - + foreach (var point in points) { int dist = point[0] * point[0] + point[1] * point[1]; maxHeap.Enqueue(point, -dist); @@ -415,7 +414,7 @@ public class Solution { while (maxHeap.Count > 0) { res.Add(maxHeap.Dequeue()); } - + return res.ToArray(); } } @@ -433,7 +432,7 @@ func kClosest(points [][]int, k int) [][]int { } return 0 }) - + for _, point := range points { x, y := point[0], point[1] dist := x*x + y*y @@ -442,14 +441,14 @@ func kClosest(points [][]int, k int) [][]int { maxHeap.Dequeue() } } - + result := make([][]int, k) for i := k - 1; i >= 0; i-- { val, _ := maxHeap.Dequeue() point := val.([]int) result[i] = []int{point[0], point[1]} } - + return result } ``` @@ -513,8 +512,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * \log k)$ -* Space complexity: $O(k)$ +- Time complexity: $O(n * \log k)$ +- Space complexity: $O(k)$ > Where $n$ is the length of the array $points$. @@ -641,7 +640,9 @@ class Solution { * @return {number[][]} */ kClosest(points, k) { - let L = 0, R = points.length - 1, pivot = points.length; + let L = 0, + R = points.length - 1, + pivot = points.length; while (pivot !== k) { pivot = this.partition(points, L, R); @@ -808,7 +809,7 @@ class Solution { func euclidean(_ point: [Int]) -> Int { return point[0] * point[0] + point[1] * point[1] } - + func partition(_ l: Int, _ r: Int) -> Int { let pivotIdx = r let pivotDist = euclidean(points[pivotIdx]) @@ -822,10 +823,10 @@ class Solution { points.swapAt(i, r) return i } - + var l = 0, r = points.count - 1 var pivot = points.count - + while pivot != k { pivot = partition(l, r) if pivot < k { @@ -834,7 +835,7 @@ class Solution { r = pivot - 1 } } - + return Array(points[.. Where $n$ is the size of the permutation and $k$ is the number of inverse pairs in the permutation. @@ -263,8 +263,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * k)$ -* Space complexity: $O(n * k)$ +- Time complexity: $O(n * k)$ +- Space complexity: $O(n * k)$ > Where $n$ is the size of the permutation and $k$ is the number of inverse pairs in the permutation. @@ -366,8 +366,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 * k)$ -* Space complexity: $O(n * k)$ +- Time complexity: $O(n ^ 2 * k)$ +- Space complexity: $O(n * k)$ > Where $n$ is the size of the permutation and $k$ is the number of inverse pairs in the permutation. @@ -477,8 +477,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * k)$ -* Space complexity: $O(n * k)$ +- Time complexity: $O(n * k)$ +- Space complexity: $O(n * k)$ > Where $n$ is the size of the permutation and $k$ is the number of inverse pairs in the permutation. @@ -593,7 +593,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * k)$ -* Space complexity: $O(k)$ +- Time complexity: $O(n * k)$ +- Space complexity: $O(k)$ -> Where $n$ is the size of the permutation and $k$ is the number of inverse pairs in the permutation. \ No newline at end of file +> Where $n$ is the size of the permutation and $k$ is the number of inverse pairs in the permutation. diff --git a/articles/k-th-smallest-in-lexicographical-order.md b/articles/k-th-smallest-in-lexicographical-order.md index e69ae8cdf..27fff97d3 100644 --- a/articles/k-th-smallest-in-lexicographical-order.md +++ b/articles/k-th-smallest-in-lexicographical-order.md @@ -75,8 +75,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -183,9 +183,11 @@ class Solution { * @return {number} */ findKthNumber(n, k) { - let cur = 1, i = 1; - const count = curVal => { - let res = 0, nei = curVal + 1; + let cur = 1, + i = 1; + const count = (curVal) => { + let res = 0, + nei = curVal + 1; while (curVal <= n) { res += Math.min(nei, n + 1) - curVal; curVal *= 10; @@ -244,5 +246,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O((\log n) ^ 2)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O((\log n) ^ 2)$ +- Space complexity: $O(1)$ diff --git a/articles/k-th-symbol-in-grammar.md b/articles/k-th-symbol-in-grammar.md index d3f782b4c..da176d7ae 100644 --- a/articles/k-th-symbol-in-grammar.md +++ b/articles/k-th-symbol-in-grammar.md @@ -96,8 +96,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(2 ^ n)$ +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(2 ^ n)$ --- @@ -111,13 +111,13 @@ class Solution: def dfs(n, k, root): if n == 1: return root - + total = 1 << (n - 1) if k > (total // 2): return dfs(n - 1, k - (total // 2), root ^ 1) else: return dfs(n - 1, k, root) - + return dfs(n, k, 0) ``` @@ -126,12 +126,12 @@ public class Solution { public int kthGrammar(int n, int k) { return dfs(n, k, 0); } - + private int dfs(int n, int k, int root) { if (n == 1) { return root; } - + int total = 1 << (n - 1); if (k > total / 2) { return dfs(n - 1, k - total / 2, root ^ 1); @@ -190,8 +190,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -204,7 +204,7 @@ class Solution: def kthGrammar(self, n: int, k: int) -> int: cur = 0 left, right = 1, 2 ** (n - 1) - + for _ in range(n - 1): mid = (left + right) // 2 if k <= mid: @@ -212,7 +212,7 @@ class Solution: else: left = mid + 1 cur = 0 if cur else 1 - + return cur ``` @@ -221,7 +221,7 @@ public class Solution { public int kthGrammar(int n, int k) { int cur = 0; int left = 1, right = 1 << (n - 1); - + for (int i = 0; i < n - 1; i++) { int mid = (left + right) / 2; if (k <= mid) { @@ -231,7 +231,7 @@ public class Solution { cur = (cur == 0) ? 1 : 0; } } - + return cur; } } @@ -243,7 +243,7 @@ public: int kthGrammar(int n, int k) { int cur = 0; int left = 1, right = 1 << (n - 1); - + for (int i = 0; i < n - 1; i++) { int mid = (left + right) / 2; if (k <= mid) { @@ -253,7 +253,7 @@ public: cur = (cur == 0) ? 1 : 0; } } - + return cur; } }; @@ -268,8 +268,9 @@ class Solution { */ kthGrammar(n, k) { let cur = 0; - let left = 1, right = 1 << (n - 1); - + let left = 1, + right = 1 << (n - 1); + for (let i = 0; i < n - 1; i++) { let mid = Math.floor((left + right) / 2); if (k <= mid) { @@ -279,7 +280,7 @@ class Solution { cur = cur === 0 ? 1 : 0; } } - + return cur; } } @@ -289,8 +290,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -360,8 +361,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -400,7 +401,7 @@ class Solution { * @return {number} */ kthGrammar(n, k) { - return (k - 1).toString(2).split('1').length - 1 & 1; + return ((k - 1).toString(2).split('1').length - 1) & 1; } } ``` @@ -409,5 +410,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ or $O(\log n)$ depending on the language. \ No newline at end of file +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ or $O(\log n)$ depending on the language. diff --git a/articles/knight-dialer.md b/articles/knight-dialer.md index 9c87f4c13..26d95ccde 100644 --- a/articles/knight-dialer.md +++ b/articles/knight-dialer.md @@ -102,8 +102,16 @@ class Solution { if (n === 1) return 10; const MOD = 1000000007; const jumps = [ - [4, 6], [6, 8], [7, 9], [4, 8], [0, 3, 9], - [], [0, 1, 7], [2, 6], [1, 3], [2, 4] + [4, 6], + [6, 8], + [7, 9], + [4, 8], + [0, 3, 9], + [], + [0, 1, 7], + [2, 6], + [1, 3], + [2, 4], ]; const dfs = (n, d) => { @@ -129,8 +137,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(3 ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(3 ^ n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -157,7 +165,7 @@ class Solution: return 1 if dp[d][n] != -1: return dp[d][n] - + dp[d][n] = 0 for j in jumps[d]: dp[d][n] = (dp[d][n] + dfs(n - 1, j)) % mod @@ -249,8 +257,16 @@ class Solution { if (n === 1) return 10; const MOD = 1000000007; const jumps = [ - [4, 6], [6, 8], [7, 9], [4, 8], [0, 3, 9], - [], [0, 1, 7], [2, 6], [1, 3], [2, 4] + [4, 6], + [6, 8], + [7, 9], + [4, 8], + [0, 3, 9], + [], + [0, 1, 7], + [2, 6], + [1, 3], + [2, 4], ]; const dp = Array.from({ length: 10 }, () => Array(n + 1).fill(-1)); @@ -279,8 +295,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -322,7 +338,7 @@ public class Solution { public int knightDialer(int n) { if (n == 1) return 10; - + int[][] dp = new int[10][n + 1]; for (int d = 0; d < 10; d++) { dp[d][0] = 1; @@ -357,7 +373,7 @@ private: public: int knightDialer(int n) { if (n == 1) return 10; - + vector> dp(10, vector(n + 1, 0)); for (int d = 0; d < 10; d++) { dp[d][0] = 1; @@ -390,8 +406,16 @@ class Solution { if (n === 1) return 10; const MOD = 1000000007; const jumps = [ - [4, 6], [6, 8], [7, 9], [4, 8], [0, 3, 9], - [], [0, 1, 7], [2, 6], [1, 3], [2, 4] + [4, 6], + [6, 8], + [7, 9], + [4, 8], + [0, 3, 9], + [], + [0, 1, 7], + [2, 6], + [1, 3], + [2, 4], ]; const dp = Array.from({ length: 10 }, () => Array(n + 1).fill(0)); @@ -420,8 +444,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -500,7 +524,7 @@ private: public: int knightDialer(int n) { if (n == 1) return 10; - + vector dp(10, 1); for (int step = 0; step < n - 1; step++) { @@ -532,8 +556,16 @@ class Solution { if (n === 1) return 10; const MOD = 1000000007; const jumps = [ - [4, 6], [6, 8], [7, 9], [4, 8], [0, 3, 9], - [], [0, 1, 7], [2, 6], [1, 3], [2, 4] + [4, 6], + [6, 8], + [7, 9], + [4, 8], + [0, 3, 9], + [], + [0, 1, 7], + [2, 6], + [1, 3], + [2, 4], ]; let dp = new Array(10).fill(1); @@ -557,8 +589,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -665,8 +697,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -878,7 +910,9 @@ class Matrix { for (let j = 0; j < this.size; j++) { let sum = BigInt(0); for (let k = 0; k < this.size; k++) { - sum = (sum + BigInt(this.a[i][k]) * BigInt(other.a[k][j])) % this.MOD; + sum = + (sum + BigInt(this.a[i][k]) * BigInt(other.a[k][j])) % + this.MOD; } product.a[i][j] = Number(sum); } @@ -912,8 +946,16 @@ class Solution { }; const jumps = [ - [4, 6], [6, 8], [7, 9], [4, 8], [0, 3, 9], - [], [0, 1, 7], [2, 6], [1, 3], [2, 4] + [4, 6], + [6, 8], + [7, 9], + [4, 8], + [0, 3, 9], + [], + [0, 1, 7], + [2, 6], + [1, 3], + [2, 4], ]; const mat = new Matrix(10); @@ -924,15 +966,15 @@ class Solution { } const res = matpow(mat, n - 1, 10); - const mod = 1e9 + 7 + const mod = 1e9 + 7; let ans = 0; - + for (let i = 0; i < 10; i++) { for (let j = 0; j < 10; j++) { ans = (ans + res.a[i][j]) % mod; } } - + return ans; } } @@ -942,5 +984,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ diff --git a/articles/kth-distinct-string-in-an-array.md b/articles/kth-distinct-string-in-an-array.md index 244281490..feaae4e1e 100644 --- a/articles/kth-distinct-string-in-an-array.md +++ b/articles/kth-distinct-string-in-an-array.md @@ -101,7 +101,7 @@ class Solution { } } } - return ""; + return ''; } } ``` @@ -110,8 +110,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -211,7 +211,7 @@ class Solution { } } - return ""; + return ''; } } ``` @@ -220,8 +220,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -337,7 +337,7 @@ class Solution { } } - return ""; + return ''; } } ``` @@ -346,5 +346,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/kth-largest-element-in-an-array.md b/articles/kth-largest-element-in-an-array.md index 28fa1c69b..35226ea32 100644 --- a/articles/kth-largest-element-in-an-array.md +++ b/articles/kth-largest-element-in-an-array.md @@ -13,7 +13,7 @@ class Solution: public class Solution { public int findKthLargest(int[] nums, int k) { Arrays.sort(nums); - return nums[nums.length - k]; + return nums[nums.length - k]; } } ``` @@ -80,8 +80,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -164,14 +164,14 @@ public class Solution { ```go func findKthLargest(nums []int, k int) int { minHeap := priorityqueue.NewWith(utils.IntComparator) - + for _, num := range nums { minHeap.Enqueue(num) if minHeap.Size() > k { minHeap.Dequeue() } } - + val, _ := minHeap.Peek() return val.(int) } @@ -181,7 +181,7 @@ func findKthLargest(nums []int, k int) int { class Solution { fun findKthLargest(nums: IntArray, k: Int): Int { val minHeap = PriorityQueue() - + for (num in nums) { minHeap.offer(num) if (minHeap.size > k) { @@ -214,8 +214,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log k)$ -* Space complexity: $O(k)$ +- Time complexity: $O(n \log k)$ +- Space complexity: $O(k)$ > Where $n$ is the length of the array $nums$. @@ -230,7 +230,7 @@ class Solution: def findKthLargest(self, nums: List[int], k: int) -> int: k = len(nums) - k - + def quickSelect(l, r): pivot, p = nums[r], l for i in range(l, r): @@ -239,7 +239,7 @@ class Solution: p += 1 nums[p], nums[r] = nums[r], nums[p] - if p > k: + if p > k: return quickSelect(l, p - 1) elif p < k: return quickSelect(p + 1, r) @@ -292,11 +292,11 @@ public: k = nums.size() - k; return quickSelect(nums, 0, nums.size() - 1, k); } - + int quickSelect(vector& nums, int left, int right, int k) { int pivot = nums[right]; int p = left; - + for (int i = left; i < right; ++i) { if (nums[i] <= pivot) { swap(nums[p], nums[i]); @@ -304,7 +304,7 @@ public: } } swap(nums[p], nums[right]); - + if (p > k) { return quickSelect(nums, left, p - 1, k); } else if (p < k) { @@ -390,7 +390,7 @@ public class Solution { ```go func findKthLargest(nums []int, k int) int { k = len(nums) - k - + var quickSelect func(l, r int) int quickSelect = func(l, r int) int { pivot, p := nums[r], l @@ -479,8 +479,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ in average case, $O(n ^ 2)$ in worst case. -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ in average case, $O(n ^ 2)$ in worst case. +- Space complexity: $O(n)$ --- @@ -493,18 +493,18 @@ class Solution: def partition(self, nums: List[int], left: int, right: int) -> int: mid = (left + right) >> 1 nums[mid], nums[left + 1] = nums[left + 1], nums[mid] - + if nums[left] < nums[right]: nums[left], nums[right] = nums[right], nums[left] if nums[left + 1] < nums[right]: nums[left + 1], nums[right] = nums[right], nums[left + 1] if nums[left] < nums[left + 1]: nums[left], nums[left + 1] = nums[left + 1], nums[left] - + pivot = nums[left + 1] i = left + 1 j = right - + while True: while True: i += 1 @@ -517,27 +517,27 @@ class Solution: if i > j: break nums[i], nums[j] = nums[j], nums[i] - + nums[left + 1], nums[j] = nums[j], nums[left + 1] return j - + def quickSelect(self, nums: List[int], k: int) -> int: left = 0 right = len(nums) - 1 - + while True: if right <= left + 1: if right == left + 1 and nums[right] > nums[left]: nums[left], nums[right] = nums[right], nums[left] return nums[k] - + j = self.partition(nums, left, right) - + if j >= k: right = j - 1 if j <= k: left = j + 1 - + def findKthLargest(self, nums: List[int], k: int) -> int: return self.quickSelect(nums, k - 1) ``` @@ -547,54 +547,54 @@ public class Solution { private int partition(int[] nums, int left, int right) { int mid = (left + right) >> 1; swap(nums, mid, left + 1); - - if (nums[left] < nums[right]) + + if (nums[left] < nums[right]) swap(nums, left, right); - if (nums[left + 1] < nums[right]) + if (nums[left + 1] < nums[right]) swap(nums, left + 1, right); - if (nums[left] < nums[left + 1]) + if (nums[left] < nums[left + 1]) swap(nums, left, left + 1); - + int pivot = nums[left + 1]; int i = left + 1; int j = right; - + while (true) { while (nums[++i] > pivot); while (nums[--j] < pivot); if (i > j) break; swap(nums, i, j); } - + nums[left + 1] = nums[j]; nums[j] = pivot; return j; } - + private void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } - + private int quickSelect(int[] nums, int k) { int left = 0; int right = nums.length - 1; - + while (true) { if (right <= left + 1) { if (right == left + 1 && nums[right] > nums[left]) swap(nums, left, right); return nums[k]; } - + int j = partition(nums, left, right); - + if (j >= k) right = j - 1; if (j <= k) left = j + 1; } } - + public int findKthLargest(int[] nums, int k) { return quickSelect(nums, k - 1); } @@ -607,48 +607,48 @@ public: int partition(vector& nums, int left, int right) { int mid = (left + right) >> 1; swap(nums[mid], nums[left + 1]); - - if (nums[left] < nums[right]) + + if (nums[left] < nums[right]) swap(nums[left], nums[right]); - if (nums[left + 1] < nums[right]) + if (nums[left + 1] < nums[right]) swap(nums[left + 1], nums[right]); - if (nums[left] < nums[left + 1]) + if (nums[left] < nums[left + 1]) swap(nums[left], nums[left + 1]); - + int pivot = nums[left + 1]; int i = left + 1; int j = right; - + while (true) { while (nums[++i] > pivot); while (nums[--j] < pivot); if (i > j) break; swap(nums[i], nums[j]); } - + nums[left + 1] = nums[j]; nums[j] = pivot; return j; } - + int quickSelect(vector& nums, int k) { int left = 0; int right = nums.size() - 1; - + while (true) { if (right <= left + 1) { if (right == left + 1 && nums[right] > nums[left]) swap(nums[left], nums[right]); return nums[k]; } - + int j = partition(nums, left, right); - + if (j >= k) right = j - 1; if (j <= k) left = j + 1; } } - + int findKthLargest(vector& nums, int k) { return quickSelect(nums, k - 1); } @@ -666,48 +666,48 @@ class Solution { function partition(left, right) { const mid = (left + right) >> 1; [nums[mid], nums[left + 1]] = [nums[left + 1], nums[mid]]; - + if (nums[left] < nums[right]) [nums[left], nums[right]] = [nums[right], nums[left]]; if (nums[left + 1] < nums[right]) [nums[left + 1], nums[right]] = [nums[right], nums[left + 1]]; if (nums[left] < nums[left + 1]) [nums[left], nums[left + 1]] = [nums[left + 1], nums[left]]; - + const pivot = nums[left + 1]; let i = left + 1; let j = right; - + while (true) { while (nums[++i] > pivot); while (nums[--j] < pivot); if (i > j) break; [nums[i], nums[j]] = [nums[j], nums[i]]; } - + nums[left + 1] = nums[j]; nums[j] = pivot; return j; } - + function quickSelect(k) { let left = 0; let right = nums.length - 1; - + while (true) { if (right <= left + 1) { if (right == left + 1 && nums[right] > nums[left]) [nums[left], nums[right]] = [nums[right], nums[left]]; return nums[k]; } - + const j = partition(left, right); - + if (j >= k) right = j - 1; if (j <= k) left = j + 1; } } - + return quickSelect(k - 1); } } @@ -718,48 +718,48 @@ public class Solution { private int Partition(int[] nums, int left, int right) { int mid = (left + right) >> 1; (nums[mid], nums[left + 1]) = (nums[left + 1], nums[mid]); - + if (nums[left] < nums[right]) (nums[left], nums[right]) = (nums[right], nums[left]); if (nums[left + 1] < nums[right]) (nums[left + 1], nums[right]) = (nums[right], nums[left + 1]); if (nums[left] < nums[left + 1]) (nums[left], nums[left + 1]) = (nums[left + 1], nums[left]); - + int pivot = nums[left + 1]; int i = left + 1; int j = right; - + while (true) { while (nums[++i] > pivot); while (nums[--j] < pivot); if (i > j) break; (nums[i], nums[j]) = (nums[j], nums[i]); } - + nums[left + 1] = nums[j]; nums[j] = pivot; return j; } - + private int QuickSelect(int[] nums, int k) { int left = 0; int right = nums.Length - 1; - + while (true) { if (right <= left + 1) { if (right == left + 1 && nums[right] > nums[left]) (nums[left], nums[right]) = (nums[right], nums[left]); return nums[k]; } - + int j = Partition(nums, left, right); - + if (j >= k) right = j - 1; if (j <= k) left = j + 1; } } - + public int FindKthLargest(int[] nums, int k) { return QuickSelect(nums, k - 1); } @@ -772,7 +772,7 @@ func findKthLargest(nums []int, k int) int { partition = func(left, right int) int { mid := (left + right) >> 1 nums[mid], nums[left+1] = nums[left+1], nums[mid] - + if nums[left] < nums[right] { nums[left], nums[right] = nums[right], nums[left] } @@ -782,11 +782,11 @@ func findKthLargest(nums []int, k int) int { if nums[left] < nums[left+1] { nums[left], nums[left+1] = nums[left+1], nums[left] } - + pivot := nums[left+1] i := left + 1 j := right - + for { for i++; nums[i] > pivot; i++ {} for j--; nums[j] < pivot; j-- {} @@ -795,15 +795,15 @@ func findKthLargest(nums []int, k int) int { } nums[i], nums[j] = nums[j], nums[i] } - + nums[left+1], nums[j] = nums[j], nums[left+1] return j } - + quickSelect := func(k int) int { left := 0 right := len(nums) - 1 - + for { if right <= left+1 { if right == left+1 && nums[right] > nums[left] { @@ -811,9 +811,9 @@ func findKthLargest(nums []int, k int) int { } return nums[k] } - + j := partition(left, right) - + if j >= k { right = j - 1 } @@ -822,7 +822,7 @@ func findKthLargest(nums []int, k int) int { } } } - + return quickSelect(k - 1) } ``` @@ -832,48 +832,48 @@ class Solution { private fun partition(nums: IntArray, left: Int, right: Int): Int { val mid = (left + right) shr 1 nums[mid] = nums[left + 1].also { nums[left + 1] = nums[mid] } - + if (nums[left] < nums[right]) nums[left] = nums[right].also { nums[right] = nums[left] } if (nums[left + 1] < nums[right]) nums[left + 1] = nums[right].also { nums[right] = nums[left + 1] } if (nums[left] < nums[left + 1]) nums[left] = nums[left + 1].also { nums[left + 1] = nums[left] } - + val pivot = nums[left + 1] var i = left + 1 var j = right - + while (true) { while (nums[++i] > pivot); while (nums[--j] < pivot); if (i > j) break nums[i] = nums[j].also { nums[j] = nums[i] } } - + nums[left + 1] = nums[j] nums[j] = pivot return j } - + private fun quickSelect(nums: IntArray, k: Int): Int { var left = 0 var right = nums.size - 1 - + while (true) { if (right <= left + 1) { if (right == left + 1 && nums[right] > nums[left]) nums[left] = nums[right].also { nums[right] = nums[left] } return nums[k] } - + val j = partition(nums, left, right) - + if (j >= k) right = j - 1 if (j <= k) left = j + 1 } } - + fun findKthLargest(nums: IntArray, k: Int): Int { return quickSelect(nums, k - 1) } @@ -948,5 +948,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ in average case, $O(n ^ 2)$ in worst case. -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ in average case, $O(n ^ 2)$ in worst case. +- Space complexity: $O(1)$ diff --git a/articles/kth-largest-integer-in-a-stream.md b/articles/kth-largest-integer-in-a-stream.md index 42a4f617a..60191a21c 100644 --- a/articles/kth-largest-integer-in-a-stream.md +++ b/articles/kth-largest-integer-in-a-stream.md @@ -26,7 +26,7 @@ class KthLargest { arr.add(nums[i]); } } - + public int add(int val) { arr.add(val); Collections.sort(arr); @@ -44,7 +44,7 @@ public: this->arr = nums; this->k = k; } - + int add(int val) { arr.push_back(val); sort(arr.begin(), arr.end()); @@ -146,10 +146,10 @@ class KthLargest { ### Time & Space Complexity -* Time complexity: $O(m * n\log n)$ -* Space complexity: - * $O(m)$ extra space. - * $O(1)$ or $O(n)$ space depending on the sorting algorithm. +- Time complexity: $O(m * n\log n)$ +- Space complexity: + - $O(m)$ extra space. + - $O(1)$ or $O(n)$ space depending on the sorting algorithm. > Where $m$ is the number of calls made to $add()$ and $n$ is the current size of the array. @@ -161,7 +161,7 @@ class KthLargest { ```python class KthLargest: - + def __init__(self, k: int, nums: List[int]): self.minHeap, self.k = nums, k heapq.heapify(self.minHeap) @@ -177,7 +177,7 @@ class KthLargest: ```java class KthLargest { - + private PriorityQueue minHeap; private int k; @@ -268,7 +268,7 @@ class KthLargest { ```csharp public class KthLargest { - + private PriorityQueue minHeap; private int k; @@ -374,7 +374,7 @@ class KthLargest { ### Time & Space Complexity -* Time complexity: $O(m * \log k)$ -* Space complexity: $O(k)$ +- Time complexity: $O(m * \log k)$ +- Space complexity: $O(k)$ -> Where $m$ is the number of calls made to $add()$. \ No newline at end of file +> Where $m$ is the number of calls made to $add()$. diff --git a/articles/kth-smallest-integer-in-bst.md b/articles/kth-smallest-integer-in-bst.md index ec5dfe795..0de482d68 100644 --- a/articles/kth-smallest-integer-in-bst.md +++ b/articles/kth-smallest-integer-in-bst.md @@ -17,11 +17,11 @@ class Solution: def dfs(node): if not node: return - + arr.append(node.val) dfs(node.left) dfs(node.right) - + dfs(root) arr.sort() return arr[k - 1] @@ -47,7 +47,7 @@ class Solution: public class Solution { public int kthSmallest(TreeNode root, int k) { List arr = new ArrayList<>(); - + dfs(root, arr); Collections.sort(arr); return arr.get(k - 1); @@ -177,18 +177,18 @@ public class Solution { */ func kthSmallest(root *TreeNode, k int) int { var arr []int - + var dfs func(node *TreeNode) dfs = func(node *TreeNode) { if node == nil { return } - + dfs(node.Left) arr = append(arr, node.Val) dfs(node.Right) } - + dfs(root) return arr[k-1] } @@ -207,17 +207,17 @@ func kthSmallest(root *TreeNode, k int) int { */ class Solution { private val arr = mutableListOf() - + fun kthSmallest(root: TreeNode?, k: Int): Int { dfs(root) return arr[k - 1] } - + private fun dfs(node: TreeNode?) { if (node == null) { return } - + dfs(node.left) arr.add(node.`val`) dfs(node.right) @@ -263,8 +263,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -287,11 +287,11 @@ class Solution: def dfs(node): if not node: return - + dfs(node.left) arr.append(node.val) dfs(node.right) - + dfs(root) return arr[k - 1] ``` @@ -316,7 +316,7 @@ class Solution: public class Solution { public int kthSmallest(TreeNode root, int k) { List arr = new ArrayList<>(); - + dfs(root, arr); return arr.get(k - 1); } @@ -442,18 +442,18 @@ public class Solution { */ func kthSmallest(root *TreeNode, k int) int { var arr []int - + var dfs func(node *TreeNode) dfs = func(node *TreeNode) { if node == nil { return } - + dfs(node.Left) arr = append(arr, node.Val) dfs(node.Right) } - + dfs(root) return arr[k-1] } @@ -472,17 +472,17 @@ func kthSmallest(root *TreeNode, k int) int { */ class Solution { private val arr = mutableListOf() - + fun kthSmallest(root: TreeNode?, k: Int): Int { dfs(root) return arr[k - 1] } - + private fun dfs(node: TreeNode?) { if (node == null) { return } - + dfs(node.left) arr.add(node.`val`) dfs(node.right) @@ -527,8 +527,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -553,14 +553,14 @@ class Solution: nonlocal cnt, res if not node: return - + dfs(node.left) cnt -= 1 if cnt == 0: res = node.val return dfs(node.right) - + dfs(root) return res ``` @@ -730,13 +730,13 @@ public class Solution { */ func kthSmallest(root *TreeNode, k int) int { cnt, res := k, 0 - + var dfs func(node *TreeNode) dfs = func(node *TreeNode) { if node == nil { return } - + dfs(node.Left) cnt-- if cnt == 0 { @@ -745,7 +745,7 @@ func kthSmallest(root *TreeNode, k int) int { } dfs(node.Right) } - + dfs(root) return res } @@ -765,18 +765,18 @@ func kthSmallest(root *TreeNode, k int) int { class Solution { private var cnt = 0 private var res = 0 - + fun kthSmallest(root: TreeNode?, k: Int): Int { cnt = k dfs(root) return res } - + private fun dfs(node: TreeNode?) { if (node == null) { return } - + dfs(node.left) cnt-- if (cnt == 0) { @@ -831,8 +831,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -937,7 +937,7 @@ public: curr = curr->right; } - return -1; + return -1; } }; ``` @@ -1030,25 +1030,25 @@ public class Solution { func kthSmallest(root *TreeNode, k int) int { stack := []*TreeNode{} curr := root - + for len(stack) > 0 || curr != nil { for curr != nil { stack = append(stack, curr) curr = curr.Left } - + curr = stack[len(stack)-1] stack = stack[:len(stack)-1] - + k-- if k == 0 { return curr.Val } - + curr = curr.Right } - - return 0 + + return 0 } ``` @@ -1068,23 +1068,23 @@ class Solution { val stack = mutableListOf() var curr: TreeNode? = root var k = k - + while (stack.isNotEmpty() || curr != null) { while (curr != null) { stack.add(curr) curr = curr.left } - + curr = stack.removeLast() k-- if (k == 0) { return curr.`val` } - + curr = curr.right } - - return 0 + + return 0 } } ``` @@ -1132,8 +1132,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -1152,7 +1152,7 @@ class Solution { class Solution: def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: curr = root - + while curr: if not curr.left: k -= 1 @@ -1163,7 +1163,7 @@ class Solution: pred = curr.left while pred.right and pred.right != curr: pred = pred.right - + if not pred.right: pred.right = curr curr = curr.left @@ -1174,7 +1174,7 @@ class Solution: return curr.val curr = curr.right - return -1 + return -1 ``` ```java @@ -1197,7 +1197,7 @@ class Solution: public class Solution { public int kthSmallest(TreeNode root, int k) { TreeNode curr = root; - + while (curr != null) { if (curr.left == null) { k--; @@ -1207,7 +1207,7 @@ public class Solution { TreeNode pred = curr.left; while (pred.right != null && pred.right != curr) pred = pred.right; - + if (pred.right == null) { pred.right = curr; curr = curr.left; @@ -1241,7 +1241,7 @@ class Solution { public: int kthSmallest(TreeNode* root, int k) { TreeNode* curr = root; - + while (curr) { if (!curr->left) { k--; @@ -1251,7 +1251,7 @@ public: TreeNode* pred = curr->left; while (pred->right && pred->right != curr) pred = pred->right; - + if (!pred->right) { pred->right = curr; curr = curr->left; @@ -1288,7 +1288,7 @@ class Solution { */ kthSmallest(root, k) { let curr = root; - + while (curr) { if (!curr.left) { k--; @@ -1296,9 +1296,8 @@ class Solution { curr = curr.right; } else { let pred = curr.left; - while (pred.right && pred.right !== curr) - pred = pred.right; - + while (pred.right && pred.right !== curr) pred = pred.right; + if (!pred.right) { pred.right = curr; curr = curr.left; @@ -1333,7 +1332,7 @@ class Solution { public class Solution { public int KthSmallest(TreeNode root, int k) { TreeNode curr = root; - + while (curr != null) { if (curr.left == null) { k--; @@ -1343,7 +1342,7 @@ public class Solution { TreeNode pred = curr.left; while (pred.right != null && pred.right != curr) pred = pred.right; - + if (pred.right == null) { pred.right = curr; curr = curr.left; @@ -1476,7 +1475,7 @@ class Solution { while pred?.right != nil && pred?.right !== curr { pred = pred?.right } - + if pred?.right == nil { pred?.right = curr curr = curr?.left @@ -1499,5 +1498,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/largest-3-same-digit-number-in-string.md b/articles/largest-3-same-digit-number-in-string.md index f96e85ee3..003c5690a 100644 --- a/articles/largest-3-same-digit-number-in-string.md +++ b/articles/largest-3-same-digit-number-in-string.md @@ -7,14 +7,14 @@ class Solution: def largestGoodInteger(self, num: str) -> str: res = "" val = 0 - + for i in range(len(num) - 2): if num[i] == num[i + 1] == num[i + 2]: tmp = num[i : i + 3] if val <= int(tmp): val = int(tmp) res = tmp - + return res ``` @@ -23,9 +23,9 @@ public class Solution { public String largestGoodInteger(String num) { String res = ""; int val = 0; - + for (int i = 0; i < num.length() - 2; i++) { - if (num.charAt(i) == num.charAt(i + 1) && + if (num.charAt(i) == num.charAt(i + 1) && num.charAt(i) == num.charAt(i + 2)) { String tmp = num.substring(i, i + 3); if (val <= Integer.parseInt(tmp)) { @@ -34,7 +34,7 @@ public class Solution { } } } - + return res; } } @@ -46,7 +46,7 @@ public: string largestGoodInteger(string num) { string res = ""; int val = 0; - + for (int i = 0; i < num.length() - 2; i++) { if (num[i] == num[i + 1] && num[i] == num[i + 2]) { string tmp = num.substr(i, 3); @@ -56,7 +56,7 @@ public: } } } - + return res; } }; @@ -69,9 +69,9 @@ class Solution { * @return {string} */ largestGoodInteger(num) { - let res = ""; + let res = ''; let val = 0; - + for (let i = 0; i < num.length - 2; i++) { if (num[i] === num[i + 1] && num[i] === num[i + 2]) { const tmp = num.slice(i, i + 3); @@ -81,7 +81,7 @@ class Solution { } } } - + return res; } } @@ -91,8 +91,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -104,11 +104,11 @@ class Solution { class Solution: def largestGoodInteger(self, num: str) -> str: res = "0" - + for i in range(len(num) - 2): if num[i] == num[i + 1] == num[i + 2]: res = max(res, num[i : i + 3]) - + return "" if res == "0" else res ``` @@ -116,9 +116,9 @@ class Solution: public class Solution { public String largestGoodInteger(String num) { String res = ""; - + for (int i = 0; i < num.length() - 2; i++) { - if (num.charAt(i) == num.charAt(i + 1) && + if (num.charAt(i) == num.charAt(i + 1) && num.charAt(i) == num.charAt(i + 2)) { String curr = num.substring(i, i + 3); if (curr.compareTo(res) > 0) { @@ -126,7 +126,7 @@ public class Solution { } } } - + return res; } } @@ -137,13 +137,13 @@ class Solution { public: string largestGoodInteger(string num) { string res = "0"; - + for (int i = 0; i < num.length() - 2; i++) { if (num[i] == num[i + 1] && num[i] == num[i + 2]) { res = max(res, num.substr(i, 3)); } } - + return res == "0" ? "" : res; } }; @@ -156,15 +156,15 @@ class Solution { * @return {string} */ largestGoodInteger(num) { - let res = "0"; - + let res = '0'; + for (let i = 0; i < num.length - 2; i++) { if (num[i] === num[i + 1] && num[i] === num[i + 2]) { res = res > num.slice(i, i + 3) ? res : num.slice(i, i + 3); } } - - return res === "0" ? "" : res; + + return res === '0' ? '' : res; } } ``` @@ -173,8 +173,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -186,7 +186,7 @@ class Solution { class Solution: def largestGoodInteger(self, num: str) -> str: res = -1 - + for i in range(len(num) - 2): if num[i] == num[i + 1] == num[i + 2]: res = max(res, int(num[i])) @@ -199,7 +199,7 @@ public class Solution { int res = -1; for (int i = 0; i < num.length() - 2; i++) { - if (num.charAt(i) == num.charAt(i + 1) && + if (num.charAt(i) == num.charAt(i + 1) && num.charAt(i) == num.charAt(i + 2)) { res = Math.max(res, num.charAt(i) - '0'); } @@ -242,7 +242,7 @@ class Solution { } } - return res !== -1 ? String(res).repeat(3) : ""; + return res !== -1 ? String(res).repeat(3) : ''; } } ``` @@ -251,5 +251,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/largest-color-value-in-a-directed-graph.md b/articles/largest-color-value-in-a-directed-graph.md index dcbf467a4..759487709 100644 --- a/articles/largest-color-value-in-a-directed-graph.md +++ b/articles/largest-color-value-in-a-directed-graph.md @@ -170,8 +170,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V * (V + E))$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V * (V + E))$ +- Space complexity: $O(V + E)$ > Where $V$ is the number of verticies and $E$ is the number of edges. @@ -204,7 +204,7 @@ class Solution: return float("inf") for c in range(26): count[node][c] = max( - count[node][c], + count[node][c], (1 if c == colorIndex else 0) + count[nei][c] ) @@ -269,7 +269,7 @@ public class Solution { } for (int c = 0; c < 26; c++) { count[node][c] = Math.max( - count[node][c], + count[node][c], (c == colorIndex ? 1 : 0) + count[nei][c] ); } @@ -324,7 +324,7 @@ private: if (dfs(nei, colors) == INF) return INF; for (int c = 0; c < 26; c++) { count[node][c] = max( - count[node][c], + count[node][c], (c == colorIndex ? 1 : 0) + count[nei][c] ); } @@ -367,8 +367,8 @@ class Solution { if (dfs(nei) === Infinity) return Infinity; for (let c = 0; c < 26; c++) { count[node][c] = Math.max( - count[node][c], - (c === colorIndex ? 1 : 0) + count[nei][c] + count[node][c], + (c === colorIndex ? 1 : 0) + count[nei][c], ); } } @@ -393,8 +393,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ > Where $V$ is the number of verticies and $E$ is the number of edges. @@ -432,7 +432,7 @@ class Solution: for nei in adj[node]: for c in range(26): count[nei][c] = max(count[nei][c], count[node][c]) - + indegree[nei] -= 1 if indegree[nei] == 0: q.append(nei) @@ -556,7 +556,8 @@ class Solution { } } - let visit = 0, res = 0; + let visit = 0, + res = 0; while (!q.isEmpty()) { const node = q.pop(); visit++; @@ -583,7 +584,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ -> Where $V$ is the number of verticies and $E$ is the number of edges. \ No newline at end of file +> Where $V$ is the number of verticies and $E$ is the number of edges. diff --git a/articles/largest-divisible-subset.md b/articles/largest-divisible-subset.md index c5d8fa381..1fc86d067 100644 --- a/articles/largest-divisible-subset.md +++ b/articles/largest-divisible-subset.md @@ -121,8 +121,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -281,8 +281,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -405,8 +405,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -568,7 +568,8 @@ class Solution { return dp[i][0]; }; - let maxLen = 1, startIndex = 0; + let maxLen = 1, + startIndex = 0; for (let i = 0; i < n; i++) { if (dfs(i) > maxLen) { maxLen = dfs(i); @@ -590,8 +591,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -705,7 +706,8 @@ class Solution { let n = nums.length; let dp = Array.from({ length: n }, () => [1, -1]); // dp[i] = [maxLen, prevIdx] - let maxLen = 1, startIndex = 0; + let maxLen = 1, + startIndex = 0; for (let i = 0; i < n; i++) { for (let j = 0; j < i; j++) { if (nums[i] % nums[j] === 0 && dp[j][0] + 1 > dp[i][0]) { @@ -734,5 +736,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ diff --git a/articles/largest-local-values-in-a-matrix.md b/articles/largest-local-values-in-a-matrix.md index 169c4d992..9d2ecb76e 100644 --- a/articles/largest-local-values-in-a-matrix.md +++ b/articles/largest-local-values-in-a-matrix.md @@ -89,10 +89,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n ^ 2)$ for the output array. +- Time complexity: $O(n ^ 2)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n ^ 2)$ for the output array. --- @@ -337,9 +337,9 @@ class SparseTable { this.sparseTable = Array.from({ length: this.n }, () => Array.from({ length: this.n }, () => Array.from({ length: maxLog + 1 }, () => - Array(maxLog + 1).fill(0) - ) - ) + Array(maxLog + 1).fill(0), + ), + ), ); for (let r = 0; r < this.n; r++) { @@ -356,23 +356,33 @@ class SparseTable { if (i === 0) { this.sparseTable[r][c][i][j] = Math.max( this.sparseTable[r][c][i][j - 1], - this.sparseTable[r][c + (1 << (j - 1))][i][j - 1] + this.sparseTable[r][c + (1 << (j - 1))][i][ + j - 1 + ], ); } else if (j === 0) { this.sparseTable[r][c][i][j] = Math.max( this.sparseTable[r][c][i - 1][j], - this.sparseTable[r + (1 << (i - 1))][c][i - 1][j] + this.sparseTable[r + (1 << (i - 1))][c][i - 1][ + j + ], ); } else { this.sparseTable[r][c][i][j] = Math.max( Math.max( this.sparseTable[r][c][i - 1][j - 1], - this.sparseTable[r + (1 << (i - 1))][c][i - 1][j - 1] + this.sparseTable[r + (1 << (i - 1))][c][ + i - 1 + ][j - 1], ), Math.max( - this.sparseTable[r][c + (1 << (j - 1))][i - 1][j - 1], - this.sparseTable[r + (1 << (i - 1))][c + (1 << (j - 1))][i - 1][j - 1] - ) + this.sparseTable[r][c + (1 << (j - 1))][ + i - 1 + ][j - 1], + this.sparseTable[r + (1 << (i - 1))][ + c + (1 << (j - 1)) + ][i - 1][j - 1], + ), ); } } @@ -394,12 +404,14 @@ class SparseTable { return Math.max( Math.max( this.sparseTable[x1][y1][lx][ly], - this.sparseTable[x2 - (1 << lx) + 1][y1][lx][ly] + this.sparseTable[x2 - (1 << lx) + 1][y1][lx][ly], ), Math.max( this.sparseTable[x1][y2 - (1 << ly) + 1][lx][ly], - this.sparseTable[x2 - (1 << lx) + 1][y2 - (1 << ly) + 1][lx][ly] - ) + this.sparseTable[x2 - (1 << lx) + 1][y2 - (1 << ly) + 1][lx][ + ly + ], + ), ); } } @@ -410,10 +422,11 @@ class Solution { * @return {number[][]} */ largestLocal(grid) { - const n = grid.length, k = 3; + const n = grid.length, + k = 3; const st = new SparseTable(grid); const res = Array.from({ length: n - k + 1 }, () => - Array(n - k + 1).fill(0) + Array(n - k + 1).fill(0), ); for (let i = 0; i <= n - k; i++) { @@ -431,9 +444,9 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 \log ^ 2 n)$ -* Space complexity: - * $O(n ^ 2 \log ^ 2 n)$ extra space. - * $O((n - k) ^ 2)$ for the output matrix. +- Time complexity: $O(n ^ 2 \log ^ 2 n)$ +- Space complexity: + - $O(n ^ 2 \log ^ 2 n)$ extra space. + - $O((n - k) ^ 2)$ for the output matrix. -> Where $n$ is the size of the given square grid and $k$ is the fixed size of the submatrix window. \ No newline at end of file +> Where $n$ is the size of the given square grid and $k$ is the fixed size of the submatrix window. diff --git a/articles/largest-number.md b/articles/largest-number.md index 5b1822fb5..cb16f81db 100644 --- a/articles/largest-number.md +++ b/articles/largest-number.md @@ -6,7 +6,7 @@ class Solution: def largestNumber(self, nums: List[int]) -> str: arr = [str(num) for num in nums] - + res = [] while arr: maxi = 0 @@ -15,7 +15,7 @@ class Solution: maxi = i res.append(arr[maxi]) arr.pop(maxi) - + result = "".join(res) return result if result[0] != '0' else '0' ``` @@ -80,7 +80,7 @@ class Solution { */ largestNumber(nums) { let arr = nums.map(String); - + let res = []; while (arr.length > 0) { let maxi = 0; @@ -93,8 +93,8 @@ class Solution { arr.splice(maxi, 1); } - let result = res.join(""); - return result[0] === "0" ? "0" : result; + let result = res.join(''); + return result[0] === '0' ? '0' : result; } } ``` @@ -103,8 +103,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * N)$ -* Space complexity: $O(N)$ +- Time complexity: $O(n * N)$ +- Space complexity: $O(N)$ > Where $n$ is the size of the array $nums$ and $N$ is the total number of digits in the array $nums$. @@ -171,9 +171,9 @@ class Solution { */ largestNumber(nums) { let arr = nums.map(String); - arr.sort((a, b) => ((b + a) - (a + b))); - let res = arr.join(""); - return res[0] === "0" ? "0" : res; + arr.sort((a, b) => b + a - (a + b)); + let res = arr.join(''); + return res[0] === '0' ? '0' : res; } } ``` @@ -182,7 +182,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(N \log N)$ -* Space complexity: $O(N)$ +- Time complexity: $O(N \log N)$ +- Space complexity: $O(N)$ -> Where $N$ is the total number of digits in the array $nums$. \ No newline at end of file +> Where $N$ is the total number of digits in the array $nums$. diff --git a/articles/largest-odd-number-in-string.md b/articles/largest-odd-number-in-string.md index 566fb7c11..451fee9d2 100644 --- a/articles/largest-odd-number-in-string.md +++ b/articles/largest-odd-number-in-string.md @@ -21,13 +21,13 @@ public class Solution { public String largestOddNumber(String num) { String res = ""; int n = num.length(); - + for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { int onesDigit = num.charAt(j) - '0'; if ((onesDigit & 1) == 1) { String cur = num.substring(i, j + 1); - if (res.length() < cur.length() || + if (res.length() < cur.length() || (res.length() == cur.length() && res.compareTo(cur) < 0)) { res = cur; } @@ -51,7 +51,7 @@ public: int onesDigit = num[j] - '0'; if (onesDigit & 1) { string cur = num.substr(i, j - i + 1); - if (res.size() < cur.size() || + if (res.size() < cur.size() || (res.size() == cur.size() && res < cur)) { res = cur; } @@ -70,7 +70,7 @@ class Solution { * @return {string} */ largestOddNumber(num) { - let res = ""; + let res = ''; const n = num.length; for (let i = 0; i < n; i++) { @@ -78,8 +78,10 @@ class Solution { const onesDigit = num[j].charCodeAt(0) - '0'.charCodeAt(0); if (onesDigit & 1) { const cur = num.slice(i, j + 1); - if (res.length < cur.length || - (res.length === cur.length && res < cur)) { + if ( + res.length < cur.length || + (res.length === cur.length && res < cur) + ) { res = cur; } } @@ -94,8 +96,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 3)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 3)$ +- Space complexity: $O(n)$ --- @@ -151,7 +153,7 @@ class Solution { return num.slice(0, i + 1); } } - return ""; + return ''; } } ``` @@ -160,7 +162,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ for the output string. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ for the output string. diff --git a/articles/largest-rectangle-in-histogram.md b/articles/largest-rectangle-in-histogram.md index 75df88ffe..14070def1 100644 --- a/articles/largest-rectangle-in-histogram.md +++ b/articles/largest-rectangle-in-histogram.md @@ -14,11 +14,11 @@ class Solution: rightMost = i + 1 while rightMost < n and heights[rightMost] >= height: rightMost += 1 - + leftMost = i while leftMost >= 0 and heights[leftMost] >= height: leftMost -= 1 - + rightMost -= 1 leftMost += 1 maxArea = max(maxArea, height * (rightMost - leftMost + 1)) @@ -146,29 +146,29 @@ public class Solution { func largestRectangleArea(heights []int) int { n := len(heights) maxArea := 0 - + for i := 0; i < n; i++ { height := heights[i] - + rightMost := i + 1 for rightMost < n && heights[rightMost] >= height { rightMost++ } - + leftMost := i for leftMost >= 0 && heights[leftMost] >= height { leftMost-- } - + rightMost-- leftMost++ - + area := height * (rightMost - leftMost + 1) if area > maxArea { maxArea = area } } - + return maxArea } ``` @@ -178,26 +178,26 @@ class Solution { fun largestRectangleArea(heights: IntArray): Int { val n = heights.size var maxArea = 0 - + for (i in 0 until n) { val height = heights[i] - + var rightMost = i + 1 while (rightMost < n && heights[rightMost] >= height) { rightMost++ } - + var leftMost = i while (leftMost >= 0 && heights[leftMost] >= height) { leftMost-- } - + rightMost-- leftMost++ - + maxArea = maxOf(maxArea, height * (rightMost - leftMost + 1)) } - + return maxArea } } @@ -236,8 +236,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -456,7 +456,7 @@ public: int minIdx = st.query(l, r); return max(max(getMaxArea(heights, l, minIdx - 1, st), - getMaxArea(heights, minIdx + 1, r, st)), + getMaxArea(heights, minIdx + 1, r, st)), (r - l + 1) * heights[minIdx]); } int largestRectangleArea(vector& heights) { @@ -555,7 +555,7 @@ class Solution { return Math.max( this.getMaxArea(heights, l, minIdx - 1, st), this.getMaxArea(heights, minIdx + 1, r, st), - (r - l + 1) * heights[minIdx] + (r - l + 1) * heights[minIdx], ); } } @@ -619,7 +619,7 @@ public class Solution { int minIdx = st.Query(l, r); return Math.Max( - Math.Max(GetMaxArea(heights, l, minIdx - 1, st), + Math.Max(GetMaxArea(heights, l, minIdx - 1, st), GetMaxArea(heights, minIdx + 1, r, st)), (r - l + 1) * heights[minIdx]); } @@ -641,12 +641,12 @@ func NewMinIdxSegtree(N int, A []int) *MinIdxSegtree { A: make([]int, N), } copy(st.A, A) - + for (st.n & (st.n - 1)) != 0 { st.A = append(st.A, st.INF) st.n++ } - + st.tree = make([]int, 2*st.n) st.build() return st @@ -656,7 +656,7 @@ func (st *MinIdxSegtree) build() { for i := 0; i < st.n; i++ { st.tree[st.n+i] = i } - + for j := st.n - 1; j > 0; j-- { a := st.tree[j<<1] b := st.tree[(j<<1)+1] @@ -719,7 +719,7 @@ func getMaxArea(heights []int, l, r int, st *MinIdxSegtree) int { area1 := getMaxArea(heights, l, minIdx-1, st) area2 := getMaxArea(heights, minIdx+1, r, st) area3 := (r - l + 1) * heights[minIdx] - + maxArea := area1 if area2 > maxArea { maxArea = area2 @@ -742,7 +742,7 @@ class MinIdxSegtree(private var n: Int, input: IntArray) { private val INF = 1000000000 private val A: IntArray private val tree: IntArray - + init { var size = n while (size and (size - 1) != 0) size++ @@ -756,17 +756,17 @@ class MinIdxSegtree(private var n: Int, input: IntArray) { tree[j] = if (A[left] <= A[right]) left else right } } - + fun query(ql: Int, qh: Int): Int = queryHelper(1, 0, n - 1, ql, qh) - + private fun queryHelper(node: Int, l: Int, h: Int, ql: Int, qh: Int): Int { if (ql > h || qh < l) return INF if (l >= ql && h <= qh) return tree[node] - + val mid = (l + h) shr 1 val a = queryHelper(node shl 1, l, mid, ql, qh) val b = queryHelper((node shl 1) + 1, mid + 1, h, ql, qh) - + return when { a == INF -> b b == INF -> a @@ -780,7 +780,7 @@ class Solution { fun largestRectangleArea(heights: IntArray): Int { val n = heights.size val st = MinIdxSegtree(n, heights) - + fun getMaxArea(l: Int, r: Int): Int { if (l > r) return 0 if (l == r) return heights[l] @@ -790,7 +790,7 @@ class Solution { val rightArea = getMaxArea(minIdx + 1, r) return maxOf(area, leftArea, rightArea) } - + return getMaxArea(0, n - 1) } } @@ -880,8 +880,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -902,7 +902,7 @@ class Solution: if stack: leftMost[i] = stack[-1] stack.append(i) - + stack = [] rightMost = [n] * n for i in range(n - 1, -1, -1): @@ -911,7 +911,7 @@ class Solution: if stack: rightMost[i] = stack[-1] stack.append(i) - + maxArea = 0 for i in range(n): leftMost[i] += 1 @@ -927,7 +927,7 @@ public class Solution { int[] leftMost = new int[n]; int[] rightMost = new int[n]; Stack stack = new Stack<>(); - + for (int i = 0; i < n; i++) { leftMost[i] = -1; while (!stack.isEmpty() && heights[stack.peek()] >= heights[i]) { @@ -1018,7 +1018,10 @@ class Solution { const stack = []; for (let i = 0; i < n; i++) { - while (stack.length && heights[stack[stack.length - 1]] >= heights[i]) { + while ( + stack.length && + heights[stack[stack.length - 1]] >= heights[i] + ) { stack.pop(); } if (stack.length) { @@ -1029,7 +1032,10 @@ class Solution { stack.length = 0; for (let i = n - 1; i >= 0; i--) { - while (stack.length && heights[stack[stack.length - 1]] >= heights[i]) { + while ( + stack.length && + heights[stack[stack.length - 1]] >= heights[i] + ) { stack.pop(); } if (stack.length) { @@ -1042,7 +1048,10 @@ class Solution { for (let i = 0; i < n; i++) { leftMost[i] += 1; rightMost[i] -= 1; - maxArea = Math.max(maxArea, heights[i] * (rightMost[i] - leftMost[i] + 1)); + maxArea = Math.max( + maxArea, + heights[i] * (rightMost[i] - leftMost[i] + 1), + ); } return maxArea; @@ -1097,12 +1106,12 @@ public class Solution { func largestRectangleArea(heights []int) int { n := len(heights) stack := make([]int, 0) - + leftMost := make([]int, n) for i := range leftMost { leftMost[i] = -1 } - + for i := 0; i < n; i++ { for len(stack) > 0 && heights[stack[len(stack)-1]] >= heights[i] { stack = stack[:len(stack)-1] @@ -1112,13 +1121,13 @@ func largestRectangleArea(heights []int) int { } stack = append(stack, i) } - + stack = stack[:0] rightMost := make([]int, n) for i := range rightMost { rightMost[i] = n } - + for i := n - 1; i >= 0; i-- { for len(stack) > 0 && heights[stack[len(stack)-1]] >= heights[i] { stack = stack[:len(stack)-1] @@ -1128,7 +1137,7 @@ func largestRectangleArea(heights []int) int { } stack = append(stack, i) } - + maxArea := 0 for i := 0; i < n; i++ { leftMost[i]++ @@ -1138,7 +1147,7 @@ func largestRectangleArea(heights []int) int { maxArea = area } } - + return maxArea } ``` @@ -1148,7 +1157,7 @@ class Solution { fun largestRectangleArea(heights: IntArray): Int { val n = heights.size val stack = ArrayDeque() - + val leftMost = IntArray(n) { -1 } for (i in 0 until n) { while (stack.isNotEmpty() && heights[stack.last()] >= heights[i]) { @@ -1159,7 +1168,7 @@ class Solution { } stack.addLast(i) } - + stack.clear() val rightMost = IntArray(n) { n } for (i in n - 1 downTo 0) { @@ -1171,14 +1180,14 @@ class Solution { } stack.addLast(i) } - + var maxArea = 0 for (i in 0 until n) { leftMost[i]++ rightMost[i]-- maxArea = maxOf(maxArea, heights[i] * (rightMost[i] - leftMost[i] + 1)) } - + return maxArea } } @@ -1228,8 +1237,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -1378,7 +1387,7 @@ public class Solution { func largestRectangleArea(heights []int) int { maxArea := 0 stack := make([][2]int, 0) - + for i, h := range heights { start := i for len(stack) > 0 && stack[len(stack)-1][1] > h { @@ -1393,7 +1402,7 @@ func largestRectangleArea(heights []int) int { } stack = append(stack, [2]int{start, h}) } - + n := len(heights) for _, pair := range stack { area := pair[1] * (n - pair[0]) @@ -1401,7 +1410,7 @@ func largestRectangleArea(heights []int) int { maxArea = area } } - + return maxArea } ``` @@ -1411,7 +1420,7 @@ class Solution { fun largestRectangleArea(heights: IntArray): Int { var maxArea = 0 val stack = ArrayDeque>() - + heights.forEachIndexed { i, h -> var start = i while (stack.isNotEmpty() && stack.last().second > h) { @@ -1421,12 +1430,12 @@ class Solution { } stack.addLast(start to h) } - + val n = heights.size for ((i, h) in stack) { maxArea = maxOf(maxArea, h * (n - i)) } - + return maxArea } } @@ -1461,8 +1470,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -1542,10 +1551,13 @@ class Solution { const stack = []; for (let i = 0; i <= n; i++) { - while (stack.length && - (i === n || heights[stack[stack.length - 1]] >= heights[i])) { + while ( + stack.length && + (i === n || heights[stack[stack.length - 1]] >= heights[i]) + ) { const height = heights[stack.pop()]; - const width = stack.length === 0 ? i : i - stack[stack.length - 1] - 1; + const width = + stack.length === 0 ? i : i - stack[stack.length - 1] - 1; maxArea = Math.max(maxArea, height * width); } stack.push(i); @@ -1581,17 +1593,17 @@ func largestRectangleArea(heights []int) int { n := len(heights) maxArea := 0 stack := make([]int, 0) - + for i := 0; i <= n; i++ { for len(stack) > 0 && (i == n || heights[stack[len(stack)-1]] >= heights[i]) { height := heights[stack[len(stack)-1]] stack = stack[:len(stack)-1] - + width := i if len(stack) > 0 { width = i - stack[len(stack)-1] - 1 } - + area := height * width if area > maxArea { maxArea = area @@ -1601,7 +1613,7 @@ func largestRectangleArea(heights []int) int { stack = append(stack, i) } } - + return maxArea } ``` @@ -1612,7 +1624,7 @@ class Solution { val n = heights.size var maxArea = 0 val stack = ArrayDeque() - + for (i in 0..n) { while (stack.isNotEmpty() && (i == n || heights[stack.last()] >= heights[i])) { val height = heights[stack.removeLast()] @@ -1621,7 +1633,7 @@ class Solution { } if (i < n) stack.addLast(i) } - + return maxArea } } @@ -1651,5 +1663,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/largest-submatrix-with-rearrangements.md b/articles/largest-submatrix-with-rearrangements.md index bebc4c94e..d1aec6383 100644 --- a/articles/largest-submatrix-with-rearrangements.md +++ b/articles/largest-submatrix-with-rearrangements.md @@ -92,7 +92,8 @@ class Solution { * @return {number} */ largestSubmatrix(matrix) { - const ROWS = matrix.length, COLS = matrix[0].length; + const ROWS = matrix.length, + COLS = matrix[0].length; let res = 0; for (let startRow = 0; startRow < ROWS; startRow++) { @@ -123,8 +124,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(m * n ^ 2)$ +- Space complexity: $O(n)$ > Where $m$ is the number of rows and $n$ is the number of columns. @@ -224,7 +225,8 @@ class Solution { * @return {number} */ largestSubmatrix(matrix) { - const ROWS = matrix.length, COLS = matrix[0].length; + const ROWS = matrix.length, + COLS = matrix[0].length; let res = 0; let prevHeights = new Array(COLS).fill(0); @@ -255,8 +257,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(m * n \log n)$ +- Space complexity: $O(n)$ > Where $m$ is the number of rows and $n$ is the number of columns. @@ -344,7 +346,8 @@ class Solution { * @return {number} */ largestSubmatrix(matrix) { - const ROWS = matrix.length, COLS = matrix[0].length; + const ROWS = matrix.length, + COLS = matrix[0].length; let res = 0; for (let r = 1; r < ROWS; r++) { @@ -370,8 +373,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algoirhtm. +- Time complexity: $O(m * n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algoirhtm. > Where $m$ is the number of rows and $n$ is the number of columns. @@ -482,8 +485,10 @@ class Solution { * @return {number} */ largestSubmatrix(matrix) { - const ROWS = matrix.length, COLS = matrix[0].length; - let res = 0, prevHeights = []; + const ROWS = matrix.length, + COLS = matrix[0].length; + let res = 0, + prevHeights = []; for (let r = 0; r < ROWS; r++) { let heights = []; @@ -516,7 +521,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(n)$ -> Where $m$ is the number of rows and $n$ is the number of columns. \ No newline at end of file +> Where $m$ is the number of rows and $n$ is the number of columns. diff --git a/articles/largest-substring-between-two-equal-characters.md b/articles/largest-substring-between-two-equal-characters.md index dc4108a60..172a0aff4 100644 --- a/articles/largest-substring-between-two-equal-characters.md +++ b/articles/largest-substring-between-two-equal-characters.md @@ -78,8 +78,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -93,16 +93,16 @@ class Solution: res = -1 firstIdx = {} lastIdx = {} - + for i, c in enumerate(s): if c not in firstIdx: firstIdx[c] = i else: lastIdx[c] = i - + for c in lastIdx: res = max(res, lastIdx[c] - firstIdx[c] - 1) - + return res ``` @@ -187,8 +187,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ since we have at most $26$ different characters. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ since we have at most $26$ different characters. --- @@ -207,7 +207,7 @@ class Solution: res = max(res, i - char_index[c] - 1) else: char_index[c] = i - + return res ``` @@ -278,8 +278,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ since we have at most $26$ different characters. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ since we have at most $26$ different characters. --- @@ -299,7 +299,7 @@ class Solution: res = max(res, i - firstIdx[j] - 1) else: firstIdx[j] = i - + return res ``` @@ -376,5 +376,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ since we have at most $26$ different characters. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ since we have at most $26$ different characters. diff --git a/articles/last-stone-weight-ii.md b/articles/last-stone-weight-ii.md index c97e0e5ab..eaa55357d 100644 --- a/articles/last-stone-weight-ii.md +++ b/articles/last-stone-weight-ii.md @@ -76,10 +76,7 @@ class Solution { if (total >= target || i === stones.length) { return Math.abs(total - (stoneSum - total)); } - return Math.min( - dfs(i + 1, total), - dfs(i + 1, total + stones[i]) - ); + return Math.min(dfs(i + 1, total), dfs(i + 1, total + stones[i])); }; return dfs(0, 0); @@ -115,8 +112,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(min(n, m))$ for recursion stack. +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(min(n, m))$ for recursion stack. > Where $n$ is the number of stones and $m$ is the sum of the weights of the stones. @@ -222,7 +219,9 @@ class Solution { lastStoneWeightII(stones) { const stoneSum = stones.reduce((a, b) => a + b, 0); const target = Math.ceil(stoneSum / 2); - const dp = Array.from({ length: stones.length }, () => Array(target + 1).fill(-1)); + const dp = Array.from({ length: stones.length }, () => + Array(target + 1).fill(-1), + ); const dfs = (i, total) => { if (total >= target || i === stones.length) { @@ -234,7 +233,7 @@ class Solution { dp[i][total] = Math.min( dfs(i + 1, total), - dfs(i + 1, total + stones[i]) + dfs(i + 1, total + stones[i]), ); return dp[i][total]; }; @@ -287,8 +286,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n * m)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n * m)$ > Where $n$ is the number of stones and $m$ is the sum of the weights of the stones. @@ -380,12 +379,17 @@ class Solution { const target = Math.floor(stoneSum / 2); const n = stones.length; - const dp = Array.from({ length: n + 1 }, () => Array(target + 1).fill(0)); + const dp = Array.from({ length: n + 1 }, () => + Array(target + 1).fill(0), + ); for (let i = 1; i <= n; i++) { for (let t = 0; t <= target; t++) { if (t >= stones[i - 1]) { - dp[i][t] = Math.max(dp[i - 1][t], dp[i - 1][t - stones[i - 1]] + stones[i - 1]); + dp[i][t] = Math.max( + dp[i - 1][t], + dp[i - 1][t - stones[i - 1]] + stones[i - 1], + ); } else { dp[i][t] = dp[i - 1][t]; } @@ -428,8 +432,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n * m)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n * m)$ > Where $n$ is the number of stones and $m$ is the sum of the weights of the stones. @@ -540,8 +544,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(m)$ > Where $n$ is the number of stones and $m$ is the sum of the weights of the stones. @@ -706,8 +710,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(m)$ > Where $n$ is the number of stones and $m$ is the sum of the weights of the stones. @@ -722,7 +726,7 @@ class Solution: def lastStoneWeightII(self, stones: List[int]) -> int: stoneSum = sum(stones) target = stoneSum // 2 - dp = 1 + dp = 1 for stone in stones: dp |= dp << stone @@ -737,14 +741,14 @@ class Solution { public: int lastStoneWeightII(vector& stones) { int stoneSum = accumulate(stones.begin(), stones.end(), 0); - int target = stoneSum / 2; + int target = stoneSum / 2; bitset<3001> dp; dp[0] = true; - + for (int stone : stones) { dp |= (dp << stone); } - + for (int t = target; t >= 0; --t) { if (dp[t]) { return stoneSum - 2 * t; @@ -759,7 +763,7 @@ public: ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(m)$ -> Where $n$ is the number of stones and $m$ is the sum of the weights of the stones. \ No newline at end of file +> Where $n$ is the number of stones and $m$ is the sum of the weights of the stones. diff --git a/articles/last-stone-weight.md b/articles/last-stone-weight.md index 69ab3403a..658773016 100644 --- a/articles/last-stone-weight.md +++ b/articles/last-stone-weight.md @@ -5,13 +5,13 @@ ```python class Solution: def lastStoneWeight(self, stones: List[int]) -> int: - + while len(stones) > 1: stones.sort() cur = stones.pop() - stones.pop() if cur: stones.append(cur) - + return stones[0] if stones else 0 ``` @@ -81,10 +81,10 @@ public class Solution { while (stoneList.Count > 1) { stoneList.Sort(); int cur = stoneList[stoneList.Count - 1] - stoneList[stoneList.Count - 2]; - stoneList.RemoveAt(stoneList.Count - 1); - stoneList.RemoveAt(stoneList.Count - 1); + stoneList.RemoveAt(stoneList.Count - 1); + stoneList.RemoveAt(stoneList.Count - 1); if (cur != 0) { - stoneList.Add(cur); + stoneList.Add(cur); } } @@ -106,7 +106,7 @@ func lastStoneWeight(stones []int) int { if len(stones) == 0 { return 0 } - return stones[0] + return stones[0] } ``` @@ -114,7 +114,7 @@ func lastStoneWeight(stones []int) int { class Solution { fun lastStoneWeight(stones: IntArray): Int { var stonesList = stones.toMutableList() - + while (stonesList.size > 1) { stonesList.sort() val cur = stonesList.removeAt(stonesList.size - 1) - stonesList.removeAt(stonesList.size - 1) @@ -131,7 +131,7 @@ class Solution { class Solution { func lastStoneWeight(_ stones: [Int]) -> Int { var stones = stones - + while stones.count > 1 { stones.sort() let cur = stones.removeLast() - stones.removeLast() @@ -139,7 +139,7 @@ class Solution { stones.append(cur) } } - + return stones.isEmpty ? 0 : stones[0] } } @@ -149,8 +149,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n ^ 2 \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -266,7 +266,8 @@ class Solution { let cur = stones.pop() - stones.pop(); n -= 2; if (cur > 0) { - let l = 0, r = n; + let l = 0, + r = n; while (l < r) { let mid = Math.floor((l + r) / 2); if (stones[mid] < cur) { @@ -326,16 +327,16 @@ public class Solution { func lastStoneWeight(stones []int) int { sort.Ints(stones) n := len(stones) - + for n > 1 { cur := stones[n-1] - stones[n-2] n -= 2 - + if cur > 0 { pos := sort.Search(n, func(i int) bool { return stones[i] >= cur }) - + for i := n; i > pos; i-- { stones[i] = stones[i-1] } @@ -343,7 +344,7 @@ func lastStoneWeight(stones []int) int { n++ } } - + if n > 0 { return stones[0] } @@ -356,11 +357,11 @@ class Solution { fun lastStoneWeight(stones: IntArray): Int { stones.sort() var n = stones.size - + while (n > 1) { val cur = stones[n-1] - stones[n-2] n -= 2 - + if (cur > 0) { var l = 0 var r = n @@ -372,7 +373,7 @@ class Solution { r = mid } } - + for (i in n downTo l+1) { stones[i] = stones[i-1] } @@ -380,7 +381,7 @@ class Solution { n++ } } - + return if (n > 0) stones[0] else 0 } } @@ -424,8 +425,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -552,13 +553,13 @@ public class Solution { ```go func lastStoneWeight(stones []int) int { pq := priorityqueue.NewWith(func(a, b interface{}) int { - return a.(int) - b.(int) + return a.(int) - b.(int) }) - + for _, s := range stones { pq.Enqueue(-s) } - + for pq.Size() > 1 { first, _ := pq.Dequeue() second, _ := pq.Dequeue() @@ -566,7 +567,7 @@ func lastStoneWeight(stones []int) int { pq.Enqueue(first.(int) - second.(int)) } } - + pq.Enqueue(0) result, _ := pq.Dequeue() return -result.(int) @@ -580,7 +581,7 @@ class Solution { for (s in stones) { minHeap.offer(-s) } - + while (minHeap.size > 1) { val first = minHeap.poll() val second = minHeap.poll() @@ -588,7 +589,7 @@ class Solution { minHeap.offer(first - second) } } - + minHeap.offer(0) return Math.abs(minHeap.peek()) } @@ -615,8 +616,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -632,17 +633,17 @@ class Solution: bucket = [0] * (maxStone + 1) for stone in stones: bucket[stone] += 1 - + first = second = maxStone while first > 0: if bucket[first] % 2 == 0: first -= 1 continue - + j = min(first - 1, second) while j > 0 and bucket[j] == 0: j -= 1 - + if j == 0: return first second = j @@ -665,30 +666,30 @@ public class Solution { for (int stone : stones) { bucket[stone]++; } - + int first = maxStone, second = maxStone; while (first > 0) { if (bucket[first] % 2 == 0) { first--; continue; } - + int j = Math.min(first - 1, second); while (j > 0 && bucket[j] == 0) { j--; } - + if (j == 0) { return first; } - + second = j; bucket[first]--; bucket[second]--; bucket[first - second]++; first = Math.max(first - second, second); } - + return first; } } @@ -707,7 +708,7 @@ public: for (int stone : stones) { bucket[stone]++; } - + int first = maxStone, second = maxStone; while (first > 0) { if (bucket[first] % 2 == 0) { @@ -753,7 +754,8 @@ class Solution { bucket[stone]++; } - let first = maxStone, second = maxStone; + let first = maxStone, + second = maxStone; while (first > 0) { if (bucket[first] % 2 === 0) { first--; @@ -830,24 +832,24 @@ func lastStoneWeight(stones []int) int { maxStone = stone } } - + bucket := make([]int, maxStone+1) for _, stone := range stones { bucket[stone]++ } - + first, second := maxStone, maxStone for first > 0 { if bucket[first]%2 == 0 { first-- continue } - + j := min(first-1, second) for j > 0 && bucket[j] == 0 { j-- } - + if j == 0 { return first } @@ -883,7 +885,7 @@ class Solution { for (stone in stones) { bucket[stone]++ } - + var first = maxStone var second = maxStone while (first > 0) { @@ -891,12 +893,12 @@ class Solution { first-- continue } - + var j = minOf(first - 1, second) while (j > 0 && bucket[j] == 0) { j-- } - + if (j == 0) { return first } @@ -929,23 +931,23 @@ class Solution { first -= 1 continue } - + var j = min(first - 1, second) while j > 0 && bucket[j] == 0 { j -= 1 } - + if j == 0 { return first } - + second = j bucket[first] -= 1 bucket[second] -= 1 bucket[first - second] += 1 first = max(first - second, second) } - + return first } } @@ -955,7 +957,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + w)$ -* Space complexity: $O(w)$ +- Time complexity: $O(n + w)$ +- Space complexity: $O(w)$ -> Where $n$ is the length of the $stones$ array and $w$ is the maximum value in the $stones$ array. \ No newline at end of file +> Where $n$ is the length of the $stones$ array and $w$ is the maximum value in the $stones$ array. diff --git a/articles/leaf-similar-trees.md b/articles/leaf-similar-trees.md index 5e92ef739..7a874fd6a 100644 --- a/articles/leaf-similar-trees.md +++ b/articles/leaf-similar-trees.md @@ -23,7 +23,7 @@ class Solution: leaf1, leaf2 = [], [] dfs(root1, leaf1) dfs(root2, leaf2) - return leaf1 == leaf2 + return leaf1 == leaf2 ``` ```java @@ -46,10 +46,10 @@ public class Solution { public boolean leafSimilar(TreeNode root1, TreeNode root2) { List leaf1 = new ArrayList<>(); List leaf2 = new ArrayList<>(); - + dfs(root1, leaf1); dfs(root2, leaf2); - + return leaf1.equals(leaf2); } @@ -141,8 +141,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n + m)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(n + m)$ > Where $n$ and $m$ are the number of nodes in the given trees. @@ -169,7 +169,7 @@ class Solution: return dfs(root.left, leaf) dfs(root.right, leaf) - + leaf1 = [] dfs(root1, leaf1) @@ -179,9 +179,9 @@ class Solution: if not root.left and not root.right: if not leaf: return False - return leaf.pop() == root.val + return leaf.pop() == root.val return dfs1(root.right, leaf) and dfs1(root.left, leaf) - + return dfs1(root2, leaf1) and not leaf1 ``` @@ -322,8 +322,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n + m)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(n + m)$ > Where $n$ and $m$ are the number of nodes in the given trees. @@ -356,7 +356,7 @@ class Solution: while stack1 and stack2: if getPathLeaf(stack1) != getPathLeaf(stack2): return False - + return not stack1 and not stack2 ``` @@ -483,7 +483,8 @@ class Solution { } }; - const stack1 = [root1], stack2 = [root2]; + const stack1 = [root1], + stack2 = [root2]; while (stack1.length && stack2.length) { if (getPathLeaf(stack1) !== getPathLeaf(stack2)) { return false; @@ -498,7 +499,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n + m)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(n + m)$ -> Where $n$ and $m$ are the number of nodes in the given trees. \ No newline at end of file +> Where $n$ and $m$ are the number of nodes in the given trees. diff --git a/articles/least-number-of-unique-integers-after-k-removals.md b/articles/least-number-of-unique-integers-after-k-removals.md index ddffbfb03..3bfa46a2d 100644 --- a/articles/least-number-of-unique-integers-after-k-removals.md +++ b/articles/least-number-of-unique-integers-after-k-removals.md @@ -100,8 +100,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -208,8 +208,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -339,5 +339,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/lemonade-change.md b/articles/lemonade-change.md index 58c3561d3..c9215562b 100644 --- a/articles/lemonade-change.md +++ b/articles/lemonade-change.md @@ -95,7 +95,8 @@ class Solution { * @return {boolean} */ lemonadeChange(bills) { - let five = 0, ten = 0; + let five = 0, + ten = 0; for (let b of bills) { if (b === 5) { five++; @@ -157,8 +158,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -242,7 +243,8 @@ class Solution { * @return {boolean} */ lemonadeChange(bills) { - let five = 0, ten = 0; + let five = 0, + ten = 0; for (let b of bills) { if (b === 5) { five++; @@ -294,5 +296,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/length-of-last-word.md b/articles/length-of-last-word.md index baa94e557..8952e481b 100644 --- a/articles/length-of-last-word.md +++ b/articles/length-of-last-word.md @@ -73,7 +73,8 @@ class Solution { * @return {number} */ lengthOfLastWord(s) { - let length = 0, i = 0; + let length = 0, + i = 0; while (i < s.length) { if (s[i] === ' ') { while (i < s.length && s[i] === ' ') { @@ -97,8 +98,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -159,7 +160,8 @@ class Solution { */ lengthOfLastWord(s) { let n = s.length; - let i = n - 1, length = 0; + let i = n - 1, + length = 0; while (s.charAt(i) === ' ') { i--; } @@ -176,8 +178,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -194,7 +196,7 @@ class Solution: ```java public class Solution { public int lengthOfLastWord(String s) { - s = s.trim(); + s = s.trim(); return s.length() - s.lastIndexOf(" ") - 1; } } @@ -204,7 +206,7 @@ public class Solution { class Solution { public: int lengthOfLastWord(string s) { - s.erase(s.find_last_not_of(' ') + 1); + s.erase(s.find_last_not_of(' ') + 1); return s.substr(s.find_last_of(' ') + 1).length(); } }; @@ -217,7 +219,7 @@ class Solution { * @return {number} */ lengthOfLastWord(s) { - return s.trim().split(' ').pop().length + return s.trim().split(' ').pop().length; } } ``` @@ -226,5 +228,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/length-of-longest-subarray-with-at-most-k-frequency.md b/articles/length-of-longest-subarray-with-at-most-k-frequency.md index 5726525c2..db3af563f 100644 --- a/articles/length-of-longest-subarray-with-at-most-k-frequency.md +++ b/articles/length-of-longest-subarray-with-at-most-k-frequency.md @@ -14,7 +14,7 @@ class Solution: if count[nums[j]] > k: break res = max(res, j - i + 1) - + return res ``` @@ -67,7 +67,8 @@ class Solution { * @return {number} */ maxSubarrayLength(nums, k) { - let n = nums.length, res = 0; + let n = nums.length, + res = 0; for (let i = 0; i < n; i++) { let count = new Map(); @@ -88,8 +89,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -182,8 +183,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -255,7 +256,8 @@ class Solution { */ maxSubarrayLength(nums, k) { let count = new Map(); - let l = 0, cnt = 0; // count of numbers with freq > k + let l = 0, + cnt = 0; // count of numbers with freq > k for (let r = 0; r < nums.length; r++) { count.set(nums[r], (count.get(nums[r]) || 0) + 1); if (count.get(nums[r]) > k) cnt++; @@ -274,5 +276,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/level-order-traversal-of-binary-tree.md b/articles/level-order-traversal-of-binary-tree.md index 28df7fc5f..1a0ab21e1 100644 --- a/articles/level-order-traversal-of-binary-tree.md +++ b/articles/level-order-traversal-of-binary-tree.md @@ -47,21 +47,21 @@ class Solution: public class Solution { List> res = new ArrayList<>(); - + public List> levelOrder(TreeNode root) { dfs(root, 0); return res; } - + private void dfs(TreeNode node, int depth) { if (node == null) { return; } - + if (res.size() == depth) { res.add(new ArrayList<>()); } - + res.get(depth).add(node.val); dfs(node.left, depth + 1); dfs(node.right, depth + 1); @@ -85,19 +85,19 @@ public class Solution { class Solution { public: vector> res; - + vector> levelOrder(TreeNode* root) { dfs(root, 0); return res; } - + void dfs(TreeNode* node, int depth) { if (!node) return; - + if (res.size() == depth) { res.push_back(vector()); } - + res[depth].push_back(node->val); dfs(node->left, depth + 1); dfs(node->right, depth + 1); @@ -124,7 +124,7 @@ class Solution { */ levelOrder(root) { let res = []; - + /** * @param {TreeNode} node * @param {number} depth @@ -161,24 +161,24 @@ class Solution { * } * } */ - + public class Solution { List> res = new List>(); - + public List> LevelOrder(TreeNode root) { dfs(root, 0); return res; } - + private void dfs(TreeNode node, int depth) { if (node == null) { return; } - + if (res.Count == depth) { res.Add(new List()); } - + res[depth].Add(node.val); dfs(node.left, depth + 1); dfs(node.right, depth + 1); @@ -197,22 +197,22 @@ public class Solution { */ func levelOrder(root *TreeNode) [][]int { res := [][]int{} - + var dfs func(node *TreeNode, depth int) dfs = func(node *TreeNode, depth int) { if node == nil { return } - + if len(res) == depth { res = append(res, []int{}) } - + res[depth] = append(res[depth], node.Val) dfs(node.Left, depth+1) dfs(node.Right, depth+1) } - + dfs(root, 0) return res } @@ -232,19 +232,19 @@ func levelOrder(root *TreeNode) [][]int { class Solution { fun levelOrder(root: TreeNode?): List> { val res = mutableListOf>() - + fun dfs(node: TreeNode?, depth: Int) { if (node == null) return - + if (res.size == depth) { res.add(mutableListOf()) } - + res[depth].add(node.`val`) dfs(node.left, depth + 1) dfs(node.right, depth + 1) } - + dfs(root, 0) return res } @@ -293,8 +293,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -328,7 +328,7 @@ class Solution: q.append(node.right) if level: res.append(level) - + return res ``` @@ -478,7 +478,7 @@ class Solution { * } * } */ - + public class Solution { public List> LevelOrder(TreeNode root) { List> res = new List>(); @@ -530,7 +530,7 @@ func levelOrder(root *TreeNode) [][]int { for i := 0; i < qLen; i++ { node := q[0] - q = q[1:] + q = q[1:] level = append(level, node.Val) if node.Left != nil { @@ -540,7 +540,7 @@ func levelOrder(root *TreeNode) [][]int { q = append(q, node.Right) } } - + res = append(res, level) } @@ -570,7 +570,7 @@ class Solution { while (q.isNotEmpty()) { val level = mutableListOf() val qLen = q.size - + for (i in 0 until qLen) { val node = q.removeFirst() level.add(node.`val`) @@ -578,10 +578,10 @@ class Solution { node.left?.let { q.add(it) } node.right?.let { q.add(it) } } - + res.add(level) } - + return res } } @@ -633,5 +633,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/lfu-cache.md b/articles/lfu-cache.md index 74fac9473..47424973c 100644 --- a/articles/lfu-cache.md +++ b/articles/lfu-cache.md @@ -4,37 +4,37 @@ ```python class LFUCache: - + def __init__(self, capacity: int): self.capacity = capacity self.cache = {} # key -> [value, frequency, timestamp] self.timestamp = 0 - + def get(self, key: int) -> int: if key not in self.cache: return -1 - + self.cache[key][1] += 1 self.timestamp += 1 self.cache[key][2] = self.timestamp return self.cache[key][0] - + def put(self, key: int, value: int) -> None: if self.capacity <= 0: return - + self.timestamp += 1 if key in self.cache: self.cache[key][0] = value self.cache[key][1] += 1 self.cache[key][2] = self.timestamp return - + if len(self.cache) >= self.capacity: min_freq = float('inf') min_timestamp = float('inf') lfu_key = None - + for k, (_, freq, ts) in self.cache.items(): if freq < min_freq or (freq == min_freq and ts < min_timestamp): min_freq = freq @@ -42,7 +42,7 @@ class LFUCache: lfu_key = k if lfu_key is not None: del self.cache[lfu_key] - + self.cache[key] = [value, 1, self.timestamp] ``` @@ -171,7 +171,7 @@ class LFUCache { this.cache = new Map(); } - /** + /** * @param {number} key * @return {number} */ @@ -184,8 +184,8 @@ class LFUCache { return node.value; } - /** - * @param {number} key + /** + * @param {number} key * @param {number} value * @return {void} */ @@ -202,10 +202,15 @@ class LFUCache { } if (this.cache.size >= this.capacity) { - let minFreq = Infinity, minTimestamp = Infinity, lfuKey = null; + let minFreq = Infinity, + minTimestamp = Infinity, + lfuKey = null; for (const [k, node] of this.cache.entries()) { - if (node.freq < minFreq || (node.freq === minFreq && node.timestamp < minTimestamp)) { + if ( + node.freq < minFreq || + (node.freq === minFreq && node.timestamp < minTimestamp) + ) { minFreq = node.freq; minTimestamp = node.timestamp; lfuKey = k; @@ -293,11 +298,11 @@ public class LFUCache { ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for initialization. - * $O(1)$ time for each $get()$ function call. - * $O(n)$ time for each $put()$ function call. -* Space complexity: $O(n)$ +- Time complexity: + - $O(1)$ time for initialization. + - $O(1)$ time for each $get()$ function call. + - $O(n)$ time for each $put()$ function call. +- Space complexity: $O(n)$ --- @@ -337,12 +342,12 @@ class LinkedList: next.prev = prev prev.next = next self.map.pop(val, None) - + def popLeft(self): res = self.left.next.val self.pop(self.left.next.val) return res - + def update(self, val): self.pop(val) self.pushRight(val) @@ -365,7 +370,7 @@ class LFUCache: if cnt == self.lfuCnt and self.listMap[cnt].length() == 0: self.lfuCnt += 1 - + def get(self, key: int) -> int: if key not in self.valMap: @@ -376,12 +381,12 @@ class LFUCache: def put(self, key: int, value: int) -> None: if self.cap == 0: return - + if key not in self.valMap and len(self.valMap) == self.cap: res = self.listMap[self.lfuCnt].popLeft() self.valMap.pop(res) self.countMap.pop(res) - + self.valMap[key] = value self.counter(key) self.lfuCnt = min(self.lfuCnt, self.countMap[key]) @@ -467,7 +472,7 @@ public class LFUCache { countMap.put(key, count + 1); listMap.putIfAbsent(count, new DoublyLinkedList()); listMap.get(count).pop(key); - + listMap.putIfAbsent(count + 1, new DoublyLinkedList()); listMap.get(count + 1).pushRight(key); @@ -518,14 +523,14 @@ class LFUCache { ListNode* left; ListNode* right; unordered_map map; - + LinkedList() { left = new ListNode(0); right = new ListNode(0); left->next = right; right->prev = left; } - + ~LinkedList() { while (left->next != right) { ListNode* temp = left->next; @@ -582,7 +587,7 @@ class LFUCache { countMap[key] = count + 1; listMap[count]->pop(key); - + if (!listMap.count(count + 1)) { listMap[count + 1] = new LinkedList(); } @@ -597,7 +602,7 @@ public: LFUCache(int capacity) : capacity(capacity), lfuCount(0) { listMap[0] = new LinkedList(); } - + ~LFUCache() { for (auto& pair : listMap) { delete pair.second; @@ -895,7 +900,7 @@ public class LFUCache { ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for initialization. - * $O(1)$ time for each $get()$ and $put()$ function calls. -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: + - $O(1)$ time for initialization. + - $O(1)$ time for each $get()$ and $put()$ function calls. +- Space complexity: $O(n)$ diff --git a/articles/linked-list-cycle-detection.md b/articles/linked-list-cycle-detection.md index f8d574c77..adaca46d0 100644 --- a/articles/linked-list-cycle-detection.md +++ b/articles/linked-list-cycle-detection.md @@ -221,8 +221,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -265,7 +265,7 @@ class Solution { public boolean hasCycle(ListNode head) { ListNode fast = head; ListNode slow = head; - + while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; @@ -297,12 +297,12 @@ public: while (fast != nullptr && fast->next != nullptr) { fast = fast->next->next; slow = slow->next; - + if (fast == slow) { return true; } } - + return false; } }; @@ -452,5 +452,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/linked-list-cycle-ii.md b/articles/linked-list-cycle-ii.md index 2964377b8..4d1a014c2 100644 --- a/articles/linked-list-cycle-ii.md +++ b/articles/linked-list-cycle-ii.md @@ -109,8 +109,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -129,7 +129,7 @@ class Solution: def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: if not head or not head.next: return None - + slow, fast = head, head while fast and fast.next: slow = slow.next @@ -236,7 +236,8 @@ class Solution { return null; } - let slow = head, fast = head; + let slow = head, + fast = head; while (fast && fast.next) { slow = slow.next; @@ -260,5 +261,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/longest-common-prefix.md b/articles/longest-common-prefix.md index 936377d1c..b03fa2a75 100644 --- a/articles/longest-common-prefix.md +++ b/articles/longest-common-prefix.md @@ -103,8 +103,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(1)$ > Where $n$ is the length of the shortest string and $m$ is the number of strings. @@ -193,8 +193,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(1)$ since we did not use extra space. +- Time complexity: $O(n * m)$ +- Space complexity: $O(1)$ since we did not use extra space. > Where $n$ is the length of the shortest string and $m$ is the number of strings. @@ -209,7 +209,7 @@ class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: if len(strs) == 1: return strs[0] - + strs = sorted(strs) for i in range(min(len(strs[0]), len(strs[-1]))): if strs[0][i] != strs[-1][i]: @@ -223,7 +223,7 @@ public class Solution { if (strs.length == 1) { return strs[0]; } - + Arrays.sort(strs); int N = Math.min(strs[0].length(), strs[strs.length - 1].length()); for (int i = 0; i < N; i++) { @@ -243,7 +243,7 @@ public: if (strs.size() == 1) { return strs[0]; } - + sort(strs.begin(), strs.end()); for (int i = 0; i < min(strs[0].length(), strs.back().length()); i++) { if (strs[0][i] != strs.back()[i]) { @@ -265,7 +265,7 @@ class Solution { if (strs.length === 1) { return strs[0]; } - + strs.sort(); let N = Math.min(strs[0].length, strs[strs.length - 1].length); for (let i = 0; i < N; i++) { @@ -306,8 +306,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m \log m)$ -* Space complexity: $O(1)$ or $O(m)$ depending on the sorting algorithm. +- Time complexity: $O(n * m \log m)$ +- Space complexity: $O(1)$ or $O(m)$ depending on the sorting algorithm. > Where $n$ is the length of the longest string and $m$ is the number of strings. @@ -332,7 +332,7 @@ class Trie: if char not in node.children: node.children[char] = TrieNode() node = node.children[char] - + def lcp(self, word: str, prefixLen: int) -> int: node = self.root for i in range(min(len(word), prefixLen)): @@ -532,7 +532,7 @@ class Solution { if (strs.length === 1) { return strs[0]; } - + let mini = 0; for (let i = 1; i < strs.length; i++) { if (strs[mini].length > strs[i].length) { @@ -615,7 +615,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n)$ -> Where $n$ is the length of the shortest string and $m$ is the number of strings. \ No newline at end of file +> Where $n$ is the length of the shortest string and $m$ is the number of strings. diff --git a/articles/longest-common-subsequence.md b/articles/longest-common-subsequence.md index 95c23cd86..0c89c32e5 100644 --- a/articles/longest-common-subsequence.md +++ b/articles/longest-common-subsequence.md @@ -5,14 +5,14 @@ ```python class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: - + def dfs(i, j): if i == len(text1) or j == len(text2): return 0 if text1[i] == text2[j]: return 1 + dfs(i + 1, j + 1) return max(dfs(i + 1, j), dfs(i, j + 1)) - + return dfs(0, 0) ``` @@ -64,7 +64,6 @@ class Solution { * @return {number} */ longestCommonSubsequence(text1, text2) { - const dfs = (i, j) => { if (i === text1.length || j === text2.length) { return 0; @@ -73,8 +72,8 @@ class Solution { return 1 + dfs(i + 1, j + 1); } return Math.max(dfs(i + 1, j), dfs(i, j + 1)); - } - + }; + return dfs(0, 0); } } @@ -93,7 +92,7 @@ public class Solution { if (text1[i] == text2[j]) { return 1 + Dfs(text1, text2, i + 1, j + 1); } - return Math.Max(Dfs(text1, text2, i + 1, j), + return Math.Max(Dfs(text1, text2, i + 1, j), Dfs(text1, text2, i, j + 1)); } } @@ -161,8 +160,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ {m + n})$ -* Space complexity: $O(m + n)$ +- Time complexity: $O(2 ^ {m + n})$ +- Space complexity: $O(m + n)$ > Where $m$ is the length of the string $text1$ and $n$ is the length of the string $text2$. @@ -182,14 +181,14 @@ class Solution: return 0 if (i, j) in memo: return memo[(i, j)] - + if text1[i] == text2[j]: memo[(i, j)] = 1 + dfs(i + 1, j + 1) else: memo[(i, j)] = max(dfs(i + 1, j), dfs(i, j + 1)) - + return memo[(i, j)] - + return dfs(0, 0) ``` @@ -217,7 +216,7 @@ public class Solution { if (text1.charAt(i) == text2.charAt(j)) { memo[i][j] = 1 + dfs(text1, text2, i + 1, j + 1); } else { - memo[i][j] = Math.max(dfs(text1, text2, i + 1, j), + memo[i][j] = Math.max(dfs(text1, text2, i + 1, j), dfs(text1, text2, i, j + 1)); } return memo[i][j]; @@ -246,7 +245,7 @@ public: if (text1[i] == text2[j]) { memo[i][j] = 1 + dfs(text1, text2, i + 1, j + 1); } else { - memo[i][j] = max(dfs(text1, text2, i + 1, j), + memo[i][j] = max(dfs(text1, text2, i + 1, j), dfs(text1, text2, i, j + 1)); } return memo[i][j]; @@ -262,9 +261,9 @@ class Solution { * @return {number} */ longestCommonSubsequence(text1, text2) { - - const memo = Array(text1.length).fill().map(() => - Array(text2.length).fill(-1)); + const memo = Array(text1.length) + .fill() + .map(() => Array(text2.length).fill(-1)); const dfs = (i, j) => { if (i === text1.length || j === text2.length) { @@ -276,8 +275,7 @@ class Solution { if (text1[i] === text2[j]) { memo[i][j] = 1 + dfs(i + 1, j + 1); } else { - memo[i][j] = Math.max(dfs(i + 1, j), - dfs(i, j + 1)); + memo[i][j] = Math.max(dfs(i + 1, j), dfs(i, j + 1)); } return memo[i][j]; }; @@ -311,7 +309,7 @@ public class Solution { if (text1[i] == text2[j]) { memo[i, j] = 1 + Dfs(text1, text2, i + 1, j + 1); } else { - memo[i, j] = Math.Max(Dfs(text1, text2, i + 1, j), + memo[i, j] = Math.Max(Dfs(text1, text2, i + 1, j), Dfs(text1, text2, i, j + 1)); } return memo[i, j]; @@ -338,13 +336,13 @@ func longestCommonSubsequence(text1 string, text2 string) int { if memo[i][j] != -1 { return memo[i][j] } - + if text1[i] == text2[j] { memo[i][j] = 1 + dfs(i+1, j+1) } else { memo[i][j] = max(dfs(i+1, j), dfs(i, j+1)) } - + return memo[i][j] } @@ -375,7 +373,7 @@ class Solution { } else { maxOf(dfs(i + 1, j), dfs(i, j + 1)) } - + return memo[i][j] } @@ -417,8 +415,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the length of the string $text1$ and $n$ is the length of the string $text2$. @@ -431,7 +429,7 @@ class Solution { ```python class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: - dp = [[0 for j in range(len(text2) + 1)] + dp = [[0 for j in range(len(text2) + 1)] for i in range(len(text1) + 1)] for i in range(len(text1) - 1, -1, -1): @@ -468,7 +466,7 @@ public class Solution { class Solution { public: int longestCommonSubsequence(string text1, string text2) { - vector> dp(text1.size() + 1, + vector> dp(text1.size() + 1, vector(text2.size() + 1)); for (int i = text1.size() - 1; i >= 0; i--) { @@ -613,8 +611,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the length of the string $text1$ and $n$ is the length of the string $text2$. @@ -629,7 +627,7 @@ class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: if len(text1) < len(text2): text1, text2 = text2, text1 - + prev = [0] * (len(text2) + 1) curr = [0] * (len(text2) + 1) @@ -765,7 +763,7 @@ func longestCommonSubsequence(text1 string, text2 string) int { if len(text1) < len(text2) { text1, text2 = text2, text1 } - + prev := make([]int, len(text2)+1) curr := make([]int, len(text2)+1) @@ -814,9 +812,9 @@ class Solution { } } val temp = prev - prev.fill(0) + prev.fill(0) prev.indices.forEach { prev[it] = curr[it] } - curr.fill(0) + curr.fill(0) } return prev[0] @@ -857,8 +855,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(min(m, n))$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(min(m, n))$ > Where $m$ is the length of the string $text1$ and $n$ is the length of the string $text2$. @@ -1104,7 +1102,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(min(m, n))$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(min(m, n))$ -> Where $m$ is the length of the string $text1$ and $n$ is the length of the string $text2$. \ No newline at end of file +> Where $m$ is the length of the string $text1$ and $n$ is the length of the string $text2$. diff --git a/articles/longest-consecutive-sequence.md b/articles/longest-consecutive-sequence.md index 22cd5db3f..6112daf7b 100644 --- a/articles/longest-consecutive-sequence.md +++ b/articles/longest-consecutive-sequence.md @@ -70,7 +70,8 @@ class Solution { const store = new Set(nums); for (let num of nums) { - let streak = 0, curr = num; + let streak = 0, + curr = num; while (store.has(curr)) { streak++; curr++; @@ -170,8 +171,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -186,7 +187,7 @@ class Solution: return 0 res = 0 nums.sort() - + curr, streak = nums[0], 0 i = 0 while i < len(nums): @@ -235,7 +236,7 @@ public: sort(nums.begin(), nums.end()); int res = 0, curr = nums[0], streak = 0, i = 0; - + while (i < nums.size()) { if (curr != nums[i]) { curr = nums[i]; @@ -264,8 +265,11 @@ class Solution { return 0; } nums.sort((a, b) => a - b); - - let res = 0, curr = nums[0], streak = 0, i = 0; + + let res = 0, + curr = nums[0], + streak = 0, + i = 0; while (i < nums.length) { if (curr !== nums[i]) { @@ -291,7 +295,7 @@ public class Solution { return 0; } Array.Sort(nums); - + int res = 0, curr = nums[0], streak = 0, i = 0; while (i < nums.Length) { @@ -317,7 +321,7 @@ func longestConsecutive(nums []int) int { return 0 } sort.Ints(nums) - + res := 0 curr, streak := nums[0], 0 i := 0 @@ -372,14 +376,14 @@ class Solution { if nums.isEmpty { return 0 } - + var res = 0 var nums = nums.sorted() - + var curr = nums[0] var streak = 0 var i = 0 - + while i < nums.count { if curr != nums[i] { curr = nums[i] @@ -392,7 +396,7 @@ class Solution { curr += 1 res = max(res, streak) } - + return res } } @@ -402,8 +406,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -509,7 +513,7 @@ public class Solution { longest = Math.Max(longest, length); } } - return longest; + return longest; } } ``` @@ -586,8 +590,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -661,7 +665,10 @@ class Solution { for (let num of nums) { if (!mp.has(num)) { - mp.set(num, (mp.get(num - 1) || 0) + (mp.get(num + 1) || 0) + 1); + mp.set( + num, + (mp.get(num - 1) || 0) + (mp.get(num + 1) || 0) + 1, + ); mp.set(num - (mp.get(num - 1) || 0), mp.get(num)); mp.set(num + (mp.get(num + 1) || 0), mp.get(num)); res = Math.max(res, mp.get(num)); @@ -680,7 +687,7 @@ public class Solution { foreach (int num in nums) { if (!mp.ContainsKey(num)) { - mp[num] = (mp.ContainsKey(num - 1) ? mp[num - 1] : 0) + + mp[num] = (mp.ContainsKey(num - 1) ? mp[num - 1] : 0) + (mp.ContainsKey(num + 1) ? mp[num + 1] : 0) + 1; mp[num - (mp.ContainsKey(num - 1) ? mp[num - 1] : 0)] = mp[num]; @@ -757,7 +764,7 @@ class Solution { res = max(res, length) } } - + return res } } @@ -767,5 +774,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.md b/articles/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.md index aa8115c06..a40a183f0 100644 --- a/articles/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.md +++ b/articles/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.md @@ -16,7 +16,7 @@ class Solution: if maxi - mini > limit: break res = max(res, j - i + 1) - + return res ``` @@ -79,7 +79,8 @@ class Solution { let res = 1; for (let i = 0; i < n; i++) { - let mini = nums[i], maxi = nums[i]; + let mini = nums[i], + maxi = nums[i]; for (let j = i + 1; j < n; j++) { mini = Math.min(mini, nums[j]); maxi = Math.max(maxi, nums[j]); @@ -122,8 +123,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -227,9 +228,10 @@ class Solution { * @return {number} */ longestSubarray(nums, limit) { - const maxHeap = new PriorityQueue((a,b) => b[0] - a[0]); - const minHeap = new PriorityQueue((a,b) => a[0] - b[0]); - let j = 0, res = 0; + const maxHeap = new PriorityQueue((a, b) => b[0] - a[0]); + const minHeap = new PriorityQueue((a, b) => a[0] - b[0]); + let j = 0, + res = 0; for (let i = 0; i < nums.length; ++i) { const v = nums[i]; @@ -238,8 +240,10 @@ class Solution { while (maxHeap.front()[0] - minHeap.front()[0] > limit) { ++j; - while (!maxHeap.isEmpty() && maxHeap.front()[1] < j) maxHeap.pop(); - while (!minHeap.isEmpty() && minHeap.front()[1] < j) minHeap.pop(); + while (!maxHeap.isEmpty() && maxHeap.front()[1] < j) + maxHeap.pop(); + while (!minHeap.isEmpty() && minHeap.front()[1] < j) + minHeap.pop(); } res = Math.max(res, i - j + 1); @@ -281,8 +285,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -373,8 +377,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -480,7 +484,8 @@ class Solution { longestSubarray(nums, limit) { const minQ = new Deque(); const maxQ = new Deque(); - let l = 0, res = 0; + let l = 0, + res = 0; for (let r = 0; r < nums.length; r++) { while (!minQ.isEmpty() && nums[r] < minQ.back()) { minQ.popBack(); @@ -545,8 +550,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -567,7 +572,7 @@ class Solution: inc.pop() while dec and dec[-1] < nums[i]: dec.pop() - + inc.append(nums[i]) dec.append(nums[i]) if dec[0] - inc[0] > limit: @@ -576,7 +581,7 @@ class Solution: if inc[0] == nums[j]: inc.popleft() j += 1 - + return len(nums) - j ``` @@ -660,7 +665,8 @@ class Solution { longestSubarray(nums, limit) { const inc = new Deque([nums[0]]); const dec = new Deque([nums[0]]); - let res = 1, j = 0; + let res = 1, + j = 0; for (let i = 1; i < nums.length; i++) { while (!inc.isEmpty() && inc.back() > nums[i]) { @@ -727,5 +733,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/longest-happy-string.md b/articles/longest-happy-string.md index 3b669e0e4..7befbdb5e 100644 --- a/articles/longest-happy-string.md +++ b/articles/longest-happy-string.md @@ -209,10 +209,10 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ space for the output string. +- Time complexity: $O(n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ space for the output string. --- @@ -228,7 +228,7 @@ class Solution: for count, char in [(-a, "a"), (-b, "b"), (-c, "c")]: if count != 0: heapq.heappush(maxHeap, (count, char)) - + while maxHeap: count, char = heapq.heappop(maxHeap) if len(res) > 1 and res[-1] == res[-2] == char: @@ -322,7 +322,7 @@ class Solution { */ longestDiverseString(a, b, c) { const res = []; - const maxHeap = new MaxPriorityQueue(x => x[0]); + const maxHeap = new MaxPriorityQueue((x) => x[0]); if (a > 0) maxHeap.enqueue([a, 'a']); if (b > 0) maxHeap.enqueue([b, 'b']); @@ -331,7 +331,11 @@ class Solution { while (!maxHeap.isEmpty()) { const [count, char] = maxHeap.dequeue(); - if (res.length > 1 && res[res.length - 1] === char && res[res.length - 2] === char) { + if ( + res.length > 1 && + res[res.length - 1] === char && + res[res.length - 2] === char + ) { if (maxHeap.isEmpty()) break; const [count2, char2] = maxHeap.dequeue(); res.push(char2); @@ -393,10 +397,10 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ space for the output string. +- Time complexity: $O(n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ space for the output string. --- @@ -414,12 +418,12 @@ class Solution: return rec(max1, max3, max2, char1, char3, char2) if max2 == 0: return [char1] * min(2, max1) - + use1 = min(2, max1) use2 = 1 if max1 - use1 >= max2 else 0 res = [char1] * use1 + [char2] * use2 return res + rec(max1 - use1, max2 - use2, max3, char1, char2, char3) - + return ''.join(rec(a, b, c, 'a', 'b', 'c')) ``` @@ -520,7 +524,9 @@ class Solution { const use2 = max1 - use1 >= max2 ? 1 : 0; const res = Array(use1).fill(char1).concat(Array(use2).fill(char2)); - return res.concat(rec(max1 - use1, max2 - use2, max3, char1, char2, char3)); + return res.concat( + rec(max1 - use1, max2 - use2, max3, char1, char2, char3), + ); }; return rec(a, b, c, 'a', 'b', 'c').join(''); @@ -561,7 +567,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(n)$ for recursion stack. - * $O(n)$ space for the output string. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: + - $O(n)$ for recursion stack. + - $O(n)$ space for the output string. diff --git a/articles/longest-ideal-subsequence.md b/articles/longest-ideal-subsequence.md index 2162b48ec..5d4e9c95e 100644 --- a/articles/longest-ideal-subsequence.md +++ b/articles/longest-ideal-subsequence.md @@ -88,8 +88,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -200,7 +200,10 @@ class Solution { } const skip = dfs(i + 1, prev); let include = 0; - if (prev === -1 || Math.abs(s.charCodeAt(i) - ('a'.charCodeAt(0) + prev)) <= k) { + if ( + prev === -1 || + Math.abs(s.charCodeAt(i) - ('a'.charCodeAt(0) + prev)) <= k + ) { include = 1 + dfs(i + 1, s.charCodeAt(i) - 'a'.charCodeAt(0)); } dp[i][prev + 1] = Math.max(skip, include); @@ -216,8 +219,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -236,7 +239,7 @@ class Solution: dp[i][prev] = max(dp[i][prev], dp[i - 1][prev]) if abs(curr - prev) <= k: dp[i][curr] = max(dp[i][curr], 1 + dp[i - 1][prev]) - + return max(dp[len(s)]) ``` @@ -316,8 +319,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -337,7 +340,7 @@ class Solution: if abs(curr - prev) <= k: longest = max(longest, 1 + dp[prev]) dp[curr] = max(dp[curr], longest) - + return max(dp) ``` @@ -418,5 +421,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ since we have at most 26 different characters. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ since we have at most 26 different characters. diff --git a/articles/longest-increasing-path-in-matrix.md b/articles/longest-increasing-path-in-matrix.md index e529b1ded..07f6ec163 100644 --- a/articles/longest-increasing-path-in-matrix.md +++ b/articles/longest-increasing-path-in-matrix.md @@ -9,11 +9,11 @@ class Solution: directions = [[-1, 0], [1, 0], [0, -1], [0, 1]] def dfs(r, c, prevVal): - if (min(r, c) < 0 or r >= ROWS or + if (min(r, c) < 0 or r >= ROWS or c >= COLS or matrix[r][c] <= prevVal ): return 0 - + res = 1 for d in directions: res = max(res, 1 + dfs(r + d[0], c + d[1], matrix[r][c])) @@ -32,14 +32,14 @@ public class Solution { private int dfs(int[][] matrix, int r, int c, int prevVal) { int ROWS = matrix.length, COLS = matrix[0].length; - if (r < 0 || r >= ROWS || c < 0 || + if (r < 0 || r >= ROWS || c < 0 || c >= COLS || matrix[r][c] <= prevVal) { return 0; } int res = 1; for (int[] d : directions) { - res = Math.max(res, 1 + dfs(matrix, r + d[0], + res = Math.max(res, 1 + dfs(matrix, r + d[0], c + d[1], matrix[r][c])); } return res; @@ -61,18 +61,18 @@ public class Solution { ```cpp class Solution { public: - vector> directions = {{-1, 0}, {1, 0}, + vector> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; - + int dfs(vector>& matrix, int r, int c, int prevVal) { int ROWS = matrix.size(), COLS = matrix[0].size(); - if (r < 0 || r >= ROWS || c < 0 || + if (r < 0 || r >= ROWS || c < 0 || c >= COLS || matrix[r][c] <= prevVal) return 0; - + int res = 1; for (auto d : directions) - res = max(res, 1 + dfs(matrix, r + d[0], + res = max(res, 1 + dfs(matrix, r + d[0], c + d[1], matrix[r][c])); return res; } @@ -96,19 +96,29 @@ class Solution { * @return {number} */ longestIncreasingPath(matrix) { - const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]; - const ROWS = matrix.length, COLS = matrix[0].length; + const directions = [ + [-1, 0], + [1, 0], + [0, -1], + [0, 1], + ]; + const ROWS = matrix.length, + COLS = matrix[0].length; const dfs = (r, c, prevVal) => { - if (r < 0 || r >= ROWS || c < 0 || - c >= COLS || matrix[r][c] <= prevVal) { + if ( + r < 0 || + r >= ROWS || + c < 0 || + c >= COLS || + matrix[r][c] <= prevVal + ) { return 0; } let res = 1; for (let d of directions) { - res = Math.max(res, 1 + dfs(r + d[0], - c + d[1], matrix[r][c])); + res = Math.max(res, 1 + dfs(r + d[0], c + d[1], matrix[r][c])); } return res; }; @@ -127,20 +137,20 @@ class Solution { ```csharp public class Solution { private static int[][] directions = new int[][] { - new int[] {-1, 0}, new int[] {1, 0}, + new int[] {-1, 0}, new int[] {1, 0}, new int[] {0, -1}, new int[] {0, 1} }; private int Dfs(int[][] matrix, int r, int c, int prevVal) { int ROWS = matrix.Length, COLS = matrix[0].Length; - if (r < 0 || r >= ROWS || c < 0 || + if (r < 0 || r >= ROWS || c < 0 || c >= COLS || matrix[r][c] <= prevVal) { return 0; } int res = 1; foreach (var dir in directions) { - res = Math.Max(res, 1 + Dfs(matrix, r + dir[0], + res = Math.Max(res, 1 + Dfs(matrix, r + dir[0], c + dir[1], matrix[r][c])); } return res; @@ -166,7 +176,7 @@ func longestIncreasingPath(matrix [][]int) int { var dfs func(r, c, prevVal int) int dfs = func(r, c, prevVal int) int { - if r < 0 || r >= rows || c < 0 || c >= cols || + if r < 0 || r >= rows || c < 0 || c >= cols || matrix[r][c] <= prevVal { return 0 } @@ -198,7 +208,7 @@ func max(a, b int) int { ```kotlin class Solution { private val directions = arrayOf( - intArrayOf(-1, 0), intArrayOf(1, 0), + intArrayOf(-1, 0), intArrayOf(1, 0), intArrayOf(0, -1), intArrayOf(0, 1) ) @@ -207,7 +217,7 @@ class Solution { val cols = matrix[0].size fun dfs(r: Int, c: Int, prevVal: Int): Int { - if (r < 0 || r >= rows || c < 0 || c >= cols || + if (r < 0 || r >= rows || c < 0 || c >= cols || matrix[r][c] <= prevVal) { return 0 } @@ -240,7 +250,7 @@ class Solution { if r < 0 || c < 0 || r >= rows || c >= cols || matrix[r][c] <= prevVal { return 0 } - + var res = 1 for (dr, dc) in directions { res = max(res, 1 + dfs(r + dr, c + dc, matrix[r][c])) @@ -263,8 +273,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n * 4 ^ {m * n})$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n * 4 ^ {m * n})$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns in the given $matrix$. @@ -281,7 +291,7 @@ class Solution: dp = {} # (r, c) -> LIP def dfs(r, c, prevVal): - if (r < 0 or r == ROWS or c < 0 or + if (r < 0 or r == ROWS or c < 0 or c == COLS or matrix[r][c] <= prevVal ): return 0 @@ -309,7 +319,7 @@ public class Solution { private int dfs(int[][] matrix, int r, int c, int prevVal) { int ROWS = matrix.length, COLS = matrix[0].length; - if (r < 0 || r >= ROWS || c < 0 || + if (r < 0 || r >= ROWS || c < 0 || c >= COLS || matrix[r][c] <= prevVal) { return 0; } @@ -317,7 +327,7 @@ public class Solution { int res = 1; for (int[] d : directions) { - res = Math.max(res, 1 + dfs(matrix, r + d[0], + res = Math.max(res, 1 + dfs(matrix, r + d[0], c + d[1], matrix[r][c])); } return dp[r][c] = res; @@ -345,13 +355,13 @@ public class Solution { ```cpp class Solution { public: - vector> directions = {{-1, 0}, {1, 0}, + vector> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; vector> dp; int dfs(vector>& matrix, int r, int c, int prevVal) { int ROWS = matrix.size(), COLS = matrix[0].size(); - if (r < 0 || r >= ROWS || c < 0 || + if (r < 0 || r >= ROWS || c < 0 || c >= COLS || matrix[r][c] <= prevVal) { return 0; } @@ -359,7 +369,7 @@ public: int res = 1; for (vector d : directions) { - res = max(res, 1 + dfs(matrix, r + d[0], + res = max(res, 1 + dfs(matrix, r + d[0], c + d[1], matrix[r][c])); } dp[r][c] = res; @@ -388,22 +398,31 @@ class Solution { * @return {number} */ longestIncreasingPath(matrix) { - const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]; - const ROWS = matrix.length, COLS = matrix[0].length; - let dp = Array.from({ length: ROWS }, () => - Array(COLS).fill(-1)); + const directions = [ + [-1, 0], + [1, 0], + [0, -1], + [0, 1], + ]; + const ROWS = matrix.length, + COLS = matrix[0].length; + let dp = Array.from({ length: ROWS }, () => Array(COLS).fill(-1)); const dfs = (r, c, prevVal) => { - if (r < 0 || r >= ROWS || c < 0 || - c >= COLS || matrix[r][c] <= prevVal) { + if ( + r < 0 || + r >= ROWS || + c < 0 || + c >= COLS || + matrix[r][c] <= prevVal + ) { return 0; } if (dp[r][c] !== -1) return dp[r][c]; let res = 1; for (let d of directions) { - res = Math.max(res, 1 + dfs(r + d[0], - c + d[1], matrix[r][c])); + res = Math.max(res, 1 + dfs(r + d[0], c + d[1], matrix[r][c])); } dp[r][c] = res; return res; @@ -423,14 +442,14 @@ class Solution { ```csharp public class Solution { int[][] directions = new int[][] { - new int[] {-1, 0}, new int[] {1, 0}, + new int[] {-1, 0}, new int[] {1, 0}, new int[] {0, -1}, new int[] {0, 1} }; int[,] dp; private int Dfs(int[][] matrix, int r, int c, int prevVal) { int ROWS = matrix.Length, COLS = matrix[0].Length; - if (r < 0 || r >= ROWS || c < 0 || + if (r < 0 || r >= ROWS || c < 0 || c >= COLS || matrix[r][c] <= prevVal) { return 0; } @@ -438,7 +457,7 @@ public class Solution { int res = 1; foreach (int[] d in directions) { - res = Math.Max(res, 1 + Dfs(matrix, r + d[0], + res = Math.Max(res, 1 + Dfs(matrix, r + d[0], c + d[1], matrix[r][c])); } @@ -449,7 +468,7 @@ public class Solution { public int LongestIncreasingPath(int[][] matrix) { int ROWS = matrix.Length, COLS = matrix[0].Length; dp = new int[ROWS, COLS]; - + for (int i = 0; i < ROWS; i++) { for (int j = 0; j < COLS; j++) { dp[i, j] = -1; @@ -477,7 +496,7 @@ func longestIncreasingPath(matrix [][]int) int { var dfs func(r, c, prevVal int) int dfs = func(r, c, prevVal int) int { - if r < 0 || r >= rows || c < 0 || c >= cols || + if r < 0 || r >= rows || c < 0 || c >= cols || matrix[r][c] <= prevVal { return 0 } @@ -519,7 +538,7 @@ class Solution { val dp = Array(rows) { IntArray(cols) } fun dfs(r: Int, c: Int, prevVal: Int): Int { - if (r < 0 || r >= rows || c < 0 || c >= cols || + if (r < 0 || r >= rows || c < 0 || c >= cols || matrix[r][c] <= prevVal) { return 0 } @@ -586,8 +605,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns in the given $matrix$. @@ -603,12 +622,12 @@ class Solution: ROWS, COLS = len(matrix), len(matrix[0]) directions = [[-1, 0], [1, 0], [0, -1], [0, 1]] indegree = [[0] * COLS for _ in range(ROWS)] - + for r in range(ROWS): for c in range(COLS): for d in directions: nr, nc = d[0] + r, d[1] + c - if (0 <= nr < ROWS and 0 <= nc < COLS and + if (0 <= nr < ROWS and 0 <= nc < COLS and matrix[nr][nc] < matrix[r][c] ): indegree[r][c] += 1 @@ -625,7 +644,7 @@ class Solution: r, c = q.popleft() for d in directions: nr, nc = r + d[0], c + d[1] - if (0 <= nr < ROWS and 0 <= nc < COLS and + if (0 <= nr < ROWS and 0 <= nc < COLS and matrix[nr][nc] > matrix[r][c] ): indegree[nr][nc] -= 1 @@ -646,7 +665,7 @@ public class Solution { for (int c = 0; c < COLS; ++c) { for (int[] d : directions) { int nr = r + d[0], nc = c + d[1]; - if (nr >= 0 && nr < ROWS && nc >= 0 && + if (nr >= 0 && nr < ROWS && nc >= 0 && nc < COLS && matrix[nr][nc] < matrix[r][c]) { indegree[r][c]++; } @@ -671,7 +690,7 @@ public class Solution { int r = node[0], c = node[1]; for (int[] d : directions) { int nr = r + d[0], nc = c + d[1]; - if (nr >= 0 && nr < ROWS && nc >= 0 && + if (nr >= 0 && nr < ROWS && nc >= 0 && nc < COLS && matrix[nr][nc] > matrix[r][c]) { if (--indegree[nr][nc] == 0) { q.offer(new int[]{nr, nc}); @@ -692,21 +711,21 @@ public: int longestIncreasingPath(vector>& matrix) { int ROWS = matrix.size(), COLS = matrix[0].size(); vector> indegree(ROWS, vector(COLS, 0)); - vector> directions = {{-1, 0}, {1, 0}, + vector> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; - + for (int r = 0; r < ROWS; ++r) { for (int c = 0; c < COLS; ++c) { for (auto& d : directions) { int nr = r + d[0], nc = c + d[1]; - if (nr >= 0 && nr < ROWS && nc >= 0 && + if (nr >= 0 && nr < ROWS && nc >= 0 && nc < COLS && matrix[nr][nc] < matrix[r][c]) { indegree[r][c]++; } } } } - + queue> q; for (int r = 0; r < ROWS; ++r) { for (int c = 0; c < COLS; ++c) { @@ -715,7 +734,7 @@ public: } } } - + int LIS = 0; while (!q.empty()) { int size = q.size(); @@ -724,7 +743,7 @@ public: q.pop(); for (auto& d : directions) { int nr = r + d[0], nc = c + d[1]; - if (nr >= 0 && nr < ROWS && nc >= 0 && + if (nr >= 0 && nr < ROWS && nc >= 0 && nc < COLS && matrix[nr][nc] > matrix[r][c]) { if (--indegree[nr][nc] == 0) { q.push({nr, nc}); @@ -746,17 +765,28 @@ class Solution { * @return {number} */ longestIncreasingPath(matrix) { - const ROWS = matrix.length, COLS = matrix[0].length; - const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]; - let indegree = Array.from({ length: ROWS }, () => - Array(COLS).fill(0)); - + const ROWS = matrix.length, + COLS = matrix[0].length; + const directions = [ + [-1, 0], + [1, 0], + [0, -1], + [0, 1], + ]; + let indegree = Array.from({ length: ROWS }, () => Array(COLS).fill(0)); + for (let r = 0; r < ROWS; r++) { for (let c = 0; c < COLS; c++) { for (const [dr, dc] of directions) { - const nr = r + dr, nc = c + dc; - if (nr >= 0 && nr < ROWS && nc >= 0 && - nc < COLS && matrix[nr][nc] < matrix[r][c]) { + const nr = r + dr, + nc = c + dc; + if ( + nr >= 0 && + nr < ROWS && + nc >= 0 && + nc < COLS && + matrix[nr][nc] < matrix[r][c] + ) { indegree[r][c]++; } } @@ -778,9 +808,15 @@ class Solution { for (let i = 0; i < size; i++) { const [r, c] = q.pop(); for (const [dr, dc] of directions) { - const nr = r + dr, nc = c + dc; - if (nr >= 0 && nr < ROWS && nc >= 0 && - nc < COLS && matrix[nr][nc] > matrix[r][c]) { + const nr = r + dr, + nc = c + dc; + if ( + nr >= 0 && + nr < ROWS && + nc >= 0 && + nc < COLS && + matrix[nr][nc] > matrix[r][c] + ) { indegree[nr][nc]--; if (indegree[nr][nc] === 0) { q.push([nr, nc]); @@ -803,16 +839,16 @@ public class Solution { for (int i = 0; i < ROWS; i++) { indegree[i] = new int[COLS]; } - int[][] directions = new int[][] { - new int[] { -1, 0 }, new int[] { 1, 0 }, - new int[] { 0, -1 }, new int[] { 0, 1 } + int[][] directions = new int[][] { + new int[] { -1, 0 }, new int[] { 1, 0 }, + new int[] { 0, -1 }, new int[] { 0, 1 } }; for (int r = 0; r < ROWS; r++) { for (int c = 0; c < COLS; c++) { foreach (var d in directions) { int nr = r + d[0], nc = c + d[1]; - if (nr >= 0 && nr < ROWS && nc >= 0 && + if (nr >= 0 && nr < ROWS && nc >= 0 && nc < COLS && matrix[nr][nc] < matrix[r][c]) { indegree[r][c]++; } @@ -837,7 +873,7 @@ public class Solution { int r = node[0], c = node[1]; foreach (var d in directions) { int nr = r + d[0], nc = c + d[1]; - if (nr >= 0 && nr < ROWS && nc >= 0 && + if (nr >= 0 && nr < ROWS && nc >= 0 && nc < COLS && matrix[nr][nc] > matrix[r][c]) { if (--indegree[nr][nc] == 0) { q.Enqueue(new int[] { nr, nc }); @@ -859,14 +895,14 @@ func longestIncreasingPath(matrix [][]int) int { for i := range indegree { indegree[i] = make([]int, cols) } - + directions := [][]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}} for r := 0; r < rows; r++ { for c := 0; c < cols; c++ { for _, d := range directions { nr, nc := r + d[0], c + d[1] - if nr >= 0 && nr < rows && nc >= 0 && nc < cols && + if nr >= 0 && nr < rows && nc >= 0 && nc < cols && matrix[nr][nc] < matrix[r][c] { indegree[r][c]++ } @@ -892,7 +928,7 @@ func longestIncreasingPath(matrix [][]int) int { r, c := node[0], node[1] for _, d := range directions { nr, nc := r + d[0], c + d[1] - if nr >= 0 && nr < rows && nc >= 0 && nc < cols && + if nr >= 0 && nr < rows && nc >= 0 && nc < cols && matrix[nr][nc] > matrix[r][c] { indegree[nr][nc]-- if indegree[nr][nc] == 0 { @@ -914,7 +950,7 @@ class Solution { val rows = matrix.size val cols = matrix[0].size val indegree = Array(rows) { IntArray(cols) } - val directions = arrayOf(intArrayOf(-1, 0), intArrayOf(1, 0), + val directions = arrayOf(intArrayOf(-1, 0), intArrayOf(1, 0), intArrayOf(0, -1), intArrayOf(0, 1)) for (r in 0 until rows) { @@ -922,7 +958,7 @@ class Solution { for (d in directions) { val nr = r + d[0] val nc = c + d[1] - if (nr in 0 until rows && nc in 0 until cols && + if (nr in 0 until rows && nc in 0 until cols && matrix[nr][nc] < matrix[r][c]) { indegree[r][c]++ } @@ -946,7 +982,7 @@ class Solution { for (d in directions) { val nr = r + d[0] val nc = c + d[1] - if (nr in 0 until rows && nc in 0 until cols && + if (nr in 0 until rows && nc in 0 until cols && matrix[nr][nc] > matrix[r][c]) { if (--indegree[nr][nc] == 0) { queue.offer(intArrayOf(nr, nc)) @@ -1016,7 +1052,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ -> Where $m$ is the number of rows and $n$ is the number of columns in the given $matrix$. \ No newline at end of file +> Where $m$ is the number of rows and $n$ is the number of columns in the given $matrix$. diff --git a/articles/longest-increasing-subsequence-ii.md b/articles/longest-increasing-subsequence-ii.md index 1d7a0030e..694390207 100644 --- a/articles/longest-increasing-subsequence-ii.md +++ b/articles/longest-increasing-subsequence-ii.md @@ -13,7 +13,7 @@ class Solution: if nums[j] - nums[i] <= k: res = max(res, 1 + dfs(j)) return res - + res = 0 for i in range(len(nums)): res = max(res, dfs(i)) @@ -113,8 +113,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 2 ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n * 2 ^ n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -212,8 +212,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -387,7 +387,7 @@ public: int n = nums.size(); unordered_map mp; set tmp = {0}; - + for (int num : nums) { if (num - k > 0) tmp.insert(num - k); if (num - 1 > 0) tmp.insert(num - 1); @@ -447,7 +447,9 @@ class SegmentTree { * @return {number} */ query(ql, qh) { - let l = ql + this.n, r = qh + this.n + 1, res = 0; + let l = ql + this.n, + r = qh + this.n + 1, + res = 0; while (l < r) { if (l & 1) res = Math.max(res, this.tree[l++]); if (r & 1) res = Math.max(res, this.tree[--r]); @@ -475,7 +477,9 @@ class Solution { const mp = new Map(); let index = 0; - Array.from(tmp).sort((a, b) => a - b).forEach(val => mp.set(val, index++)); + Array.from(tmp) + .sort((a, b) => a - b) + .forEach((val) => mp.set(val, index++)); const ST = new SegmentTree(index); let ans = 0; @@ -495,8 +499,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -703,7 +707,9 @@ class SegmentTree { * @return {number} */ query(ql, qh) { - let l = ql + this.n, r = qh + this.n + 1, res = 0; + let l = ql + this.n, + r = qh + this.n + 1, + res = 0; while (l < r) { if (l & 1) res = Math.max(res, this.tree[l++]); if (r & 1) res = Math.max(res, this.tree[--r]); @@ -740,7 +746,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n\log m)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n\log m)$ +- Space complexity: $O(m)$ -> Where $n$ is the size of the array $nums$ and $m$ is the maximum element in the array. \ No newline at end of file +> Where $n$ is the size of the array $nums$ and $m$ is the maximum element in the array. diff --git a/articles/longest-increasing-subsequence.md b/articles/longest-increasing-subsequence.md index 79391921a..c02c4264f 100644 --- a/articles/longest-increasing-subsequence.md +++ b/articles/longest-increasing-subsequence.md @@ -5,16 +5,16 @@ ```python class Solution: def lengthOfLIS(self, nums: List[int]) -> int: - + def dfs(i, j): if i == len(nums): return 0 - + LIS = dfs(i + 1, j) # not include if j == -1 or nums[j] < nums[i]: LIS = max(LIS, 1 + dfs(i + 1, i)) # include - + return LIS return dfs(0, -1) @@ -55,7 +55,7 @@ private: return 0; } - int LIS = dfs(nums, i + 1, j); // not include + int LIS = dfs(nums, i + 1, j); // not include if (j == -1 || nums[j] < nums[i]) { LIS = max(LIS, 1 + dfs(nums, i + 1, i)); // include @@ -87,7 +87,7 @@ class Solution { return 0; } - let LIS = this.dfs(nums, i + 1, j); // not include + let LIS = this.dfs(nums, i + 1, j); // not include if (j === -1 || nums[j] < nums[i]) { LIS = Math.max(LIS, 1 + this.dfs(nums, i + 1, i)); // include @@ -196,8 +196,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ --- @@ -209,7 +209,7 @@ class Solution { class Solution: def lengthOfLIS(self, nums): n = len(nums) - memo = [[-1] * (n + 1) for _ in range(n)] + memo = [[-1] * (n + 1) for _ in range(n)] def dfs(i, j): if i == n: @@ -236,7 +236,7 @@ public class Solution { if (i == nums.length) { return 0; } - if (memo[i][j + 1] != -1) { + if (memo[i][j + 1] != -1) { return memo[i][j + 1]; } @@ -252,9 +252,9 @@ public class Solution { public int lengthOfLIS(int[] nums) { int n = nums.length; - memo = new int[n][n + 1]; + memo = new int[n][n + 1]; for (int[] row : memo) { - Arrays.fill(row, -1); + Arrays.fill(row, -1); } return dfs(0, -1, nums); } @@ -265,12 +265,12 @@ public class Solution { class Solution { public: vector> memo; - + int dfs(int i, int j, vector& nums) { if (i == nums.size()) { return 0; } - if (memo[i][j + 1] != -1) { + if (memo[i][j + 1] != -1) { return memo[i][j + 1]; } @@ -283,10 +283,10 @@ public: memo[i][j + 1] = LIS; return LIS; } - + int lengthOfLIS(vector& nums) { int n = nums.size(); - memo = vector>(n, vector(n + 1, -1)); + memo = vector>(n, vector(n + 1, -1)); return dfs(0, -1, nums); } }; @@ -300,9 +300,8 @@ class Solution { */ lengthOfLIS(nums) { const n = nums.length; - const memo = Array.from({ length: n }, () => - Array(n + 2).fill(-1)); - + const memo = Array.from({ length: n }, () => Array(n + 2).fill(-1)); + return this.dfs(nums, 0, -1, memo); } @@ -314,9 +313,8 @@ class Solution { * @return {number} */ dfs(nums, i, j, memo) { - if (i === nums.length) return 0; - if (memo[i][j + 1] !== -1) - return memo[i][j + 1]; + if (i === nums.length) return 0; + if (memo[i][j + 1] !== -1) return memo[i][j + 1]; let LIS = this.dfs(nums, i + 1, j, memo); @@ -344,7 +342,7 @@ public class Solution { } private int DFS(int[] nums, int i, int j, int[,] memo) { - if (i == nums.Length) return 0; + if (i == nums.Length) return 0; if (memo[i, j + 1] != -1) { return memo[i, j + 1]; } @@ -366,9 +364,9 @@ func lengthOfLIS(nums []int) int { n := len(nums) memo := make([][]int, n) for i := range memo { - memo[i] = make([]int, n+1) + memo[i] = make([]int, n+1) for j := range memo[i] { - memo[i][j] = -1 + memo[i][j] = -1 } } @@ -381,10 +379,10 @@ func lengthOfLIS(nums []int) int { return memo[i][j+1] } - LIS := dfs(i + 1, j) + LIS := dfs(i + 1, j) if j == -1 || nums[j] < nums[i] { - LIS = max(LIS, 1 + dfs(i + 1, i)) + LIS = max(LIS, 1 + dfs(i + 1, i)) } memo[i][j+1] = LIS @@ -414,10 +412,10 @@ class Solution { return memo[i][j + 1] } - var LIS = dfs(i + 1, j, nums) + var LIS = dfs(i + 1, j, nums) if (j == -1 || nums[j] < nums[i]) { - LIS = maxOf(LIS, 1 + dfs(i + 1, i, nums)) + LIS = maxOf(LIS, 1 + dfs(i + 1, i, nums)) } memo[i][j + 1] = LIS @@ -426,7 +424,7 @@ class Solution { fun lengthOfLIS(nums: IntArray): Int { val n = nums.size - memo = Array(n) { IntArray(n + 1) { -1 } } + memo = Array(n) { IntArray(n + 1) { -1 } } return dfs(0, -1, nums) } } @@ -465,8 +463,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -533,7 +531,7 @@ public class Solution { class Solution { private: vector memo; - + int dfs(vector& nums, int i) { if (memo[i] != -1) { return memo[i]; @@ -733,8 +731,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -746,7 +744,7 @@ class Solution { class Solution: def lengthOfLIS(self, nums): n = len(nums) - dp = [[0] * (n + 1) for _ in range(n + 1)] + dp = [[0] * (n + 1) for _ in range(n + 1)] for i in range(n - 1, -1, -1): for j in range(i - 1, -2, -1): @@ -815,7 +813,9 @@ class Solution { */ lengthOfLIS(nums) { const n = nums.length; - const dp = Array.from({ length: n + 1 }, () => new Array(n + 1).fill(0)); + const dp = Array.from({ length: n + 1 }, () => + new Array(n + 1).fill(0), + ); for (let i = n - 1; i >= 0; i--) { for (let j = i - 1; j >= -1; j--) { @@ -938,8 +938,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -1040,7 +1040,7 @@ func lengthOfLIS(nums []int) int { for i := range LIS { LIS[i] = 1 } - + for i := len(nums) - 1; i >= 0; i-- { for j := i + 1; j < len(nums); j++ { if nums[i] < nums[j] { @@ -1050,14 +1050,14 @@ func lengthOfLIS(nums []int) int { } } } - + maxLen := 1 for _, length := range LIS { if length > maxLen { maxLen = length } } - + return maxLen } ``` @@ -1066,7 +1066,7 @@ func lengthOfLIS(nums []int) int { class Solution { fun lengthOfLIS(nums: IntArray): Int { val LIS = IntArray(nums.size) { 1 } - + for (i in nums.size - 1 downTo 0) { for (j in (i + 1) until nums.size) { if (nums[i] < nums[j]) { @@ -1074,7 +1074,7 @@ class Solution { } } } - + return LIS.maxOrNull() ?: 1 } } @@ -1101,8 +1101,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -1151,7 +1151,7 @@ class Solution: for num in arr: order.append(bisect_left(sortedArr, num)) return order - + nums = compress(nums) n = len(nums) segTree = SegmentTree(n) @@ -1281,7 +1281,7 @@ public: int lengthOfLIS(vector& nums) { vector sortedArr = nums; sort(sortedArr.begin(), sortedArr.end()); - sortedArr.erase(unique(sortedArr.begin(), + sortedArr.erase(unique(sortedArr.begin(), sortedArr.end()), sortedArr.end()); vector order(nums.size()); @@ -1322,7 +1322,7 @@ class SegmentTree { this.tree[this.n + i] = val; let j = (this.n + i) >> 1; while (j >= 1) { - this.tree[j] = Math.max(this.tree[j << 1], this.tree[j << 1 | 1]); + this.tree[j] = Math.max(this.tree[j << 1], this.tree[(j << 1) | 1]); j >>= 1; } } @@ -1363,12 +1363,12 @@ class Solution { lengthOfLIS(nums) { const sortedArr = Array.from(new Set(nums)).sort((a, b) => a - b); const map = new Map(); - + sortedArr.forEach((num, index) => { map.set(num, index); }); - - const order = nums.map(num => map.get(num)); + + const order = nums.map((num) => map.get(num)); const n = sortedArr.length; const segTree = new SegmentTree(n, order); @@ -1430,14 +1430,14 @@ public class Solution { public int LengthOfLIS(int[] nums) { var sortedArr = nums.Distinct().OrderBy(x => x).ToArray(); var map = new Dictionary(); - + for (int i = 0; i < sortedArr.Length; i++) { map[sortedArr[i]] = i; } - + int n = sortedArr.Length; var segTree = new SegmentTree(n); - + int LIS = 0; foreach (var num in nums) { int compressedIndex = map[num]; @@ -1662,8 +1662,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -1680,13 +1680,13 @@ class Solution: LIS = 1 for i in range(1, len(nums)): - if dp[-1] < nums[i]: + if dp[-1] < nums[i]: dp.append(nums[i]) LIS += 1 continue idx = bisect_left(dp, nums[i]) - dp[idx] = nums[i] + dp[idx] = nums[i] return LIS ``` @@ -1699,15 +1699,15 @@ public class Solution { int LIS = 1; for (int i = 1; i < nums.length; i++) { - if (dp.get(dp.size() - 1) < nums[i]) { + if (dp.get(dp.size() - 1) < nums[i]) { dp.add(nums[i]); LIS++; continue; } int idx = Collections.binarySearch(dp, nums[i]); - if (idx < 0) idx = -idx - 1; - dp.set(idx, nums[i]); + if (idx < 0) idx = -idx - 1; + dp.set(idx, nums[i]); } return LIS; @@ -1724,15 +1724,15 @@ public: int LIS = 1; for (int i = 1; i < nums.size(); i++) { - if (dp.back() < nums[i]) { + if (dp.back() < nums[i]) { dp.push_back(nums[i]); LIS++; continue; } - int idx = lower_bound(dp.begin(), + int idx = lower_bound(dp.begin(), dp.end(), nums[i]) - dp.begin(); - dp[idx] = nums[i]; + dp[idx] = nums[i]; } return LIS; @@ -1752,13 +1752,14 @@ class Solution { let LIS = 1; for (let i = 1; i < nums.length; i++) { - if (dp[dp.length - 1] < nums[i]) { + if (dp[dp.length - 1] < nums[i]) { dp.push(nums[i]); LIS++; continue; } - let left = 0, right = dp.length - 1; + let left = 0, + right = dp.length - 1; while (left < right) { const mid = Math.floor((left + right) / 2); if (dp[mid] < nums[i]) { @@ -1767,7 +1768,7 @@ class Solution { right = mid; } } - dp[left] = nums[i]; + dp[left] = nums[i]; } return LIS; @@ -1783,15 +1784,15 @@ public class Solution { int LIS = 1; for (int i = 1; i < nums.Length; i++) { - if (dp[dp.Count - 1] < nums[i]) { + if (dp[dp.Count - 1] < nums[i]) { dp.Add(nums[i]); LIS++; continue; } int idx = dp.BinarySearch(nums[i]); - if (idx < 0) idx = ~idx; - dp[idx] = nums[i]; + if (idx < 0) idx = ~idx; + dp[idx] = nums[i]; } return LIS; @@ -1882,5 +1883,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ diff --git a/articles/longest-palindrome.md b/articles/longest-palindrome.md index 635b7a163..454318e98 100644 --- a/articles/longest-palindrome.md +++ b/articles/longest-palindrome.md @@ -105,8 +105,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n)$ +- Space complexity: $O(m)$ > Where $n$ is the length of the given string, and $m$ is the number of distinct characters in the string. @@ -193,8 +193,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n)$ +- Space complexity: $O(m)$ > Where $n$ is the length of the given string, and $m$ is the number of distinct characters in the string. @@ -289,8 +289,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n)$ +- Space complexity: $O(m)$ > Where $n$ is the length of the given string, and $m$ is the number of distinct characters in the string. @@ -406,7 +406,7 @@ class Solution { } } - return (mask1 || mask2) ? res + 1 : res; + return mask1 || mask2 ? res + 1 : res; } } ``` @@ -415,5 +415,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/longest-palindromic-subsequence.md b/articles/longest-palindromic-subsequence.md index c216ab542..693d178fa 100644 --- a/articles/longest-palindromic-subsequence.md +++ b/articles/longest-palindromic-subsequence.md @@ -13,19 +13,19 @@ class Solution: return 0 if dp[i][j] != -1: return dp[i][j] - + if s[i] == s[j]: length = 1 if i == j else 2 dp[i][j] = length + dfs(i - 1, j + 1) else: dp[i][j] = max(dfs(i - 1, j), dfs(i, j + 1)) - + return dp[i][j] for i in range(n): dfs(i, i) # odd length dfs(i, i + 1) # even length - + return max(max(row) for row in dp if row != -1) ``` @@ -151,8 +151,8 @@ class Solution { }; for (let i = 0; i < n; i++) { - dfs(i, i); // Odd length - dfs(i, i + 1); // Even length + dfs(i, i); // Odd length + dfs(i, i + 1); // Even length } let maxLength = 0; @@ -171,8 +171,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -192,12 +192,12 @@ class Solution: return 1 if (i, j) in cache: return cache[(i, j)] - + if s[i] == s[j]: cache[(i, j)] = dfs(i + 1, j - 1) + 2 else: cache[(i, j)] = max(dfs(i + 1, j), dfs(i, j - 1)) - + return cache[(i, j)] return dfs(0, len(s) - 1) @@ -314,8 +314,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -411,7 +411,8 @@ class Solution { * @return {number} */ longestCommonSubsequence(s1, s2) { - const N = s1.length, M = s2.length; + const N = s1.length, + M = s2.length; const dp = Array.from({ length: N + 1 }, () => Array(M + 1).fill(0)); for (let i = 0; i < N; i++) { @@ -433,8 +434,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -458,7 +459,7 @@ class Solution: dp[j] = prev + 2 else: dp[j] = max(dp[j], dp[j - 1]) - + prev = temp return dp[n - 1] @@ -469,7 +470,7 @@ public class Solution { public int longestPalindromeSubseq(String s) { int n = s.length(); int[] dp = new int[n]; - + for (int i = n - 1; i >= 0; i--) { dp[i] = 1; int prev = 0; @@ -484,7 +485,7 @@ public class Solution { prev = temp; } } - + return dp[n - 1]; } } @@ -553,5 +554,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ diff --git a/articles/longest-palindromic-substring.md b/articles/longest-palindromic-substring.md index 1d0f82c17..2e5b429fa 100644 --- a/articles/longest-palindromic-substring.md +++ b/articles/longest-palindromic-substring.md @@ -13,7 +13,7 @@ class Solution: while l < r and s[l] == s[r]: l += 1 r -= 1 - + if l >= r and resLen < (j - i + 1): res = s[i : j + 1] resLen = j - i + 1 @@ -80,18 +80,19 @@ class Solution { * @return {string} */ longestPalindrome(s) { - let res = ""; + let res = ''; let resLen = 0; for (let i = 0; i < s.length; i++) { for (let j = i; j < s.length; j++) { - let l = i, r = j; + let l = i, + r = j; while (l < r && s[l] === s[r]) { l++; r--; } - if (l >= r && resLen < (j - i + 1)) { + if (l >= r && resLen < j - i + 1) { res = s.slice(i, j + 1); resLen = j - i + 1; } @@ -194,7 +195,7 @@ class Solution { l += 1 r -= 1 } - + if l >= r && resLen < (j - i + 1) { res = String(chars[i...j]) resLen = j - i + 1 @@ -210,8 +211,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 3)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 3)$ +- Space complexity: $O(n)$ --- @@ -248,9 +249,9 @@ public class Solution { for (int i = n - 1; i >= 0; i--) { for (int j = i; j < n; j++) { - if (s.charAt(i) == s.charAt(j) && + if (s.charAt(i) == s.charAt(j) && (j - i <= 2 || dp[i + 1][j - 1])) { - + dp[i][j] = true; if (resLen < (j - i + 1)) { resIdx = i; @@ -276,7 +277,7 @@ public: for (int i = n - 1; i >= 0; i--) { for (int j = i; j < n; j++) { - if (s[i] == s[j] && + if (s[i] == s[j] && (j - i <= 2 || dp[i + 1][j - 1])) { dp[i][j] = true; @@ -300,18 +301,17 @@ class Solution { * @return {string} */ longestPalindrome(s) { - let resIdx = 0, resLen = 0; + let resIdx = 0, + resLen = 0; const n = s.length; const dp = Array.from({ length: n }, () => Array(n).fill(false)); for (let i = n - 1; i >= 0; i--) { for (let j = i; j < n; j++) { - if (s[i] === s[j] && - (j - i <= 2 || dp[i + 1][j - 1])) { - + if (s[i] === s[j] && (j - i <= 2 || dp[i + 1][j - 1])) { dp[i][j] = true; - if (resLen < (j - i + 1)) { + if (resLen < j - i + 1) { resIdx = i; resLen = j - i + 1; } @@ -334,9 +334,9 @@ public class Solution { for (int i = n - 1; i >= 0; i--) { for (int j = i; j < n; j++) { - if (s[i] == s[j] && + if (s[i] == s[j] && (j - i <= 2 || dp[i + 1, j - 1])) { - + dp[i, j] = true; if (resLen < (j - i + 1)) { resIdx = i; @@ -432,8 +432,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -477,7 +477,7 @@ class Solution { for (int i = 0; i < s.length(); i++) { // odd length int l = i, r = i; - while (l >= 0 && r < s.length() && + while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { if (r - l + 1 > resLen) { resIdx = l; @@ -490,7 +490,7 @@ class Solution { // even length l = i; r = i + 1; - while (l >= 0 && r < s.length() && + while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { if (r - l + 1 > resLen) { resIdx = l; @@ -557,9 +557,8 @@ class Solution { for (let i = 0; i < s.length; i++) { // odd length let l = i; - let r = i; - while (l >= 0 && r < s.length && - s.charAt(l) === s.charAt(r)) { + let r = i; + while (l >= 0 && r < s.length && s.charAt(l) === s.charAt(r)) { if (r - l + 1 > resLen) { resIdx = l; resLen = r - l + 1; @@ -571,8 +570,7 @@ class Solution { // even length l = i; r = i + 1; - while (l >= 0 && r < s.length && - s.charAt(l) === s.charAt(r)) { + while (l >= 0 && r < s.length && s.charAt(l) === s.charAt(r)) { if (r - l + 1 > resLen) { resIdx = l; resLen = r - l + 1; @@ -734,10 +732,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ space for the output string. +- Time complexity: $O(n ^ 2)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ space for the output string. --- @@ -755,13 +753,13 @@ class Solution: l, r = 0, 0 for i in range(n): p[i] = min(r - i, p[l + (r - i)]) if i < r else 0 - while (i + p[i] + 1 < n and i - p[i] - 1 >= 0 + while (i + p[i] + 1 < n and i - p[i] - 1 >= 0 and t[i + p[i] + 1] == t[i - p[i] - 1]): p[i] += 1 if i + p[i] > r: l, r = i - p[i], i + p[i] return p - + p = manacher(s) resLen, center_idx = max((v, i) for i, v in enumerate(p)) resIdx = (center_idx - resLen) // 2 @@ -791,7 +789,7 @@ public class Solution { } return p; } - + public String longestPalindrome(String s) { int[] p = manacher(s); int resLen = 0, center_idx = 0; @@ -828,7 +826,7 @@ public: } return p; } - + string longestPalindrome(string s) { vector p = manacher(s); int resLen = 0, center_idx = 0; @@ -854,11 +852,15 @@ class Solution { const t = '#' + s.split('').join('#') + '#'; const n = t.length; const p = new Array(n).fill(0); - let l = 0, r = 0; + let l = 0, + r = 0; for (let i = 0; i < n; i++) { - p[i] = (i < r) ? Math.min(r - i, p[l + (r - i)]) : 0; - while (i + p[i] + 1 < n && i - p[i] - 1 >= 0 && - t[i + p[i] + 1] === t[i - p[i] - 1]) { + p[i] = i < r ? Math.min(r - i, p[l + (r - i)]) : 0; + while ( + i + p[i] + 1 < n && + i - p[i] - 1 >= 0 && + t[i + p[i] + 1] === t[i - p[i] - 1] + ) { p[i]++; } if (i + p[i] > r) { @@ -875,7 +877,8 @@ class Solution { */ longestPalindrome(s) { const p = this.manacher(s); - let resLen = 0, center_idx = 0; + let resLen = 0, + center_idx = 0; for (let i = 0; i < p.length; i++) { if (p[i] > resLen) { resLen = p[i]; @@ -947,7 +950,7 @@ func longestPalindrome(s string) string { } return p } - + p := manacher(s) resLen, centerIdx := 0, 0 for i, v := range p { @@ -956,7 +959,7 @@ func longestPalindrome(s string) string { centerIdx = i } } - + resIdx := (centerIdx - resLen) / 2 return s[resIdx : resIdx + resLen] } @@ -971,10 +974,10 @@ class Solution { val p = IntArray(n) var l = 0 var r = 0 - + for (i in 0 until n) { p[i] = if (i < r) Math.min(r - i, p[l + (r - i)]) else 0 - while (i + p[i] + 1 < n && i - p[i] - 1 >= 0 && + while (i + p[i] + 1 < n && i - p[i] - 1 >= 0 && t[i + p[i] + 1] == t[i - p[i] - 1]) { p[i]++ } @@ -985,7 +988,7 @@ class Solution { } return p } - + val p = manacher(s) var resLen = 0 var centerIdx = 0 @@ -995,7 +998,7 @@ class Solution { centerIdx = i } } - + val resIdx = (centerIdx - resLen) / 2 return s.substring(resIdx, resIdx + resLen) } @@ -1050,5 +1053,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/longest-repeating-substring-with-replacement.md b/articles/longest-repeating-substring-with-replacement.md index 481559d2d..46405986d 100644 --- a/articles/longest-repeating-substring-with-replacement.md +++ b/articles/longest-repeating-substring-with-replacement.md @@ -72,7 +72,7 @@ class Solution { for (let j = i; j < s.length; j++) { count.set(s[j], (count.get(s[j]) || 0) + 1); maxf = Math.max(maxf, count.get(s[j])); - if ((j - i + 1) - maxf <= k) { + if (j - i + 1 - maxf <= k) { res = Math.max(res, j - i + 1); } } @@ -179,8 +179,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(m)$ > Where $n$ is the length of the string and $m$ is the total number of unique characters in the string. @@ -206,7 +206,7 @@ class Solution: if s[l] == c: count -= 1 l += 1 - + res = max(res, r - l + 1) return res ``` @@ -283,13 +283,14 @@ class Solution { let charSet = new Set(s); for (let c of charSet) { - let count = 0, l = 0; + let count = 0, + l = 0; for (let r = 0; r < s.length; r++) { if (s[r] === c) { count++; } - while ((r - l + 1) - count > k) { + while (r - l + 1 - count > k) { if (s[l] === c) { count--; } @@ -336,7 +337,7 @@ public class Solution { func characterReplacement(s string, k int) int { res := 0 charSet := make(map[byte]bool) - + for i := 0; i < len(s); i++ { charSet[s[i]] = true } @@ -358,7 +359,7 @@ func characterReplacement(s string, k int) int { res = max(res, r - l + 1) } } - + return res } @@ -434,8 +435,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m)$ > Where $n$ is the length of the string and $m$ is the total number of unique characters in the string. @@ -450,7 +451,7 @@ class Solution: def characterReplacement(self, s: str, k: int) -> int: count = {} res = 0 - + l = 0 maxf = 0 for r in range(len(s)): @@ -523,12 +524,13 @@ class Solution { let count = new Map(); let res = 0; - let l = 0, maxf = 0; + let l = 0, + maxf = 0; for (let r = 0; r < s.length; r++) { count.set(s[r], (count.get(s[r]) || 0) + 1); maxf = Math.max(maxf, count.get(s[r])); - while ((r - l + 1) - maxf > k) { + while (r - l + 1 - maxf > k) { count.set(s[l], count.get(s[l]) - 1); l++; } @@ -582,12 +584,12 @@ func characterReplacement(s string, k int) int { count[s[l]]-- l++ } - + if r - l + 1 > res { res = r - l + 1 } } - + return res } ``` @@ -608,7 +610,7 @@ class Solution { count[s[l]] = count[s[l]]!! - 1 l++ } - + res = maxOf(res, r - l + 1) } @@ -635,7 +637,7 @@ class Solution { } res = max(res, r - l + 1) } - + return res } } @@ -645,7 +647,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n)$ +- Space complexity: $O(m)$ -> Where $n$ is the length of the string and $m$ is the total number of unique characters in the string. \ No newline at end of file +> Where $n$ is the length of the string and $m$ is the total number of unique characters in the string. diff --git a/articles/longest-strictly-increasing-or-strictly-decreasing-subarray.md b/articles/longest-strictly-increasing-or-strictly-decreasing-subarray.md index 4c55b7a6b..614f61df8 100644 --- a/articles/longest-strictly-increasing-or-strictly-decreasing-subarray.md +++ b/articles/longest-strictly-increasing-or-strictly-decreasing-subarray.md @@ -78,7 +78,10 @@ class Solution { for (let i = 0; i < n - 1; i++) { let curLen = 1; for (let j = i + 1; j < n; j++) { - if (nums[j] === nums[j - 1] || ((nums[i] < nums[i + 1]) !== (nums[j - 1] < nums[j]))) { + if ( + nums[j] === nums[j - 1] || + nums[i] < nums[i + 1] !== nums[j - 1] < nums[j] + ) { break; } curLen++; @@ -95,8 +98,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -243,8 +246,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -325,7 +328,9 @@ class Solution { * @return {number} */ longestMonotonicSubarray(nums) { - let inc = 1, dec = 1, res = 1; + let inc = 1, + dec = 1, + res = 1; for (let i = 1; i < nums.length; i++) { if (nums[i] === nums[i - 1]) { @@ -349,8 +354,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -426,12 +431,14 @@ class Solution { * @return {number} */ longestMonotonicSubarray(nums) { - let curLen = 1, res = 1; + let curLen = 1, + res = 1; for (let i = 1; i < nums.length; i++) { if ( nums[i] === nums[i - 1] || - ((nums[i - curLen] < nums[i - curLen + 1]) !== (nums[i - 1] < nums[i])) + nums[i - curLen] < nums[i - curLen + 1] !== + nums[i - 1] < nums[i] ) { curLen = nums[i] === nums[i - 1] ? 1 : 2; continue; @@ -450,5 +457,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/longest-string-chain.md b/articles/longest-string-chain.md index b033bad4a..5dd13a5d2 100644 --- a/articles/longest-string-chain.md +++ b/articles/longest-string-chain.md @@ -152,8 +152,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m ^ 2)$ -* Space complexity: $O(n * m)$ +- Time complexity: $O(n * m ^ 2)$ +- Space complexity: $O(n * m)$ > Where $n$ is the number of words and $m$ is the average length of each word. @@ -303,7 +303,10 @@ class Solution { if (words[j].length + 1 < words[i].length) { break; } - if (words[j].length + 1 > words[i].length || !isPred(words[j], words[i])) { + if ( + words[j].length + 1 > words[i].length || + !isPred(words[j], words[i]) + ) { continue; } dp[i] = Math.max(dp[i], 1 + dp[j]); @@ -319,8 +322,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 * m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2 * m)$ +- Space complexity: $O(n)$ > Where $n$ is the number of words and $m$ is the average length of each word. @@ -429,7 +432,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m ^ 2)$ -* Space complexity: $O(n * m)$ +- Time complexity: $O(n * m ^ 2)$ +- Space complexity: $O(n * m)$ -> Where $n$ is the number of words and $m$ is the average length of each word. \ No newline at end of file +> Where $n$ is the number of words and $m$ is the average length of each word. diff --git a/articles/longest-substring-without-duplicates.md b/articles/longest-substring-without-duplicates.md index 3d197dc21..66169d861 100644 --- a/articles/longest-substring-without-duplicates.md +++ b/articles/longest-substring-without-duplicates.md @@ -162,8 +162,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(m)$ > Where $n$ is the length of the string and $m$ is the total number of unique characters in the string. @@ -337,8 +337,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n)$ +- Space complexity: $O(m)$ > Where $n$ is the length of the string and $m$ is the total number of unique characters in the string. @@ -354,7 +354,7 @@ class Solution: mp = {} l = 0 res = 0 - + for r in range(len(s)): if s[r] in mp: l = max(mp[s[r]] + 1, l) @@ -368,7 +368,7 @@ public class Solution { public int lengthOfLongestSubstring(String s) { HashMap mp = new HashMap<>(); int l = 0, res = 0; - + for (int r = 0; r < s.length(); r++) { if (mp.containsKey(s.charAt(r))) { l = Math.max(mp.get(s.charAt(r)) + 1, l); @@ -387,7 +387,7 @@ public: int lengthOfLongestSubstring(string s) { unordered_map mp; int l = 0, res = 0; - + for (int r = 0; r < s.size(); r++) { if (mp.find(s[r]) != mp.end()) { l = max(mp[s[r]] + 1, l); @@ -408,8 +408,9 @@ class Solution { */ lengthOfLongestSubstring(s) { let mp = new Map(); - let l = 0, res = 0; - + let l = 0, + res = 0; + for (let r = 0; r < s.length; r++) { if (mp.has(s[r])) { l = Math.max(mp.get(s[r]) + 1, l); @@ -427,7 +428,7 @@ public class Solution { public int LengthOfLongestSubstring(string s) { Dictionary mp = new Dictionary(); int l = 0, res = 0; - + for (int r = 0; r < s.Length; r++) { if (mp.ContainsKey(s[r])) { l = Math.Max(mp[s[r]] + 1, l); @@ -500,7 +501,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n)$ +- Space complexity: $O(m)$ -> Where $n$ is the length of the string and $m$ is the total number of unique characters in the string. \ No newline at end of file +> Where $n$ is the length of the string and $m$ is the total number of unique characters in the string. diff --git a/articles/longest-turbulent-subarray.md b/articles/longest-turbulent-subarray.md index 21e4958d2..1ff1ccd4f 100644 --- a/articles/longest-turbulent-subarray.md +++ b/articles/longest-turbulent-subarray.md @@ -7,11 +7,11 @@ class Solution: def maxTurbulenceSize(self, arr: List[int]) -> int: n = len(arr) res = 1 - + for i in range(n - 1): if arr[i] == arr[i + 1]: continue - + sign = 1 if arr[i] > arr[i + 1] else 0 j = i + 1 while j < n - 1: @@ -19,12 +19,12 @@ class Solution: break curSign = 1 if arr[j] > arr[j + 1] else 0 if sign == curSign: - break + break sign = curSign j += 1 - + res = max(res, j - i + 1) - + return res ``` @@ -157,8 +157,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ extra space. --- @@ -179,7 +179,7 @@ class Solution: return memo[(i, sign)] res = 1 - if ((sign and arr[i] > arr[i + 1]) or + if ((sign and arr[i] > arr[i + 1]) or (not sign and arr[i] < arr[i + 1]) ): res = 1 + dfs(i + 1, not sign) @@ -224,7 +224,7 @@ public class Solution { } int res = 1; - if ((sign && arr[i] > arr[i + 1]) || + if ((sign && arr[i] > arr[i + 1]) || (!sign && arr[i] < arr[i + 1])) { res = 1 + dfs(i + 1, !sign, arr); } @@ -261,7 +261,7 @@ public: } int res = 1; - if ((sign && arr[i] > arr[i + 1]) || + if ((sign && arr[i] > arr[i + 1]) || (!sign && arr[i] < arr[i + 1])) { res = 1 + dfs(i + 1, !sign, arr); } @@ -290,8 +290,10 @@ class Solution { } let res = 1; - if ((sign && arr[i] > arr[i + 1]) || - (!sign && arr[i] < arr[i + 1])) { + if ( + (sign && arr[i] > arr[i + 1]) || + (!sign && arr[i] < arr[i + 1]) + ) { res = 1 + dfs(i + 1, !sign); } @@ -348,8 +350,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -488,8 +490,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -581,21 +583,24 @@ class Solution { * @return {number} */ maxTurbulenceSize(arr) { - let l = 0, r = 1, res = 1, prev = ""; + let l = 0, + r = 1, + res = 1, + prev = ''; while (r < arr.length) { - if (arr[r - 1] > arr[r] && prev !== ">") { + if (arr[r - 1] > arr[r] && prev !== '>') { res = Math.max(res, r - l + 1); r++; - prev = ">"; - } else if (arr[r - 1] < arr[r] && prev !== "<") { + prev = '>'; + } else if (arr[r - 1] < arr[r] && prev !== '<') { res = Math.max(res, r - l + 1); r++; - prev = "<"; + prev = '<'; } else { - r = (arr[r] === arr[r - 1]) ? r + 1 : r; + r = arr[r] === arr[r - 1] ? r + 1 : r; l = r - 1; - prev = ""; + prev = ''; } } @@ -635,8 +640,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -650,7 +655,7 @@ class Solution: n = len(arr) res = cnt = 0 sign = -1 - + for i in range(n - 1): if arr[i] > arr[i + 1]: cnt = cnt + 1 if sign == 0 else 1 @@ -661,9 +666,9 @@ class Solution: else: cnt = 0 sign = -1 - + res = max(res, cnt) - + return res + 1 ``` @@ -672,7 +677,7 @@ public class Solution { public int maxTurbulenceSize(int[] arr) { int n = arr.length; int res = 0, cnt = 0, sign = -1; - + for (int i = 0; i < n - 1; i++) { if (arr[i] > arr[i + 1]) { cnt = (sign == 0) ? cnt + 1 : 1; @@ -684,10 +689,10 @@ public class Solution { cnt = 0; sign = -1; } - + res = Math.max(res, cnt); } - + return res + 1; } } @@ -699,7 +704,7 @@ public: int maxTurbulenceSize(vector& arr) { int n = arr.size(); int res = 0, cnt = 0, sign = -1; - + for (int i = 0; i < n - 1; i++) { if (arr[i] > arr[i + 1]) { cnt = (sign == 0) ? cnt + 1 : 1; @@ -711,10 +716,10 @@ public: cnt = 0; sign = -1; } - + res = max(res, cnt); } - + return res + 1; } }; @@ -728,23 +733,25 @@ class Solution { */ maxTurbulenceSize(arr) { const n = arr.length; - let res = 0, cnt = 0, sign = -1; - + let res = 0, + cnt = 0, + sign = -1; + for (let i = 0; i < n - 1; i++) { if (arr[i] > arr[i + 1]) { - cnt = (sign === 0) ? cnt + 1 : 1; + cnt = sign === 0 ? cnt + 1 : 1; sign = 1; } else if (arr[i] < arr[i + 1]) { - cnt = (sign === 1) ? cnt + 1 : 1; + cnt = sign === 1 ? cnt + 1 : 1; sign = 0; } else { cnt = 0; sign = -1; } - + res = Math.max(res, cnt); } - + return res + 1; } } @@ -780,5 +787,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/lowest-common-ancestor-in-binary-search-tree.md b/articles/lowest-common-ancestor-in-binary-search-tree.md index 798316614..0dd47e964 100644 --- a/articles/lowest-common-ancestor-in-binary-search-tree.md +++ b/articles/lowest-common-ancestor-in-binary-search-tree.md @@ -247,8 +247,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(h)$ -* Space complexity: $O(h)$ +- Time complexity: $O(h)$ +- Space complexity: $O(h)$ > Where $h$ is the height of the tree. @@ -299,7 +299,7 @@ class Solution: public class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { TreeNode cur = root; - + while (cur != null) { if (p.val > cur.val && q.val > cur.val) { cur = cur.right; @@ -507,7 +507,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(h)$ -* Space complexity: $O(1)$ +- Time complexity: $O(h)$ +- Space complexity: $O(1)$ -> Where $h$ is the height of the tree. \ No newline at end of file +> Where $h$ is the height of the tree. diff --git a/articles/lowest-common-ancestor-of-a-binary-tree-iii.md b/articles/lowest-common-ancestor-of-a-binary-tree-iii.md index 344d0e4f0..6f6084f25 100644 --- a/articles/lowest-common-ancestor-of-a-binary-tree-iii.md +++ b/articles/lowest-common-ancestor-of-a-binary-tree-iii.md @@ -144,8 +144,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -176,16 +176,16 @@ class Solution: h1, h2 = height(p), height(q) if h2 < h1: p, q = q, p - + diff = abs(h1 - h2) while diff: q = q.parent diff -= 1 - + while p != q: p = p.parent q = q.parent - + return p ``` @@ -207,19 +207,19 @@ public class Solution { Node tmp = p; p = q; q = tmp; int th = h1; h1 = h2; h2 = th; } - + int diff = h2 - h1; while (diff-- > 0) { q = q.parent; } - + while (p != q) { p = p.parent; q = q.parent; } return p; } - + private int height(Node node) { int h = 0; while (node != null) { @@ -261,7 +261,7 @@ public: } return p; } - + private: int height(Node* node) { int h = 0; @@ -291,7 +291,7 @@ class Solution { * @return {_Node} */ lowestCommonAncestor(p, q) { - const height = node => { + const height = (node) => { let h = 0; while (node) { h++; @@ -300,7 +300,8 @@ class Solution { return h; }; - let h1 = height(p), h2 = height(q); + let h1 = height(p), + h2 = height(q); if (h2 < h1) { [p, q] = [q, p]; [h1, h2] = [h2, h1]; @@ -338,19 +339,19 @@ public class Solution { var tmp = p; p = q; q = tmp; int th = h1; h1 = h2; h2 = th; } - + int diff = h2 - h1; while (diff-- > 0) { q = q.parent; } - + while (p != q) { p = p.parent; q = q.parent; } return p; } - + private int Height(Node node) { int h = 0; while (node != null) { @@ -366,8 +367,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -461,7 +462,8 @@ class Solution { * @return {_Node} */ lowestCommonAncestor(p, q) { - let ptr1 = p, ptr2 = q; + let ptr1 = p, + ptr2 = q; while (ptr1 !== ptr2) { ptr1 = ptr1 ? ptr1.parent : q; ptr2 = ptr2 ? ptr2.parent : p; @@ -498,5 +500,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/lru-cache.md b/articles/lru-cache.md index 2bd939f9c..d36605c15 100644 --- a/articles/lru-cache.md +++ b/articles/lru-cache.md @@ -27,7 +27,7 @@ class LRUCache: if self.capacity == len(self.cache): self.cache.pop(0) - + self.cache.append([key, value]) ``` @@ -82,7 +82,7 @@ public: LRUCache(int capacity) { this->capacity = capacity; } - + int get(int key) { for (int i = 0; i < cache.size(); i++) { if (cache[i].first == key) { @@ -94,7 +94,7 @@ public: } return -1; } - + void put(int key, int value) { for (int i = 0; i < cache.size(); i++) { if (cache[i].first == key) { @@ -170,7 +170,7 @@ public class LRUCache { this.cache = new List>(); this.capacity = capacity; } - + public int Get(int key) { for (int i = 0; i < cache.Count; i++) { if (cache[i].Key == key) { @@ -182,7 +182,7 @@ public class LRUCache { } return -1; } - + public void Put(int key, int value) { for (int i = 0; i < cache.Count; i++) { if (cache[i].Key == key) { @@ -236,11 +236,11 @@ func (this *LRUCache) Put(key int, value int) { return } } - + if len(this.cache) == this.capacity { this.cache = this.cache[1:] } - + this.cache = append(this.cache, [2]int{key, value}) } ``` @@ -249,7 +249,7 @@ func (this *LRUCache) Put(key int, value int) { class LRUCache(capacity: Int) { private val capacity = capacity private val cache = mutableListOf>() - + fun get(key: Int): Int { for (i in cache.indices) { if (cache[i].first == key) { @@ -260,7 +260,7 @@ class LRUCache(capacity: Int) { } return -1 } - + fun put(key: Int, value: Int) { for (i in cache.indices) { if (cache[i].first == key) { @@ -269,11 +269,11 @@ class LRUCache(capacity: Int) { return } } - + if (cache.size == capacity) { cache.removeAt(0) } - + cache.add(Pair(key, value)) } } @@ -323,8 +323,8 @@ class LRUCache { ### Time & Space Complexity -* Time complexity: $O(n)$ for each $put()$ and $get()$ operation. -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ for each $put()$ and $get()$ operation. +- Space complexity: $O(n)$ --- @@ -390,7 +390,7 @@ public class Node { } public class LRUCache { - + private int cap; private HashMap cache; private Node left; @@ -618,7 +618,7 @@ public class Node { } public class LRUCache { - + private int cap; private Dictionary cache; private Node left; @@ -727,11 +727,11 @@ func (this *LRUCache) Put(key int, value int) { this.remove(node) delete(this.cache, key) } - + node := &Node{key: key, val: value} this.cache[key] = node this.insert(node) - + if len(this.cache) > this.cap { lru := this.left.next this.remove(lru) @@ -749,23 +749,23 @@ class LRUCache(capacity: Int) { var prev: Node? = null, var next: Node? = null ) - + private val cache = mutableMapOf() private val left = Node(0, 0) private val right = Node(0, 0) - + init { left.next = right right.prev = left } - + private fun remove(node: Node) { val prev = node.prev val next = node.next prev?.next = next next?.prev = prev } - + private fun insert(node: Node) { val prev = right.prev val next = right @@ -774,7 +774,7 @@ class LRUCache(capacity: Int) { node.next = next node.prev = prev } - + fun get(key: Int): Int { return cache[key]?.let { node -> remove(node) @@ -782,17 +782,17 @@ class LRUCache(capacity: Int) { node.value } ?: -1 } - + fun put(key: Int, value: Int) { cache[key]?.let { node -> remove(node) cache.remove(key) } - + val node = Node(key, value) cache[key] = node insert(node) - + if (cache.size > capacity) { left.next?.let { lru -> remove(lru) @@ -877,8 +877,8 @@ class LRUCache { ### Time & Space Complexity -* Time complexity: $O(1)$ for each $put()$ and $get()$ operation. -* Space complexity: $O(n)$ +- Time complexity: $O(1)$ for each $put()$ and $get()$ operation. +- Space complexity: $O(n)$ --- @@ -943,7 +943,7 @@ public: LRUCache(int capacity) { this->capacity = capacity; } - + int get(int key) { if (cache.find(key) == cache.end()) return -1; order.erase(cache[key].second); @@ -951,7 +951,7 @@ public: cache[key].second = --order.end(); return cache[key].first; } - + void put(int key, int value) { if (cache.find(key) != cache.end()) { order.erase(cache[key].second); @@ -1101,11 +1101,11 @@ class LRUCache(capacity: Int) { return size > capacity } } - + fun get(key: Int): Int { return cache.getOrDefault(key, -1) } - + fun put(key: Int, value: Int) { cache[key] = value } @@ -1155,5 +1155,5 @@ class LRUCache { ### Time & Space Complexity -* Time complexity: $O(1)$ for each $put()$ and $get()$ operation. -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(1)$ for each $put()$ and $get()$ operation. +- Space complexity: $O(n)$ diff --git a/articles/majority-element-ii.md b/articles/majority-element-ii.md index aca6e49c3..ea1a647ef 100644 --- a/articles/majority-element-ii.md +++ b/articles/majority-element-ii.md @@ -94,8 +94,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ since output array size will be at most $2$. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ since output array size will be at most $2$. --- @@ -108,7 +108,7 @@ class Solution: def majorityElement(self, nums: List[int]) -> List[int]: nums.sort() res, n = [], len(nums) - + i = 0 while i < n: j = i + 1 @@ -139,7 +139,7 @@ public class Solution { } i = j; } - + return res; } } @@ -164,7 +164,7 @@ public: } i = j; } - + return res; } }; @@ -192,7 +192,7 @@ class Solution { } i = j; } - + return res; } } @@ -204,7 +204,7 @@ public class Solution { Array.Sort(nums); List res = new List(); int n = nums.Length; - + int i = 0; while (i < n) { int j = i + 1; @@ -226,8 +226,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -244,7 +244,7 @@ class Solution: for key in count: if count[key] > len(nums) // 3: res.append(key) - + return res ``` @@ -262,7 +262,7 @@ public class Solution { res.add(key); } } - + return res; } } @@ -283,7 +283,7 @@ public: res.push_back(pair.first); } } - + return res; } }; @@ -342,8 +342,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -372,20 +372,20 @@ class Solution: else: cnt1 -= 1 cnt2 -= 1 - + cnt1 = cnt2 = 0 for num in nums: if num == num1: cnt1 += 1 elif num == num2: cnt2 += 1 - + res = [] if cnt1 > n // 3: res.append(num1) if cnt2 > n // 3: res.append(num2) - + return res ``` @@ -477,7 +477,10 @@ class Solution { */ majorityElement(nums) { const n = nums.length; - let num1 = -1, num2 = -1, cnt1 = 0, cnt2 = 0; + let num1 = -1, + num2 = -1, + cnt1 = 0, + cnt2 = 0; for (const num of nums) { if (num === num1) { @@ -554,8 +557,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ since output array size will be at most $2$. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ since output array size will be at most $2$. --- @@ -567,24 +570,24 @@ public class Solution { class Solution: def majorityElement(self, nums: List[int]) -> List[int]: count = defaultdict(int) - + for num in nums: count[num] += 1 - + if len(count) <= 2: continue - + new_count = defaultdict(int) for num, c in count.items(): if c > 1: new_count[num] = c - 1 count = new_count - + res = [] for num in count: if nums.count(num) > len(nums) // 3: res.append(num) - + return res ``` @@ -684,7 +687,7 @@ class Solution { const res = []; for (const [key] of count.entries()) { - const frequency = nums.filter(num => num === key).length; + const frequency = nums.filter((num) => num === key).length; if (frequency > Math.floor(nums.length / 3)) { res.push(key); } @@ -742,5 +745,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ since output array size will be at most $2$. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ since output array size will be at most $2$. diff --git a/articles/majority-element.md b/articles/majority-element.md index 225347051..c87bb8139 100644 --- a/articles/majority-element.md +++ b/articles/majority-element.md @@ -62,7 +62,10 @@ class Solution { majorityElement(nums) { let n = nums.length; for (let num of nums) { - let count = nums.reduce((acc, val) => acc + (val === num ? 1 : 0), 0); + let count = nums.reduce( + (acc, val) => acc + (val === num ? 1 : 0), + 0, + ); if (count > Math.floor(n / 2)) { return num; } @@ -96,8 +99,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -164,7 +167,8 @@ class Solution { */ majorityElement(nums) { const count = new Map(); - let res = 0, maxCount = 0; + let res = 0, + maxCount = 0; for (let num of nums) { count.set(num, (count.get(num) || 0) + 1); @@ -205,8 +209,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -266,8 +270,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -283,11 +287,11 @@ class Solution: for num in nums: for i in range(32): bit[i] += ((num >> i) & 1) - + res = 0 for i in range(32): if bit[i] > (n // 2): - if i == 31: + if i == 31: res -= (1 << i) else: res |= (1 << i) @@ -357,7 +361,7 @@ class Solution { let res = 0; for (let i = 0; i < 32; i++) { if (bit[i] > Math.floor(n / 2)) { - res |= (1 << i); + res |= 1 << i; } } return res; @@ -393,8 +397,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 32)$ -* Space complexity: $O(32)$ +- Time complexity: $O(n * 32)$ +- Space complexity: $O(32)$ > $32$ represents the number of bits as the given numbers are integers. @@ -456,13 +460,14 @@ class Solution { * @return {number} */ majorityElement(nums) { - let res = 0, count = 0; + let res = 0, + count = 0; for (let num of nums) { if (count === 0) { res = num; } - count += (num === res) ? 1 : -1; + count += num === res ? 1 : -1; } return res; } @@ -490,8 +495,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -600,7 +605,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ -> The probability of randomly choosing the majority element is greater than $50\%$, so the expected number of iterations in the outer while loop is constant. \ No newline at end of file +> The probability of randomly choosing the majority element is greater than $50\%$, so the expected number of iterations in the outer while loop is constant. diff --git a/articles/make-sum-divisible-by-p.md b/articles/make-sum-divisible-by-p.md index 493f5732c..921528010 100644 --- a/articles/make-sum-divisible-by-p.md +++ b/articles/make-sum-divisible-by-p.md @@ -109,8 +109,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -231,5 +231,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/make-the-string-great.md b/articles/make-the-string-great.md index f8ee712f7..74e991df2 100644 --- a/articles/make-the-string-great.md +++ b/articles/make-the-string-great.md @@ -22,7 +22,7 @@ public class Solution { int n = s.length(); int i = 0; while (i < n) { - if (i > 0 && s.charAt(i) != s.charAt(i - 1) && + if (i > 0 && s.charAt(i) != s.charAt(i - 1) && Character.toLowerCase(s.charAt(i)) == Character.toLowerCase(s.charAt(i - 1))) { s = s.substring(0, i - 1) + s.substring(i + 1); n -= 2; @@ -64,7 +64,11 @@ class Solution { let n = s.length; let i = 0; while (i < n) { - if (i > 0 && s[i] !== s[i - 1] && s[i].toLowerCase() === s[i - 1].toLowerCase()) { + if ( + i > 0 && + s[i] !== s[i - 1] && + s[i].toLowerCase() === s[i - 1].toLowerCase() + ) { s = s.slice(0, i - 1) + s.slice(i + 1); n -= 2; i -= 2; @@ -80,8 +84,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -113,7 +117,7 @@ public class Solution { public String makeGood(String s) { StringBuilder stack = new StringBuilder(); for (char c : s.toCharArray()) { - if (stack.length() > 0 && stack.charAt(stack.length() - 1) != c && + if (stack.length() > 0 && stack.charAt(stack.length() - 1) != c && Character.toLowerCase(stack.charAt(stack.length() - 1)) == Character.toLowerCase(c)) { stack.deleteCharAt(stack.length() - 1); } else { @@ -131,7 +135,7 @@ public: string makeGood(string s) { string stack; for (char c : s) { - if (!stack.empty() && stack.back() != c && + if (!stack.empty() && stack.back() != c && tolower(stack.back()) == tolower(c)) { stack.pop_back(); } else { @@ -152,14 +156,17 @@ class Solution { makeGood(s) { const stack = []; for (const c of s) { - if (stack.length > 0 && stack[stack.length - 1] !== c && - stack[stack.length - 1].toLowerCase() === c.toLowerCase()) { + if ( + stack.length > 0 && + stack[stack.length - 1] !== c && + stack[stack.length - 1].toLowerCase() === c.toLowerCase() + ) { stack.pop(); } else { stack.push(c); } } - return stack.join(""); + return stack.join(''); } } ``` @@ -168,8 +175,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -194,7 +201,7 @@ public class Solution { public String makeGood(String s) { StringBuilder stack = new StringBuilder(); for (int i = 0; i < s.length(); i++) { - if (stack.length() > 0 && + if (stack.length() > 0 && Math.abs(stack.charAt(stack.length() - 1) - s.charAt(i)) == 32) { stack.deleteCharAt(stack.length() - 1); } else { @@ -232,14 +239,18 @@ class Solution { makeGood(s) { const stack = []; for (const c of s) { - if (stack.length > 0 && - Math.abs(stack[stack.length - 1].charCodeAt(0) - c.charCodeAt(0)) === 32) { + if ( + stack.length > 0 && + Math.abs( + stack[stack.length - 1].charCodeAt(0) - c.charCodeAt(0), + ) === 32 + ) { stack.pop(); } else { stack.push(c); } } - return stack.join(""); + return stack.join(''); } } ``` @@ -248,8 +259,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -315,7 +326,10 @@ class Solution { let l = 0; let arr = s.split(''); for (let r = 0; r < arr.length; r++) { - if (l > 0 && Math.abs(arr[r].charCodeAt(0) - arr[l - 1].charCodeAt(0)) === 32) { + if ( + l > 0 && + Math.abs(arr[r].charCodeAt(0) - arr[l - 1].charCodeAt(0)) === 32 + ) { l--; } else { arr[l++] = arr[r]; @@ -330,5 +344,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the language. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the language. diff --git a/articles/matchsticks-to-square.md b/articles/matchsticks-to-square.md index ae760c5ac..91cb7ede0 100644 --- a/articles/matchsticks-to-square.md +++ b/articles/matchsticks-to-square.md @@ -7,21 +7,21 @@ class Solution: def makesquare(self, matchsticks: List[int]) -> bool: if sum(matchsticks) % 4 != 0: return False - + sides = [0] * 4 - + def dfs(i): if i == len(matchsticks): return sides[0] == sides[1] == sides[2] == sides[3] - + for side in range(4): sides[side] += matchsticks[i] if dfs(i + 1): return True sides[side] -= matchsticks[i] - + return False - + return dfs(0) ``` @@ -92,7 +92,11 @@ class Solution { const sides = Array(4).fill(0); const dfs = (i) => { if (i === matchsticks.length) { - return sides[0] === sides[1] && sides[1] === sides[2] && sides[2] === sides[3]; + return ( + sides[0] === sides[1] && + sides[1] === sides[2] && + sides[2] === sides[3] + ); } for (let j = 0; j < 4; j++) { @@ -146,8 +150,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(4 ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(4 ^ n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -161,27 +165,27 @@ class Solution: total_length = sum(matchsticks) if total_length % 4 != 0: return False - + length = total_length // 4 sides = [0] * 4 matchsticks.sort(reverse=True) - + def dfs(i): if i == len(matchsticks): return True - + for side in range(4): if sides[side] + matchsticks[i] <= length: sides[side] += matchsticks[i] if dfs(i + 1): return True sides[side] -= matchsticks[i] - + if sides[side] == 0: break - + return False - + return dfs(0) ``` @@ -190,33 +194,33 @@ public class Solution { public boolean makesquare(int[] matchsticks) { int totalLength = Arrays.stream(matchsticks).sum(); if (totalLength % 4 != 0) return false; - + int length = totalLength / 4; int[] sides = new int[4]; Arrays.sort(matchsticks); reverse(matchsticks); - + return dfs(matchsticks, sides, 0, length); } - + private boolean dfs(int[] matchsticks, int[] sides, int index, int length) { if (index == matchsticks.length) { return true; } - + for (int i = 0; i < 4; i++) { if (sides[i] + matchsticks[index] <= length) { sides[i] += matchsticks[index]; if (dfs(matchsticks, sides, index + 1, length)) return true; sides[i] -= matchsticks[index]; } - + if (sides[i] == 0) break; } - + return false; } - + private void reverse(int[] matchsticks) { for (int i = 0, j = matchsticks.length - 1; i < j; i++, j--) { int temp = matchsticks[i]; @@ -342,8 +346,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(4 ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(4 ^ n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -357,11 +361,11 @@ class Solution: total_length = sum(matchsticks) if total_length % 4 != 0: return False - + length = total_length // 4 if max(matchsticks) > length: return False - + n = len(matchsticks) dp = [float("-inf")] * (1 << n) matchsticks.sort(reverse=True) @@ -371,7 +375,7 @@ class Solution: return 0 if dp[mask] != float("-inf"): return dp[mask] - + for i in range(n): if mask & (1 << i): res = dfs(mask ^ (1 << i)) @@ -381,10 +385,10 @@ class Solution: if mask == (1 << n) - 1: dp[mask] = -1 return -1 - + dp[mask] = -1 return -1 - + return not dfs((1 << n) - 1) ``` @@ -459,7 +463,7 @@ public: if (*max_element(matchsticks.begin(), matchsticks.end()) > length) { return false; } - + sort(matchsticks.rbegin(), matchsticks.rend()); n = matchsticks.size(); dp.resize(1 << n, INT_MIN); @@ -582,5 +586,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 2 ^ n)$ -* Space complexity: $O(n + 2 ^ n)$ \ No newline at end of file +- Time complexity: $O(n * 2 ^ n)$ +- Space complexity: $O(n + 2 ^ n)$ diff --git a/articles/matrix-diagonal-sum.md b/articles/matrix-diagonal-sum.md index 8524ff1a7..e090285bb 100644 --- a/articles/matrix-diagonal-sum.md +++ b/articles/matrix-diagonal-sum.md @@ -96,7 +96,11 @@ class Solution { return res; }; - return helper(mat) + helper(mat) - (n % 2 === 1 ? mat[Math.floor(n / 2)][Math.floor(n / 2)] : 0); + return ( + helper(mat) + + helper(mat) - + (n % 2 === 1 ? mat[Math.floor(n / 2)][Math.floor(n / 2)] : 0) + ); } } ``` @@ -105,8 +109,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ extra space. --- @@ -164,14 +168,17 @@ class Solution { * @return {number} */ diagonalSum(mat) { - let res = 0, n = mat.length; + let res = 0, + n = mat.length; for (let r = 0; r < n; r++) { res += mat[r][r]; res += mat[r][n - r - 1]; } - return res - (n % 2 == 1 ? mat[Math.floor(n / 2)][Math.floor(n / 2)] : 0); + return ( + res - (n % 2 == 1 ? mat[Math.floor(n / 2)][Math.floor(n / 2)] : 0) + ); } } ``` @@ -180,5 +187,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/max-area-of-island.md b/articles/max-area-of-island.md index cb69ca56d..b9d0e944f 100644 --- a/articles/max-area-of-island.md +++ b/articles/max-area-of-island.md @@ -15,9 +15,9 @@ class Solution: ): return 0 visit.add((r, c)) - return (1 + dfs(r + 1, c) + - dfs(r - 1, c) + - dfs(r, c + 1) + + return (1 + dfs(r + 1, c) + + dfs(r - 1, c) + + dfs(r, c + 1) + dfs(r, c - 1)) area = 0 @@ -29,13 +29,13 @@ class Solution: ```java public class Solution { - private static final int[][] directions = {{1, 0}, {-1, 0}, + private static final int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; - + public int maxAreaOfIsland(int[][] grid) { int ROWS = grid.length, COLS = grid[0].length; int area = 0; - + for (int r = 0; r < ROWS; r++) { for (int c = 0; c < COLS; c++) { if (grid[r][c] == 1) { @@ -43,16 +43,16 @@ public class Solution { } } } - + return area; } - + private int dfs(int[][] grid, int r, int c) { - if (r < 0 || c < 0 || r >= grid.length || + if (r < 0 || c < 0 || r >= grid.length || c >= grid[0].length || grid[r][c] == 0) { return 0; } - + grid[r][c] = 0; int res = 1; for (int[] dir : directions) { @@ -78,20 +78,20 @@ public: } } } - + return area; } - + int dfs(vector>& grid, int r, int c) { - if (r < 0 || c < 0 || r >= grid.size() || + if (r < 0 || c < 0 || r >= grid.size() || c >= grid[0].size() || grid[r][c] == 0) { return 0; } - + grid[r][c] = 0; int res = 1; for (int i = 0; i < 4; i++) { - res += dfs(grid, r + directions[i][0], + res += dfs(grid, r + directions[i][0], c + directions[i][1]); } return res; @@ -106,13 +106,19 @@ class Solution { * @return {number} */ maxAreaOfIsland(grid) { - const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; - const ROWS = grid.length, COLS = grid[0].length; + const directions = [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + ]; + const ROWS = grid.length, + COLS = grid[0].length; const dfs = (r, c) => { - if (r < 0 || c < 0 || r >= ROWS || - c >= COLS || grid[r][c] === 0) return 0; - + if (r < 0 || c < 0 || r >= ROWS || c >= COLS || grid[r][c] === 0) + return 0; + grid[r][c] = 0; let res = 1; for (const [dr, dc] of directions) { @@ -138,10 +144,10 @@ class Solution { ```csharp public class Solution { private static readonly int[][] directions = new int[][] { - new int[] {1, 0}, new int[] {-1, 0}, + new int[] {1, 0}, new int[] {-1, 0}, new int[] {0, 1}, new int[] {0, -1} }; - + public int MaxAreaOfIsland(int[][] grid) { int ROWS = grid.Length, COLS = grid[0].Length; int area = 0; @@ -158,7 +164,7 @@ public class Solution { } private int Dfs(int[][] grid, int r, int c) { - if (r < 0 || c < 0 || r >= grid.Length || + if (r < 0 || c < 0 || r >= grid.Length || c >= grid[0].Length || grid[r][c] == 0) { return 0; } @@ -180,7 +186,7 @@ func maxAreaOfIsland(grid [][]int) int { var dfs func(r, c int) int dfs = func(r, c int) int { - if r < 0 || r >= rows || c < 0 || c >= cols || + if r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] == 0 || visit[[2]int{r, c}] { return 0 } @@ -213,7 +219,7 @@ class Solution { val visit = HashSet>() fun dfs(r: Int, c: Int): Int { - if (r < 0 || r >= rows || c < 0 || c >= cols || + if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] == 0 || visit.contains(r to c)) { return 0 } @@ -264,8 +270,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns in the $grid$. @@ -289,7 +295,7 @@ class Solution: res = 1 while q: - row, col = q.popleft() + row, col = q.popleft() for dr, dc in directions: nr, nc = dr + row, dc + col if (nr < 0 or nc < 0 or nr >= ROWS or @@ -311,13 +317,13 @@ class Solution: ```java public class Solution { - private static final int[][] directions = {{1, 0}, {-1, 0}, + private static final int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; - + public int maxAreaOfIsland(int[][] grid) { int ROWS = grid.length, COLS = grid[0].length; int area = 0; - + for (int r = 0; r < ROWS; r++) { for (int c = 0; c < COLS; c++) { if (grid[r][c] == 1) { @@ -325,10 +331,10 @@ public class Solution { } } } - + return area; } - + private int bfs(int[][] grid, int r, int c) { Queue q = new LinkedList<>(); grid[r][c] = 0; @@ -338,10 +344,10 @@ public class Solution { while (!q.isEmpty()) { int[] node = q.poll(); int row = node[0], col = node[1]; - + for (int[] dir : directions) { int nr = row + dir[0], nc = col + dir[1]; - if (nr >= 0 && nc >= 0 && nr < grid.length && + if (nr >= 0 && nc >= 0 && nr < grid.length && nc < grid[0].length && grid[nr][nc] == 1) { q.add(new int[]{nr, nc}); grid[nr][nc] = 0; @@ -356,7 +362,7 @@ public class Solution { ```cpp class Solution { - int directions[4][2] = {{1, 0}, {-1, 0}, + int directions[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; public: int maxAreaOfIsland(vector>& grid) { @@ -386,7 +392,7 @@ public: for (int i = 0; i < 4; i++) { int nr = row + directions[i][0]; int nc = col + directions[i][1]; - if (nr >= 0 && nc >= 0 && nr < grid.size() && + if (nr >= 0 && nc >= 0 && nr < grid.size() && nc < grid[0].size() && grid[nr][nc] == 1) { q.push({nr, nc}); grid[nr][nc] = 0; @@ -406,8 +412,14 @@ class Solution { * @return {number} */ maxAreaOfIsland(grid) { - const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; - const ROWS = grid.length, COLS = grid[0].length; + const directions = [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + ]; + const ROWS = grid.length, + COLS = grid[0].length; let area = 0; const bfs = (r, c) => { @@ -415,13 +427,19 @@ class Solution { q.push([r, c]); grid[r][c] = 0; let res = 1; - + while (!q.isEmpty()) { const [row, col] = q.pop(); for (const [dr, dc] of directions) { - const nr = row + dr, nc = col + dc; - if (nr >= 0 && nc >= 0 && nr < ROWS && - nc < COLS && grid[nr][nc] === 1) { + const nr = row + dr, + nc = col + dc; + if ( + nr >= 0 && + nc >= 0 && + nr < ROWS && + nc < COLS && + grid[nr][nc] === 1 + ) { q.push([nr, nc]); grid[nr][nc] = 0; res++; @@ -447,7 +465,7 @@ class Solution { ```csharp public class Solution { private static readonly int[][] directions = new int[][] { - new int[] {1, 0}, new int[] {-1, 0}, + new int[] {1, 0}, new int[] {-1, 0}, new int[] {0, 1}, new int[] {0, -1} }; @@ -478,7 +496,7 @@ public class Solution { foreach (var dir in directions) { int nr = row + dir[0], nc = col + dir[1]; - if (nr >= 0 && nc >= 0 && nr < grid.Length && + if (nr >= 0 && nc >= 0 && nr < grid.Length && nc < grid[0].Length && grid[nr][nc] == 1) { q.Enqueue(new int[] { nr, nc }); grid[nr][nc] = 0; @@ -509,7 +527,7 @@ func maxAreaOfIsland(grid [][]int) int { row, col := front[0], front[1] for _, dir := range directions { nr, nc := row+dir[0], col+dir[1] - if nr < 0 || nc < 0 || nr >= rows || + if nr < 0 || nc < 0 || nr >= rows || nc >= cols || grid[nr][nc] == 0 { continue } @@ -542,41 +560,41 @@ func max(a, b int) int { ```kotlin class Solution { fun maxAreaOfIsland(grid: Array): Int { - val directions = arrayOf(intArrayOf(1, 0), - intArrayOf(-1, 0), - intArrayOf(0, 1), + val directions = arrayOf(intArrayOf(1, 0), + intArrayOf(-1, 0), + intArrayOf(0, 1), intArrayOf(0, -1)) val rows = grid.size val cols = grid[0].size var area = 0 - + fun bfs(r: Int, c: Int): Int { val queue = ArrayDeque>() grid[r][c] = 0 queue.add(Pair(r, c)) var res = 1 - + while (queue.isNotEmpty()) { val (row, col) = queue.removeFirst() - + for ((dr, dc) in directions) { val nr = dr + row val nc = dc + col - - if (nr < 0 || nc < 0 || nr >= rows || + + if (nr < 0 || nc < 0 || nr >= rows || nc >= cols || grid[nr][nc] == 0) { continue } - + queue.add(Pair(nr, nc)) grid[nr][nc] = 0 res++ } } - + return res } - + for (r in 0 until rows) { for (c in 0 until cols) { if (grid[r][c] == 1) { @@ -584,7 +602,7 @@ class Solution { } } } - + return area } } @@ -638,8 +656,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns in the $grid$. @@ -672,7 +690,7 @@ class DSU: self.Size[pv] += self.Size[pu] self.Parent[pu] = pv return True - + def getSize(self, node): par = self.find(node) return self.Size[par] @@ -697,7 +715,7 @@ class Solution: nc >= COLS or grid[nr][nc] == 0 ): continue - + dsu.union(index(r, c), index(nr, nc)) area = max(area, dsu.getSize(index(r, c))) @@ -759,7 +777,7 @@ public class Solution { for (int[] d : directions) { int nr = r + d[0]; int nc = c + d[1]; - if (nr >= 0 && nc >= 0 && nr < ROWS && + if (nr >= 0 && nc >= 0 && nr < ROWS && nc < COLS && grid[nr][nc] == 1) { dsu.union(r * COLS + c, nr * COLS + nc); } @@ -833,7 +851,7 @@ public: for (auto& d : directions) { int nr = r + d[0]; int nc = c + d[1]; - if (nr >= 0 && nc >= 0 && nr < ROWS && + if (nr >= 0 && nc >= 0 && nr < ROWS && nc < COLS && grid[nr][nc] == 1) { dsu.unionBySize(index(r, c), index(nr, nc)); } @@ -851,7 +869,9 @@ public: ```javascript class DSU { constructor(n) { - this.Parent = Array(n + 1).fill(0).map((_, i) => i); + this.Parent = Array(n + 1) + .fill(0) + .map((_, i) => i); this.Size = Array(n + 1).fill(1); } @@ -905,7 +925,10 @@ class Solution { const dsu = new DSU(ROWS * COLS); const directions = [ - [1, 0], [-1, 0], [0, 1], [0, -1] + [1, 0], + [-1, 0], + [0, 1], + [0, -1], ]; let area = 0; @@ -915,9 +938,15 @@ class Solution { for (let c = 0; c < COLS; c++) { if (grid[r][c] === 1) { for (let [dr, dc] of directions) { - let nr = r + dr, nc = c + dc; - if (nr >= 0 && nc >= 0 && nr < ROWS && - nc < COLS && grid[nr][nc] === 1) { + let nr = r + dr, + nc = c + dc; + if ( + nr >= 0 && + nc >= 0 && + nr < ROWS && + nc < COLS && + grid[nr][nc] === 1 + ) { dsu.union(index(r, c), index(nr, nc)); } } @@ -977,7 +1006,7 @@ public class Solution { DSU dsu = new DSU(ROWS * COLS); int[][] directions = new int[][] { - new int[] { 1, 0 }, new int[] { -1, 0 }, + new int[] { 1, 0 }, new int[] { -1, 0 }, new int[] { 0, 1 }, new int[] { 0, -1 } }; int area = 0; @@ -988,7 +1017,7 @@ public class Solution { foreach (var d in directions) { int nr = r + d[0]; int nc = c + d[1]; - if (nr >= 0 && nc >= 0 && nr < ROWS && + if (nr >= 0 && nc >= 0 && nr < ROWS && nc < COLS && grid[nr][nc] == 1) { dsu.Union(r * COLS + c, nr * COLS + nc); } @@ -1061,7 +1090,7 @@ func maxAreaOfIsland(grid [][]int) int { if grid[r][c] == 1 { for _, dir := range directions { nr, nc := r+dir[0], c+dir[1] - if nr < 0 || nc < 0 || nr >= rows || + if nr < 0 || nc < 0 || nr >= rows || nc >= cols || grid[nr][nc] == 0 { continue } @@ -1138,7 +1167,7 @@ class Solution { for (dir in directions) { val nr = r + dir[0] val nc = c + dir[1] - if (nr < 0 || nc < 0 || nr >= rows || + if (nr < 0 || nc < 0 || nr >= rows || nc >= cols || grid[nr][nc] == 0) { continue } @@ -1231,7 +1260,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ -> Where $m$ is the number of rows and $n$ is the number of columns in the $grid$. \ No newline at end of file +> Where $m$ is the number of rows and $n$ is the number of columns in the $grid$. diff --git a/articles/max-points-on-a-line.md b/articles/max-points-on-a-line.md index 8c87a3369..a760de0e4 100644 --- a/articles/max-points-on-a-line.md +++ b/articles/max-points-on-a-line.md @@ -139,8 +139,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 3)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n ^ 3)$ +- Space complexity: $O(1)$ extra space. --- @@ -175,7 +175,7 @@ public class Solution { for (int j = i + 1; j < points.length; j++) { double slope = getSlope(points[i], points[j]); if (slope == -0.0) slope = 0.0; - + count.put(slope, count.getOrDefault(slope, 0) + 1); res = Math.max(res, count.get(slope) + 1); } @@ -202,7 +202,7 @@ public: unordered_map count; for (int j = i + 1; j < points.size(); j++) { vector& p2 = points[j]; - double slope = (p2[0] == p1[0]) ? INFINITY : + double slope = (p2[0] == p1[0]) ? INFINITY : (double)(p2[1] - p1[1]) / (p2[0] - p1[0]); count[slope]++; res = max(res, count[slope] + 1); @@ -226,8 +226,10 @@ class Solution { const count = new Map(); for (let j = i + 1; j < points.length; j++) { const p2 = points[j]; - const slope = (p2[0] === p1[0]) ? Infinity : - (p2[1] - p1[1]) / (p2[0] - p1[0]); + const slope = + p2[0] === p1[0] + ? Infinity + : (p2[1] - p1[1]) / (p2[0] - p1[0]); count.set(slope, (count.get(slope) || 0) + 1); res = Math.max(res, count.get(slope) + 1); } @@ -241,8 +243,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -378,7 +380,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 \log m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2 \log m)$ +- Space complexity: $O(n)$ -> Where $n$ is the number of points and $m$ is the maximum value in the points. \ No newline at end of file +> Where $n$ is the number of points and $m$ is the maximum value in the points. diff --git a/articles/max-water-container.md b/articles/max-water-container.md index bb1ea6083..f2c2a83df 100644 --- a/articles/max-water-container.md +++ b/articles/max-water-container.md @@ -128,8 +128,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -159,7 +159,7 @@ public class Solution { int l = 0; int r = heights.length - 1; int res = 0; - + while (l < r) { int area = Math.min(heights[l], heights[r]) * (r - l); res = Math.max(res, area); @@ -181,11 +181,11 @@ public: int l = 0; int r = heights.size() - 1; int res = 0; - + while (l < r) { int area = min(heights[l], heights[r]) * (r - l); res = max(res, area); - + if (heights[l] <= heights[r]) { l++; } else { @@ -227,11 +227,11 @@ public class Solution { public int MaxArea(int[] heights) { int res = 0; int l = 0, r = heights.Length-1; - + while (l < r){ int area = (Math.Min(heights[l], heights[r])) * (r - l); res = Math.Max(area, res); - + if (heights[l] <= heights[r]){ l++; } else{ @@ -315,5 +315,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/maximal-square.md b/articles/maximal-square.md index ab7d2fce0..fd294c36f 100644 --- a/articles/maximal-square.md +++ b/articles/maximal-square.md @@ -17,7 +17,7 @@ class Solution: if r + k > m or c + k > n: break flag = True - + for i in range(r, r + k): if matrix[i][c + k - 1] == "0": flag = False @@ -26,12 +26,12 @@ class Solution: if matrix[r + k - 1][j] == "0": flag = False break - + if not flag: - break + break res = max(res, k * k) k += 1 - + return res ``` @@ -52,7 +52,7 @@ public class Solution { break; } boolean flag = true; - + for (int i = r; i < r + k; i++) { if (matrix[i][c + k - 1] == '0') { flag = false; @@ -65,7 +65,7 @@ public class Solution { break; } } - + if (!flag) { break; } @@ -74,7 +74,7 @@ public class Solution { } } } - + return res; } } @@ -98,7 +98,7 @@ public: break; } bool flag = true; - + for (int i = r; i < r + k; i++) { if (matrix[i][c + k - 1] == '0') { flag = false; @@ -111,7 +111,7 @@ public: break; } } - + if (!flag) { break; } @@ -120,7 +120,7 @@ public: } } } - + return res; } }; @@ -133,12 +133,13 @@ class Solution { * @return {number} */ maximalSquare(matrix) { - const m = matrix.length, n = matrix[0].length; + const m = matrix.length, + n = matrix[0].length; let res = 0; for (let r = 0; r < m; r++) { for (let c = 0; c < n; c++) { - if (matrix[r][c] === "0") { + if (matrix[r][c] === '0') { continue; } let k = 1; @@ -149,13 +150,13 @@ class Solution { let flag = true; for (let i = r; i < r + k; i++) { - if (matrix[i][c + k - 1] === "0") { + if (matrix[i][c + k - 1] === '0') { flag = false; break; } } for (let j = c; j < c + k; j++) { - if (matrix[r + k - 1][j] === "0") { + if (matrix[r + k - 1][j] === '0') { flag = false; break; } @@ -179,8 +180,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O((m * n) ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O((m * n) ^ 2)$ +- Space complexity: $O(1)$ > Where $m$ is the number of rows and $n$ is the number columns. @@ -300,7 +301,8 @@ class Solution { * @return {number} */ maximalSquare(matrix) { - const ROWS = matrix.length, COLS = matrix[0].length; + const ROWS = matrix.length, + COLS = matrix[0].length; const dp = Array.from({ length: ROWS }, () => Array(COLS).fill(-1)); const dfs = (r, c) => { @@ -314,7 +316,7 @@ class Solution { const right = dfs(r, c + 1); const diag = dfs(r + 1, c + 1); dp[r][c] = 0; - if (matrix[r][c] === "1") { + if (matrix[r][c] === '1') { dp[r][c] = 1 + Math.min(down, Math.min(right, diag)); } return dp[r][c]; @@ -336,8 +338,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number columns. @@ -413,14 +415,17 @@ class Solution { * @return {number} */ maximalSquare(matrix) { - const m = matrix.length, n = matrix[0].length; + const m = matrix.length, + n = matrix[0].length; const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)); let maxSquare = 0; for (let r = m - 1; r >= 0; r--) { for (let c = n - 1; c >= 0; c--) { - if (matrix[r][c] === "1") { - dp[r][c] = 1 + Math.min(dp[r + 1][c], dp[r][c + 1], dp[r + 1][c + 1]); + if (matrix[r][c] === '1') { + dp[r][c] = + 1 + + Math.min(dp[r + 1][c], dp[r][c + 1], dp[r + 1][c + 1]); maxSquare = Math.max(maxSquare, dp[r][c]); } } @@ -435,8 +440,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number columns. @@ -527,7 +532,8 @@ class Solution { * @return {number} */ maximalSquare(matrix) { - const m = matrix.length, n = matrix[0].length; + const m = matrix.length, + n = matrix[0].length; const dp = new Array(n + 1).fill(0); let maxSquare = 0; let prev = 0; @@ -535,7 +541,7 @@ class Solution { for (let r = m - 1; r >= 0; r--) { for (let c = n - 1; c >= 0; c--) { const temp = dp[c]; - if (matrix[r][c] === "1") { + if (matrix[r][c] === '1') { dp[c] = 1 + Math.min(dp[c], dp[c + 1], prev); maxSquare = Math.max(maxSquare, dp[c]); } else { @@ -554,7 +560,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(n)$ -> Where $m$ is the number of rows and $n$ is the number columns. \ No newline at end of file +> Where $m$ is the number of rows and $n$ is the number columns. diff --git a/articles/maximize-score-after-n-operations.md b/articles/maximize-score-after-n-operations.md index bf90e9d55..26608bfdf 100644 --- a/articles/maximize-score-after-n-operations.md +++ b/articles/maximize-score-after-n-operations.md @@ -149,8 +149,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ n * \log m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ n * \log m)$ +- Space complexity: $O(n)$ > Where $n$ is the size of the array $nums$ and $m$ is the maximum element in the array. @@ -277,7 +277,8 @@ class Solution { for (let j = i + 1; j < n; j++) { if ((mask & (1 << j)) !== 0) continue; let newMask = mask | (1 << i) | (1 << j); - let score = op * gcd(nums[i], nums[j]) + dfs(newMask, op + 1); + let score = + op * gcd(nums[i], nums[j]) + dfs(newMask, op + 1); maxScore = Math.max(maxScore, score); } } @@ -286,7 +287,6 @@ class Solution { return maxScore; }; - return dfs(0, 1); } } @@ -296,8 +296,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 * 2 ^ n * \log m)$ -* Space complexity: $O(2 ^ n)$ +- Time complexity: $O(n ^ 2 * 2 ^ n * \log m)$ +- Space complexity: $O(2 ^ n)$ > Where $n$ is the size of the array $nums$ and $m$ is the maximum element in the array. @@ -323,10 +323,10 @@ class Solution: max_score = 0 for i in range(n): - if mask & (1 << i): + if mask & (1 << i): continue for j in range(i + 1, n): - if mask & (1 << j): + if mask & (1 << j): continue new_mask = mask | (1 << i) | (1 << j) max_score = max( @@ -454,11 +454,11 @@ class Solution { const newMask = mask | (1 << i) | (1 << j); maxScore = Math.max( maxScore, - op * GCD[i][j] + dfs(newMask, op + 1) + op * GCD[i][j] + dfs(newMask, op + 1), ); } } - return dp[mask] = maxScore; + return (dp[mask] = maxScore); }; return dfs(0, 1); @@ -470,8 +470,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 * (2 ^ n + \log m))$ -* Space complexity: $O(n ^ 2 + 2 ^ n)$ +- Time complexity: $O(n ^ 2 * (2 ^ n + \log m))$ +- Space complexity: $O(n ^ 2 + 2 ^ n)$ > Where $n$ is the size of the array $nums$ and $m$ is the maximum element in the array. @@ -601,7 +601,7 @@ class Solution { const dp = Array(N).fill(0); for (let mask = N - 1; mask >= 0; mask--) { - let bits = mask.toString(2).split("0").join("").length; + let bits = mask.toString(2).split('0').join('').length; if (bits % 2 === 1) continue; let op = bits / 2 + 1; @@ -623,7 +623,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 * (2 ^ n + \log m))$ -* Space complexity: $O(n ^ 2 + 2 ^ n)$ +- Time complexity: $O(n ^ 2 * (2 ^ n + \log m))$ +- Space complexity: $O(n ^ 2 + 2 ^ n)$ -> Where $n$ is the size of the array $nums$ and $m$ is the maximum element in the array. \ No newline at end of file +> Where $n$ is the size of the array $nums$ and $m$ is the maximum element in the array. diff --git a/articles/maximum-alternating-subsequence-sum.md b/articles/maximum-alternating-subsequence-sum.md index 0f296306c..21e7642f0 100644 --- a/articles/maximum-alternating-subsequence-sum.md +++ b/articles/maximum-alternating-subsequence-sum.md @@ -10,7 +10,7 @@ class Solution: return 0 total = nums[i] if even else -nums[i] return max(total + dfs(i + 1, not even), dfs(i + 1, even)) - + return dfs(0, True) ``` @@ -73,8 +73,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -92,11 +92,11 @@ class Solution: return 0 if (i, even) in dp: return dp[(i, even)] - + total = nums[i] if even else -nums[i] dp[(i, even)] = max(total + dfs(i + 1, not even), dfs(i + 1, even)) return dp[(i, even)] - + return dfs(0, True) ``` @@ -173,7 +173,10 @@ class Solution { } const total = even === 1 ? nums[i] : -nums[i]; - dp[i][even] = Math.max(total + dfs(i + 1, 1 - even), dfs(i + 1, even)); + dp[i][even] = Math.max( + total + dfs(i + 1, 1 - even), + dfs(i + 1, even), + ); return dp[i][even]; }; @@ -186,8 +189,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -265,8 +268,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -283,7 +286,7 @@ class Solution: tmpEven = max(sumOdd + nums[i], sumEven) tmpOdd = max(sumEven - nums[i], sumOdd) sumEven, sumOdd = tmpEven, tmpOdd - + return sumEven ``` @@ -329,7 +332,8 @@ class Solution { * @return {number} */ maxAlternatingSum(nums) { - let sumEven = 0, sumOdd = 0; + let sumEven = 0, + sumOdd = 0; for (let i = nums.length - 1; i >= 0; i--) { let tmpEven = Math.max(nums[i] + sumOdd, sumEven); @@ -347,5 +351,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/maximum-ascending-subarray-sum.md b/articles/maximum-ascending-subarray-sum.md index 5d4e47a60..c980a6b7a 100644 --- a/articles/maximum-ascending-subarray-sum.md +++ b/articles/maximum-ascending-subarray-sum.md @@ -82,8 +82,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -150,7 +150,8 @@ class Solution { * @return {number} */ maxAscendingSum(nums) { - let res = nums[0], curSum = nums[0]; + let res = nums[0], + curSum = nums[0]; for (let i = 1; i < nums.length; i++) { if (nums[i] <= nums[i - 1]) { @@ -169,5 +170,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/maximum-element-after-decreasing-and-rearranging.md b/articles/maximum-element-after-decreasing-and-rearranging.md index b7c01b0db..811cb9673 100644 --- a/articles/maximum-element-after-decreasing-and-rearranging.md +++ b/articles/maximum-element-after-decreasing-and-rearranging.md @@ -60,8 +60,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -154,5 +154,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/maximum-frequency-stack.md b/articles/maximum-frequency-stack.md index 3579efbc6..bee45e019 100644 --- a/articles/maximum-frequency-stack.md +++ b/articles/maximum-frequency-stack.md @@ -88,7 +88,7 @@ class FreqStack { this.stack = []; } - /** + /** * @param {number} val * @return {void} */ @@ -155,10 +155,10 @@ public class FreqStack { ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for each $push()$ function call. - * $O(n)$ time for each $pop()$ function call. -* Space complexity: $O(n)$ +- Time complexity: + - $O(1)$ time for each $push()$ function call. + - $O(n)$ time for each $pop()$ function call. +- Space complexity: $O(n)$ > Where $n$ is the number of elements in the stack. @@ -170,7 +170,7 @@ public class FreqStack { ```python class FreqStack: - + def __init__(self): self.heap = [] self.cnt = defaultdict(int) @@ -194,7 +194,7 @@ public class FreqStack { private int index; public FreqStack() { - heap = new PriorityQueue<>((a, b) -> + heap = new PriorityQueue<>((a, b) -> a[0] != b[0] ? Integer.compare(b[0], a[0]) : Integer.compare(b[1], a[1]) ); cnt = new HashMap<>(); @@ -250,7 +250,7 @@ class FreqStack { this.index = 0; } - /** + /** * @param {number} val * @return {void} */ @@ -321,10 +321,10 @@ public class FreqStack { ### Time & Space Complexity -* Time complexity: - * $O(\log n)$ time for each $push()$ function call. - * $O(\log n)$ time for each $pop()$ function call. -* Space complexity: $O(n)$ +- Time complexity: + - $O(\log n)$ time for each $push()$ function call. + - $O(\log n)$ time for each $pop()$ function call. +- Space complexity: $O(n)$ > Where $n$ is the number of elements in the stack. @@ -431,7 +431,7 @@ class FreqStack { this.maxCnt = 0; } - /** + /** * @param {number} val * @return {void} */ @@ -505,10 +505,10 @@ public class FreqStack { ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for each $push()$ function call. - * $O(1)$ time for each $pop()$ function call. -* Space complexity: $O(n)$ +- Time complexity: + - $O(1)$ time for each $push()$ function call. + - $O(1)$ time for each $pop()$ function call. +- Space complexity: $O(n)$ > Where $n$ is the number of elements in the stack. @@ -610,7 +610,7 @@ class FreqStack { this.stacks = [[]]; } - /** + /** * @param {number} val * @return {void} */ @@ -681,9 +681,9 @@ public class FreqStack { ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for each $push()$ function call. - * $O(1)$ time for each $pop()$ function call. -* Space complexity: $O(n)$ +- Time complexity: + - $O(1)$ time for each $push()$ function call. + - $O(1)$ time for each $pop()$ function call. +- Space complexity: $O(n)$ -> Where $n$ is the number of elements in the stack. \ No newline at end of file +> Where $n$ is the number of elements in the stack. diff --git a/articles/maximum-length-of-a-concatenated-string-with-unique-characters.md b/articles/maximum-length-of-a-concatenated-string-with-unique-characters.md index f8cdea423..b32a1bb69 100644 --- a/articles/maximum-length-of-a-concatenated-string-with-unique-characters.md +++ b/articles/maximum-length-of-a-concatenated-string-with-unique-characters.md @@ -160,8 +160,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * 2 ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(m * 2 ^ n)$ +- Space complexity: $O(n)$ for recursion stack. > Where $n$ is the number of strings and $m$ is the maximum length of a string. @@ -338,8 +338,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * 2 ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(m * 2 ^ n)$ +- Space complexity: $O(n)$ for recursion stack. > Where $n$ is the number of strings and $m$ is the maximum length of a string. @@ -484,7 +484,7 @@ class Solution { valid = false; break; } - cur |= (1 << (c.charCodeAt(0) - 97)); + cur |= 1 << (c.charCodeAt(0) - 97); } if (valid) { @@ -515,8 +515,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n + 2 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(m * n + 2 ^ n)$ +- Space complexity: $O(n)$ > Where $n$ is the number of strings and $m$ is the maximum length of a string. @@ -652,7 +652,7 @@ class Solution { valid = false; break; } - cur |= (1 << (c.charCodeAt(0) - 97)); + cur |= 1 << (c.charCodeAt(0) - 97); } if (valid) { @@ -680,8 +680,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * (m + 2 ^ n))$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * (m + 2 ^ n))$ +- Space complexity: $O(n)$ > Where $n$ is the number of strings and $m$ is the maximum length of a string. @@ -833,11 +833,14 @@ class Solution { let next_dp = new Set(dp); for (let seq of dp) { - if ((seq & cur) || next_dp.has(seq | cur)) { + if (seq & cur || next_dp.has(seq | cur)) { continue; } next_dp.add(seq | cur); - res = Math.max(res, (seq | cur).toString(2).split('0').join('').length); + res = Math.max( + res, + (seq | cur).toString(2).split('0').join('').length, + ); } dp = next_dp; } @@ -851,7 +854,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * (m + 2 ^ n))$ -* Space complexity: $O(2 ^ n)$ +- Time complexity: $O(n * (m + 2 ^ n))$ +- Space complexity: $O(2 ^ n)$ -> Where $n$ is the number of strings and $m$ is the maximum length of a string. \ No newline at end of file +> Where $n$ is the number of strings and $m$ is the maximum length of a string. diff --git a/articles/maximum-length-of-pair-chain.md b/articles/maximum-length-of-pair-chain.md index 2855ede51..4aa351d1a 100644 --- a/articles/maximum-length-of-pair-chain.md +++ b/articles/maximum-length-of-pair-chain.md @@ -104,8 +104,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -129,7 +129,7 @@ class Solution: res = dfs(i + 1, j) if j == -1 or pairs[j][1] < pairs[i][0]: res = max(res, 1 + dfs(i + 1, i)) - + dp[i][j + 1] = res return res @@ -243,8 +243,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -257,7 +257,7 @@ class Solution: def findLongestChain(self, pairs: List[List[int]]) -> int: n = len(pairs) pairs.sort(key=lambda x: x[1]) - dp = [1] * n + dp = [1] * n for i in range(n): for j in range(i): @@ -340,8 +340,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -430,7 +430,8 @@ class Solution { let dp = []; const binarySearch = (target) => { - let left = 0, right = dp.length - 1; + let left = 0, + right = dp.length - 1; while (left <= right) { let mid = Math.floor((left + right) / 2); if (dp[mid] < target) { @@ -460,8 +461,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -552,5 +553,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n\log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. \ No newline at end of file +- Time complexity: $O(n\log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. diff --git a/articles/maximum-nesting-depth-of-the-parentheses.md b/articles/maximum-nesting-depth-of-the-parentheses.md index f18d24a7f..ad7681323 100644 --- a/articles/maximum-nesting-depth-of-the-parentheses.md +++ b/articles/maximum-nesting-depth-of-the-parentheses.md @@ -17,7 +17,7 @@ class Solution: cur += 1 elif s[i] == ')': cur -= 1 - + res = max(res, abs(cur)) return cur @@ -116,8 +116,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -209,8 +209,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -281,7 +281,8 @@ class Solution { * @return {number} */ maxDepth(s) { - let res = 0, cur = 0; + let res = 0, + cur = 0; for (let c of s) { if (c === '(') { @@ -301,5 +302,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/maximum-number-of-balloons.md b/articles/maximum-number-of-balloons.md index 597cbf295..1985fb9c3 100644 --- a/articles/maximum-number-of-balloons.md +++ b/articles/maximum-number-of-balloons.md @@ -45,7 +45,7 @@ public: countText[c]++; } - unordered_map balloon = {{'b', 1}, {'a', 1}, + unordered_map balloon = {{'b', 1}, {'a', 1}, {'l', 2}, {'o', 2}, {'n', 1}}; int res = text.length(); @@ -84,8 +84,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ since we have at most $26$ different characters. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ since we have at most $26$ different characters. --- @@ -100,10 +100,10 @@ class Solution: for c in text: if c in "balon": mp[c] += 1 - + if len(mp) < 5: return 0 - + mp['l'] //= 2 mp['o'] //= 2 return min(mp.values()) @@ -118,11 +118,11 @@ public class Solution { mp.put(c, mp.getOrDefault(c, 0) + 1); } } - + if (mp.size() < 5) { return 0; } - + mp.put('l', mp.get('l') / 2); mp.put('o', mp.get('o') / 2); return Collections.min(mp.values()); @@ -140,11 +140,11 @@ public: mp[c]++; } } - + if (mp.size() < 5) { return 0; } - + mp['l'] /= 2; mp['o'] /= 2; return min({mp['b'], mp['a'], mp['l'], mp['o'], mp['n']}); @@ -161,15 +161,15 @@ class Solution { maxNumberOfBalloons(text) { const mp = new Map(); for (let c of text) { - if ("balon".includes(c)) { + if ('balon'.includes(c)) { mp.set(c, (mp.get(c) || 0) + 1); } } - + if (mp.size < 5) { return 0; } - + mp.set('l', Math.floor(mp.get('l') / 2)); mp.set('o', Math.floor(mp.get('o') / 2)); return Math.min(...Array.from(mp.values())); @@ -181,5 +181,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ since $balloon$ has $5$ different characters. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ since $balloon$ has $5$ different characters. diff --git a/articles/maximum-number-of-removable-characters.md b/articles/maximum-number-of-removable-characters.md index bc22c959f..efba78ca4 100644 --- a/articles/maximum-number-of-removable-characters.md +++ b/articles/maximum-number-of-removable-characters.md @@ -88,14 +88,16 @@ class Solution { * @return {number} */ maximumRemovals(s, p, removable) { - let n = s.length, m = p.length; + let n = s.length, + m = p.length; let marked = new Set(); let res = 0; for (let removeIdx of removable) { marked.add(removeIdx); - let sIdx = 0, pIdx = 0; + let sIdx = 0, + pIdx = 0; while (pIdx < m && sIdx < n) { if (!marked.has(sIdx) && s[sIdx] === p[pIdx]) { pIdx++; @@ -116,8 +118,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(k * (n + m))$ -* Space complexity: $O(k)$ +- Time complexity: $O(k * (n + m))$ +- Space complexity: $O(k)$ > Where $n$ and $m$ are the lengths of the given strings $s$ and $p$ respectively. $k$ is the size of the array $removable$. @@ -238,7 +240,9 @@ class Solution { * @return {number} */ maximumRemovals(s, p, removable) { - let res = 0, l = 0, r = removable.length - 1; + let res = 0, + l = 0, + r = removable.length - 1; while (l <= r) { let m = Math.floor((l + r) / 2); @@ -262,7 +266,8 @@ class Solution { * @return {boolean} */ isSubseq(s, subseq, removed) { - let i1 = 0, i2 = 0; + let i1 = 0, + i2 = 0; while (i1 < s.length && i2 < subseq.length) { if (removed.has(i1) || s[i1] !== subseq[i2]) { i1++; @@ -280,8 +285,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O((n + m) * \log k)$ -* Space complexity: $O(k)$ +- Time complexity: $O((n + m) * \log k)$ +- Space complexity: $O(k)$ > Where $n$ and $m$ are the lengths of the given strings $s$ and $p$ respectively. $k$ is the size of the array $removable$. @@ -407,11 +412,14 @@ class Solution { * @return {number} */ maximumRemovals(s, p, removable) { - let l = 0, r = removable.length; - let n = s.length, m = p.length; + let l = 0, + r = removable.length; + let n = s.length, + m = p.length; const isSubseq = (tmpS) => { - let i1 = 0, i2 = 0; + let i1 = 0, + i2 = 0; while (i1 < n && i2 < m) { if (tmpS[i1] === p[i2]) { i2++; @@ -423,10 +431,10 @@ class Solution { while (l < r) { let mid = Math.floor(l + (r - l) / 2); - let tmpS = s.split(""); + let tmpS = s.split(''); for (let i = 0; i <= mid; i++) { - tmpS[removable[i]] = "#"; + tmpS[removable[i]] = '#'; } if (isSubseq(tmpS)) { @@ -445,7 +453,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O((n + m) * \log k)$ -* Space complexity: $O(n)$ +- Time complexity: $O((n + m) * \log k)$ +- Space complexity: $O(n)$ -> Where $n$ and $m$ are the lengths of the given strings $s$ and $p$ respectively. $k$ is the size of the array $removable$. \ No newline at end of file +> Where $n$ and $m$ are the lengths of the given strings $s$ and $p$ respectively. $k$ is the size of the array $removable$. diff --git a/articles/maximum-number-of-vowels-in-a-substring-of-given-length.md b/articles/maximum-number-of-vowels-in-a-substring-of-given-length.md index 371aff2b3..9dd1f6645 100644 --- a/articles/maximum-number-of-vowels-in-a-substring-of-given-length.md +++ b/articles/maximum-number-of-vowels-in-a-substring-of-given-length.md @@ -13,7 +13,7 @@ class Solution: for j in range(i, i + k): cnt += 1 if s[j] in vowel else 0 res = max(res, cnt) - + return res ``` @@ -90,8 +90,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ extra space. --- @@ -106,11 +106,11 @@ class Solution: prefix = [0] * (len(s) + 1) for i in range(len(s)): prefix[i + 1] = prefix[i] + (1 if s[i] in vowel else 0) - + res = 0 for i in range(k, len(s) + 1): res = max(res, prefix[i] - prefix[i - k]) - + return res ``` @@ -184,8 +184,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -197,7 +197,7 @@ class Solution { class Solution: def maxVowels(self, s: str, k: int) -> int: vowel = {'a', 'e', 'i', 'o', 'u'} - + l = cnt = res = 0 for r in range(len(s)): cnt += 1 if s[r] in vowel else 0 @@ -212,7 +212,7 @@ class Solution: public class Solution { public int maxVowels(String s, int k) { Set vowels = Set.of('a', 'e', 'i', 'o', 'u'); - + int l = 0, cnt = 0, res = 0; for (int r = 0; r < s.length(); r++) { cnt += (vowels.contains(s.charAt(r)) ? 1 : 0); @@ -232,7 +232,7 @@ class Solution { public: int maxVowels(string s, int k) { unordered_set vowels = {'a', 'e', 'i', 'o', 'u'}; - + int l = 0, cnt = 0, res = 0; for (int r = 0; r < s.length(); r++) { cnt += (vowels.count(s[r]) ? 1 : 0); @@ -255,12 +255,14 @@ class Solution { */ maxVowels(s, k) { const vowels = new Set(['a', 'e', 'i', 'o', 'u']); - - let l = 0, cnt = 0, res = 0; + + let l = 0, + cnt = 0, + res = 0; for (let r = 0; r < s.length; r++) { - cnt += (vowels.has(s[r]) ? 1 : 0); + cnt += vowels.has(s[r]) ? 1 : 0; if (r - l + 1 > k) { - cnt -= (vowels.has(s[l++]) ? 1 : 0); + cnt -= vowels.has(s[l++]) ? 1 : 0; } res = Math.max(res, cnt); } @@ -273,8 +275,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -291,7 +293,7 @@ class Solution: mask = (1 << getId('a')) | (1 << getId('e')) | \ (1 << getId('i')) | (1 << getId('o')) | \ (1 << getId('u')) - + l = cnt = res = 0 for r in range(len(s)): cnt += ((mask >> getId(s[r])) & 1) @@ -305,8 +307,8 @@ class Solution: ```java public class Solution { public int maxVowels(String s, int k) { - int mask = (1 << ('a' - 'a')) | (1 << ('e' - 'a')) | - (1 << ('i' - 'a')) | (1 << ('o' - 'a')) | + int mask = (1 << ('a' - 'a')) | (1 << ('e' - 'a')) | + (1 << ('i' - 'a')) | (1 << ('o' - 'a')) | (1 << ('u' - 'a')); int l = 0, cnt = 0, res = 0; @@ -328,8 +330,8 @@ public class Solution { class Solution { public: int maxVowels(string s, int k) { - int mask = (1 << ('a' - 'a')) | (1 << ('e' - 'a')) | - (1 << ('i' - 'a')) | (1 << ('o' - 'a')) | + int mask = (1 << ('a' - 'a')) | (1 << ('e' - 'a')) | + (1 << ('i' - 'a')) | (1 << ('o' - 'a')) | (1 << ('u' - 'a')); int l = 0, cnt = 0, res = 0; @@ -356,13 +358,18 @@ class Solution { */ maxVowels(s, k) { const getId = (c) => { - return c.charCodeAt(0) - 'a'.charCodeAt(0); + return c.charCodeAt(0) - 'a'.charCodeAt(0); }; - const mask = (1 << getId('a')) | (1 << getId('e')) | - (1 << getId('i')) | (1 << getId('o')) | - (1 << getId('u')); - - let l = 0, cnt = 0, res = 0; + const mask = + (1 << getId('a')) | + (1 << getId('e')) | + (1 << getId('i')) | + (1 << getId('o')) | + (1 << getId('u')); + + let l = 0, + cnt = 0, + res = 0; for (let r = 0; r < s.length; r++) { cnt += (mask >> getId(s.charAt(r))) & 1; if (r - l + 1 > k) { @@ -381,5 +388,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/maximum-odd-binary-number.md b/articles/maximum-odd-binary-number.md index 41846d673..c3a60840d 100644 --- a/articles/maximum-odd-binary-number.md +++ b/articles/maximum-odd-binary-number.md @@ -10,7 +10,7 @@ class Solution: i = len(s) - 1 while i >= 0 and s[i] == "0": i -= 1 - + s[i], s[len(s) - 1] = s[len(s) - 1], s[i] return ''.join(s) ``` @@ -57,7 +57,7 @@ public: while (i >= 0 && s[i] == '0') { i--; } - + swap(s[i], s[n - 1]); return s; } @@ -89,8 +89,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -105,7 +105,7 @@ class Solution: for c in s: if c == "1": count += 1 - + return (count - 1) * "1" + (len(s) - count) * "0" + "1" ``` @@ -116,12 +116,12 @@ public class Solution { for (char c : s.toCharArray()) { if (c == '1') count++; } - + StringBuilder result = new StringBuilder(); for (int i = 0; i < count - 1; i++) result.append('1'); for (int i = 0; i < s.length() - count; i++) result.append('0'); result.append('1'); - + return result.toString(); } } @@ -135,11 +135,11 @@ public: for (char c : s) { if (c == '1') count++; } - + string result((count - 1), '1'); result += string(s.length() - count, '0'); result += '1'; - + return result; } }; @@ -156,7 +156,7 @@ class Solution { for (const c of s) { if (c === '1') count++; } - + return '1'.repeat(count - 1) + '0'.repeat(s.length - count) + '1'; } } @@ -166,8 +166,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -226,7 +226,7 @@ public: left++; } } - + swap(arr[left - 1], arr[arr.size() - 1]); return string(arr.begin(), arr.end()); } @@ -250,7 +250,10 @@ class Solution { } } - [arr[left - 1], arr[arr.length - 1]] = [arr[arr.length - 1], arr[left - 1]]; + [arr[left - 1], arr[arr.length - 1]] = [ + arr[arr.length - 1], + arr[left - 1], + ]; return arr.join(''); } } @@ -260,5 +263,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/maximum-performance-of-a-team.md b/articles/maximum-performance-of-a-team.md index 3fc63e969..b51355ecd 100644 --- a/articles/maximum-performance-of-a-team.md +++ b/articles/maximum-performance-of-a-team.md @@ -96,7 +96,12 @@ class Solution { if (i === n || k === 0) return; dfs(i + 1, k, minEff, speedSum); - dfs(i + 1, k - 1, Math.min(minEff, efficiency[i]), speedSum + speed[i]); + dfs( + i + 1, + k - 1, + Math.min(minEff, efficiency[i]), + speedSum + speed[i], + ); }; dfs(0, k, Infinity, 0); @@ -109,8 +114,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -212,7 +217,8 @@ class Solution { engineers.sort((a, b) => b[0] - a[0]); const minHeap = new MinPriorityQueue(); - let speedSum = BigInt(0), res = BigInt(0); + let speedSum = BigInt(0), + res = BigInt(0); for (const [eff, spd] of engineers) { if (minHeap.size() === k) { @@ -232,7 +238,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * (\log n + \log k))$ -* Space complexity: $O(n + k)$ +- Time complexity: $O(n * (\log n + \log k))$ +- Space complexity: $O(n + k)$ -> Where $n$ is the number of engineers and $k$ is the maximum number of engineers that can be selected. \ No newline at end of file +> Where $n$ is the number of engineers and $k$ is the maximum number of engineers that can be selected. diff --git a/articles/maximum-points-you-can-obtain-from-cards.md b/articles/maximum-points-you-can-obtain-from-cards.md index 8d1b9294a..87d28bbd8 100644 --- a/articles/maximum-points-you-can-obtain-from-cards.md +++ b/articles/maximum-points-you-can-obtain-from-cards.md @@ -101,8 +101,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(k ^ 2)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(k ^ 2)$ +- Space complexity: $O(1)$ extra space. > Where $k$ is the number of cards to pick. @@ -221,8 +221,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -349,8 +349,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -431,7 +431,8 @@ class Solution { * @return {number} */ maxScore(cardPoints, k) { - let l = 0, r = cardPoints.length - k; + let l = 0, + r = cardPoints.length - k; let total = 0; for (let i = r; i < cardPoints.length; i++) { @@ -456,7 +457,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(k)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(k)$ +- Space complexity: $O(1)$ extra space. -> Where $k$ is the number of cards to pick. \ No newline at end of file +> Where $k$ is the number of cards to pick. diff --git a/articles/maximum-product-difference-between-two-pairs.md b/articles/maximum-product-difference-between-two-pairs.md index e5425c2f8..1f5f4ce9d 100644 --- a/articles/maximum-product-difference-between-two-pairs.md +++ b/articles/maximum-product-difference-between-two-pairs.md @@ -76,7 +76,10 @@ class Solution { if (a === c || b === c) continue; for (let d = 0; d < n; d++) { if (a === d || b === d || c === d) continue; - res = Math.max(res, nums[a] * nums[b] - nums[c] * nums[d]); + res = Math.max( + res, + nums[a] * nums[b] - nums[c] * nums[d], + ); } } } @@ -90,8 +93,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 4)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 4)$ +- Space complexity: $O(1)$ --- @@ -133,7 +136,9 @@ class Solution { */ maxProductDifference(nums) { nums.sort((a, b) => a - b); - return nums[nums.length - 1] * nums[nums.length - 2] - nums[0] * nums[1]; + return ( + nums[nums.length - 1] * nums[nums.length - 2] - nums[0] * nums[1] + ); } } ``` @@ -142,8 +147,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -166,7 +171,7 @@ class Solution: min1, min2 = num, min1 elif num < min2: min2 = num - + return (max1 * max2) - (min1 * min2) ``` @@ -226,8 +231,10 @@ class Solution { * @return {number} */ maxProductDifference(nums) { - let max1 = 0, max2 = 0; - let min1 = Infinity, min2 = Infinity; + let max1 = 0, + max2 = 0; + let min1 = Infinity, + min2 = Infinity; for (const num of nums) { if (num > max1) { max2 = max1; @@ -242,7 +249,7 @@ class Solution { min2 = num; } } - return (max1 * max2) - (min1 * min2); + return max1 * max2 - min1 * min2; } } ``` @@ -251,5 +258,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/maximum-product-of-the-length-of-two-palindromic-subsequences.md b/articles/maximum-product-of-the-length-of-two-palindromic-subsequences.md index bd17730e3..5aaccd7a7 100644 --- a/articles/maximum-product-of-the-length-of-two-palindromic-subsequences.md +++ b/articles/maximum-product-of-the-length-of-two-palindromic-subsequences.md @@ -21,11 +21,11 @@ class Solution: if isPal(seq1) and isPal(seq2): res = max(res, len(seq1) * len(seq2)) return - + rec(i + 1, seq1, seq2) rec(i + 1, seq1 + s[i], seq2) rec(i + 1, seq1, seq2 + s[i]) - + rec(0, "", "") return res ``` @@ -115,7 +115,8 @@ class Solution { */ maxProduct(s) { const isPal = (str) => { - let i = 0, j = str.length - 1; + let i = 0, + j = str.length - 1; while (i < j) { if (str[i] !== str[j]) return false; i++; @@ -139,7 +140,7 @@ class Solution { rec(i + 1, seq1, seq2 + s[i]); }; - rec(0, "", ""); + rec(0, '', ''); return res; } } @@ -149,8 +150,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 3 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * 3 ^ n)$ +- Space complexity: $O(n)$ --- @@ -177,16 +178,16 @@ class Solution: for i in range(N): if mask & (1 << i): subseq += s[i] - + if isPal(subseq): pali[mask] = len(subseq) - + res = 0 for m1 in pali: for m2 in pali: if m1 & m2 == 0: res = max(res, pali[m1] * pali[m2]) - + return res ``` @@ -290,7 +291,8 @@ class Solution { */ maxProduct(s) { const isPal = (str) => { - let i = 0, j = str.length - 1; + let i = 0, + j = str.length - 1; while (i < j) { if (str[i] !== str[j]) return false; i++; @@ -298,13 +300,13 @@ class Solution { } return true; }; - + const N = s.length; let res = 0; const pali = new Map(); - for (let mask = 1; mask < (1 << N); mask++) { - let subseq = ""; + for (let mask = 1; mask < 1 << N; mask++) { + let subseq = ''; for (let i = 0; i < N; i++) { if ((mask & (1 << i)) !== 0) { subseq += s[i]; @@ -333,8 +335,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(4 ^ n)$ -* Space complexity: $O(2 ^ n)$ +- Time complexity: $O(4 ^ n)$ +- Space complexity: $O(2 ^ n)$ --- @@ -348,7 +350,7 @@ class Solution: n = len(s) if n == 0: return 0 - + dp = [1] * n for i in range(n - 1, -1, -1): prev = 0 @@ -360,14 +362,14 @@ class Solution: dp[j] = max(dp[j - 1], dp[j]) prev = tmp return dp[n - 1] - + def maxProduct(self, s: str) -> int: n = len(s) res = 0 - + for i in range(1, 1 << n): seq1, seq2 = [], [] - + for j in range(n): if (i & (1 << j)) != 0: seq1.append(s[j]) @@ -379,9 +381,9 @@ class Solution: lps = self.longestPalindromeSubseq(''.join(seq2)) res = max(res, len(seq1) * lps) - + return res - + def isPal(self, s: str) -> bool: i, j = 0, len(s) - 1 while i < j: @@ -397,7 +399,7 @@ public class Solution { public int longestPalindromeSubseq(String s) { int n = s.length(); if (n == 0) return 0; - + int[] dp = new int[n]; Arrays.fill(dp, 1); for (int i = n - 1; i >= 0; i--) { @@ -414,14 +416,14 @@ public class Solution { } return dp[n - 1]; } - + public int maxProduct(String s) { int n = s.length(); int res = 0; - + for (int i = 1; i < (1 << n); i++) { StringBuilder seq1 = new StringBuilder(), seq2 = new StringBuilder(); - + for (int j = 0; j < n; j++) { char c = s.charAt(j); if ((i & (1 << j)) != 0) seq1.append(c); @@ -432,7 +434,7 @@ public class Solution { int lps = longestPalindromeSubseq(seq2.toString()); res = Math.max(res, seq1.length() * lps); } - + return res; } @@ -456,7 +458,7 @@ public: int longestPalindromeSubseq(string& s) { int n = s.length(); if (n == 0) return 0; - + vector dp(n, 1); for (int i = n - 1; i >= 0; i--) { int prev = 0; @@ -476,10 +478,10 @@ public: int maxProduct(string s) { int n = s.length(); int res = 0; - + for (int i = 1; i < (1 << n); i++) { string seq1 = "", seq2 = ""; - + for (int j = 0; j < n; j++) { if ((i & (1 << j)) != 0) seq1 += s[j]; else seq2 += s[j]; @@ -490,7 +492,7 @@ public: int lps = longestPalindromeSubseq(seq2); res = max(res, int(seq1.length()) * lps); } - + return res; } @@ -517,7 +519,7 @@ class Solution { longestPalindromeSubseq(s) { const n = s.length; if (n === 0) return 0; - + const dp = new Array(n).fill(1); for (let i = n - 1; i >= 0; i--) { let prev = 0; @@ -541,10 +543,11 @@ class Solution { maxProduct(s) { const n = s.length; let res = 0; - - for (let i = 1; i < (1 << n); i++) { - let seq1 = "", seq2 = ""; - + + for (let i = 1; i < 1 << n; i++) { + let seq1 = '', + seq2 = ''; + for (let j = 0; j < n; j++) { if ((i & (1 << j)) !== 0) seq1 += s[j]; else seq2 += s[j]; @@ -555,7 +558,7 @@ class Solution { const lps = this.longestPalindromeSubseq(seq2); res = Math.max(res, seq1.length * lps); } - + return res; } @@ -564,7 +567,8 @@ class Solution { * @return {boolean} */ isPal(s) { - let i = 0, j = s.length - 1; + let i = 0, + j = s.length - 1; while (i < j) { if (s[i] !== s[j]) { return false; @@ -581,8 +585,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 * 2 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2 * 2 ^ n)$ +- Space complexity: $O(n)$ --- @@ -806,7 +810,7 @@ class Solution { let res = 0; const dp = Array(n).fill(1); - for (let i = 1; i < (1 << n); i++) { + for (let i = 1; i < 1 << n; i++) { const m1 = this.palsize(s, i); if (m1 === 0) continue; @@ -822,21 +826,22 @@ class Solution { } return res; } - + /** * @param {string} s * @param {number} mask * @return {number} */ palsize(s, mask) { - let i = 0, j = s.length - 1; + let i = 0, + j = s.length - 1; let res = 0; while (i <= j) { if ((mask & (1 << i)) === 0) i++; else if ((mask & (1 << j)) === 0) j--; else { if (s[i] !== s[j]) return 0; - res += (i === j) ? 1 : 2; + res += i === j ? 1 : 2; i++; j--; } @@ -850,5 +855,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 * 2 ^ n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n ^ 2 * 2 ^ n)$ +- Space complexity: $O(n)$ diff --git a/articles/maximum-product-subarray.md b/articles/maximum-product-subarray.md index f163b341f..83fcbea27 100644 --- a/articles/maximum-product-subarray.md +++ b/articles/maximum-product-subarray.md @@ -13,7 +13,7 @@ class Solution: for j in range(i + 1, len(nums)): cur *= nums[j] res = max(res, cur) - + return res ``` @@ -30,7 +30,7 @@ public class Solution { res = Math.max(res, cur); } } - + return res; } } @@ -50,7 +50,7 @@ public: res = max(res, cur); } } - + return res; } }; @@ -73,7 +73,7 @@ class Solution { res = Math.max(res, cur); } } - + return res; } } @@ -92,7 +92,7 @@ public class Solution { res = Math.Max(res, cur); } } - + return res; } } @@ -160,8 +160,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -309,7 +309,7 @@ class Solution { let cur = []; let res = -Infinity; - nums.forEach(num => { + nums.forEach((num) => { res = Math.max(res, num); if (num === 0) { if (cur.length) A.push(cur); @@ -320,14 +320,14 @@ class Solution { }); if (cur.length) A.push(cur); - A.forEach(sub => { + A.forEach((sub) => { let negs = 0; - sub.forEach(i => { + sub.forEach((i) => { if (i < 0) negs++; }); let prod = 1; - let need = (negs % 2 === 0) ? negs : (negs - 1); + let need = negs % 2 === 0 ? negs : negs - 1; negs = 0; for (let i = 0, j = 0; i < sub.length; i++) { prod *= sub[i]; @@ -572,8 +572,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -735,8 +735,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -798,8 +798,10 @@ class Solution { * @return {number} */ maxProduct(nums) { - let n = nums.length, res = nums[0]; - let prefix = 0, suffix = 0; + let n = nums.length, + res = nums[0]; + let prefix = 0, + suffix = 0; for (let i = 0; i < n; i++) { prefix = nums[i] * (prefix === 0 ? 1 : prefix); @@ -841,7 +843,7 @@ func maxProduct(nums []int) int { if suffix == 0 { suffix = 1 } - + prefix *= nums[i] suffix *= nums[n-1-i] res = max(res, max(prefix, suffix)) @@ -901,5 +903,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/maximum-profit-in-job-scheduling.md b/articles/maximum-profit-in-job-scheduling.md index 0c0d40541..f8eee55d4 100644 --- a/articles/maximum-profit-in-job-scheduling.md +++ b/articles/maximum-profit-in-job-scheduling.md @@ -123,9 +123,9 @@ class Solution { */ jobScheduling(startTime, endTime, profit) { let n = startTime.length; - let intervals = new Array(n).fill(null).map((_, i) => - [startTime[i], endTime[i], profit[i]] - ); + let intervals = new Array(n) + .fill(null) + .map((_, i) => [startTime[i], endTime[i], profit[i]]); intervals.sort((a, b) => a[0] - b[0]); let cache = new Array(n).fill(-1); @@ -195,8 +195,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -231,7 +231,7 @@ class Solution: public class Solution { private int[][] intervals; private int[] cache; - + public int jobScheduling(int[] startTime, int[] endTime, int[] profit) { int n = startTime.length; intervals = new int[n][3]; @@ -328,9 +328,9 @@ class Solution { */ jobScheduling(startTime, endTime, profit) { let n = startTime.length; - let intervals = new Array(n).fill(null).map((_, i) => - [startTime[i], endTime[i], profit[i]] - ); + let intervals = new Array(n) + .fill(null) + .map((_, i) => [startTime[i], endTime[i], profit[i]]); intervals.sort((a, b) => a[0] - b[0]); let cache = new Array(n).fill(-1); @@ -345,7 +345,9 @@ class Solution { let res = dfs(i + 1); - let left = i + 1, right = n, j = n; + let left = i + 1, + right = n, + j = n; while (left < right) { let mid = Math.floor((left + right) / 2); if (intervals[mid][0] >= intervals[i][1]) { @@ -410,8 +412,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -576,7 +578,9 @@ class Solution { let res = dfs(i + 1); - let left = i + 1, right = n, j = n; + let left = i + 1, + right = n, + j = n; while (left < right) { let mid = Math.floor((left + right) / 2); if (startTime[index[mid]] >= endTime[index[i]]) { @@ -645,8 +649,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -753,7 +757,9 @@ class Solution { let dp = new Array(n + 1).fill(0); for (let i = n - 1; i >= 0; i--) { - let left = i + 1, right = n, j = n; + let left = i + 1, + right = n, + j = n; while (left < right) { let mid = Math.floor((left + right) / 2); if (startTime[index[mid]] >= endTime[index[i]]) { @@ -806,5 +812,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ diff --git a/articles/maximum-score-after-splitting-a-string.md b/articles/maximum-score-after-splitting-a-string.md index 04d95fb31..dc14477e0 100644 --- a/articles/maximum-score-after-splitting-a-string.md +++ b/articles/maximum-score-after-splitting-a-string.md @@ -76,7 +76,8 @@ class Solution { const n = s.length; let res = 0; for (let i = 1; i < n; i++) { - let leftZero = 0, rightOne = 0; + let leftZero = 0, + rightOne = 0; for (let j = 0; j < i; j++) { if (s[j] === '0') { leftZero++; @@ -98,8 +99,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -250,8 +251,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -334,7 +335,9 @@ class Solution { * @return {number} */ maxScore(s) { - let zero = 0, one = 0, res = 0; + let zero = 0, + one = 0, + res = 0; for (const c of s) { if (c === '1') { @@ -360,8 +363,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -391,7 +394,7 @@ class Solution: zeros += 1 else: ones += 1 - + return res + ones ``` @@ -465,7 +468,9 @@ class Solution { // res = Max of all (leftZeros + (totalOnes - leftOnes)) // res = totalOnes (constant) + Max of all (leftZeros - leftOnes) - let zeros = 0, ones = 0, res = -Infinity; + let zeros = 0, + ones = 0, + res = -Infinity; if (s[0] === '0') { zeros++; @@ -491,5 +496,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/maximum-score-of-a-good-subarray.md b/articles/maximum-score-of-a-good-subarray.md index f8b6fbdc0..4af0c3934 100644 --- a/articles/maximum-score-of-a-good-subarray.md +++ b/articles/maximum-score-of-a-good-subarray.md @@ -64,7 +64,8 @@ class Solution { * @return {number} */ maximumScore(nums, k) { - let n = nums.length, res = 0; + let n = nums.length, + res = 0; for (let i = 0; i <= k; i++) { let minEle = nums[i]; @@ -84,8 +85,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ extra space. --- @@ -234,7 +235,8 @@ class Solution { * @return {number} */ maximumScore(nums, k) { - let n = nums.length, res = 0; + let n = nums.length, + res = 0; let arr = [...nums]; for (let i = k - 1; i >= 0; i--) { @@ -248,7 +250,8 @@ class Solution { let rightArr = arr.slice(k); const findLeft = (target) => { - let lo = 0, hi = leftArr.length - 1; + let lo = 0, + hi = leftArr.length - 1; while (lo <= hi) { let mid = Math.floor((lo + hi) / 2); if (leftArr[mid] < target) { @@ -261,7 +264,9 @@ class Solution { }; const findRight = (target) => { - let lo = 0, hi = rightArr.length - 1, pos = 0; + let lo = 0, + hi = rightArr.length - 1, + pos = 0; while (lo <= hi) { let mid = Math.floor((lo + hi) / 2); if (rightArr[mid] >= target) { @@ -289,8 +294,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -446,7 +451,8 @@ class Solution { * @return {number} */ maximumScore(nums, k) { - let n = nums.length, res = 0; + let n = nums.length, + res = 0; for (let i = k - 1; i >= 0; i--) { nums[i] = Math.min(nums[i], nums[i + 1]); @@ -456,7 +462,8 @@ class Solution { } const findLeft = (target) => { - let lo = 0, hi = k; + let lo = 0, + hi = k; while (lo <= hi) { let mid = Math.floor((lo + hi) / 2); if (nums[mid] < target) { @@ -469,7 +476,8 @@ class Solution { }; const findRight = (target) => { - let lo = k, hi = n - 1; + let lo = k, + hi = n - 1; while (lo <= hi) { let mid = Math.floor((lo + hi) / 2); if (nums[mid] >= target) { @@ -496,8 +504,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -576,11 +584,15 @@ class Solution { * @return {number} */ maximumScore(nums, k) { - let n = nums.length, res = 0; + let n = nums.length, + res = 0; let stack = []; for (let i = 0; i <= n; i++) { - while (stack.length && (i === n || nums[stack[stack.length - 1]] >= nums[i])) { + while ( + stack.length && + (i === n || nums[stack[stack.length - 1]] >= nums[i]) + ) { let mini = nums[stack.pop()]; let j = stack.length ? stack[stack.length - 1] : -1; if (j < k && k < i) { @@ -599,8 +611,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -696,14 +708,15 @@ class Solution { * @return {number} */ maximumScore(nums, k) { - let l = k, r = k; + let l = k, + r = k; let res = nums[k]; let curMin = nums[k]; let n = nums.length; while (l > 0 || r < n - 1) { - let left = (l > 0) ? nums[l - 1] : 0; - let right = (r < n - 1) ? nums[r + 1] : 0; + let left = l > 0 ? nums[l - 1] : 0; + let right = r < n - 1 ? nums[r + 1] : 0; if (left > right) { l--; @@ -725,5 +738,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/maximum-score-words-formed-by-letters.md b/articles/maximum-score-words-formed-by-letters.md index f9b510481..30ab627ee 100644 --- a/articles/maximum-score-words-formed-by-letters.md +++ b/articles/maximum-score-words-formed-by-letters.md @@ -192,7 +192,8 @@ class Solution { let res = backtrack(i + 1); // skip - if (canFormWord(words[i], letterCnt)) { // include (when possible) + if (canFormWord(words[i], letterCnt)) { + // include (when possible) for (let c of words[i]) { letterCnt[c.charCodeAt(0) - 'a'.charCodeAt(0)]--; } @@ -214,8 +215,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n * (w + m) + N)$ -* Space complexity: $O(n + w)$ +- Time complexity: $O(2 ^ n * (w + m) + N)$ +- Space complexity: $O(n + w)$ > Where $n$ is the number of words, $w$ is the maximum length of a word, $m$ is the size of the array $scores$, and $N$ is the size of the array $letters$. @@ -420,7 +421,8 @@ class Solution { } } - if (canInclude) { // include (when possible) + if (canInclude) { + // include (when possible) for (let j = 0; j < 26; j++) { letterCnt[j] -= wordFreqs[i][j]; } @@ -442,8 +444,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * 2 ^ n + N)$ -* Space complexity: $O(n + w)$ +- Time complexity: $O(m * 2 ^ n + N)$ +- Space complexity: $O(n + w)$ > Where $n$ is the number of words, $w$ is the maximum length of a word, $m$ is the size of the array $scores$, and $N$ is the size of the array $letters$. @@ -488,7 +490,7 @@ class Solution: for j in range(26): cur_letter_cnt[j] -= word_freqs[i][j] - + cur_score += word_scores[i] if valid: @@ -633,7 +635,7 @@ class Solution { } let res = 0; - for (let mask = 0; mask < (1 << n); mask++) { + for (let mask = 0; mask < 1 << n; mask++) { let curScore = 0; let curLetterCnt = [...letterCnt]; let valid = true; @@ -670,7 +672,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n * 2 ^ n + N)$ -* Space complexity: $O(n + w)$ +- Time complexity: $O(m * n * 2 ^ n + N)$ +- Space complexity: $O(n + w)$ -> Where $n$ is the number of words, $w$ is the maximum length of a word, $m$ is the size of the array $scores$, and $N$ is the size of the array $letters$. \ No newline at end of file +> Where $n$ is the number of words, $w$ is the maximum length of a word, $m$ is the size of the array $scores$, and $N$ is the size of the array $letters$. diff --git a/articles/maximum-subarray-min-product.md b/articles/maximum-subarray-min-product.md index 1ac42156b..84cc2cab6 100644 --- a/articles/maximum-subarray-min-product.md +++ b/articles/maximum-subarray-min-product.md @@ -61,9 +61,11 @@ class Solution { * @return {number} */ maxSumMinProduct(nums) { - let res = 0, MOD = 1000000007; + let res = 0, + MOD = 1000000007; for (let i = 0; i < nums.length; i++) { - let totalSum = 0, mini = Infinity; + let totalSum = 0, + mini = Infinity; for (let j = i; j < nums.length; j++) { mini = Math.min(mini, nums[j]); totalSum += nums[j]; @@ -80,8 +82,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ extra space. --- @@ -97,20 +99,20 @@ class Solution: def rec(l, r): if l > r: return 0 - + min_idx = l total_sum = 0 for i in range(l, r + 1): total_sum += nums[i] if nums[i] < nums[min_idx]: min_idx = i - + cur = total_sum * nums[min_idx] left = rec(l, min_idx - 1) right = rec(min_idx + 1, r) - + return max(cur, left, right) - + return rec(0, len(nums) - 1) % MOD ``` @@ -196,7 +198,7 @@ class Solution { let cur = totalSum * BigInt(nums[minIdx]); let left = rec(l, minIdx - 1); let right = rec(minIdx + 1, r); - + if (cur < left) cur = left; if (cur < right) cur = right; return cur; @@ -211,8 +213,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -261,15 +263,15 @@ class Solution: def rec(l, r): if l > r: return 0 - + min_idx = segTree.query(l, r) total_sum = prefix_sum[r + 1] - prefix_sum[l] - cur = total_sum * nums[min_idx] + cur = total_sum * nums[min_idx] left = rec(l, min_idx - 1) right = rec(min_idx + 1, r) - + return max(cur, left, right) - + return rec(0, len(nums) - 1) % MOD ``` @@ -421,12 +423,18 @@ class SegmentTree { * @return {void} */ build(n, nums) { - this.tree = Array(2 * this.n).fill([BigInt(-1), BigInt(Number.MAX_SAFE_INTEGER)]); + this.tree = Array(2 * this.n).fill([ + BigInt(-1), + BigInt(Number.MAX_SAFE_INTEGER), + ]); for (let i = 0; i < n; i++) { this.tree[this.n + i] = [BigInt(i), BigInt(nums[i])]; } for (let i = this.n - 1; i > 0; i--) { - this.tree[i] = this._merge(this.tree[i << 1], this.tree[i << 1 | 1]); + this.tree[i] = this._merge( + this.tree[i << 1], + this.tree[(i << 1) | 1], + ); } } @@ -478,7 +486,7 @@ class Solution { let cur = totalSum * BigInt(nums[minIdx]); let left = rec(l, minIdx - 1); let right = rec(minIdx + 1, r); - + if (cur < left) cur = left; if (cur < right) cur = right; return cur; @@ -493,8 +501,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -512,30 +520,30 @@ class Solution: prev_min, nxt_min = [-1] * n, [n] * n stack = [] - + for i in range(n): while stack and nums[stack[-1]] >= nums[i]: stack.pop() if stack: prev_min[i] = stack[-1] stack.append(i) - + stack.clear() - + for i in range(n - 1, -1, -1): while stack and nums[stack[-1]] >= nums[i]: stack.pop() if stack: nxt_min[i] = stack[-1] stack.append(i) - + res = 0 - + for i in range(n): l, r = prev_min[i] + 1, nxt_min[i] - 1 total_sum = prefix_sum[r + 1] - prefix_sum[l] res = max(res, nums[i] * total_sum) - + return res % (10 ** 9 + 7) ``` @@ -552,7 +560,7 @@ public class Solution { int[] nxtMin = new int[n]; Arrays.fill(prevMin, -1); Arrays.fill(nxtMin, n); - + Stack stack = new Stack<>(); for (int i = 0; i < n; i++) { while (!stack.isEmpty() && nums[stack.peek()] >= nums[i]) { @@ -563,7 +571,7 @@ public class Solution { } stack.push(i); } - + stack.clear(); for (int i = n - 1; i >= 0; i--) { while (!stack.isEmpty() && nums[stack.peek()] >= nums[i]) { @@ -574,7 +582,7 @@ public class Solution { } stack.push(i); } - + long res = 0; int MOD = 1_000_000_007; for (int i = 0; i < n; i++) { @@ -582,7 +590,7 @@ public class Solution { long totalSum = prefixSum[r + 1] - prefixSum[l]; res = Math.max(res, nums[i] * totalSum); } - + return (int)(res % MOD); } } @@ -600,7 +608,7 @@ public: vector prevMin(n, -1), nxtMin(n, n); stack stack; - + for (int i = 0; i < n; i++) { while (!stack.empty() && nums[stack.top()] >= nums[i]) { stack.pop(); @@ -610,7 +618,7 @@ public: } stack.push(i); } - + while (!stack.empty()) stack.pop(); for (int i = n - 1; i >= 0; i--) { while (!stack.empty() && nums[stack.top()] >= nums[i]) { @@ -621,7 +629,7 @@ public: } stack.push(i); } - + long long res = 0; int MOD = 1e9 + 7; for (int i = 0; i < n; i++) { @@ -629,7 +637,7 @@ public: long long totalSum = prefixSum[r + 1] - prefixSum[l]; res = max(res, nums[i] * totalSum); } - + return res % MOD; } }; @@ -651,7 +659,7 @@ class Solution { const prevMin = new Array(n).fill(-1); const nxtMin = new Array(n).fill(n); const stack = []; - + for (let i = 0; i < n; i++) { while (stack.length && nums[stack[stack.length - 1]] >= nums[i]) { stack.pop(); @@ -661,7 +669,7 @@ class Solution { } stack.push(i); } - + stack.length = 0; for (let i = n - 1; i >= 0; i--) { while (stack.length && nums[stack[stack.length - 1]] >= nums[i]) { @@ -672,7 +680,7 @@ class Solution { } stack.push(i); } - + let res = 0n; const MOD = 10n ** 9n + 7n; for (let i = 0; i < n; i++) { @@ -682,7 +690,7 @@ class Solution { const tmp = BigInt(nums[i]) * totalSum; if (tmp > res) res = tmp; } - + return Number(res % MOD); } } @@ -692,8 +700,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -816,7 +824,7 @@ class Solution { let res = 0n; const MOD = 10n ** 9n + 7n; const stack = []; - + for (let i = 0; i < n; i++) { let newStart = i; while (stack.length && stack[stack.length - 1][1] > nums[i]) { @@ -845,8 +853,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -861,7 +869,7 @@ class Solution: prefix_sum = [0] * (n + 1) for i in range(n): prefix_sum[i + 1] = prefix_sum[i] + nums[i] - + res, stack = 0, [] for i in range(n + 1): while stack and (i == n or nums[i] < nums[stack[-1]]): @@ -869,7 +877,7 @@ class Solution: start = 0 if not stack else stack[-1] + 1 res = max(res, nums[j] * (prefix_sum[i] - prefix_sum[start])) stack.append(i) - + return res % (10 ** 9 + 7) ``` @@ -881,7 +889,7 @@ public class Solution { for (int i = 0; i < n; i++) { prefixSum[i + 1] = prefixSum[i] + nums[i]; } - + long res = 0; int mod = 1_000_000_007; Stack stack = new Stack<>(); @@ -893,7 +901,7 @@ public class Solution { } stack.push(i); } - + return (int) (res % mod); } } @@ -908,7 +916,7 @@ public: for (int i = 0; i < n; i++) { prefixSum[i + 1] = prefixSum[i] + nums[i]; } - + long long res = 0; const int mod = 1e9 + 7; stack st; @@ -921,7 +929,7 @@ public: } st.push(i); } - + return res % mod; } }; @@ -944,9 +952,13 @@ class Solution { const MOD = 10n ** 9n + 7n; const stack = []; for (let i = 0; i <= n; i++) { - while (stack.length && (i === n || nums[i] < nums[stack[stack.length - 1]])) { + while ( + stack.length && + (i === n || nums[i] < nums[stack[stack.length - 1]]) + ) { const j = stack.pop(); - const start = stack.length === 0 ? 0 : stack[stack.length - 1] + 1; + const start = + stack.length === 0 ? 0 : stack[stack.length - 1] + 1; const total = BigInt(prefixSum[i] - prefixSum[start]); const tmp = BigInt(nums[j]) * total; if (tmp > res) res = tmp; @@ -963,5 +975,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/maximum-subarray.md b/articles/maximum-subarray.md index 678ab39c8..cc8073f80 100644 --- a/articles/maximum-subarray.md +++ b/articles/maximum-subarray.md @@ -54,7 +54,8 @@ class Solution { * @return {number} */ maxSubArray(nums) { - let n = nums.length, res = nums[0]; + let n = nums.length, + res = nums[0]; for (let i = 0; i < n; i++) { let cur = 0; for (let j = i; j < n; j++) { @@ -142,8 +143,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -176,7 +177,7 @@ public class Solution { if (flag) { return Math.max(0, nums[i] + dfs(nums, i + 1, true)); } - return Math.max(dfs(nums, i + 1, false), + return Math.max(dfs(nums, i + 1, false), nums[i] + dfs(nums, i + 1, true)); } } @@ -193,7 +194,7 @@ private: int dfs(vector& nums, int i, bool flag) { if (i == nums.size()) return flag ? 0 : -1e6; if (flag) return max(0, nums[i] + dfs(nums, i + 1, true)); - return max(dfs(nums, i + 1, false), + return max(dfs(nums, i + 1, false), nums[i] + dfs(nums, i + 1, true)); } }; @@ -209,8 +210,7 @@ class Solution { const dfs = (i, flag) => { if (i === nums.length) return flag ? 0 : -1e6; if (flag) return Math.max(0, nums[i] + dfs(i + 1, true)); - return Math.max(dfs(i + 1, false), - nums[i] + dfs(i + 1, true)); + return Math.max(dfs(i + 1, false), nums[i] + dfs(i + 1, true)); }; return dfs(0, false); } @@ -226,7 +226,7 @@ public class Solution { private int Dfs(int[] nums, int i, bool flag) { if (i == nums.Length) return flag ? 0 : (int)-1e6; if (flag) return Math.Max(0, nums[i] + Dfs(nums, i + 1, true)); - return Math.Max(Dfs(nums, i + 1, false), + return Math.Max(Dfs(nums, i + 1, false), nums[i] + Dfs(nums, i + 1, true)); } } @@ -240,7 +240,7 @@ func maxSubArray(nums []int) int { if flag { return 0 } - return -1e6 + return -1e6 } if flag { return max(0, nums[i] + dfs(i + 1, true)) @@ -302,8 +302,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ --- @@ -324,7 +324,7 @@ class Solution: if flag: memo[i][flag] = max(0, nums[i] + dfs(i + 1, True)) else: - memo[i][flag] = max(dfs(i + 1, False), + memo[i][flag] = max(dfs(i + 1, False), nums[i] + dfs(i + 1, True)) return memo[i][flag] @@ -346,7 +346,7 @@ public class Solution { int f = flag ? 1 : 0; if (memo[i][f] != Integer.MIN_VALUE) return memo[i][f]; memo[i][f] = flag ? Math.max(0, nums[i] + dfs(nums, i + 1, true)) - : Math.max(dfs(nums, i + 1, false), + : Math.max(dfs(nums, i + 1, false), nums[i] + dfs(nums, i + 1, true)); return memo[i][f]; } @@ -360,7 +360,7 @@ public: vector> memo(nums.size() + 1, vector(2, INT_MIN)); return dfs(nums, 0, false, memo); } - + private: int dfs(vector& nums, int i, bool flag, vector>& memo) { if (i == nums.size()) return flag ? 0 : -1e6; @@ -369,7 +369,7 @@ private: if (flag) memo[i][f] = max(0, nums[i] + dfs(nums, i + 1, true, memo)); else - memo[i][f] = max(dfs(nums, i + 1, false, memo), + memo[i][f] = max(dfs(nums, i + 1, false, memo), nums[i] + dfs(nums, i + 1, true, memo)); return memo[i][f]; } @@ -383,18 +383,18 @@ class Solution { * @return {number} */ maxSubArray(nums) { - const memo = Array(nums.length + 1).fill(null).map( - () => [null, null] - ); + const memo = Array(nums.length + 1) + .fill(null) + .map(() => [null, null]); const dfs = (i, flag) => { if (i === nums.length) return flag ? 0 : -1e6; if (memo[i][+flag] !== null) return memo[i][+flag]; - memo[i][+flag] = flag ? Math.max(0, nums[i] + dfs(i + 1, true)) - : Math.max(dfs(i + 1, false), - nums[i] + dfs(i + 1, true)); + memo[i][+flag] = flag + ? Math.max(0, nums[i] + dfs(i + 1, true)) + : Math.max(dfs(i + 1, false), nums[i] + dfs(i + 1, true)); return memo[i][+flag]; - } + }; return dfs(0, false); } } @@ -417,7 +417,7 @@ public class Solution { int f = flag ? 1 : 0; if (memo[i, f] != int.MinValue) return memo[i, f]; memo[i, f] = flag ? Math.Max(0, nums[i] + Dfs(nums, i + 1, true)) - : Math.Max(Dfs(nums, i + 1, false), + : Math.Max(Dfs(nums, i + 1, false), nums[i] + Dfs(nums, i + 1, true)); return memo[i, f]; } @@ -519,8 +519,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -537,7 +537,7 @@ class Solution: for i in range(n - 2, -1, -1): dp[i][1] = max(nums[i], nums[i] + dp[i + 1][1]) dp[i][0] = max(dp[i + 1][0], dp[i][1]) - + return dp[0][0] ``` @@ -546,13 +546,13 @@ public class Solution { public int maxSubArray(int[] nums) { int n = nums.length; int[][] dp = new int[n + 1][2]; - + dp[n - 1][1] = dp[n - 1][0] = nums[n - 1]; for (int i = n - 2; i >= 0; i--) { dp[i][1] = Math.max(nums[i], nums[i] + dp[i + 1][1]); dp[i][0] = Math.max(dp[i + 1][0], dp[i][1]); } - + return dp[0][0]; } } @@ -564,13 +564,13 @@ public: int maxSubArray(vector& nums) { int n = nums.size(); vector> dp(n + 1, vector(2, 0)); - + dp[n - 1][1] = dp[n - 1][0] = nums[n - 1]; for (int i = n - 2; i >= 0; i--) { dp[i][1] = max(nums[i], nums[i] + dp[i + 1][1]); dp[i][0] = max(dp[i + 1][0], dp[i][1]); } - + return dp[0][0]; } }; @@ -585,13 +585,13 @@ class Solution { maxSubArray(nums) { const n = nums.length; const dp = Array.from({ length: n + 1 }, () => Array(2).fill(0)); - + dp[n - 1][1] = dp[n - 1][0] = nums[n - 1]; for (let i = n - 2; i >= 0; i--) { dp[i][1] = Math.max(nums[i], nums[i] + dp[i + 1][1]); dp[i][0] = Math.max(dp[i + 1][0], dp[i][1]); } - + return dp[0][0]; } } @@ -602,13 +602,13 @@ public class Solution { public int MaxSubArray(int[] nums) { int n = nums.Length; int[,] dp = new int[n + 1, 2]; - + dp[n - 1, 1] = dp[n - 1, 0] = nums[n - 1]; for (int i = n - 2; i >= 0; i--) { dp[i, 1] = Math.Max(nums[i], nums[i] + dp[i + 1, 1]); dp[i, 0] = Math.Max(dp[i + 1, 0], dp[i, 1]); } - + return dp[0, 0]; } } @@ -621,15 +621,15 @@ func maxSubArray(nums []int) int { for i := range dp { dp[i] = make([]int, 2) } - + dp[n-1][1] = nums[n-1] dp[n-1][0] = nums[n-1] - + for i := n-2; i >= 0; i-- { dp[i][1] = max(nums[i], nums[i] + dp[i+1][1]) dp[i][0] = max(dp[i+1][0], dp[i][1]) } - + return dp[0][0] } @@ -646,15 +646,15 @@ class Solution { fun maxSubArray(nums: IntArray): Int { val n = nums.size val dp = Array(n) { IntArray(2) } - + dp[n-1][1] = nums[n-1] dp[n-1][0] = nums[n-1] - + for (i in n-2 downTo 0) { dp[i][1] = maxOf(nums[i], nums[i] + dp[i+1][1]) dp[i][0] = maxOf(dp[i+1][0], dp[i][1]) } - + return dp[0][0] } } @@ -682,8 +682,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -765,18 +765,18 @@ public class Solution { func maxSubArray(nums []int) int { dp := make([]int, len(nums)) copy(dp, nums) - + for i := 1; i < len(nums); i++ { dp[i] = max(nums[i], nums[i] + dp[i-1]) } - + maxSum := dp[0] for _, v := range dp { if v > maxSum { maxSum = v } } - + return maxSum } @@ -792,11 +792,11 @@ func max(a, b int) int { class Solution { fun maxSubArray(nums: IntArray): Int { val dp = nums.copyOf() - + for (i in 1 until nums.size) { dp[i] = maxOf(nums[i], nums[i] + dp[i-1]) } - + return dp.maxOrNull() ?: nums[0] } } @@ -820,8 +820,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -882,7 +882,8 @@ class Solution { * @return {number} */ maxSubArray(nums) { - let maxSub = nums[0], curSum = 0; + let maxSub = nums[0], + curSum = 0; for (const num of nums) { if (curSum < 0) { curSum = 0; @@ -972,8 +973,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -999,10 +1000,10 @@ class Solution: curSum += nums[i] rightSum = max(rightSum, curSum) - return (max(dfs(l, m - 1), - dfs(m + 1, r), + return (max(dfs(l, m - 1), + dfs(m + 1, r), leftSum + nums[m] + rightSum)) - + return dfs(0, len(nums) - 1) ``` @@ -1011,7 +1012,7 @@ public class Solution { public int maxSubArray(int[] nums) { return dfs(nums, 0, nums.length - 1); } - + private int dfs(int[] nums, int l, int r) { if (l > r) { return Integer.MIN_VALUE; @@ -1029,8 +1030,8 @@ public class Solution { rightSum = Math.max(rightSum, curSum); } - return Math.max(dfs(nums, l, m - 1), - Math.max(dfs(nums, m + 1, r), + return Math.max(dfs(nums, l, m - 1), + Math.max(dfs(nums, m + 1, r), leftSum + nums[m] + rightSum)); } } @@ -1059,8 +1060,8 @@ private: curSum += nums[i]; rightSum = max(rightSum, curSum); } - return max(dfs(nums, l, m - 1), - max(dfs(nums, m + 1, r), + return max(dfs(nums, l, m - 1), + max(dfs(nums, m + 1, r), leftSum + nums[m] + rightSum)); } }; @@ -1078,7 +1079,9 @@ class Solution { return -Infinity; } let m = (l + r) >> 1; - let leftSum = 0, rightSum = 0, curSum = 0; + let leftSum = 0, + rightSum = 0, + curSum = 0; for (let i = m - 1; i >= l; i--) { curSum += nums[i]; leftSum = Math.max(leftSum, curSum); @@ -1089,11 +1092,12 @@ class Solution { curSum += nums[i]; rightSum = Math.max(rightSum, curSum); } - return Math.max(dfs(l, m - 1), - Math.max(dfs(m + 1, r), - leftSum + nums[m] + rightSum)); - } - + return Math.max( + dfs(l, m - 1), + Math.max(dfs(m + 1, r), leftSum + nums[m] + rightSum), + ); + }; + return dfs(0, nums.length - 1); } } @@ -1104,7 +1108,7 @@ public class Solution { public int MaxSubArray(int[] nums) { return Dfs(nums, 0, nums.Length - 1); } - + private int Dfs(int[] nums, int l, int r) { if (l > r) { return int.MinValue; @@ -1122,8 +1126,8 @@ public class Solution { rightSum = Math.Max(rightSum, curSum); } - return Math.Max(Dfs(nums, l, m - 1), - Math.Max(Dfs(nums, m + 1, r), + return Math.Max(Dfs(nums, l, m - 1), + Math.Max(Dfs(nums, m + 1, r), leftSum + nums[m] + rightSum)); } } @@ -1136,17 +1140,17 @@ func maxSubArray(nums []int) int { if l > r { return math.MinInt64 } - + m := (l + r) >> 1 leftSum, rightSum, curSum := 0, 0, 0 - + for i := m - 1; i >= l; i-- { curSum += nums[i] if curSum > leftSum { leftSum = curSum } } - + curSum = 0 for i := m + 1; i <= r; i++ { curSum += nums[i] @@ -1154,14 +1158,14 @@ func maxSubArray(nums []int) int { rightSum = curSum } } - + maxLeft := dfs(l, m-1) maxRight := dfs(m+1, r) crossSum := leftSum + nums[m] + rightSum - + return max(max(maxLeft, maxRight), crossSum) } - + return dfs(0, len(nums)-1) } @@ -1180,30 +1184,30 @@ class Solution { if (l > r) { return Int.MIN_VALUE } - + val m = (l + r) shr 1 var leftSum = 0 var rightSum = 0 var curSum = 0 - + for (i in (m - 1) downTo l) { curSum += nums[i] leftSum = maxOf(leftSum, curSum) } - + curSum = 0 for (i in (m + 1)..r) { curSum += nums[i] rightSum = maxOf(rightSum, curSum) } - + return maxOf( dfs(l, m - 1), dfs(m + 1, r), leftSum + nums[m] + rightSum ) } - + return dfs(0, nums.size - 1) } } @@ -1246,5 +1250,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(\log n)$ \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(\log n)$ diff --git a/articles/maximum-subsequence-score.md b/articles/maximum-subsequence-score.md index 97c461caa..b2f71c469 100644 --- a/articles/maximum-subsequence-score.md +++ b/articles/maximum-subsequence-score.md @@ -103,7 +103,7 @@ class Solution { if (k === 0) { return curSum * minVal; } - if (i === n || (n - i) < k) { + if (i === n || n - i < k) { return -Infinity; } if (minVal === 0) { @@ -112,9 +112,14 @@ class Solution { let res = dfs(i + 1, k, minVal, curSum); res = Math.max( - res, - dfs(i + 1, k - 1, Math.min(minVal, nums2[i]), curSum + nums1[i]) - ); + res, + dfs( + i + 1, + k - 1, + Math.min(minVal, nums2[i]), + curSum + nums1[i], + ), + ); return res; }; @@ -127,8 +132,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -242,7 +247,8 @@ class Solution { pairs.sort((a, b) => b[1] - a[1]); let minHeap = new MinPriorityQueue(); - let n1Sum = 0, res = 0; + let n1Sum = 0, + res = 0; for (let [n1, n2] of pairs) { n1Sum += n1; @@ -266,8 +272,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -383,7 +389,8 @@ class Solution { arr.sort((a, b) => Number(b - a)); const minHeap = new MinPriorityQueue(); - let n1Sum = 0n, res = 0n; + let n1Sum = 0n, + res = 0n; for (let num of arr) { let n1 = Number(num & ((1n << 30n) - 1n)); @@ -408,5 +415,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ diff --git a/articles/maximum-sum-circular-subarray.md b/articles/maximum-sum-circular-subarray.md index 5c7558ca0..844b40c7d 100644 --- a/articles/maximum-sum-circular-subarray.md +++ b/articles/maximum-sum-circular-subarray.md @@ -13,7 +13,7 @@ class Solution: for j in range(i, i + n): cur_sum += nums[j % n] res = max(res, cur_sum) - + return res ``` @@ -102,8 +102,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ extra space. --- @@ -118,22 +118,22 @@ class Solution: right_max = [0] * n right_max[-1] = nums[-1] suffix_sum = nums[-1] - + for i in range(n - 2, -1, -1): suffix_sum += nums[i] right_max[i] = max(right_max[i + 1], suffix_sum) - + max_sum = nums[0] cur_max = 0 prefix_sum = 0 - + for i in range(n): cur_max = max(cur_max, 0) + nums[i] max_sum = max(max_sum, cur_max) prefix_sum += nums[i] if i + 1 < n: max_sum = max(max_sum, prefix_sum + right_max[i + 1]) - + return max_sum ``` @@ -270,8 +270,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -342,8 +342,11 @@ class Solution { * @return {number} */ maxSubarraySumCircular(nums) { - let globMax = nums[0], globMin = nums[0]; - let curMax = 0, curMin = 0, total = 0; + let globMax = nums[0], + globMin = nums[0]; + let curMax = 0, + curMin = 0, + total = 0; for (const num of nums) { curMax = Math.max(curMax + num, num); @@ -383,5 +386,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/maximum-twin-sum-of-a-linked-list.md b/articles/maximum-twin-sum-of-a-linked-list.md index b896b8cae..d10e9ec86 100644 --- a/articles/maximum-twin-sum-of-a-linked-list.md +++ b/articles/maximum-twin-sum-of-a-linked-list.md @@ -116,7 +116,9 @@ class Solution { cur = cur.next; } - let i = 0, j = arr.length - 1, res = 0; + let i = 0, + j = arr.length - 1, + res = 0; while (i < j) { res = Math.max(res, arr[i] + arr[j]); i++; @@ -132,8 +134,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -267,13 +269,15 @@ class Solution { * @return {number} */ pairSum(head) { - let slow = head, fast = head; + let slow = head, + fast = head; while (fast && fast.next) { slow = slow.next; fast = fast.next.next; } - let prev = null, cur = slow; + let prev = null, + cur = slow; while (cur) { let nxt = cur.next; cur.next = prev; @@ -281,7 +285,9 @@ class Solution { cur = nxt; } - let res = 0, first = head, second = prev; + let res = 0, + first = head, + second = prev; while (second) { res = Math.max(res, first.val + second.val); first = first.next; @@ -297,8 +303,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -420,7 +426,9 @@ class Solution { * @return {number} */ pairSum(head) { - let slow = head, fast = head, prev = null; + let slow = head, + fast = head, + prev = null; while (fast && fast.next) { fast = fast.next.next; @@ -446,5 +454,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/maximum-value-of-k-coins-from-piles.md b/articles/maximum-value-of-k-coins-from-piles.md index bf108e73c..9f97cf068 100644 --- a/articles/maximum-value-of-k-coins-from-piles.md +++ b/articles/maximum-value-of-k-coins-from-piles.md @@ -100,8 +100,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(k ^ n)$ -* Space complexity: $O(n)$ for the recursion stack. +- Time complexity: $O(k ^ n)$ +- Space complexity: $O(n)$ for the recursion stack. > Where $n$ is the number of piles and $k$ is the number of coins to choose. @@ -215,7 +215,10 @@ class Solution { let curPile = 0; for (let j = 0; j < Math.min(coins, piles[i].length); j++) { curPile += piles[i][j]; - dp[i][coins] = Math.max(dp[i][coins], curPile + dfs(i + 1, coins - (j + 1))); + dp[i][coins] = Math.max( + dp[i][coins], + curPile + dfs(i + 1, coins - (j + 1)), + ); } return dp[i][coins]; }; @@ -229,8 +232,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * k)$ -* Space complexity: $O(n * k)$ +- Time complexity: $O(m * k)$ +- Space complexity: $O(n * k)$ > Where $n$ is the number of piles, $k$ is the number of coins to choose, and $m$ is the total number of coins among all the piles. @@ -245,11 +248,11 @@ class Solution: def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int: n = len(piles) dp = [[0] * (k + 1) for _ in range(n + 1)] - + for i in range(n - 1, -1, -1): for coins in range(k + 1): dp[i][coins] = dp[i + 1][coins] - + curPile = 0 for j in range(min(coins, len(piles[i]))): curPile += piles[i][j] @@ -257,7 +260,7 @@ class Solution: dp[i][coins], curPile + dp[i + 1][coins - (j + 1)] ) - + return dp[0][k] ``` @@ -334,7 +337,7 @@ class Solution { curPile += piles[i][j]; dp[i][coins] = Math.max( dp[i][coins], - curPile + dp[i + 1][coins - (j + 1)] + curPile + dp[i + 1][coins - (j + 1)], ); } } @@ -349,8 +352,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * k)$ -* Space complexity: $O(n * k)$ +- Time complexity: $O(m * k)$ +- Space complexity: $O(n * k)$ > Where $n$ is the number of piles, $k$ is the number of coins to choose, and $m$ is the total number of coins among all the piles. @@ -431,7 +434,10 @@ class Solution { let curPile = 0; for (let j = 0; j < Math.min(coins, pile.length); j++) { curPile += pile[j]; - dp[coins] = Math.max(dp[coins], dp[coins - (j + 1)] + curPile); + dp[coins] = Math.max( + dp[coins], + dp[coins - (j + 1)] + curPile, + ); } } } @@ -445,7 +451,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * k)$ -* Space complexity: $O(n * k)$ +- Time complexity: $O(m * k)$ +- Space complexity: $O(n * k)$ -> Where $n$ is the number of piles, $k$ is the number of coins to choose, and $m$ is the total number of coins among all the piles. \ No newline at end of file +> Where $n$ is the number of piles, $k$ is the number of coins to choose, and $m$ is the total number of coins among all the piles. diff --git a/articles/maximum-width-of-binary-tree.md b/articles/maximum-width-of-binary-tree.md index ba741fb5d..3c86c8f23 100644 --- a/articles/maximum-width-of-binary-tree.md +++ b/articles/maximum-width-of-binary-tree.md @@ -158,7 +158,8 @@ class Solution { let res = 0n; const queue = new Queue([[root, 1n, 0]]); // [node, num, level] - let prevLevel = 0, prevNum = 1n; + let prevLevel = 0, + prevNum = 1n; while (!queue.isEmpty()) { const [node, num, level] = queue.pop(); @@ -168,7 +169,7 @@ class Solution { prevNum = num; } - res = res > (num - prevNum + 1n) ? res : (num - prevNum + 1n); + res = res > num - prevNum + 1n ? res : num - prevNum + 1n; if (node.left) { queue.push([node.left, 2n * num, level + 1]); } @@ -186,8 +187,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -351,8 +352,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -376,10 +377,10 @@ class Solution: nonlocal res if not node: return - + if level not in first: first[level] = num - + res = max(res, num - first[level] + 1) dfs(node.left, level + 1, 2 * num) dfs(node.right, level + 1, 2 * num + 1) @@ -409,7 +410,7 @@ public class Solution { public int widthOfBinaryTree(TreeNode root) { first = new HashMap<>(); int[] res = new int[1]; - + dfs(root, 0, 0, res); return res[0]; } @@ -418,7 +419,7 @@ public class Solution { if (node == null) { return; } - + first.putIfAbsent(level, num); res[0] = Math.max(res[0], num - first.get(level) + 1); dfs(node.left, level + 1, 2 * num, res); @@ -445,7 +446,7 @@ class Solution { public: int widthOfBinaryTree(TreeNode* root) { unsigned long long res = 0; - + dfs(root, 0, 0, res); return int(res); } @@ -455,11 +456,11 @@ private: if (!node) { return; } - + if (!first.count(level)) { first[level] = num; } - + res = max(res, num - first[level] + 1); dfs(node->left, level + 1, 2 * (num - first[level]), res); dfs(node->right, level + 1, 2 * (num - first[level]) + 1, res); @@ -509,5 +510,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/median-of-two-sorted-arrays.md b/articles/median-of-two-sorted-arrays.md index 3ac051111..562924891 100644 --- a/articles/median-of-two-sorted-arrays.md +++ b/articles/median-of-two-sorted-arrays.md @@ -9,7 +9,7 @@ class Solution: len2 = len(nums2) merged = nums1 + nums2 merged.sort() - + totalLen = len(merged) if totalLen % 2 == 0: return (merged[totalLen // 2 - 1] + merged[totalLen // 2]) / 2.0 @@ -25,7 +25,7 @@ public class Solution { System.arraycopy(nums1, 0, merged, 0, len1); System.arraycopy(nums2, 0, merged, len1, len2); Arrays.sort(merged); - + int totalLen = merged.length; if (totalLen % 2 == 0) { return (merged[totalLen / 2 - 1] + merged[totalLen / 2]) / 2.0; @@ -46,7 +46,7 @@ public: copy(nums1.begin(), nums1.end(), merged.begin()); copy(nums2.begin(), nums2.end(), merged.begin() + len1); sort(merged.begin(), merged.end()); - + int totalLen = merged.size(); if (totalLen % 2 == 0) { return (merged[totalLen / 2 - 1] + merged[totalLen / 2]) / 2.0; @@ -69,7 +69,7 @@ class Solution { const len2 = nums2.length; const merged = nums1.concat(nums2); merged.sort((a, b) => a - b); - + const totalLen = merged.length; if (totalLen % 2 === 0) { return (merged[totalLen / 2 - 1] + merged[totalLen / 2]) / 2.0; @@ -89,7 +89,7 @@ public class Solution { Array.Copy(nums1, merged, len1); Array.Copy(nums2, 0, merged, len1, len2); Array.Sort(merged); - + int totalLen = merged.Length; if (totalLen % 2 == 0) { return (merged[totalLen / 2 - 1] + merged[totalLen / 2]) / 2.0; @@ -132,7 +132,7 @@ class Solution { func findMedianSortedArrays(_ nums1: [Int], _ nums2: [Int]) -> Double { var merged = nums1 + nums2 merged.sort() - + let totalLen = merged.count if totalLen % 2 == 0 { return (Double(merged[totalLen / 2 - 1]) + Double(merged[totalLen / 2])) / 2.0 @@ -147,8 +147,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O((n + m)\log (n + m))$ -* Space complexity: $O(n + m)$ +- Time complexity: $O((n + m)\log (n + m))$ +- Space complexity: $O(n + m)$ > Where $n$ is the length of $nums1$ and $m$ is the length of $nums2$. @@ -266,11 +266,18 @@ class Solution { * @return {number} */ findMedianSortedArrays(nums1, nums2) { - let len1 = nums1.length, len2 = nums2.length; - let i = 0, j = 0; - let median1 = 0, median2 = 0; - - for (let count = 0; count < Math.floor((len1 + len2) / 2) + 1; count++) { + let len1 = nums1.length, + len2 = nums2.length; + let i = 0, + j = 0; + let median1 = 0, + median2 = 0; + + for ( + let count = 0; + count < Math.floor((len1 + len2) / 2) + 1; + count++ + ) { median2 = median1; if (i < len1 && j < len2) { if (nums1[i] > nums2[j]) { @@ -446,8 +453,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(1)$ > Where $n$ is the length of $nums1$ and $m$ is the length of $nums2$. @@ -466,15 +473,15 @@ class Solution: return b[b_start + k - 1] if k == 1: return min(a[a_start], b[b_start]) - + i = min(m, k // 2) j = min(n, k // 2) - + if a[a_start + i - 1] > b[b_start + j - 1]: return self.get_kth(a, m, b, n - j, k - j, a_start, b_start + j) else: return self.get_kth(a, m - i, b, n, k - i, a_start + i, b_start) - + def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: left = (len(nums1) + len(nums2) + 1) // 2 right = (len(nums1) + len(nums2) + 2) // 2 @@ -559,9 +566,12 @@ class Solution { const n = nums2.length; const left = Math.floor((m + n + 1) / 2); const right = Math.floor((m + n + 2) / 2); - - return (this.getKth(nums1, m, nums2, n, left) + - this.getKth(nums1, m, nums2, n, right)) / 2.0; + + return ( + (this.getKth(nums1, m, nums2, n, left) + + this.getKth(nums1, m, nums2, n, right)) / + 2.0 + ); } /** @@ -647,10 +657,10 @@ func getKth(a []int, m int, b []int, n int, k int, aStart int, bStart int) int { } return b[bStart] } - + i := min(m, k/2) j := min(n, k/2) - + if a[aStart+i-1] > b[bStart+j-1] { return getKth(a, m, b[bStart+j:], n-j, k-j, aStart, 0) } @@ -684,17 +694,17 @@ class Solution { if (k == 1) { return minOf(a[aStart], b[bStart]) } - + val i = minOf(m, k / 2) val j = minOf(n, k / 2) - + return if (a[aStart + i - 1] > b[bStart + j - 1]) { getKth(a, m, b, n - j, k - j, aStart, bStart + j) } else { getKth(a, m - i, b, n, k - i, aStart + i, bStart) } } - + fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double { val left = (nums1.size + nums2.size + 1) / 2 val right = (nums1.size + nums2.size + 2) / 2 @@ -716,17 +726,17 @@ class Solution { if k == 1 { return min(a[aStart], b[bStart]) } - + let i = min(m, k / 2) let j = min(n, k / 2) - + if a[aStart + i - 1] > b[bStart + j - 1] { return getKth(a, m, b, n - j, k - j, aStart, bStart + j) } else { return getKth(a, m - i, b, n, k - i, aStart + i, bStart) } } - + func findMedianSortedArrays(_ nums1: [Int], _ nums2: [Int]) -> Double { let left = (nums1.count + nums2.count + 1) / 2 let right = (nums1.count + nums2.count + 2) / 2 @@ -740,8 +750,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log (m + n))$ -* Space complexity: $O(\log (m + n))$ for recursion stack. +- Time complexity: $O(\log (m + n))$ +- Space complexity: $O(\log (m + n))$ for recursion stack. > Where $n$ is the length of $nums1$ and $m$ is the length of $nums2$. @@ -1038,7 +1048,7 @@ class Solution { return if (total % 2 != 0) { Math.max(Aleft.toDouble(), Bleft.toDouble()) } else { - (Math.max(Aleft.toDouble(), Bleft.toDouble()) + + (Math.max(Aleft.toDouble(), Bleft.toDouble()) + Math.min(Aright.toDouble(), Bright.toDouble())) / 2.0 } } else if (Aleft > Bright) { @@ -1094,7 +1104,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log (min(n, m)))$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log (min(n, m)))$ +- Space complexity: $O(1)$ -> Where $n$ is the length of $nums1$ and $m$ is the length of $nums2$. \ No newline at end of file +> Where $n$ is the length of $nums1$ and $m$ is the length of $nums2$. diff --git a/articles/meeting-rooms-iii.md b/articles/meeting-rooms-iii.md index 1c82624f1..3505e7bb0 100644 --- a/articles/meeting-rooms-iii.md +++ b/articles/meeting-rooms-iii.md @@ -18,14 +18,14 @@ class Solution: meeting_count[i] += 1 rooms[i] = e break - + if rooms[min_room] > rooms[i]: min_room = i if found: continue meeting_count[min_room] += 1 rooms[min_room] += e - s - + return meeting_count.index(max(meeting_count)) ``` @@ -194,8 +194,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m\log m + n * m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(m\log m + n * m)$ +- Space complexity: $O(n)$ > Where $n$ is the number of rooms and $m$ is the number of meetings. @@ -222,7 +222,7 @@ class Solution: end_time, room = heapq.heappop(used) end = end_time + (end - start) heapq.heappush(available, room) - + room = heapq.heappop(available) heapq.heappush(used, (end, room)) count[room] += 1 @@ -233,14 +233,14 @@ class Solution: ```java public class Solution { public int mostBooked(int n, int[][] meetings) { - Arrays.sort(meetings, (a, b) -> Long.compare(a[0], b[0])); - PriorityQueue available = new PriorityQueue<>(); - PriorityQueue used = new PriorityQueue<>((a, b) -> + Arrays.sort(meetings, (a, b) -> Long.compare(a[0], b[0])); + PriorityQueue available = new PriorityQueue<>(); + PriorityQueue used = new PriorityQueue<>((a, b) -> a[0] == b[0] ? Long.compare(a[1], b[1]) : Long.compare(a[0], b[0]) - ); + ); for (int i = 0; i < n; i++) { available.offer(i); - } + } int[] count = new int[n]; for (int[] meeting : meetings) { @@ -329,8 +329,8 @@ class Solution { mostBooked(n, meetings) { meetings.sort((a, b) => a[0] - b[0]); const available = new PriorityQueue((a, b) => a - b); - const used = new PriorityQueue( - (a, b) => (a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]), + const used = new PriorityQueue((a, b) => + a[0] === b[0] ? a[1] - b[1] : a[0] - b[0], ); for (let i = 0; i < n; i++) { available.enqueue(i); @@ -413,8 +413,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m\log m + m \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(m\log m + m \log n)$ +- Space complexity: $O(n)$ > Where $n$ is the number of rooms and $m$ is the number of meetings. @@ -438,7 +438,7 @@ class Solution: while available and available[0][0] < start: end_time, room = heapq.heappop(available) heapq.heappush(available, (start, room)) - + end_time, room = heapq.heappop(available) heapq.heappush(available, (end_time + (end - start), room)) count[room] += 1 @@ -450,7 +450,7 @@ class Solution: public class Solution { public int mostBooked(int n, int[][] meetings) { Arrays.sort(meetings, (a, b) -> Integer.compare(a[0], b[0])); - PriorityQueue available = new PriorityQueue<>((a, b) -> + PriorityQueue available = new PriorityQueue<>((a, b) -> a[0] == b[0] ? Long.compare(a[1], b[1]) : Long.compare(a[0], b[0]) ); for (int i = 0; i < n; i++) { @@ -521,8 +521,8 @@ class Solution { */ mostBooked(n, meetings) { meetings.sort((a, b) => a[0] - b[0]); - const available = new PriorityQueue( - (a, b) => (a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]) + const available = new PriorityQueue((a, b) => + a[0] === b[0] ? a[1] - b[1] : a[0] - b[0], ); for (let i = 0; i < n; i++) { available.enqueue([0, i]); @@ -598,9 +598,9 @@ public class Solution { ### Time & Space Complexity -* Time complexity: - * $O(m \log m + m \log n)$ time in average case. - * $O(m \log m + m * n)$ time in worst case. -* Space complexity: $O(n)$ +- Time complexity: + - $O(m \log m + m \log n)$ time in average case. + - $O(m \log m + m * n)$ time in worst case. +- Space complexity: $O(n)$ -> Where $n$ is the number of rooms and $m$ is the number of meetings. \ No newline at end of file +> Where $n$ is the number of rooms and $m$ is the number of meetings. diff --git a/articles/meeting-schedule-ii.md b/articles/meeting-schedule-ii.md index afd50a48e..e8bd996b2 100644 --- a/articles/meeting-schedule-ii.md +++ b/articles/meeting-schedule-ii.md @@ -128,14 +128,14 @@ public class Solution { public int MinMeetingRooms(List intervals) { intervals.Sort((a, b) => a.start.CompareTo(b.start)); var minHeap = new PriorityQueue(); - + foreach (var interval in intervals) { if (minHeap.Count > 0 && minHeap.Peek() <= interval.start) { minHeap.Dequeue(); } minHeap.Enqueue(interval.end, interval.end); } - + return minHeap.Count; } } @@ -225,8 +225,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -341,7 +341,8 @@ class Solution { mp.set(i.end, (mp.get(i.end) || 0) - 1); } const sortedKeys = Array.from(mp.keys()).sort((a, b) => a - b); - let prev = 0, res = 0; + let prev = 0, + res = 0; for (const key of sortedKeys) { prev += mp.get(key); res = Math.max(res, prev); @@ -397,13 +398,13 @@ func minMeetingRooms(intervals []Interval) int { mp[i.start]++ mp[i.end]-- } - + keys := make([]int, 0, len(mp)) for k := range mp { keys = append(keys, k) } sort.Ints(keys) - + prev := 0 res := 0 for _, k := range keys { @@ -429,7 +430,7 @@ class Solution { mp[i.start] = mp.getOrDefault(i.start, 0) + 1 mp[i.end] = mp.getOrDefault(i.end, 0) - 1 } - + val keys = mp.keys.sorted() var prev = 0 var res = 0 @@ -477,8 +478,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -499,7 +500,7 @@ class Solution: def minMeetingRooms(self, intervals: List[Interval]) -> int: start = sorted([i.start for i in intervals]) end = sorted([i.end for i in intervals]) - + res = count = 0 s = e = 0 while s < len(intervals): @@ -530,15 +531,15 @@ public class Solution { int n = intervals.size(); int[] start = new int[n]; int[] end = new int[n]; - + for (int i = 0; i < n; i++) { start[i] = intervals.get(i).start; end[i] = intervals.get(i).end; } - + Arrays.sort(start); Arrays.sort(end); - + int res = 0, count = 0, s = 0, e = 0; while (s < n) { if (start[s] < end[e]) { @@ -572,15 +573,15 @@ class Solution { public: int minMeetingRooms(vector& intervals) { vector start, end; - + for (const auto& i : intervals) { start.push_back(i.start); end.push_back(i.end); } - + sort(start.begin(), start.end()); sort(end.begin(), end.end()); - + int res = 0, count = 0, s = 0, e = 0; while (s < intervals.size()) { if (start[s] < end[e]) { @@ -614,10 +615,13 @@ class Solution { * @returns {number} */ minMeetingRooms(intervals) { - const start = intervals.map(i => i.start).sort((a, b) => a - b); - const end = intervals.map(i => i.end).sort((a, b) => a - b); - - let res = 0, count = 0, s = 0, e = 0; + const start = intervals.map((i) => i.start).sort((a, b) => a - b); + const end = intervals.map((i) => i.end).sort((a, b) => a - b); + + let res = 0, + count = 0, + s = 0, + e = 0; while (s < intervals.length) { if (start[s] < end[e]) { s++; @@ -650,15 +654,15 @@ public class Solution { int n = intervals.Count; int[] start = new int[n]; int[] end = new int[n]; - + for (int i = 0; i < n; i++) { start[i] = intervals[i].start; end[i] = intervals[i].end; } - + Array.Sort(start); Array.Sort(end); - + int res = 0, count = 0, s = 0, e = 0; while (s < n) { if (start[s] < end[e]) { @@ -687,18 +691,18 @@ public class Solution { func minMeetingRooms(intervals []Interval) int { start := make([]int, len(intervals)) end := make([]int, len(intervals)) - + for i, interval := range intervals { start[i] = interval.start end[i] = interval.end } - + sort.Ints(start) sort.Ints(end) - + res, count := 0, 0 s, e := 0, 0 - + for s < len(intervals) { if start[s] < end[e] { s++ @@ -711,7 +715,7 @@ func minMeetingRooms(intervals []Interval) int { res = count } } - + return res } ``` @@ -726,12 +730,12 @@ class Solution { fun minMeetingRooms(intervals: List): Int { val start = intervals.map { it.start }.sorted() val end = intervals.map { it.end }.sorted() - + var res = 0 var count = 0 var s = 0 var e = 0 - + while (s < intervals.size) { if (start[s] < end[e]) { s++ @@ -742,7 +746,7 @@ class Solution { } res = maxOf(res, count) } - + return res } } @@ -765,7 +769,7 @@ class Solution { func minMeetingRooms(_ intervals: [Interval]) -> Int { let starts = intervals.map { $0.start }.sorted() let ends = intervals.map { $0.end }.sorted() - + var res = 0, count = 0, s = 0, e = 0 while s < intervals.count { if starts[s] < ends[e] { @@ -786,8 +790,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -810,9 +814,9 @@ class Solution: for i in intervals: time.append((i.start, 1)) time.append((i.end, -1)) - + time.sort(key=lambda x: (x[0], x[1])) - + res = count = 0 for t in time: count += t[1] @@ -839,9 +843,9 @@ public class Solution { time.add(new int[] { i.start, 1 }); time.add(new int[] { i.end, -1 }); } - + time.sort((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); - + int res = 0, count = 0; for (int[] t : time) { count += t[1]; @@ -873,11 +877,11 @@ public: time.push_back({i.start, 1}); time.push_back({i.end, -1}); } - + sort(time.begin(), time.end(), [](auto& a, auto& b) { return a.first == b.first ? a.second < b.second : a.first < b.first; }); - + int res = 0, count = 0; for (const auto& t : time) { count += t.second; @@ -910,10 +914,11 @@ class Solution { time.push([i.start, 1]); time.push([i.end, -1]); } - - time.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]); - - let res = 0, count = 0; + + time.sort((a, b) => (a[0] === b[0] ? a[1] - b[1] : a[0] - b[0])); + + let res = 0, + count = 0; for (const t of time) { count += t[1]; res = Math.max(res, count); @@ -942,11 +947,11 @@ public class Solution { time.Add(new int[] { i.start, 1 }); time.Add(new int[] { i.end, -1 }); } - - time.Sort((a, b) => a[0] == b[0] ? + + time.Sort((a, b) => a[0] == b[0] ? a[1].CompareTo(b[1]) : a[0].CompareTo(b[0] )); - + int res = 0, count = 0; foreach (var t in time) { count += t[1]; @@ -1000,23 +1005,23 @@ func minMeetingRooms(intervals []Interval) int { class Solution { fun minMeetingRooms(intervals: Array): Int { val time = mutableListOf>() - + for (i in intervals) { time.add(Pair(i.start, 1)) time.add(Pair(i.end, -1)) } - + time.sortWith(compareBy> { it.first } .thenBy { it.second }) - + var res = 0 var count = 0 - + for (t in time) { count += t.second res = maxOf(res, count) } - + return res } } @@ -1043,7 +1048,7 @@ class Solution { times.append((interval.end, -1)) } - times.sort { + times.sort { if $0.0 != $1.0 { return $0.0 < $1.0 } else { @@ -1067,5 +1072,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ diff --git a/articles/meeting-schedule.md b/articles/meeting-schedule.md index 226a6a70f..e86091d50 100644 --- a/articles/meeting-schedule.md +++ b/articles/meeting-schedule.md @@ -239,8 +239,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -316,8 +316,8 @@ public class Solution { class Solution { public: bool canAttendMeetings(vector& intervals) { - sort(intervals.begin(), intervals.end(), [](auto& x, auto& y) { - return x.start < y.start; + sort(intervals.begin(), intervals.end(), [](auto& x, auto& y) { + return x.start < y.start; }); for (int i = 1; i < intervals.size(); ++i) { if (intervals[i].start < intervals[i - 1].end) { @@ -460,5 +460,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. diff --git a/articles/merge-in-between-linked-lists.md b/articles/merge-in-between-linked-lists.md index 2d8a1774f..5901892e9 100644 --- a/articles/merge-in-between-linked-lists.md +++ b/articles/merge-in-between-linked-lists.md @@ -20,7 +20,7 @@ class Solution: cur = list2 while cur.next: cur = cur.next - + cur.next = arr[b + 1] return list1 ``` @@ -40,19 +40,19 @@ public class Solution { public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) { ListNode cur = list1; List arr = new ArrayList<>(); - + while (cur != null) { arr.add(cur); cur = cur.next; } - + arr.get(a - 1).next = list2; cur = list2; - + while (cur.next != null) { cur = cur.next; } - + cur.next = arr.get(b + 1); return list1; } @@ -75,19 +75,19 @@ public: ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) { ListNode* cur = list1; vector arr; - + while (cur) { arr.push_back(cur); cur = cur->next; } - + arr[a - 1]->next = list2; cur = list2; - + while (cur->next) { cur = cur->next; } - + cur->next = arr[b + 1]; return list1; } @@ -115,19 +115,19 @@ class Solution { mergeInBetween(list1, a, b, list2) { let cur = list1; let arr = []; - + while (cur) { arr.push(cur); cur = cur.next; } - + arr[a - 1].next = list2; cur = list2; - + while (cur.next) { cur = cur.next; } - + cur.next = arr[b + 1]; return list1; } @@ -138,8 +138,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(n)$ > Where $n$ is the length of the first list and $m$ is the length of the second list. @@ -159,23 +159,23 @@ class Solution: def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode: curr = list1 i = 0 - + while i < a - 1: curr = curr.next i += 1 head = curr - + while i <= b: curr = curr.next i += 1 - + head.next = list2 - + while list2.next: list2 = list2.next list2.next = curr - - return list1 + + return list1 ``` ```java @@ -193,25 +193,25 @@ public class Solution { public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) { ListNode curr = list1; int i = 0; - + while (i < a - 1) { curr = curr.next; i++; } ListNode head = curr; - + while (i <= b) { curr = curr.next; i++; } - + head.next = list2; - + while (list2.next != null) { list2 = list2.next; } list2.next = curr; - + return list1; } } @@ -233,24 +233,24 @@ public: ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) { ListNode* curr = list1; int i = 0; - + while (i < a - 1) { curr = curr->next; i++; } ListNode* head = curr; - + while (i <= b) { curr = curr->next; i++; } head->next = list2; - + while (list2->next) { list2 = list2->next; } list2->next = curr; - + return list1; } }; @@ -275,25 +275,26 @@ class Solution { * @return {ListNode} */ mergeInBetween(list1, a, b, list2) { - let curr = list1, i = 0; - + let curr = list1, + i = 0; + while (i < a - 1) { curr = curr.next; i++; } let head = curr; - + while (i <= b) { curr = curr.next; i++; } head.next = list2; - + while (list2.next) { list2 = list2.next; } list2.next = curr; - + return list1; } } @@ -303,8 +304,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n + m)$ +- Space complexity: $O(1)$ extra space. > Where $n$ is the length of the first list and $m$ is the length of the second list. @@ -329,11 +330,11 @@ class Solution: list2 = list2.next self.mergeInBetween(nxt, 0, b - 1, list2) return list1 - + if b == 0: list2.next = list1.next return list1 - + self.mergeInBetween(list1.next, a - 1, b - 1, list2) return list1 ``` @@ -354,19 +355,19 @@ public class Solution { if (a == 1) { ListNode nxt = list1.next; list1.next = list2; - + while (list2.next != null) { list2 = list2.next; } mergeInBetween(nxt, 0, b - 1, list2); return list1; } - + if (b == 0) { list2.next = list1.next; return list1; } - + mergeInBetween(list1.next, a - 1, b - 1, list2); return list1; } @@ -390,19 +391,19 @@ public: if (a == 1) { ListNode* nxt = list1->next; list1->next = list2; - + while (list2->next) { list2 = list2->next; } mergeInBetween(nxt, 0, b - 1, list2); return list1; } - + if (b == 0) { list2->next = list1->next; return list1; } - + mergeInBetween(list1->next, a - 1, b - 1, list2); return list1; } @@ -431,19 +432,19 @@ class Solution { if (a === 1) { let nxt = list1.next; list1.next = list2; - + while (list2.next) { list2 = list2.next; } this.mergeInBetween(nxt, 0, b - 1, list2); return list1; } - + if (b === 0) { list2.next = list1.next; return list1; } - + this.mergeInBetween(list1.next, a - 1, b - 1, list2); return list1; } @@ -454,7 +455,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n + m)$ +- Space complexity: $O(n)$ for recursion stack. -> Where $n$ is the length of the first list and $m$ is the length of the second list. \ No newline at end of file +> Where $n$ is the length of the first list and $m$ is the length of the second list. diff --git a/articles/merge-intervals.md b/articles/merge-intervals.md index 100d894b6..9662e4587 100644 --- a/articles/merge-intervals.md +++ b/articles/merge-intervals.md @@ -190,10 +190,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: - * $O(1)$ or $O(n)$ space depending on the sorting algorithm. - * $O(n)$ for the output list. +- Time complexity: $O(n \log n)$ +- Space complexity: + - $O(1)$ or $O(n)$ space depending on the sorting algorithm. + - $O(n)$ for the output list. --- @@ -227,16 +227,16 @@ class Solution: public class Solution { public int[][] merge(int[][] intervals) { TreeMap map = new TreeMap<>(); - + for (int[] interval : intervals) { map.put(interval[0], map.getOrDefault(interval[0], 0) + 1); map.put(interval[1], map.getOrDefault(interval[1], 0) - 1); } - + List res = new ArrayList<>(); int have = 0; int[] interval = new int[2]; - + for (int point : map.keySet()) { if (have == 0) interval[0] = point; have += map.get(point); @@ -245,7 +245,7 @@ public class Solution { res.add(new int[] {interval[0], interval[1]}); } } - + return res.toArray(new int[res.size()][]); } } @@ -409,7 +409,7 @@ class Solution { class Solution { func merge(_ intervals: [[Int]]) -> [[Int]] { var mp = [Int: Int]() - + for interval in intervals { let start = interval[0] let end = interval[1] @@ -441,8 +441,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -454,7 +454,7 @@ class Solution { class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: max_val = max(interval[0] for interval in intervals) - + mp = [0] * (max_val + 1) for start, end in intervals: mp[start] = max(end + 1, mp[start]) @@ -774,7 +774,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(n)$ -> Where $n$ is the length of the array and $m$ is the maximum start value among all the intervals. \ No newline at end of file +> Where $n$ is the length of the array and $m$ is the maximum start value among all the intervals. diff --git a/articles/merge-k-sorted-linked-lists.md b/articles/merge-k-sorted-linked-lists.md index 6150fa6f5..a57acd659 100644 --- a/articles/merge-k-sorted-linked-lists.md +++ b/articles/merge-k-sorted-linked-lists.md @@ -9,7 +9,7 @@ # self.val = val # self.next = next -class Solution: +class Solution: def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]: nodes = [] for lst in lists: @@ -38,7 +38,7 @@ class Solution: * } */ -public class Solution { +public class Solution { public ListNode mergeKLists(ListNode[] lists) { List nodes = new ArrayList<>(); for (ListNode lst : lists) { @@ -72,7 +72,7 @@ public class Solution { * }; */ -class Solution { +class Solution { public: ListNode* mergeKLists(vector& lists) { vector nodes; @@ -145,7 +145,7 @@ class Solution { * } */ -public class Solution { +public class Solution { public ListNode MergeKLists(ListNode[] lists) { List nodes = new List(); foreach (ListNode lst in lists) { @@ -178,7 +178,7 @@ public class Solution { */ func mergeKLists(lists []*ListNode) *ListNode { nodes := make([]int, 0) - + for _, list := range lists { curr := list for curr != nil { @@ -186,17 +186,17 @@ func mergeKLists(lists []*ListNode) *ListNode { curr = curr.Next } } - + sort.Ints(nodes) - + dummy := &ListNode{Val: 0} curr := dummy - + for _, val := range nodes { curr.Next = &ListNode{Val: val} curr = curr.Next } - + return dummy.Next } ``` @@ -214,7 +214,7 @@ func mergeKLists(lists []*ListNode) *ListNode { class Solution { fun mergeKLists(lists: Array): ListNode? { val nodes = mutableListOf() - + for (list in lists) { var curr = list while (curr != null) { @@ -222,17 +222,17 @@ class Solution { curr = curr.next } } - + nodes.sort() - + val dummy = ListNode(0) var curr = dummy - + for (value in nodes) { curr.next = ListNode(value) curr = curr.next!! } - + return dummy.next } } @@ -279,8 +279,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -295,11 +295,11 @@ class Solution { # self.val = val # self.next = next -class Solution: +class Solution: def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]: res = ListNode(0) cur = res - + while True: minNode = -1 for i in range(len(lists)): @@ -307,7 +307,7 @@ class Solution: continue if minNode == -1 or lists[minNode].val > lists[i].val: minNode = i - + if minNode == -1: break cur.next = lists[minNode] @@ -329,7 +329,7 @@ class Solution: * } */ -public class Solution { +public class Solution { public ListNode mergeKLists(ListNode[] lists) { ListNode res = new ListNode(0); ListNode cur = res; @@ -370,7 +370,7 @@ public class Solution { * }; */ -class Solution { +class Solution { public: ListNode* mergeKLists(vector& lists) { ListNode* res = new ListNode(0); @@ -447,7 +447,7 @@ class Solution { * } */ -public class Solution { +public class Solution { public ListNode MergeKLists(ListNode[] lists) { ListNode res = new ListNode(0); ListNode cur = res; @@ -482,7 +482,7 @@ public class Solution { func mergeKLists(lists []*ListNode) *ListNode { res := &ListNode{Val: 0} cur := res - + for { minNode := -1 for i := range lists { @@ -493,16 +493,16 @@ func mergeKLists(lists []*ListNode) *ListNode { minNode = i } } - + if minNode == -1 { break } - + cur.Next = lists[minNode] lists[minNode] = lists[minNode].Next cur = cur.Next } - + return res.Next } ``` @@ -521,7 +521,7 @@ class Solution { fun mergeKLists(lists: Array): ListNode? { val res = ListNode(0) var cur = res - + while (true) { var minNode = -1 for (i in lists.indices) { @@ -532,16 +532,16 @@ class Solution { minNode = i } } - + if (minNode == -1) { break } - + cur.next = lists[minNode] lists[minNode] = lists[minNode]!!.next cur = cur.next!! } - + return res.next } } @@ -577,7 +577,7 @@ class Solution { if minNodeIndex == nil { break } - + cur.next = lists[minNodeIndex!] lists[minNodeIndex!] = lists[minNodeIndex!]?.next cur = cur.next! @@ -592,8 +592,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * k)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n * k)$ +- Space complexity: $O(1)$ > Where $k$ is the total number of lists and $n$ is the total number of nodes across $k$ lists. @@ -610,14 +610,14 @@ class Solution { # self.val = val # self.next = next -class Solution: +class Solution: def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]: if len(lists) == 0: return None for i in range(1, len(lists)): lists[i] = self.mergeList(lists[i - 1], lists[i]) - + return lists[-1] def mergeList(self, l1, l2): @@ -853,7 +853,7 @@ public class Solution { func mergeList(l1 *ListNode, l2 *ListNode) *ListNode { dummy := &ListNode{} tail := dummy - + for l1 != nil && l2 != nil { if l1.Val < l2.Val { tail.Next = l1 @@ -864,14 +864,14 @@ func mergeList(l1 *ListNode, l2 *ListNode) *ListNode { } tail = tail.Next } - + if l1 != nil { tail.Next = l1 } if l2 != nil { tail.Next = l2 } - + return dummy.Next } @@ -879,11 +879,11 @@ func mergeKLists(lists []*ListNode) *ListNode { if len(lists) == 0 { return nil } - + for i := 1; i < len(lists); i++ { lists[i] = mergeList(lists[i-1], lists[i]) } - + return lists[len(lists)-1] } ``` @@ -904,7 +904,7 @@ class Solution { var tail = dummy var first = l1 var second = l2 - + while (first != null && second != null) { if (first.`val` < second.`val`) { tail.next = first @@ -915,26 +915,26 @@ class Solution { } tail = tail.next!! } - + if (first != null) { tail.next = first } if (second != null) { tail.next = second } - + return dummy.next } - + fun mergeKLists(lists: Array): ListNode? { if (lists.isEmpty()) { return null } - + for (i in 1 until lists.size) { lists[i] = mergeList(lists[i-1], lists[i]) } - + return lists.last() } } @@ -987,7 +987,7 @@ class Solution { if l2 != nil { tail.next = l2 } - + return dummy.next } } @@ -997,8 +997,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * k)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n * k)$ +- Space complexity: $O(1)$ > Where $k$ is the total number of lists and $n$ is the total number of nodes across $k$ lists. @@ -1022,7 +1022,7 @@ class NodeWrapper: def __lt__(self, other): return self.node.val < other.node.val -class Solution: +class Solution: def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]: if len(lists) == 0: return None @@ -1039,10 +1039,10 @@ class Solution: node_wrapper = heapq.heappop(minHeap) cur.next = node_wrapper.node cur = cur.next - + if node_wrapper.node.next: heapq.heappush(minHeap, NodeWrapper(node_wrapper.node.next)) - + return res.next ``` @@ -1061,7 +1061,7 @@ class Solution: class Solution { public ListNode mergeKLists(ListNode[] lists) { if (lists.length == 0) return null; - + PriorityQueue minHeap = new PriorityQueue<>((a, b) -> a.val - b.val); for (ListNode list : lists) { if (list != null) { @@ -1105,7 +1105,7 @@ public: auto cmp = [](ListNode* a, ListNode* b) { return a->val > b->val; }; priority_queue, decltype(cmp)> minHeap(cmp); - + for (ListNode* list : lists) { if (list != nullptr) { minHeap.push(list); @@ -1148,10 +1148,9 @@ class Solution { */ mergeKLists(lists) { if (lists.length === 0) return null; - const minHeap = new MinPriorityQueue(x => x.val); + const minHeap = new MinPriorityQueue((x) => x.val); for (let list of lists) { - if (list != null) - minHeap.enqueue(list); + if (list != null) minHeap.enqueue(list); } let res = new ListNode(0); @@ -1224,30 +1223,30 @@ func mergeKLists(lists []*ListNode) *ListNode { if len(lists) == 0 { return nil } - + minHeap := priorityqueue.NewWith(func(a, b interface{}) int { return a.(*ListNode).Val - b.(*ListNode).Val }) - + for _, list := range lists { if list != nil { minHeap.Enqueue(list) } } - + res := &ListNode{Val: 0} cur := res - + for !minHeap.Empty() { node, _ := minHeap.Dequeue() cur.Next = node.(*ListNode) cur = cur.Next - + if cur.Next != nil { minHeap.Enqueue(cur.Next) } } - + return res.Next } ``` @@ -1265,24 +1264,24 @@ func mergeKLists(lists []*ListNode) *ListNode { class Solution { fun mergeKLists(lists: Array): ListNode? { if (lists.isEmpty()) return null - + val minHeap = PriorityQueue(compareBy { it.`val` }) - + for (list in lists) { list?.let { minHeap.offer(it) } } - + val res = ListNode(0) var cur = res - + while (minHeap.isNotEmpty()) { val node = minHeap.poll() cur.next = node cur = cur.next!! - + node.next?.let { minHeap.offer(it) } } - + return res.next } } @@ -1346,8 +1345,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log k)$ -* Space complexity: $O(k)$ +- Time complexity: $O(n \log k)$ +- Space complexity: $O(k)$ > Where $k$ is the total number of lists and $n$ is the total number of nodes across $k$ lists. @@ -1424,14 +1423,14 @@ class Solution { } private ListNode divide(ListNode[] lists, int l, int r) { - if (l > r) { + if (l > r) { return null; } if (l == r) { return lists[l]; } - int mid = l + (r - l) / 2; + int mid = l + (r - l) / 2; ListNode left = divide(lists, l, mid); ListNode right = divide(lists, mid + 1, r); @@ -1791,7 +1790,7 @@ class Solution { if l == r { return lists[l] } - + let mid = l + (r - l) / 2 let left = divide(lists, l, mid) let right = divide(lists, mid + 1, r) @@ -1824,8 +1823,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log k)$ -* Space complexity: $O(\log k)$ +- Time complexity: $O(n \log k)$ +- Space complexity: $O(\log k)$ > Where $k$ is the total number of lists and $n$ is the total number of nodes across $k$ lists. @@ -1843,7 +1842,7 @@ class Solution { # self.next = next class Solution: - + def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]: if not lists or len(lists) == 0: return None @@ -2019,7 +2018,7 @@ class Solution { const mergedLists = []; for (let i = 0; i < lists.length; i += 2) { const l1 = lists[i]; - const l2 = (i + 1) < lists.length ? lists[i + 1] : null; + const l2 = i + 1 < lists.length ? lists[i + 1] : null; mergedLists.push(this.mergeList(l1, l2)); } lists = mergedLists; @@ -2230,21 +2229,21 @@ class Solution { if lists.isEmpty { return nil } - + var lists = lists - + while lists.count > 1 { var mergedLists: [ListNode?] = [] - + for i in stride(from: 0, to: lists.count, by: 2) { let l1 = lists[i] let l2 = i + 1 < lists.count ? lists[i + 1] : nil mergedLists.append(mergeList(l1, l2)) } - + lists = mergedLists } - + return lists[0] } @@ -2274,7 +2273,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log k)$ -* Space complexity: $O(k)$ +- Time complexity: $O(n \log k)$ +- Space complexity: $O(k)$ -> Where $k$ is the total number of lists and $n$ is the total number of nodes across $k$ lists. \ No newline at end of file +> Where $k$ is the total number of lists and $n$ is the total number of nodes across $k$ lists. diff --git a/articles/merge-sorted-array.md b/articles/merge-sorted-array.md index a0e701ef0..c5721d231 100644 --- a/articles/merge-sorted-array.md +++ b/articles/merge-sorted-array.md @@ -68,8 +68,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O((m + n) \log (m + n))$ -* Space complexity: $O(1)$ or $O(m + n)$ depending on the sorting algorithm. +- Time complexity: $O((m + n) \log (m + n))$ +- Space complexity: $O(1)$ or $O(m + n)$ depending on the sorting algorithm. > Where $m$ and $n$ represent the number of elements in the arrays $nums1$ and $nums2$, respectively. @@ -103,7 +103,7 @@ public class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { int[] nums1Copy = Arrays.copyOf(nums1, m); int idx = 0, i = 0, j = 0; - + while (idx < m + n) { if (j >= n || (i < m && nums1Copy[i] <= nums2[j])) { nums1[idx++] = nums1Copy[i++]; @@ -121,7 +121,7 @@ public: void merge(vector& nums1, int m, vector& nums2, int n) { vector nums1Copy(nums1.begin(), nums1.begin() + m); int idx = 0, i = 0, j = 0; - + while (idx < m + n) { if (j >= n || (i < m && nums1Copy[i] <= nums2[j])) { nums1[idx++] = nums1Copy[i++]; @@ -144,7 +144,9 @@ class Solution { */ merge(nums1, m, nums2, n) { const nums1Copy = nums1.slice(0, m); - let idx = 0, i = 0, j = 0; + let idx = 0, + i = 0, + j = 0; while (idx < m + n) { if (j >= n || (i < m && nums1Copy[i] <= nums2[j])) { @@ -180,8 +182,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n)$ -* Space complexity: $O(m)$ +- Time complexity: $O(m + n)$ +- Space complexity: $O(m)$ > Where $m$ and $n$ represent the number of elements in the arrays $nums1$ and $nums2$, respectively. @@ -331,8 +333,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(m + n)$ +- Space complexity: $O(1)$ extra space. > Where $m$ and $n$ represent the number of elements in the arrays $nums1$ and $nums2$, respectively. @@ -358,8 +360,8 @@ class Solution: else: nums1[last] = nums2[j] j -= 1 - - last -= 1 + + last -= 1 ``` ```java @@ -408,7 +410,8 @@ class Solution { */ merge(nums1, m, nums2, n) { let last = m + n - 1; - let i = m - 1, j = n - 1; + let i = m - 1, + j = n - 1; while (j >= 0) { if (i >= 0 && nums1[i] > nums2[j]) { @@ -442,7 +445,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(m + n)$ +- Space complexity: $O(1)$ extra space. -> Where $m$ and $n$ represent the number of elements in the arrays $nums1$ and $nums2$, respectively. \ No newline at end of file +> Where $m$ and $n$ represent the number of elements in the arrays $nums1$ and $nums2$, respectively. diff --git a/articles/merge-strings-alternately.md b/articles/merge-strings-alternately.md index d61a657cd..7e3b7582b 100644 --- a/articles/merge-strings-alternately.md +++ b/articles/merge-strings-alternately.md @@ -59,13 +59,14 @@ class Solution { */ mergeAlternately(word1, word2) { let res = []; - let i = 0, j = 0; + let i = 0, + j = 0; while (i < word1.length && j < word2.length) { res.push(word1[i++], word2[j++]); } res.push(word1.slice(i)); res.push(word2.slice(j)); - return res.join(""); + return res.join(''); } } ``` @@ -95,8 +96,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n + m)$ for the output string. +- Time complexity: $O(n + m)$ +- Space complexity: $O(n + m)$ for the output string. > Where $n$ and $m$ are the lengths of the strings $word1$ and $word2$ respectively. @@ -161,14 +162,16 @@ class Solution { * @return {string} */ mergeAlternately(word1, word2) { - const n = word1.length, m = word2.length; + const n = word1.length, + m = word2.length; const res = []; - let i = 0, j = 0; + let i = 0, + j = 0; while (i < n || j < m) { if (i < n) res.push(word1[i++]); if (j < m) res.push(word2[j++]); } - return res.join(""); + return res.join(''); } } ``` @@ -200,8 +203,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n + m)$ for the output string. +- Time complexity: $O(n + m)$ +- Space complexity: $O(n + m)$ for the output string. > Where $n$ and $m$ are the lengths of the strings $word1$ and $word2$ respectively. @@ -269,7 +272,8 @@ class Solution { * @return {string} */ mergeAlternately(word1, word2) { - const n = word1.length, m = word2.length; + const n = word1.length, + m = word2.length; const res = []; for (let i = 0; i < m || i < n; i++) { if (i < n) { @@ -279,7 +283,7 @@ class Solution { res.push(word2.charAt(i)); } } - return res.join(""); + return res.join(''); } } ``` @@ -308,7 +312,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n + m)$ for the output string. +- Time complexity: $O(n + m)$ +- Space complexity: $O(n + m)$ for the output string. -> Where $n$ and $m$ are the lengths of the strings $word1$ and $word2$ respectively. \ No newline at end of file +> Where $n$ and $m$ are the lengths of the strings $word1$ and $word2$ respectively. diff --git a/articles/merge-triplets-to-form-target.md b/articles/merge-triplets-to-form-target.md index 268d8ae9d..09ea587fd 100644 --- a/articles/merge-triplets-to-form-target.md +++ b/articles/merge-triplets-to-form-target.md @@ -163,8 +163,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -226,11 +226,13 @@ class Solution { * @return {boolean} */ mergeTriplets(triplets, target) { - let x = false, y = false, z = false; + let x = false, + y = false, + z = false; for (let t of triplets) { - x |= (t[0] === target[0] && t[1] <= target[1] && t[2] <= target[2]); - y |= (t[0] <= target[0] && t[1] === target[1] && t[2] <= target[2]); - z |= (t[0] <= target[0] && t[1] <= target[1] && t[2] === target[2]); + x |= t[0] === target[0] && t[1] <= target[1] && t[2] <= target[2]; + y |= t[0] <= target[0] && t[1] === target[1] && t[2] <= target[2]; + z |= t[0] <= target[0] && t[1] <= target[1] && t[2] === target[2]; if (x && y && z) return true; } return false; @@ -261,7 +263,7 @@ func mergeTriplets(triplets [][]int, target []int) bool { x = x || (t[0] == target[0] && t[1] <= target[1] && t[2] <= target[2]) y = y || (t[0] <= target[0] && t[1] == target[1] && t[2] <= target[2]) z = z || (t[0] <= target[0] && t[1] <= target[1] && t[2] == target[2]) - + if x && y && z { return true } @@ -315,5 +317,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/merge-two-binary-trees.md b/articles/merge-two-binary-trees.md index 0b7636434..d0811dfb2 100644 --- a/articles/merge-two-binary-trees.md +++ b/articles/merge-two-binary-trees.md @@ -13,14 +13,14 @@ class Solution: def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]: if not root1 and not root2: return None - + v1 = root1.val if root1 else 0 v2 = root2.val if root2 else 0 root = TreeNode(v1 + v2) - + root.left = self.mergeTrees(root1.left if root1 else None, root2.left if root2 else None) root.right = self.mergeTrees(root1.right if root1 else None, root2.right if root2 else None) - + return root ``` @@ -119,8 +119,14 @@ class Solution { const v2 = root2 ? root2.val : 0; const root = new TreeNode(v1 + v2); - root.left = this.mergeTrees(root1 ? root1.left : null, root2 ? root2.left : null); - root.right = this.mergeTrees(root1 ? root1.right : null, root2 ? root2.right : null); + root.left = this.mergeTrees( + root1 ? root1.left : null, + root2 ? root2.left : null, + ); + root.right = this.mergeTrees( + root1 ? root1.right : null, + root2 ? root2.right : null, + ); return root; } @@ -131,10 +137,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n)$ -* Space complexity: - * $O(m + n)$ space for recursion stack. - * $O(m + n)$ space for the output. +- Time complexity: $O(m + n)$ +- Space complexity: + - $O(m + n)$ space for recursion stack. + - $O(m + n)$ space for the output. > Where $m$ and $n$ are the number of nodes in the given trees. @@ -252,8 +258,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(min(m, n))$ -* Space complexity: $O(min(m, n))$ for recursion stack. +- Time complexity: $O(min(m, n))$ +- Space complexity: $O(min(m, n))$ for recursion stack. > Where $m$ and $n$ are the number of nodes in the given trees. @@ -282,7 +288,7 @@ class Solution: while stack: node1, node2, node = stack.pop() - + if node1.left and node2.left: node.left = TreeNode(node1.left.val + node2.left.val) stack.append((node1.left, node2.left, node.left)) @@ -439,7 +445,8 @@ class Solution { let right1 = node1 ? node1.right : null; let right2 = node2 ? node2.right : null; if (right1 || right2) { - let rightVal = (right1 ? right1.val : 0) + (right2 ? right2.val : 0); + let rightVal = + (right1 ? right1.val : 0) + (right2 ? right2.val : 0); node.right = new TreeNode(rightVal); stack.push([right1, right2, node.right]); } @@ -454,10 +461,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n)$ -* Space complexity: - * $O(m + n)$ space for the stack. - * $O(m + n)$ space for the output. +- Time complexity: $O(m + n)$ +- Space complexity: + - $O(m + n)$ space for the stack. + - $O(m + n)$ space for the output. > Where $m$ and $n$ are the number of nodes in the given trees. @@ -652,7 +659,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(min(m, n))$ -* Space complexity: $O(min(m, n))$ for the stack. +- Time complexity: $O(min(m, n))$ +- Space complexity: $O(min(m, n))$ for the stack. -> Where $m$ and $n$ are the number of nodes in the given trees. \ No newline at end of file +> Where $m$ and $n$ are the number of nodes in the given trees. diff --git a/articles/merge-two-sorted-linked-lists.md b/articles/merge-two-sorted-linked-lists.md index b65407ade..c2419b978 100644 --- a/articles/merge-two-sorted-linked-lists.md +++ b/articles/merge-two-sorted-linked-lists.md @@ -133,7 +133,7 @@ class Solution { * } * } */ - + public class Solution { public ListNode MergeTwoLists(ListNode list1, ListNode list2) { if (list1 == null) { @@ -191,7 +191,7 @@ class Solution { fun mergeTwoLists(list1: ListNode?, list2: ListNode?): ListNode? { if (list1 == null) return list2 if (list2 == null) return list1 - + return if (list1.`val` <= list2.`val`) { list1.next = mergeTwoLists(list1.next, list2) list1 @@ -237,8 +237,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n + m)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(n + m)$ > Where $n$ is the length of $list1$ and $m$ is the length of $list2$. @@ -407,7 +407,7 @@ class Solution { * } * } */ - + public class Solution { public ListNode MergeTwoLists(ListNode list1, ListNode list2) { ListNode dummy = new ListNode(0); @@ -543,7 +543,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(1)$ -> Where $n$ is the length of $list1$ and $m$ is the length of $list2$. \ No newline at end of file +> Where $n$ is the length of $list1$ and $m$ is the length of $list2$. diff --git a/articles/middle-of-the-linked-list.md b/articles/middle-of-the-linked-list.md index 935efc3d4..9d1f36d04 100644 --- a/articles/middle-of-the-linked-list.md +++ b/articles/middle-of-the-linked-list.md @@ -98,8 +98,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -119,7 +119,7 @@ class Solution: while cur: cur = cur.next n += 1 - + n //= 2 cur = head while n: @@ -229,8 +229,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -320,7 +320,8 @@ class Solution { * @return {ListNode} */ middleNode(head) { - let slow = head, fast = head; + let slow = head, + fast = head; while (fast && fast.next) { slow = slow.next; @@ -335,5 +336,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/min-cost-climbing-stairs.md b/articles/min-cost-climbing-stairs.md index 9433d007b..edfedb3da 100644 --- a/articles/min-cost-climbing-stairs.md +++ b/articles/min-cost-climbing-stairs.md @@ -5,22 +5,22 @@ ```python class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: - + def dfs(i): if i >= len(cost): return 0 return cost[i] + min(dfs(i + 1), dfs(i + 2)) - + return min(dfs(0), dfs(1)) ``` ```java public class Solution { public int minCostClimbingStairs(int[] cost) { - + return Math.min(dfs(cost, 0), dfs(cost, 1)); } - + private int dfs(int[] cost, int i) { if (i >= cost.length) { return 0; @@ -37,7 +37,7 @@ public: int minCostClimbingStairs(vector& cost) { return min(dfs(cost, 0), dfs(cost, 1)); } - + int dfs(vector& cost, int i) { if (i >= cost.size()) { return 0; @@ -60,7 +60,7 @@ class Solution { return 0; } return cost[i] + Math.min(dfs(i + 1), dfs(i + 2)); - } + }; return Math.min(dfs(0), dfs(1)); } } @@ -71,7 +71,7 @@ public class Solution { public int MinCostClimbingStairs(int[] cost) { return Math.Min(Dfs(cost, 0), Dfs(cost, 1)); } - + private int Dfs(int[] cost, int i) { if (i >= cost.Length) { return 0; @@ -91,7 +91,7 @@ func minCostClimbingStairs(cost []int) int { } return cost[i] + min(dfs(i+1), dfs(i+2)) } - + return min(dfs(0), dfs(1)) } @@ -112,7 +112,7 @@ class Solution { } return cost[i] + minOf(dfs(i + 1), dfs(i + 2)) } - + return minOf(dfs(0), dfs(1)) } } @@ -137,8 +137,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ --- @@ -150,7 +150,7 @@ class Solution { class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: memo = [-1] * len(cost) - + def dfs(i): if i >= len(cost): return 0 @@ -158,20 +158,20 @@ class Solution: return memo[i] memo[i] = cost[i] + min(dfs(i + 1), dfs(i + 2)) return memo[i] - + return min(dfs(0), dfs(1)) ``` ```java public class Solution { int[] memo; - + public int minCostClimbingStairs(int[] cost) { memo = new int[cost.length]; Arrays.fill(memo, -1); return Math.min(dfs(cost, 0), dfs(cost, 1)); } - + private int dfs(int[] cost, int i) { if (i >= cost.length) { return 0; @@ -190,12 +190,12 @@ public class Solution { class Solution { public: vector memo; - + int minCostClimbingStairs(vector& cost) { memo.resize(cost.size(), -1); return min(dfs(cost, 0), dfs(cost, 1)); } - + int dfs(vector& cost, int i) { if (i >= cost.size()) { return 0; @@ -225,10 +225,9 @@ class Solution { if (memo[i] !== -1) { return memo[i]; } - memo[i] = cost[i] + Math.min(dfs(i + 1), - dfs(i + 2)); + memo[i] = cost[i] + Math.min(dfs(i + 1), dfs(i + 2)); return memo[i]; - } + }; return Math.min(dfs(0), dfs(1)); } } @@ -237,13 +236,13 @@ class Solution { ```csharp public class Solution { int[] memo; - + public int MinCostClimbingStairs(int[] cost) { memo = new int[cost.Length]; Array.Fill(memo, -1); return Math.Min(Dfs(cost, 0), Dfs(cost, 1)); } - + private int Dfs(int[] cost, int i) { if (i >= cost.Length) { return 0; @@ -276,7 +275,7 @@ func minCostClimbingStairs(cost []int) int { memo[i] = cost[i] + min(dfs(i+1), dfs(i+2)) return memo[i] } - + return min(dfs(0), dfs(1)) } @@ -300,7 +299,7 @@ class Solution { memo[i] = cost[i] + minOf(dfs(i + 1), dfs(i + 2)) return memo[i] } - + return minOf(dfs(0), dfs(1)) } } @@ -331,8 +330,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -345,11 +344,11 @@ class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: n = len(cost) dp = [0] * (n + 1) - + for i in range(2, n + 1): dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]) - + return dp[n] ``` @@ -358,12 +357,12 @@ public class Solution { public int minCostClimbingStairs(int[] cost) { int n = cost.length; int[] dp = new int[n + 1]; - + for (int i = 2; i <= n; i++) { dp[i] = Math.min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]); } - + return dp[n]; } } @@ -375,12 +374,12 @@ public: int minCostClimbingStairs(vector& cost) { int n = cost.size(); vector dp(n + 1); - + for (int i = 2; i <= n; i++) { dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]); } - + return dp[n]; } }; @@ -395,12 +394,11 @@ class Solution { minCostClimbingStairs(cost) { const n = cost.length; const dp = new Array(n + 1).fill(0); - + for (let i = 2; i <= n; i++) { - dp[i] = Math.min(dp[i - 1] + cost[i - 1], - dp[i - 2] + cost[i - 2]); + dp[i] = Math.min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]); } - + return dp[n]; } } @@ -411,12 +409,12 @@ public class Solution { public int MinCostClimbingStairs(int[] cost) { int n = cost.Length; int[] dp = new int[n + 1]; - + for (int i = 2; i <= n; i++) { dp[i] = Math.Min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]); } - + return dp[n]; } } @@ -466,7 +464,7 @@ class Solution { var dp = Array(repeating: 0, count: n + 1) for i in 2...n { - dp[i] = min(dp[i - 1] + cost[i - 1], + dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]) } @@ -479,8 +477,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -590,5 +588,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/min-cost-to-connect-points.md b/articles/min-cost-to-connect-points.md index 6688ee3a1..624ac66da 100644 --- a/articles/min-cost-to-connect-points.md +++ b/articles/min-cost-to-connect-points.md @@ -35,7 +35,7 @@ class Solution: x2, y2 = points[j] dist = abs(x1 - x2) + abs(y1 - y2) edges.append((dist, i, j)) - + edges.sort() res = 0 for dist, u, v in edges: @@ -84,12 +84,12 @@ public class Solution { for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { - int dist = Math.abs(points[i][0] - points[j][0]) + + int dist = Math.abs(points[i][0] - points[j][0]) + Math.abs(points[i][1] - points[j][1]); edges.add(new int[] {dist, i, j}); } } - + edges.sort((a, b) -> Integer.compare(a[0], b[0])); int res = 0; @@ -107,7 +107,7 @@ public class Solution { class DSU { public: vector Parent, Size; - + DSU(int n) : Parent(n + 1), Size(n + 1, 1) { for (int i = 0; i <= n; ++i) Parent[i] = i; } @@ -138,7 +138,7 @@ public: for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { - int dist = abs(points[i][0] - points[j][0]) + + int dist = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]); edges.push_back({dist, i, j}); } @@ -181,7 +181,8 @@ class DSU { * @return {boolean} */ union(u, v) { - let pu = this.find(u), pv = this.find(v); + let pu = this.find(u), + pv = this.find(v); if (pu === pv) return false; if (this.Size[pu] < this.Size[pv]) [pu, pv] = [pv, pu]; this.Size[pu] += this.Size[pv]; @@ -202,8 +203,9 @@ class Solution { for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { - const dist = Math.abs(points[i][0] - points[j][0]) + - Math.abs(points[i][1] - points[j][1]); + const dist = + Math.abs(points[i][0] - points[j][0]) + + Math.abs(points[i][1] - points[j][1]); edges.push([dist, i, j]); } } @@ -224,7 +226,7 @@ class Solution { ```csharp public class DSU { public int[] Parent, Size; - + public DSU(int n) { Parent = new int[n + 1]; Size = new int[n + 1]; @@ -261,7 +263,7 @@ public class Solution { for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { - int dist = Math.Abs(points[i][0] - points[j][0]) + + int dist = Math.Abs(points[i][0] - points[j][0]) + Math.Abs(points[i][1] - points[j][1]); edges.Add((dist, i, j)); } @@ -464,8 +466,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 \log n)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2 \log n)$ +- Space complexity: $O(n ^ 2)$ --- @@ -564,7 +566,7 @@ public: int res = 0; unordered_set visit; - priority_queue, vector>, + priority_queue, vector>, greater>> minH; minH.push({0, 0}); while (visit.size() < N) { @@ -615,7 +617,7 @@ class Solution { let res = 0; const visit = new Set(); - const minHeap = new MinPriorityQueue(entry => entry[0]); + const minHeap = new MinPriorityQueue((entry) => entry[0]); minHeap.push([0, 0]); while (visit.size < N) { @@ -658,8 +660,8 @@ public class Solution { int res = 0; var visit = new HashSet(); - var pq = new PriorityQueue(); - pq.Enqueue(0, 0); + var pq = new PriorityQueue(); + pq.Enqueue(0, 0); while (visit.Count < N && pq.Count > 0) { if (pq.TryPeek(out int i, out int cost)) { @@ -738,7 +740,7 @@ class Solution { fun minCostConnectPoints(points: Array): Int { val n = points.size val adj = HashMap>>() - + for (i in 0 until n) { val (x1, y1) = points[i] for (j in i + 1 until n) { @@ -752,9 +754,9 @@ class Solution { var res = 0 val visited = mutableSetOf() val minHeap = PriorityQueue(compareBy> { it.first }) - - minHeap.add(0 to 0) - + + minHeap.add(0 to 0) + while (visited.size < n) { val (cost, point) = minHeap.poll() if (point in visited) continue @@ -832,8 +834,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 \log n)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2 \log n)$ +- Space complexity: $O(n ^ 2)$ --- @@ -855,12 +857,12 @@ class Solution: for i in range(n): if visit[i]: continue - curDist = (abs(points[i][0] - points[node][0]) + + curDist = (abs(points[i][0] - points[node][0]) + abs(points[i][1] - points[node][1])) dist[i] = min(dist[i], curDist) if nextNode == -1 or dist[i] < dist[nextNode]: nextNode = i - + res += dist[nextNode] node = nextNode edges += 1 @@ -882,7 +884,7 @@ public class Solution { int nextNode = -1; for (int i = 0; i < n; i++) { if (visit[i]) continue; - int curDist = Math.abs(points[i][0] - points[node][0]) + + int curDist = Math.abs(points[i][0] - points[node][0]) + Math.abs(points[i][1] - points[node][1]); dist[i] = Math.min(dist[i], curDist); if (nextNode == -1 || dist[i] < dist[nextNode]) { @@ -912,7 +914,7 @@ public: int nextNode = -1; for (int i = 0; i < n; i++) { if (visit[i]) continue; - int curDist = abs(points[i][0] - points[node][0]) + + int curDist = abs(points[i][0] - points[node][0]) + abs(points[i][1] - points[node][1]); dist[i] = min(dist[i], curDist); if (nextNode == -1 || dist[i] < dist[nextNode]) { @@ -939,15 +941,17 @@ class Solution { let node = 0; const dist = new Array(n).fill(100000000); const visit = new Array(n).fill(false); - let edges = 0, res = 0; + let edges = 0, + res = 0; while (edges < n - 1) { visit[node] = true; let nextNode = -1; for (let i = 0; i < n; i++) { if (visit[i]) continue; - const curDist = Math.abs(points[i][0] - points[node][0]) + - Math.abs(points[i][1] - points[node][1]); + const curDist = + Math.abs(points[i][0] - points[node][0]) + + Math.abs(points[i][1] - points[node][1]); dist[i] = Math.min(dist[i], curDist); if (nextNode === -1 || dist[i] < dist[nextNode]) { nextNode = i; @@ -976,7 +980,7 @@ public class Solution { int nextNode = -1; for (int i = 0; i < n; i++) { if (visit[i]) continue; - int curDist = Math.Abs(points[i][0] - points[node][0]) + + int curDist = Math.Abs(points[i][0] - points[node][0]) + Math.Abs(points[i][1] - points[node][1]); dist[i] = Math.Min(dist[i], curDist); if (nextNode == -1 || dist[i] < dist[nextNode]) { @@ -1010,7 +1014,7 @@ func minCostConnectPoints(points [][]int) int { if visit[i] { continue } - curDist := int(math.Abs(float64(points[i][0]-points[node][0])) + + curDist := int(math.Abs(float64(points[i][0]-points[node][0])) + math.Abs(float64(points[i][1]-points[node][1]))) if curDist < dist[i] { dist[i] = curDist @@ -1042,7 +1046,7 @@ class Solution { var nextNode = -1 for (i in 0 until n) { if (visit[i]) continue - val curDist = abs(points[i][0] - points[node][0]) + + val curDist = abs(points[i][0] - points[node][0]) + abs(points[i][1] - points[node][1]) dist[i] = minOf(dist[i], curDist) if (nextNode == -1 || dist[i] < dist[nextNode]) { @@ -1076,7 +1080,7 @@ class Solution { if visit[i] { continue } - let curDist = abs(points[i][0] - points[node][0]) + + let curDist = abs(points[i][0] - points[node][0]) + abs(points[i][1] - points[node][1]) dist[i] = min(dist[i], curDist) if nextNode == -1 || dist[i] < dist[nextNode] { @@ -1098,5 +1102,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ diff --git a/articles/minimize-deviation-in-array.md b/articles/minimize-deviation-in-array.md index 34f231a21..4d9c01eae 100644 --- a/articles/minimize-deviation-in-array.md +++ b/articles/minimize-deviation-in-array.md @@ -61,7 +61,7 @@ public class Solution { int[] seen = new int[n]; int count = 0, i = 0; - + for (int j = 0; j < arr.size(); j++) { seen[arr.get(j)[1]]++; if (seen[arr.get(j)[1]] == 1) { @@ -155,7 +155,8 @@ class Solution { let res = Infinity; let seen = new Array(n).fill(0); - let count = 0, i = 0; + let count = 0, + i = 0; for (let j = 0; j < arr.length; j++) { seen[arr[j][1]]++; @@ -180,8 +181,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O((n \log m) * \log (n \log m))$ -* Space complexity: $O(n \log m)$ +- Time complexity: $O((n \log m) * \log (n \log m))$ +- Space complexity: $O(n \log m)$ > Where $n$ is the size of the array $nums$ and $m$ is the maximum element in $nums$. @@ -291,7 +292,7 @@ class Solution { * @return {number} */ minimumDeviation(nums) { - const minHeap = new MinPriorityQueue(x => x[0]); + const minHeap = new MinPriorityQueue((x) => x[0]); let heapMax = 0; for (let num of nums) { @@ -324,8 +325,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n *\log n * \log m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n *\log n * \log m)$ +- Space complexity: $O(n)$ > Where $n$ is the size of the array $nums$ and $m$ is the maximum element in $nums$. @@ -462,7 +463,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n *\log n * \log m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n *\log n * \log m)$ +- Space complexity: $O(n)$ -> Where $n$ is the size of the array $nums$ and $m$ is the maximum element in $nums$. \ No newline at end of file +> Where $n$ is the size of the array $nums$ and $m$ is the maximum element in $nums$. diff --git a/articles/minimize-maximum-of-array.md b/articles/minimize-maximum-of-array.md index b851e40b5..a6fa25980 100644 --- a/articles/minimize-maximum-of-array.md +++ b/articles/minimize-maximum-of-array.md @@ -107,7 +107,8 @@ class Solution { return true; }; - let left = 0, right = Math.max(...nums); + let left = 0, + right = Math.max(...nums); while (left < right) { let mid = left + Math.floor((right - left) / 2); if (isValid(mid)) { @@ -126,8 +127,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log m)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n \log m)$ +- Space complexity: $O(1)$ extra space. > Where $n$ is the size of the array $nums$ and $m$ is the maximum value in the array. @@ -206,5 +207,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/minimize-the-maximum-difference-of-pairs.md b/articles/minimize-the-maximum-difference-of-pairs.md index 5ad0f31b1..04d2f5cd7 100644 --- a/articles/minimize-the-maximum-difference-of-pairs.md +++ b/articles/minimize-the-maximum-difference-of-pairs.md @@ -38,7 +38,7 @@ public class Solution { private int dfs(int i, int pairs, int[] nums, int p) { if (pairs == p) return 0; if (i >= nums.length - 1) return Integer.MAX_VALUE; - + String key = i + "," + pairs; if (dp.containsKey(key)) return dp.get(key); @@ -114,8 +114,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * p)$ -* Space complexity: $O(n * p)$ +- Time complexity: $O(n * p)$ +- Space complexity: $O(n * p)$ > Where $n$ is the size of the input array and $p$ is the number of pairs to select. @@ -140,7 +140,7 @@ class Solution: take = float('inf') if i + 1 < n: take = max(nums[i + 1] - nums[i], dp[i + 2][pairs - 1]) - + skip = dp[i + 1][pairs] dp[i][pairs] = min(take, skip) @@ -215,7 +215,7 @@ class Solution { nums.sort((a, b) => a - b); const dp = Array.from({ length: n + 1 }, () => - new Array(p + 1).fill(Infinity) + new Array(p + 1).fill(Infinity), ); for (let i = 0; i <= n; i++) { dp[i][0] = 0; @@ -225,7 +225,10 @@ class Solution { for (let pairs = 1; pairs <= p; pairs++) { let take = Infinity; if (i + 1 < n) { - take = Math.max(nums[i + 1] - nums[i], dp[i + 2][pairs - 1]); + take = Math.max( + nums[i + 1] - nums[i], + dp[i + 2][pairs - 1], + ); } const skip = dp[i + 1][pairs]; dp[i][pairs] = Math.min(take, skip); @@ -241,8 +244,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * p)$ -* Space complexity: $O(n * p)$ +- Time complexity: $O(n * p)$ +- Space complexity: $O(n * p)$ > Where $n$ is the size of the input array and $p$ is the number of pairs to select. @@ -257,7 +260,7 @@ class Solution: def minimizeMax(self, nums: List[int], p: int) -> int: n = len(nums) nums.sort() - + dp = [float('inf')] * (p + 1) dp1 = [float('inf')] * (p + 1) dp2 = [float('inf')] * (p + 1) @@ -270,12 +273,12 @@ class Solution: take = max(nums[i + 1] - nums[i], dp2[pairs - 1]) skip = dp1[pairs] dp[pairs] = min(take, skip) - + dp2 = dp1[:] dp1 = dp[:] dp = [float('inf')] * (p + 1) dp[0] = 0 - + return dp1[p] ``` @@ -387,8 +390,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * p)$ -* Space complexity: $O(p)$ +- Time complexity: $O(n * p)$ +- Space complexity: $O(p)$ > Where $n$ is the size of the input array and $p$ is the number of pairs to select. @@ -403,7 +406,7 @@ class Solution: def minimizeMax(self, nums: List[int], p: int) -> int: if p == 0: return 0 - + def isValid(threshold): i, cnt = 0, 0 while i < len(nums) - 1: @@ -415,11 +418,11 @@ class Solution: if cnt == p: return True return False - + nums.sort() l, r = 0, nums[-1] - nums[0] res = nums[-1] - nums[0] - + while l <= r: m = l + (r - l) // 2 if isValid(m): @@ -427,7 +430,7 @@ class Solution: r = m - 1 else: l = m + 1 - + return res ``` @@ -435,11 +438,11 @@ class Solution: public class Solution { public int minimizeMax(int[] nums, int p) { if (p == 0) return 0; - + Arrays.sort(nums); int left = 0, right = nums[nums.length - 1] - nums[0]; int result = right; - + while (left <= right) { int mid = left + (right - left) / 2; if (isValid(nums, mid, p)) { @@ -449,10 +452,10 @@ public class Solution { left = mid + 1; } } - + return result; } - + private boolean isValid(int[] nums, int threshold, int p) { int i = 0, count = 0; while (i < nums.length - 1) { @@ -474,11 +477,11 @@ class Solution { public: int minimizeMax(vector& nums, int p) { if (p == 0) return 0; - + sort(nums.begin(), nums.end()); int left = 0, right = nums.back() - nums[0]; int result = right; - + while (left <= right) { int mid = left + (right - left) / 2; if (isValid(nums, mid, p)) { @@ -488,10 +491,10 @@ public: left = mid + 1; } } - + return result; } - + private: bool isValid(vector& nums, int threshold, int p) { int i = 0, count = 0; @@ -520,10 +523,13 @@ class Solution { if (p === 0) return 0; nums.sort((a, b) => a - b); - let l = 0, r = nums[nums.length - 1] - nums[0], res = r; + let l = 0, + r = nums[nums.length - 1] - nums[0], + res = r; const isValid = (threshold) => { - let i = 0, cnt = 0; + let i = 0, + cnt = 0; while (i < nums.length - 1) { if (Math.abs(nums[i] - nums[i + 1]) <= threshold) { cnt++; @@ -555,7 +561,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n\log n + n\log m)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n\log n + n\log m)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. -> Where $n$ is the size of the input array and $m$ is the maximum value in the array. \ No newline at end of file +> Where $n$ is the size of the input array and $m$ is the maximum value in the array. diff --git a/articles/minimum-array-end.md b/articles/minimum-array-end.md index 2089bca1d..1c9894d1b 100644 --- a/articles/minimum-array-end.md +++ b/articles/minimum-array-end.md @@ -69,8 +69,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -262,8 +262,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(\log n)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(\log n)$ --- @@ -388,5 +388,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ diff --git a/articles/minimum-changes-to-make-alternating-binary-string.md b/articles/minimum-changes-to-make-alternating-binary-string.md index 05b5629b5..3aeb66a56 100644 --- a/articles/minimum-changes-to-make-alternating-binary-string.md +++ b/articles/minimum-changes-to-make-alternating-binary-string.md @@ -1,4 +1,4 @@ -## 1. Start with Zero and One +## 1. Start with Zero and One ::tabs-start @@ -10,14 +10,14 @@ class Solution: if int(c) != cur: cnt1 += 1 cur ^= 1 - + cur = 1 cnt2 = 0 for c in s: if int(c) != cur: cnt2 += 1 cur ^= 1 - + return min(cnt1, cnt2) ``` @@ -79,7 +79,8 @@ class Solution { * @return {number} */ minOperations(s) { - let cur = 0, cnt1 = 0; + let cur = 0, + cnt1 = 0; for (let c of s) { if (parseInt(c) !== cur) { cnt1++; @@ -105,8 +106,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -124,7 +125,7 @@ class Solution: count += 1 if s[i] == '0' else 0 else: count += 1 if s[i] == '1' else 0 - + return min(count, len(s) - count) ``` @@ -203,5 +204,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/minimum-cost-for-tickets.md b/articles/minimum-cost-for-tickets.md index 1b32c8980..c7ccc7e12 100644 --- a/articles/minimum-cost-for-tickets.md +++ b/articles/minimum-cost-for-tickets.md @@ -11,19 +11,19 @@ class Solution: if i == n: return 0 - res = costs[0] + dfs(i + 1) + res = costs[0] + dfs(i + 1) j = i while j < n and days[j] < days[i] + 7: j += 1 res = min(res, costs[1] + dfs(j)) - + j = i while j < n and days[j] < days[i] + 30: j += 1 res = min(res, costs[2] + dfs(j)) return res - + return dfs(0) ``` @@ -124,8 +124,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(3 ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(3 ^ n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -252,8 +252,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -266,7 +266,7 @@ class Solution: def mincostTickets(self, days: List[int], costs: List[int]) -> int: n = len(days) dp = [0] * (n + 1) - + for i in range(n - 1, -1, -1): dp[i] = float('inf') j = i @@ -274,7 +274,7 @@ class Solution: while j < n and days[j] < days[i] + d: j += 1 dp[i] = min(dp[i], c + dp[j]) - + return dp[0] ``` @@ -283,7 +283,7 @@ public class Solution { public int mincostTickets(int[] days, int[] costs) { int n = days.length; int[] dp = new int[n + 1]; - + for (int i = n - 1; i >= 0; i--) { dp[i] = Integer.MAX_VALUE; int idx = 0, j = i; @@ -295,7 +295,7 @@ public class Solution { idx++; } } - + return dp[0]; } } @@ -355,8 +355,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -453,7 +453,8 @@ class Solution { days.push(days[days.length - 1] + 30); const n = days.length; const dp = new Array(n).fill(0); - let last7 = n, last30 = n; + let last7 = n, + last30 = n; for (let i = n - 2; i >= 0; i--) { dp[i] = dp[i + 1] + costs[0]; @@ -478,8 +479,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -496,14 +497,14 @@ class Solution: for d in days: while dp7 and dp7[0][0] + 7 <= d: dp7.popleft() - + while dp30 and dp30[0][0] + 30 <= d: dp30.popleft() - + dp7.append([d, dp + costs[1]]) dp30.append([d, dp + costs[2]]) dp = min(dp + costs[0], dp7[0][1], dp30[0][1]) - + return dp ``` @@ -567,8 +568,8 @@ class Solution { * @return {number} */ mincostTickets(days, costs) { - const dp7 = new Queue; - const dp30 = new Queue; + const dp7 = new Queue(); + const dp30 = new Queue(); let dp = 0; for (const d of days) { @@ -595,8 +596,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ since we keep at most $30$ values in the queue. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ since we keep at most $30$ values in the queue. --- @@ -695,7 +696,9 @@ class Solution { mincostTickets(days, costs) { const dp7 = new Deque(); const dp30 = new Deque(); - let dp = 0, last7 = 0, last30 = 0; + let dp = 0, + last7 = 0, + last30 = 0; for (let i = days.length - 1; i >= 0; i--) { dp += costs[0]; @@ -722,8 +725,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ since we keep at most $30$ values in the deque. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ since we keep at most $30$ values in the deque. --- @@ -836,9 +839,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ since the size of the $dp$ array is $366$. - +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ since the size of the $dp$ array is $366$. --- @@ -855,7 +857,7 @@ class Solution: for d in range(1, 366): if i >= len(days): break - + dp[d % 31] = dp[(d - 1) % 31] if d == days[i]: @@ -934,8 +936,14 @@ class Solution { if (d === days[i]) { dp[d % 31] += costs[0]; - dp[d % 31] = Math.min(dp[d % 31], costs[1] + dp[Math.max(0, d - 7) % 31]); - dp[d % 31] = Math.min(dp[d % 31], costs[2] + dp[Math.max(0, d - 30) % 31]); + dp[d % 31] = Math.min( + dp[d % 31], + costs[1] + dp[Math.max(0, d - 7) % 31], + ); + dp[d % 31] = Math.min( + dp[d % 31], + costs[2] + dp[Math.max(0, d - 30) % 31], + ); i++; } } @@ -949,5 +957,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ since the size of the $dp$ array is $31$. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ since the size of the $dp$ array is $31$. diff --git a/articles/minimum-cost-to-cut-a-stick.md b/articles/minimum-cost-to-cut-a-stick.md index 0ef0f2484..1504ae10f 100644 --- a/articles/minimum-cost-to-cut-a-stick.md +++ b/articles/minimum-cost-to-cut-a-stick.md @@ -77,7 +77,7 @@ class Solution { let res = Infinity; for (const c of cuts) { if (l < c && c < r) { - res = Math.min(res, (r - l) + dfs(l, c) + dfs(c, r)); + res = Math.min(res, r - l + dfs(l, c) + dfs(c, r)); } } return res === Infinity ? 0 : res; @@ -92,8 +92,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m ^ N)$ -* Space complexity: $O(N)$ for recursion stack. +- Time complexity: $O(m ^ N)$ +- Space complexity: $O(N)$ for recursion stack. > Where $m$ is the size of the $cuts$ array, $n$ is the length of the stick, and $N = min(n, m)$. @@ -210,7 +210,7 @@ class Solution { let res = Infinity; for (const c of cuts) { if (l < c && c < r) { - res = Math.min(res, (r - l) + dfs(l, c) + dfs(c, r)); + res = Math.min(res, r - l + dfs(l, c) + dfs(c, r)); } } res = res === Infinity ? 0 : res; @@ -227,8 +227,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * N ^ 2)$ -* Space complexity: $O(N ^ 2)$ +- Time complexity: $O(m * N ^ 2)$ +- Space complexity: $O(N ^ 2)$ > Where $m$ is the size of the $cuts$ array, $n$ is the length of the stick, and $N = min(n, m)$. @@ -342,7 +342,11 @@ class Solution { let res = Infinity; for (let mid = i; mid <= j; mid++) { - const cur = (r - l) + dfs(l, cuts[mid], i, mid - 1) + dfs(cuts[mid], r, mid + 1, j); + const cur = + r - + l + + dfs(l, cuts[mid], i, mid - 1) + + dfs(cuts[mid], r, mid + 1, j); res = Math.min(res, cur); } @@ -359,8 +363,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m\log m + m ^ 3)$ -* Space complexity: $O(m ^ 2)$ +- Time complexity: $O(m\log m + m ^ 3)$ +- Space complexity: $O(m ^ 2)$ > Where $m$ is the size of the $cuts$ array and $n$ is the length of the stick. @@ -383,7 +387,7 @@ class Solution: dp[i][j] = float("inf") for mid in range(i + 1, j): dp[i][j] = min( - dp[i][j], + dp[i][j], cuts[j] - cuts[i] + dp[i][mid] + dp[mid][j] ) @@ -407,7 +411,7 @@ public class Solution { int j = i + length; dp[i][j] = Integer.MAX_VALUE; for (int mid = i + 1; mid < j; mid++) { - dp[i][j] = Math.min(dp[i][j], + dp[i][j] = Math.min(dp[i][j], newCuts[j] - newCuts[i] + dp[i][mid] + dp[mid][j]); } } @@ -434,7 +438,7 @@ public: int j = i + length; dp[i][j] = INT_MAX; for (int mid = i + 1; mid < j; mid++) { - dp[i][j] = min(dp[i][j], + dp[i][j] = min(dp[i][j], cuts[j] - cuts[i] + dp[i][mid] + dp[mid][j]); } } @@ -464,7 +468,7 @@ class Solution { for (let mid = i + 1; mid < j; mid++) { dp[i][j] = Math.min( dp[i][j], - cuts[j] - cuts[i] + dp[i][mid] + dp[mid][j] + cuts[j] - cuts[i] + dp[i][mid] + dp[mid][j], ); } } @@ -479,7 +483,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m\log m + m ^ 3)$ -* Space complexity: $O(m ^ 2)$ +- Time complexity: $O(m\log m + m ^ 3)$ +- Space complexity: $O(m ^ 2)$ -> Where $m$ is the size of the $cuts$ array and $n$ is the length of the stick. \ No newline at end of file +> Where $m$ is the size of the $cuts$ array and $n$ is the length of the stick. diff --git a/articles/minimum-cost-to-hire-k-workers.md b/articles/minimum-cost-to-hire-k-workers.md index f205b01e7..46e0ba222 100644 --- a/articles/minimum-cost-to-hire-k-workers.md +++ b/articles/minimum-cost-to-hire-k-workers.md @@ -30,7 +30,7 @@ public class Solution { int n = quality.length; double res = Double.MAX_VALUE; double totalQuality = 0; - + double[][] workers = new double[n][2]; for (int i = 0; i < n; i++) { workers[i] = new double[]{ @@ -114,7 +114,8 @@ class Solution { workers.sort((a, b) => a[0] - b[0]); const maxHeap = new MaxPriorityQueue(); - let totalQuality = 0, res = Number.MAX_VALUE; + let totalQuality = 0, + res = Number.MAX_VALUE; for (let [ratio, q] of workers) { maxHeap.enqueue(q); @@ -138,7 +139,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * (\log n + \log k))$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * (\log n + \log k))$ +- Space complexity: $O(n)$ -> Where $n$ is the number of workers, and $k$ is the number of workers to be hired. \ No newline at end of file +> Where $n$ is the number of workers, and $k$ is the number of workers to be hired. diff --git a/articles/minimum-deletions-to-make-character-frequencies-unique.md b/articles/minimum-deletions-to-make-character-frequencies-unique.md index 60c9564fa..f9ba829b4 100644 --- a/articles/minimum-deletions-to-make-character-frequencies-unique.md +++ b/articles/minimum-deletions-to-make-character-frequencies-unique.md @@ -101,8 +101,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m ^ 2)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n + m ^ 2)$ +- Space complexity: $O(m)$ > Where $n$ is the length of the string $s$ and $m$ is the total number of unique frequncies possible. @@ -226,8 +226,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m ^ 2 \log m)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n + m ^ 2 \log m)$ +- Space complexity: $O(m)$ > Where $n$ is the length of the string $s$ and $m$ is the total number of unique frequncies possible. @@ -342,7 +342,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m \log m)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n + m \log m)$ +- Space complexity: $O(m)$ -> Where $n$ is the length of the string $s$ and $m$ is the total number of unique frequncies possible. \ No newline at end of file +> Where $n$ is the length of the string $s$ and $m$ is the total number of unique frequncies possible. diff --git a/articles/minimum-difference-between-highest-and-lowest-of-k-scores.md b/articles/minimum-difference-between-highest-and-lowest-of-k-scores.md index de7c35615..835d2b623 100644 --- a/articles/minimum-difference-between-highest-and-lowest-of-k-scores.md +++ b/articles/minimum-difference-between-highest-and-lowest-of-k-scores.md @@ -55,7 +55,9 @@ class Solution { */ minimumDifference(nums, k) { nums.sort((a, b) => a - b); - let l = 0, r = k - 1, res = Infinity; + let l = 0, + r = k - 1, + res = Infinity; while (r < nums.length) { res = Math.min(res, nums[r] - nums[l]); l++; @@ -70,5 +72,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. diff --git a/articles/minimum-difficulty-of-a-job-schedule.md b/articles/minimum-difficulty-of-a-job-schedule.md index 5738623eb..f2d9962f8 100644 --- a/articles/minimum-difficulty-of-a-job-schedule.md +++ b/articles/minimum-difficulty-of-a-job-schedule.md @@ -7,7 +7,7 @@ class Solution: def minDifficulty(self, jobDifficulty: List[int], d: int) -> int: if len(jobDifficulty) < d: return -1 - + n = len(jobDifficulty) dp = {} @@ -116,7 +116,7 @@ class Solution { } const dp = Array.from({ length: n }, () => - Array.from({ length: d + 1 }, () => Array(m + 5).fill(-1)) + Array.from({ length: d + 1 }, () => Array(m + 5).fill(-1)), ); const dfs = (i, d, curMax) => { @@ -127,7 +127,7 @@ class Solution { const maxSoFar = Math.max(curMax, jobDifficulty[i]); const res = Math.min( dfs(i + 1, d, maxSoFar), - maxSoFar + dfs(i + 1, d - 1, -1) + maxSoFar + dfs(i + 1, d - 1, -1), ); dp[i][d][curMax + 1] = res; @@ -143,8 +143,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * d * m)$ -* Space complexity: $O(n * d * m)$ +- Time complexity: $O(n * d * m)$ +- Space complexity: $O(n * d * m)$ > Where $n$ is the number of jobs, $d$ is the number of days, and $m$ is the maximum difficulty value among all the job difficulties. @@ -305,8 +305,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 * d)$ -* Space complexity: $O(n * d)$ +- Time complexity: $O(n ^ 2 * d)$ +- Space complexity: $O(n * d)$ > Where $n$ is the number of jobs and $d$ is the number of days. @@ -397,7 +397,9 @@ class Solution { const n = jobDifficulty.length; if (n < d) return -1; - const dp = Array.from({ length: n + 1 }, () => Array(d + 1).fill(Infinity)); + const dp = Array.from({ length: n + 1 }, () => + Array(d + 1).fill(Infinity), + ); dp[n][0] = 0; for (let day = 1; day <= d; day++) { @@ -405,7 +407,10 @@ class Solution { let maxi = 0; for (let j = i; j <= n - day; j++) { maxi = Math.max(maxi, jobDifficulty[j]); - dp[i][day] = Math.min(dp[i][day], maxi + dp[j + 1][day - 1]); + dp[i][day] = Math.min( + dp[i][day], + maxi + dp[j + 1][day - 1], + ); } } } @@ -419,8 +424,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 * d)$ -* Space complexity: $O(n * d)$ +- Time complexity: $O(n ^ 2 * d)$ +- Space complexity: $O(n * d)$ > Where $n$ is the number of jobs and $d$ is the number of days. @@ -539,8 +544,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 * d)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2 * d)$ +- Space complexity: $O(n)$ > Where $n$ is the number of jobs and $d$ is the number of days. @@ -655,12 +660,21 @@ class Solution { const stack = []; for (let i = day - 1; i < n; i++) { nextDp[i] = (i > 0 ? dp[i - 1] : 0) + jobDifficulty[i]; - while (stack.length > 0 && jobDifficulty[stack[stack.length - 1]] <= jobDifficulty[i]) { + while ( + stack.length > 0 && + jobDifficulty[stack[stack.length - 1]] <= jobDifficulty[i] + ) { const j = stack.pop(); - nextDp[i] = Math.min(nextDp[i], nextDp[j] - jobDifficulty[j] + jobDifficulty[i]); + nextDp[i] = Math.min( + nextDp[i], + nextDp[j] - jobDifficulty[j] + jobDifficulty[i], + ); } if (stack.length > 0) { - nextDp[i] = Math.min(nextDp[i], nextDp[stack[stack.length - 1]]); + nextDp[i] = Math.min( + nextDp[i], + nextDp[stack[stack.length - 1]], + ); } stack.push(i); } @@ -676,7 +690,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * d)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * d)$ +- Space complexity: $O(n)$ -> Where $n$ is the number of jobs and $d$ is the number of days. \ No newline at end of file +> Where $n$ is the number of jobs and $d$ is the number of days. diff --git a/articles/minimum-distance-between-bst-nodes.md b/articles/minimum-distance-between-bst-nodes.md index d8cd6bda0..1c9e31cb8 100644 --- a/articles/minimum-distance-between-bst-nodes.md +++ b/articles/minimum-distance-between-bst-nodes.md @@ -18,18 +18,18 @@ class Solution: res = min(res, dfs(node.left)) res = min(res, dfs(node.right)) return res - + def dfs1(root, node): if not root: return float("inf") - + res = float("inf") if root != node: res = abs(root.val - node.val) res = min(res, dfs1(root.left, node)) res = min(res, dfs1(root.right, node)) return res - + return dfs(root) ``` @@ -172,8 +172,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -198,7 +198,7 @@ class Solution: dfs(node.left) arr.append(node.val) dfs(node.right) - + dfs(root) res = arr[1] - arr[0] for i in range(2, len(arr)): @@ -225,7 +225,7 @@ class Solution: public class Solution { public int minDiffInBST(TreeNode root) { List arr = new ArrayList<>(); - + dfs(root, arr); int res = arr.get(1) - arr.get(0); for (int i = 2; i < arr.size(); i++) { @@ -233,7 +233,7 @@ public class Solution { } return res; } - + private void dfs(TreeNode node, List arr) { if (node == null) { return; @@ -262,14 +262,14 @@ public: int minDiffInBST(TreeNode* root) { vector arr; dfs(root, arr); - + int res = arr[1] - arr[0]; for (int i = 2; i < arr.size(); i++) { res = min(res, arr[i] - arr[i - 1]); } return res; } - + private: void dfs(TreeNode* node, vector& arr) { if (!node) return; @@ -298,14 +298,14 @@ class Solution { */ minDiffInBST(root) { const arr = []; - + const dfs = (node) => { if (!node) return; dfs(node.left); arr.push(node.val); dfs(node.right); }; - + dfs(root); let res = arr[1] - arr[0]; for (let i = 2; i < arr.length; i++) { @@ -320,8 +320,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -344,7 +344,7 @@ class Solution: nonlocal prev, res if not node: return - + dfs(node.left) if prev: res = min(res, node.val - prev.val) @@ -470,8 +470,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -495,7 +495,7 @@ class Solution: while cur: stack.append(cur) cur = cur.left - + cur = stack.pop() if prev: res = min(res, cur.val - prev.val) @@ -632,8 +632,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -797,7 +797,8 @@ class Solution { * @return {number} */ minDiffInBST(root) { - let prevVal = Infinity, res = Infinity; + let prevVal = Infinity, + res = Infinity; let cur = root; while (cur !== null) { @@ -836,5 +837,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/minimum-falling-path-sum-ii.md b/articles/minimum-falling-path-sum-ii.md index b43db319c..1ba118d7d 100644 --- a/articles/minimum-falling-path-sum-ii.md +++ b/articles/minimum-falling-path-sum-ii.md @@ -110,8 +110,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n ^ n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -130,7 +130,7 @@ class Solution: return grid[r][c] if (r, c) in cache: return cache[(r, c)] - + res = float("inf") for next_col in range(N): if c != next_col: @@ -253,8 +253,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 3)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 3)$ +- Space complexity: $O(n ^ 2)$ --- @@ -267,7 +267,7 @@ class Solution: def minFallingPathSum(self, grid: List[List[int]]) -> int: N = len(grid) dp = [[float("inf")] * N for _ in range(N)] - + for c in range(N): dp[N - 1][c] = grid[N - 1][c] @@ -276,7 +276,7 @@ class Solution: for next_col in range(N): if c != next_col: dp[r][c] = min(dp[r][c], grid[r][c] + dp[r + 1][next_col]) - + return min(dp[0]) ``` @@ -285,11 +285,11 @@ public class Solution { public int minFallingPathSum(int[][] grid) { int N = grid.length; int[][] dp = new int[N][N]; - + for (int c = 0; c < N; c++) { dp[N - 1][c] = grid[N - 1][c]; } - + for (int r = N - 2; r >= 0; r--) { for (int c = 0; c < N; c++) { dp[r][c] = Integer.MAX_VALUE; @@ -300,7 +300,7 @@ public class Solution { } } } - + int res = Integer.MAX_VALUE; for (int c = 0; c < N; c++) { res = Math.min(res, dp[0][c]); @@ -350,7 +350,7 @@ class Solution { minFallingPathSum(grid) { const N = grid.length; const dp = Array.from({ length: N }, () => Array(N).fill(Infinity)); - + for (let c = 0; c < N; c++) { dp[N - 1][c] = grid[N - 1][c]; } @@ -359,7 +359,10 @@ class Solution { for (let c = 0; c < N; c++) { for (let nextCol = 0; nextCol < N; nextCol++) { if (c !== nextCol) { - dp[r][c] = Math.min(dp[r][c], grid[r][c] + dp[r + 1][nextCol]); + dp[r][c] = Math.min( + dp[r][c], + grid[r][c] + dp[r + 1][nextCol], + ); } } } @@ -374,8 +377,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 3)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 3)$ +- Space complexity: $O(n ^ 2)$ --- @@ -477,7 +480,7 @@ class Solution { if (prevC !== currC) { nextDp[currC] = Math.min( nextDp[currC], - grid[r][currC] + dp[prevC] + grid[r][currC] + dp[prevC], ); } } @@ -494,8 +497,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 3)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 3)$ +- Space complexity: $O(n)$ --- @@ -682,8 +685,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -697,7 +700,7 @@ class Solution: n = len(grid) if n == 1: return grid[0][0] - + dp_idx1 = dp_idx2 = -1 dp_val1 = dp_val2 = 0 @@ -813,15 +816,19 @@ class Solution { const n = grid.length; if (n === 1) return grid[0][0]; - let dpIdx1 = -1, dpIdx2 = -1; - let dpVal1 = 0, dpVal2 = 0; + let dpIdx1 = -1, + dpIdx2 = -1; + let dpVal1 = 0, + dpVal2 = 0; for (let i = 0; i < n; i++) { - let nextDpIdx1 = -1, nextDpIdx2 = -1; - let nextDpVal1 = Infinity, nextDpVal2 = Infinity; + let nextDpIdx1 = -1, + nextDpIdx2 = -1; + let nextDpVal1 = Infinity, + nextDpVal2 = Infinity; for (let j = 0; j < n; j++) { - let cur = (j !== dpIdx1) ? dpVal1 : dpVal2; + let cur = j !== dpIdx1 ? dpVal1 : dpVal2; cur += grid[i][j]; if (nextDpIdx1 === -1 || cur < nextDpVal1) { @@ -850,5 +857,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/minimum-falling-path-sum.md b/articles/minimum-falling-path-sum.md index c12290d15..c275985e0 100644 --- a/articles/minimum-falling-path-sum.md +++ b/articles/minimum-falling-path-sum.md @@ -83,10 +83,9 @@ class Solution { const dfs = (r, c) => { if (r === N) return 0; if (c < 0 || c >= N) return Infinity; - return matrix[r][c] + Math.min( - dfs(r + 1, c - 1), - dfs(r + 1, c), - dfs(r + 1, c + 1) + return ( + matrix[r][c] + + Math.min(dfs(r + 1, c - 1), dfs(r + 1, c), dfs(r + 1, c + 1)) ); }; @@ -103,8 +102,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(3 ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(3 ^ n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -217,11 +216,9 @@ class Solution { if (c < 0 || c >= N) return Infinity; if (cache[r][c] !== null) return cache[r][c]; - cache[r][c] = matrix[r][c] + Math.min( - dfs(r + 1, c - 1), - dfs(r + 1, c), - dfs(r + 1, c + 1) - ); + cache[r][c] = + matrix[r][c] + + Math.min(dfs(r + 1, c - 1), dfs(r + 1, c), dfs(r + 1, c + 1)); return cache[r][c]; }; @@ -238,8 +235,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * n)$ -* Space complexity: $O(n * n)$ +- Time complexity: $O(n * n)$ +- Space complexity: $O(n * n)$ --- @@ -298,7 +295,7 @@ public: int minFallingPathSum(vector>& matrix) { int N = matrix.size(); vector dp(N); - + for (int c = 0; c < N; c++) { dp[c] = matrix[0][c]; } @@ -336,7 +333,7 @@ class Solution { let leftUp = Infinity; for (let c = 0; c < N; c++) { const midUp = dp[c]; - const rightUp = (c < N - 1) ? dp[c + 1] : Infinity; + const rightUp = c < N - 1 ? dp[c + 1] : Infinity; dp[c] = matrix[r][c] + Math.min(midUp, leftUp, rightUp); leftUp = midUp; } @@ -351,8 +348,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -445,5 +442,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/minimum-fuel-cost-to-report-to-the-capital.md b/articles/minimum-fuel-cost-to-report-to-the-capital.md index 77dda576e..bd67d1dea 100644 --- a/articles/minimum-fuel-cost-to-report-to-the-capital.md +++ b/articles/minimum-fuel-cost-to-report-to-the-capital.md @@ -135,8 +135,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -295,5 +295,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/minimum-height-trees.md b/articles/minimum-height-trees.md index d78d73e73..215681564 100644 --- a/articles/minimum-height-trees.md +++ b/articles/minimum-height-trees.md @@ -9,7 +9,7 @@ class Solution: for u, v in edges: adj[u].append(v) adj[v].append(u) - + def dfs(node, parent): hgt = 0 for nei in adj[node]: @@ -17,7 +17,7 @@ class Solution: continue hgt = max(hgt, 1 + dfs(nei, node)) return hgt - + minHgt = n res = [] for i in range(n): @@ -27,7 +27,7 @@ class Solution: elif curHgt < minHgt: res = [i] minHgt = curHgt - + return res ``` @@ -195,8 +195,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(V * (V + E))$ -* Space complexity: $O(V)$ +- Time complexity: $O(V * (V + E))$ +- Space complexity: $O(V)$ > Where $V$ is the number of vertices and $E$ is the number of edges. @@ -213,7 +213,7 @@ class Solution: for u, v in edges: adj[u].append(v) adj[v].append(u) - + dp = [[0] * 2 for _ in range(n)] # top two heights for each node def dfs(node, parent): @@ -240,7 +240,7 @@ class Solution: continue toChild = 1 + (dp[node][1] if dp[node][0] == 1 + dp[nei][0] else dp[node][0]) dfs1(nei, node, toChild) - + dfs(0, -1) dfs1(0, -1, 0) @@ -419,7 +419,11 @@ class Solution { for (const nei of adj[node]) { if (nei === parent) continue; - const toChild = 1 + ((dp[node][0] === 1 + dp[nei][0]) ? dp[node][1] : dp[node][0]); + const toChild = + 1 + + (dp[node][0] === 1 + dp[nei][0] + ? dp[node][1] + : dp[node][0]); dfs1(nei, node, toChild); } }; @@ -514,8 +518,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V)$ > Where $V$ is the number of vertices and $E$ is the number of edges. @@ -645,7 +649,7 @@ public: vector findMinHeightTrees(int n, vector>& edges) { if (n == 1) return {0}; - + adj.resize(n); for (const auto& edge : edges) { adj[edge[0]].push_back(edge[1]); @@ -832,8 +836,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V)$ > Where $V$ is the number of vertices and $E$ is the number of edges. @@ -1061,7 +1065,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V)$ -> Where $V$ is the number of vertices and $E$ is the number of edges. \ No newline at end of file +> Where $V$ is the number of vertices and $E$ is the number of edges. diff --git a/articles/minimum-index-of-a-valid-split.md b/articles/minimum-index-of-a-valid-split.md index 17548cd54..f877fc5a5 100644 --- a/articles/minimum-index-of-a-valid-split.md +++ b/articles/minimum-index-of-a-valid-split.md @@ -101,8 +101,10 @@ class Solution { } for (const num in leftCnt) { - if (leftCnt[num] > Math.floor((i + 1) / 2) && - (rightCnt[num] || 0) > Math.floor((n - i - 1) / 2)) { + if ( + leftCnt[num] > Math.floor((i + 1) / 2) && + (rightCnt[num] || 0) > Math.floor((n - i - 1) / 2) + ) { return i; } } @@ -117,8 +119,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -240,8 +242,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -348,14 +350,15 @@ class Solution { * @return {number} */ minimumIndex(nums) { - let majority = 0, count = 0; + let majority = 0, + count = 0; for (let num of nums) { if (count === 0) majority = num; - count += (num === majority ? 1 : -1); + count += num === majority ? 1 : -1; } let leftCnt = 0; - let rightCnt = nums.filter(x => x === majority).length; + let rightCnt = nums.filter((x) => x === majority).length; const n = nums.length; for (let i = 0; i < n; i++) { @@ -381,5 +384,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/minimum-interval-including-query.md b/articles/minimum-interval-including-query.md index 3c1cf82d5..2d705b5d3 100644 --- a/articles/minimum-interval-including-query.md +++ b/articles/minimum-interval-including-query.md @@ -74,7 +74,7 @@ class Solution { let cur = -1; for (const [l, r] of intervals) { if (l <= q && q <= r) { - if (cur === -1 || (r - l + 1) < cur) { + if (cur === -1 || r - l + 1 < cur) { cur = r - l + 1; } } @@ -178,10 +178,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(m)$ space for the output array. +- Time complexity: $O(m * n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(m)$ space for the output array. > Where $m$ is the length of the array $queries$ and $n$ is the length of the array $intervals$. @@ -197,21 +197,21 @@ class Solution: events = [] # Create events for intervals for idx, (start, end) in enumerate(intervals): - events.append((start, 0, end - start + 1, idx)) - events.append((end, 2, end - start + 1, idx)) - + events.append((start, 0, end - start + 1, idx)) + events.append((end, 2, end - start + 1, idx)) + # Create events for queries for i, q in enumerate(queries): events.append((q, 1, i)) - + # Sort by time and type (end before query) events.sort(key=lambda x: (x[0], x[1])) - + # Min heap storing [size, index] - sizes = [] + sizes = [] ans = [-1] * len(queries) inactive = [False] * len(intervals) - + for time, type, *rest in events: if type == 0: # Interval start interval_size, idx = rest @@ -225,7 +225,7 @@ class Solution: heapq.heappop(sizes) if sizes: ans[query_idx] = sizes[0][0] - + return ans ``` @@ -235,32 +235,32 @@ public class Solution { List events = new ArrayList<>(); for (int i = 0; i < intervals.length; i++) { events.add(new int[]{intervals[i][0], 0, intervals[i][1] - intervals[i][0] + 1, i}); - events.add(new int[]{intervals[i][1], 2, intervals[i][1] - intervals[i][0] + 1, i}); + events.add(new int[]{intervals[i][1], 2, intervals[i][1] - intervals[i][0] + 1, i}); } - + for (int i = 0; i < queries.length; i++) { events.add(new int[]{queries[i], 1, i}); } - + // Sort by time and type (end before query) - events.sort((a, b) -> a[0] != b[0] ? - Integer.compare(a[0], b[0]) : + events.sort((a, b) -> a[0] != b[0] ? + Integer.compare(a[0], b[0]) : Integer.compare(a[1], b[1])); - + int[] ans = new int[queries.length]; Arrays.fill(ans, -1); - + // Min heap storing [size, index] PriorityQueue pq = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0])); boolean[] inactive = new boolean[intervals.length]; - + for (int[] event : events) { if (event[1] == 0) { // Interval start pq.offer(new int[]{event[2], event[3]}); - } + } else if (event[1] == 2) { // Interval end inactive[event[3]] = true; - } + } else { // Query while (!pq.isEmpty() && inactive[pq.peek()[1]]) { pq.poll(); @@ -270,7 +270,7 @@ public class Solution { } } } - + return ans; } } @@ -286,22 +286,22 @@ public: events.push_back({intervals[i][0], 0, intervals[i][1] - intervals[i][0] + 1, i}); events.push_back({intervals[i][1], 2, intervals[i][1] - intervals[i][0] + 1, i}); } - + // Create events for queries for (int i = 0; i < queries.size(); i++) { events.push_back({queries[i], 1, i}); } - + // Sort by time and type (end before query) sort(events.begin(), events.end(), [](const vector& a, const vector& b) { return a[0] == b[0] ? a[1] < b[1] : a[0] < b[0]; }); - + vector ans(queries.size(), -1); // Min heap storing [size, index] priority_queue, vector>, greater>> pq; vector inactive(intervals.size(), false); - + for (const auto& event : events) { if (event[1] == 0) { // Interval start pq.push({event[2], event[3]}); @@ -317,7 +317,7 @@ public: } } } - + return ans; } }; @@ -352,11 +352,14 @@ class Solution { const inactive = Array(intervals.length).fill(false); for (const [time, type, ...rest] of events) { - if (type === 0) { // Interval start + if (type === 0) { + // Interval start pq.push([rest[0], rest[1]]); - } else if (type === 2) { // Interval end + } else if (type === 2) { + // Interval end inactive[rest[1]] = true; - } else { // Query + } else { + // Query while (!pq.isEmpty() && inactive[pq.front()[1]]) { pq.pop(); } @@ -365,7 +368,7 @@ class Solution { } } } - + return ans; } } @@ -380,20 +383,20 @@ public class Solution { events.Add(new int[] { intervals[i][0], 0, intervals[i][1] - intervals[i][0] + 1, i }); events.Add(new int[] { intervals[i][1], 2, intervals[i][1] - intervals[i][0] + 1, i }); } - + // Create events for queries for (int i = 0; i < queries.Length; i++) { events.Add(new int[] { queries[i], 1, i }); } // Sort by time and type (end before query) events.Sort((a, b) => a[0] == b[0] ? a[1].CompareTo(b[1]) : a[0].CompareTo(b[0])); - + int[] ans = new int[queries.Length]; Array.Fill(ans, -1); // Min heap storing [size, index] var pq = new PriorityQueue<(int size, int idx), int>(); var inactive = new bool[intervals.Length]; - + foreach (var e in events) { if (e[1] == 0) { // Interval start pq.Enqueue((e[2], e[3]), e[2]); @@ -409,7 +412,7 @@ public class Solution { } } } - + return ans; } } @@ -425,7 +428,7 @@ type Event struct { func minInterval(intervals [][]int, queries []int) []int { events := []Event{} - + // Create events for intervals for idx, interval := range intervals { start, end := interval[0], interval[1] @@ -433,12 +436,12 @@ func minInterval(intervals [][]int, queries []int) []int { events = append(events, Event{start, 0, size, idx}) events = append(events, Event{end, 2, size, idx}) } - + // Create events for queries for i, q := range queries { events = append(events, Event{q, 1, i, -1}) } - + // Sort events by time and type sort.Slice(events, func(i, j int) bool { if events[i].time == events[j].time { @@ -456,7 +459,7 @@ func minInterval(intervals [][]int, queries []int) []int { ans[i] = -1 } inactive := make([]bool, len(intervals)) - + for _, event := range events { switch event.typ { case 0: // Interval start @@ -489,7 +492,7 @@ data class Event(val time: Int, val type: Int, val sizeOrQueryIndex: Int, val id class Solution { fun minInterval(intervals: Array, queries: IntArray): IntArray { val events = mutableListOf() - + // Create events for intervals for ((idx, interval) in intervals.withIndex()) { val (start, end) = interval @@ -497,19 +500,19 @@ class Solution { events.add(Event(start, 0, size, idx)) events.add(Event(end, 2, size, idx)) } - + // Create events for queries for ((i, q) in queries.withIndex()) { events.add(Event(q, 1, i, -1)) } - + // Sort events by time and type events.sortWith(compareBy({ it.time }, { it.type })) - + val sizes = PriorityQueue>(compareBy { it.first }) val ans = IntArray(queries.size) { -1 } val inactive = BooleanArray(intervals.size) - + for (event in events) { when (event.type) { 0 -> { // Interval start @@ -529,7 +532,7 @@ class Solution { } } } - + return ans } } @@ -555,7 +558,7 @@ struct Item: Comparable { class Solution { func minInterval(_ intervals: [[Int]], _ queries: [Int]) -> [Int] { var events = [Event]() - + // Create events for intervals for (idx, interval) in intervals.enumerated() { let start = interval[0] @@ -564,12 +567,12 @@ class Solution { events.append(Event(time: start, type: 0, size: intervalSize, idx: idx)) events.append(Event(time: end, type: 2, size: intervalSize, idx: idx)) } - + // Create events for queries for (i, q) in queries.enumerated() { events.append(Event(time: q, type: 1, size: nil, idx: i)) } - + // Sort by time and type (end before query) events.sort { (a, b) in if a.time != b.time { @@ -577,12 +580,12 @@ class Solution { } return a.type < b.type } - + // Min heap storing [size, index] var sizes = Heap() var ans = Array(repeating: -1, count: queries.count) var inactive = Array(repeating: false, count: intervals.count) - + for event in events { if event.type == 0 { // Interval start let intervalSize = event.size! @@ -601,7 +604,7 @@ class Solution { } } } - + return ans } } @@ -611,8 +614,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O((n + m) \log (n + m))$ -* Space complexity: $O(n + m)$ +- Time complexity: $O((n + m) \log (n + m))$ +- Space complexity: $O(n + m)$ > Where $m$ is the length of the array $queries$ and $n$ is the length of the array $intervals$. @@ -726,7 +729,7 @@ class Solution { */ minInterval(intervals, queries) { intervals.sort((a, b) => a[0] - b[0]); - const minHeap = new MinPriorityQueue(entry => entry[0]); + const minHeap = new MinPriorityQueue((entry) => entry[0]); const res = {}; let i = 0; @@ -746,7 +749,7 @@ class Solution { res[q] = !minHeap.isEmpty() ? minHeap.front()[0] : -1; } - return queries.map(q => res[q]); + return queries.map((q) => res[q]); } } ``` @@ -791,7 +794,7 @@ func minInterval(intervals [][]int, queries []int) []int { sort.Slice(intervals, func(i, j int) bool { return intervals[i][0] < intervals[j][0] }) - + queriesWithIdx := make([][2]int, len(queries)) for i, q := range queries { queriesWithIdx[i] = [2]int{q, i} @@ -799,7 +802,7 @@ func minInterval(intervals [][]int, queries []int) []int { sort.Slice(queriesWithIdx, func(i, j int) bool { return queriesWithIdx[i][0] < queriesWithIdx[j][0] }) - + comparator := func(a, b interface{}) int { pair1 := a.([2]int) pair2 := b.([2]int) @@ -811,20 +814,20 @@ func minInterval(intervals [][]int, queries []int) []int { } return 0 } - + pq := priorityqueue.NewWith(comparator) res := make([]int, len(queries)) i := 0 - + for _, qPair := range queriesWithIdx { q, originalIdx := qPair[0], qPair[1] - + for i < len(intervals) && intervals[i][0] <= q { size := intervals[i][1] - intervals[i][0] + 1 pq.Enqueue([2]int{size, intervals[i][1]}) i++ } - + for !pq.Empty() { if top, _ := pq.Peek(); top.([2]int)[1] < q { pq.Dequeue() @@ -832,7 +835,7 @@ func minInterval(intervals [][]int, queries []int) []int { break } } - + if !pq.Empty() { if top, _ := pq.Peek(); true { res[originalIdx] = top.([2]int)[0] @@ -841,7 +844,7 @@ func minInterval(intervals [][]int, queries []int) []int { res[originalIdx] = -1 } } - + return res } ``` @@ -850,29 +853,29 @@ func minInterval(intervals [][]int, queries []int) []int { class Solution { fun minInterval(intervals: Array, queries: IntArray): IntArray { intervals.sortBy { it[0] } - + val queriesWithIndex = queries.withIndex() .map { it.value to it.index } .sortedBy { it.first } - + val minHeap = PriorityQueue>(compareBy { it.first }) val result = IntArray(queries.size) var i = 0 - + for ((q, originalIdx) in queriesWithIndex) { while (i < intervals.size && intervals[i][0] <= q) { val size = intervals[i][1] - intervals[i][0] + 1 minHeap.offer(size to intervals[i][1]) i++ } - + while (minHeap.isNotEmpty() && minHeap.peek().second < q) { minHeap.poll() } - + result[originalIdx] = if (minHeap.isNotEmpty()) minHeap.peek().first else -1 } - + return result } } @@ -920,8 +923,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n + m \log m)$ -* Space complexity: $O(n + m)$ +- Time complexity: $O(n \log n + m \log m)$ +- Space complexity: $O(n + m)$ > Where $m$ is the length of the array $queries$ and $n$ is the length of the array $intervals$. @@ -1000,7 +1003,7 @@ class Solution: ans = [] for q in queries: idx = compress[q] - + # query for minSize res = segTree.query_point(idx) ans.append(res if res != float('inf') else -1) @@ -1132,7 +1135,7 @@ public: void update(int treeidx, int lo, int hi, int left, int right, int val) { propagate(treeidx, lo, hi); - + if (lo > right || hi < left) return; if (lo >= left && hi <= right) { @@ -1144,14 +1147,14 @@ public: int mid = (lo + hi) / 2; update(2 * treeidx + 1, lo, mid, left, right, val); update(2 * treeidx + 2, mid + 1, hi, left, right, val); - + tree[treeidx] = min(tree[2 * treeidx + 1], tree[2 * treeidx + 2]); } int query(int treeidx, int lo, int hi, int idx) { propagate(treeidx, lo, hi); if (lo == hi) return tree[treeidx]; - + int mid = (lo + hi) / 2; if (idx <= mid) return query(2 * treeidx + 1, lo, mid, idx); else return query(2 * treeidx + 2, mid + 1, hi, idx); @@ -1225,10 +1228,19 @@ class SegmentTree { */ propagate(treeidx, lo, hi) { if (this.lazy[treeidx] !== Infinity) { - this.tree[treeidx] = Math.min(this.tree[treeidx], this.lazy[treeidx]); + this.tree[treeidx] = Math.min( + this.tree[treeidx], + this.lazy[treeidx], + ); if (lo !== hi) { - this.lazy[2 * treeidx + 1] = Math.min(this.lazy[2 * treeidx + 1], this.lazy[treeidx]); - this.lazy[2 * treeidx + 2] = Math.min(this.lazy[2 * treeidx + 2], this.lazy[treeidx]); + this.lazy[2 * treeidx + 1] = Math.min( + this.lazy[2 * treeidx + 1], + this.lazy[treeidx], + ); + this.lazy[2 * treeidx + 2] = Math.min( + this.lazy[2 * treeidx + 2], + this.lazy[treeidx], + ); } this.lazy[treeidx] = Infinity; } @@ -1254,7 +1266,10 @@ class SegmentTree { const mid = Math.floor((lo + hi) / 2); this.update(2 * treeidx + 1, lo, mid, left, right, val); this.update(2 * treeidx + 2, mid + 1, hi, left, right, val); - this.tree[treeidx] = Math.min(this.tree[2 * treeidx + 1], this.tree[2 * treeidx + 2]); + this.tree[treeidx] = Math.min( + this.tree[2 * treeidx + 1], + this.tree[2 * treeidx + 2], + ); } /** @@ -1492,27 +1507,27 @@ func minInterval(intervals [][]int, queries []int) []int { for _, q := range queries { points[q] = true } - + pointsList := make([]int, 0, len(points)) for point := range points { pointsList = append(pointsList, point) } sort.Ints(pointsList) - + compress := make(map[int]int) for i, point := range pointsList { compress[point] = i } - + segTree := NewSegmentTree(len(pointsList)) - + for _, interval := range intervals { start := compress[interval[0]] end := compress[interval[1]] length := interval[1] - interval[0] + 1 segTree.Update(start, end, length) } - + ans := make([]int, len(queries)) for i, q := range queries { idx := compress[q] @@ -1523,7 +1538,7 @@ func minInterval(intervals [][]int, queries []int) []int { ans[i] = res } } - + return ans } ``` @@ -1532,7 +1547,7 @@ func minInterval(intervals [][]int, queries []int) []int { class SegmentTree(private val n: Int) { private val tree = IntArray(4 * n) { Int.MAX_VALUE } private val lazy = IntArray(4 * n) { Int.MAX_VALUE } - + private fun propagate(treeIdx: Int, lo: Int, hi: Int) { if (lazy[treeIdx] != Int.MAX_VALUE) { tree[treeIdx] = minOf(tree[treeIdx], lazy[treeIdx]) @@ -1543,7 +1558,7 @@ class SegmentTree(private val n: Int) { lazy[treeIdx] = Int.MAX_VALUE } } - + private fun updateRange(treeIdx: Int, lo: Int, hi: Int, left: Int, right: Int, value: Int) { propagate(treeIdx, lo, hi) if (lo > right || hi < left) return @@ -1557,7 +1572,7 @@ class SegmentTree(private val n: Int) { updateRange(2 * treeIdx + 2, mid + 1, hi, left, right, value) tree[treeIdx] = minOf(tree[2 * treeIdx + 1], tree[2 * treeIdx + 2]) } - + private fun queryPoint(treeIdx: Int, lo: Int, hi: Int, idx: Int): Int { propagate(treeIdx, lo, hi) if (lo == hi) return tree[treeIdx] @@ -1568,11 +1583,11 @@ class SegmentTree(private val n: Int) { queryPoint(2 * treeIdx + 2, mid + 1, hi, idx) } } - + fun update(left: Int, right: Int, value: Int) { updateRange(0, 0, n - 1, left, right, value) } - + fun query(idx: Int): Int { return queryPoint(0, 0, n - 1, idx) } @@ -1586,19 +1601,19 @@ class Solution { points.add(interval[1]) } queries.forEach { points.add(it) } - + val pointsList = points.sorted() val compress = pointsList.withIndex().associate { it.value to it.index } - + val segTree = SegmentTree(pointsList.size) - + intervals.forEach { interval -> val start = compress[interval[0]]!! val end = compress[interval[1]]!! val length = interval[1] - interval[0] + 1 segTree.update(start, end, length) } - + return queries.map { q -> val idx = compress[q]!! val res = segTree.query(idx) @@ -1685,7 +1700,7 @@ class Solution { for q in queries { points.append(q) } - + // Compress the coordinates let sortedPoints = Array(Set(points)).sorted() var compress = [Int: Int]() @@ -1719,9 +1734,9 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O((n + m)\log k)$ -* Space complexity: - * $O(k)$ extra space. - * $O(m)$ space for the output array. +- Time complexity: $O((n + m)\log k)$ +- Space complexity: + - $O(k)$ extra space. + - $O(m)$ space for the output array. -> Where $m$ is the length of the array $queries$, $n$ is the length of the array $intervals$ and $k$ is the number of unique points. \ No newline at end of file +> Where $m$ is the length of the array $queries$, $n$ is the length of the array $intervals$ and $k$ is the number of unique points. diff --git a/articles/minimum-length-of-string-after-deleting-similar-ends.md b/articles/minimum-length-of-string-after-deleting-similar-ends.md index 81155cffe..09f9b244d 100644 --- a/articles/minimum-length-of-string-after-deleting-similar-ends.md +++ b/articles/minimum-length-of-string-after-deleting-similar-ends.md @@ -62,7 +62,8 @@ class Solution { * @return {number} */ minimumLength(s) { - let l = 0, r = s.length - 1; + let l = 0, + r = s.length - 1; while (l < r && s[l] === s[r]) { const tmp = s[l]; @@ -82,5 +83,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/minimum-number-of-arrows-to-burst-balloons.md b/articles/minimum-number-of-arrows-to-burst-balloons.md index 195e1e3e0..729a95031 100644 --- a/articles/minimum-number-of-arrows-to-burst-balloons.md +++ b/articles/minimum-number-of-arrows-to-burst-balloons.md @@ -70,7 +70,8 @@ class Solution { */ findMinArrowShots(points) { points.sort((a, b) => a[0] - b[0]); - let res = points.length, prevEnd = points[0][1]; + let res = points.length, + prevEnd = points[0][1]; for (let i = 1; i < points.length; i++) { let curr = points[i]; @@ -91,8 +92,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -161,7 +162,8 @@ class Solution { */ findMinArrowShots(points) { points.sort((a, b) => a[1] - b[1]); - let res = 1, prevEnd = points[0][1]; + let res = 1, + prevEnd = points[0][1]; for (let i = 1; i < points.length; i++) { if (points[i][0] > prevEnd) { @@ -179,5 +181,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. diff --git a/articles/minimum-number-of-days-to-eat-n-oranges.md b/articles/minimum-number-of-days-to-eat-n-oranges.md index 115da181e..7ff6b0c81 100644 --- a/articles/minimum-number-of-days-to-eat-n-oranges.md +++ b/articles/minimum-number-of-days-to-eat-n-oranges.md @@ -12,7 +12,7 @@ class Solution: return 0 if n in dp: return dp[n] - + res = 1 + dfs(n - 1) if n % 3 == 0: res = min(res, 1 + dfs(n // 3)) @@ -99,8 +99,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -200,8 +200,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(\log n)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(\log n)$ --- @@ -350,5 +350,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(\log n)$ \ No newline at end of file +- Time complexity: $O(\log n)$ +- Space complexity: $O(\log n)$ diff --git a/articles/minimum-number-of-flips-to-make-the-binary-string-alternating.md b/articles/minimum-number-of-flips-to-make-the-binary-string-alternating.md index b0afa6412..03398e5ad 100644 --- a/articles/minimum-number-of-flips-to-make-the-binary-string-alternating.md +++ b/articles/minimum-number-of-flips-to-make-the-binary-string-alternating.md @@ -16,7 +16,7 @@ class Solution: for i in range(n): cnt += 1 if (A[i] != B[i]) else 0 return cnt - + for i in range(n): newS = s[i:] + s[:i] res = min(res, min(diff(alt1, newS), diff(alt2, newS))) @@ -93,7 +93,8 @@ class Solution { minFlips(s) { const n = s.length; let res = n; - let alt1 = "", alt2 = ""; + let alt1 = '', + alt2 = ''; for (let i = 0; i < n; i++) { alt1 += i % 2 === 0 ? '0' : '1'; @@ -122,8 +123,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -146,7 +147,7 @@ class Solution: start_0 += 1 if s[j] == c else 0 c = '0' if c == '1' else '1' j = (j + 1) % n - + res = min(res, min(start_1, start_0)) return res ``` @@ -240,8 +241,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ extra space. --- @@ -360,14 +361,18 @@ class Solution { minFlips(s) { const n = s.length; s = s + s; - let alt1 = [], alt2 = []; + let alt1 = [], + alt2 = []; for (let i = 0; i < s.length; i++) { - alt1.push(i % 2 === 0 ? "0" : "1"); - alt2.push(i % 2 === 0 ? "1" : "0"); + alt1.push(i % 2 === 0 ? '0' : '1'); + alt2.push(i % 2 === 0 ? '1' : '0'); } - let res = n, diff1 = 0, diff2 = 0, l = 0; + let res = n, + diff1 = 0, + diff2 = 0, + l = 0; for (let r = 0; r < s.length; r++) { if (s[r] !== alt1[r]) diff1++; @@ -393,8 +398,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -423,12 +428,12 @@ class Solution: diff2 -= 1 l += 1 lstart_0 = '1' if lstart_0 == '0' else '0' - + if r - l + 1 == n: res = min(res, diff1, diff2) rstart_0 = '1' if rstart_0 == '0' else '0' - + return res ``` @@ -503,9 +508,13 @@ class Solution { */ minFlips(s) { const n = s.length; - let res = n, diff1 = 0, diff2 = 0, l = 0; + let res = n, + diff1 = 0, + diff2 = 0, + l = 0; - let rstart_0 = '0', lstart_0 = '0'; + let rstart_0 = '0', + lstart_0 = '0'; for (let r = 0; r < 2 * n; r++) { if (s[r % n] !== rstart_0) diff1++; @@ -534,8 +543,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -675,7 +684,8 @@ class Solution { return ans; } - let dp0 = start_0, dp1 = start_1; + let dp0 = start_0, + dp1 = start_1; for (const c of s) { [dp0, dp1] = [dp1, dp0]; if (c === '1') { @@ -697,5 +707,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/minimum-number-of-operations-to-make-array-continuous.md b/articles/minimum-number-of-operations-to-make-array-continuous.md index fda4f013d..bfdf2e87d 100644 --- a/articles/minimum-number-of-operations-to-make-array-continuous.md +++ b/articles/minimum-number-of-operations-to-make-array-continuous.md @@ -103,8 +103,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -207,7 +207,8 @@ class Solution { const n = uniqueNums.length; for (let i = 0; i < n; i++) { - let l = i, r = n; + let l = i, + r = n; while (l < r) { const mid = Math.floor((l + r) / 2); if (uniqueNums[mid] < uniqueNums[i] + N) { @@ -229,8 +230,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -310,10 +311,14 @@ class Solution { minOperations(nums) { const length = nums.length; const uniqueNums = Array.from(new Set(nums)).sort((a, b) => a - b); - let res = length, r = 0; + let res = length, + r = 0; for (let l = 0; l < uniqueNums.length; l++) { - while (r < uniqueNums.length && uniqueNums[r] < uniqueNums[l] + length) { + while ( + r < uniqueNums.length && + uniqueNums[r] < uniqueNums[l] + length + ) { r++; } const window = r - l; @@ -329,8 +334,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -350,7 +355,7 @@ class Solution: if nums[i] != nums[i - 1]: nums[n] = nums[i] n += 1 - + l = 0 for r in range(n): l += (nums[r] - nums[l] > length - 1) @@ -371,7 +376,7 @@ public class Solution { n++; } } - + int l = 0; for (int r = 0; r < n; r++) { if (nums[r] - nums[l] > length - 1) { @@ -445,5 +450,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. diff --git a/articles/minimum-number-of-operations-to-make-array-empty.md b/articles/minimum-number-of-operations-to-make-array-empty.md index fbb2aa367..f0cd1394b 100644 --- a/articles/minimum-number-of-operations-to-make-array-empty.md +++ b/articles/minimum-number-of-operations-to-make-array-empty.md @@ -10,10 +10,10 @@ class Solution: return float('inf') if cur == 0: return 0 - + ops = min(dfs(cur - 2), dfs(cur - 3)) return 1 + ops - + count = Counter(nums) res = 0 for num, cnt in count.items(): @@ -21,7 +21,7 @@ class Solution: if op == float("inf"): return -1 res += op - + return res ``` @@ -137,8 +137,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 2 ^ m)$ -* Space complexity: $O(n + m)$ +- Time complexity: $O(n * 2 ^ m)$ +- Space complexity: $O(n + m)$ > Where $n$ is the size of the array $nums$ and $m$ is the average frequency of the array elements. @@ -160,7 +160,7 @@ class Solution: return 1 if num in cache: return cache[num] - + res = min(dfs(num - 2), dfs(num - 3)) cache[num] = res + 1 return cache[num] @@ -172,14 +172,14 @@ class Solution: if op == float("inf"): return -1 res += op - + return res ``` ```java public class Solution { private Map cache; - + public int minOperations(int[] nums) { Map count = new HashMap<>(); for (int num : nums) { @@ -281,7 +281,7 @@ class Solution { cache.set(cur, isFinite(res) ? 1 + res : res); return cache.get(cur); }; - + const count = new Map(); for (const num of nums) { count.set(num, (count.get(num) || 0) + 1); @@ -305,8 +305,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n + m)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(n + m)$ > Where $n$ is the size of the array $nums$ and $m$ is the average frequency of the array elements. @@ -462,8 +462,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n + m)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(n + m)$ > Where $n$ is the size of the array $nums$ and $m$ is the average frequency of the array elements. @@ -478,12 +478,12 @@ class Solution: def minOperations(self, nums: List[int]) -> int: count = Counter(nums) res = 0 - + for num, cnt in count.items(): if cnt == 1: return -1 res += math.ceil(cnt / 3) - + return res ``` @@ -559,5 +559,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/minimum-number-of-operations-to-move-all-balls-to-each-box.md b/articles/minimum-number-of-operations-to-move-all-balls-to-each-box.md index c00bbfdb0..31cc68370 100644 --- a/articles/minimum-number-of-operations-to-move-all-balls-to-each-box.md +++ b/articles/minimum-number-of-operations-to-move-all-balls-to-each-box.md @@ -82,10 +82,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ space for the output list. +- Time complexity: $O(n ^ 2)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ space for the output list. --- @@ -205,8 +205,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -296,7 +296,8 @@ class Solution { const n = boxes.length; const res = new Array(n).fill(0); - let balls = 0, moves = 0; + let balls = 0, + moves = 0; for (let i = 0; i < n; i++) { res[i] = balls + moves; moves += balls; @@ -319,7 +320,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ space for the output list. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ space for the output list. diff --git a/articles/minimum-number-of-swaps-to-make-the-string-balanced.md b/articles/minimum-number-of-swaps-to-make-the-string-balanced.md index 8c18a3ae2..9f3c6aaa8 100644 --- a/articles/minimum-number-of-swaps-to-make-the-string-balanced.md +++ b/articles/minimum-number-of-swaps-to-make-the-string-balanced.md @@ -71,8 +71,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -91,7 +91,7 @@ class Solution: else: close += 1 maxClose = max(maxClose, close) - + return (maxClose + 1) // 2 ``` @@ -131,7 +131,8 @@ class Solution { * @return {number} */ minSwaps(s) { - let close = 0, maxClose = 0; + let close = 0, + maxClose = 0; for (let i = 0; i < s.length; i++) { if (s.charAt(i) == '[') close--; else close++; @@ -146,8 +147,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -215,5 +216,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/minimum-number-of-vertices-to-reach-all-nodes.md b/articles/minimum-number-of-vertices-to-reach-all-nodes.md index aa09f1c80..3952cd31b 100644 --- a/articles/minimum-number-of-vertices-to-reach-all-nodes.md +++ b/articles/minimum-number-of-vertices-to-reach-all-nodes.md @@ -122,8 +122,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ > Where $V$ is the number of vertices and $E$ is the number of edges. @@ -269,7 +269,7 @@ class Solution { } } - return res.map((val, i) => val ? i : -1).filter(i => i !== -1); + return res.map((val, i) => (val ? i : -1)).filter((i) => i !== -1); } } ``` @@ -278,8 +278,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ > Where $V$ is the number of vertices and $E$ is the number of edges. @@ -354,7 +354,7 @@ class Solution { */ findSmallestSetOfVertices(n, edges) { const incoming = Array.from({ length: n }, () => []); - + for (const [src, dst] of edges) { incoming[dst].push(src); } @@ -374,8 +374,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V)$ > Where $V$ is the number of vertices and $E$ is the number of edges. @@ -459,7 +459,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V)$ -> Where $V$ is the number of vertices and $E$ is the number of edges. \ No newline at end of file +> Where $V$ is the number of vertices and $E$ is the number of edges. diff --git a/articles/minimum-one-bit-operations-to-make-integers-zero.md b/articles/minimum-one-bit-operations-to-make-integers-zero.md index 7e4071ce6..9d3dc8766 100644 --- a/articles/minimum-one-bit-operations-to-make-integers-zero.md +++ b/articles/minimum-one-bit-operations-to-make-integers-zero.md @@ -62,7 +62,7 @@ class Solution { } let k = 1; - while ((k << 1) <= n) { + while (k << 1 <= n) { k <<= 1; } @@ -75,8 +75,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(\log n)$ for recursion stack. +- Time complexity: $O(\log n)$ +- Space complexity: $O(\log n)$ for recursion stack. --- @@ -150,7 +150,9 @@ class Solution { * @return {number} */ minimumOneBitOperations(n) { - let res = 0, k = 1 << 30, sign = 1; + let res = 0, + k = 1 << 30, + sign = 1; while (n !== 0) { while (k > n) { @@ -171,8 +173,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ --- @@ -227,10 +229,11 @@ class Solution { * @return {number} */ minimumOneBitOperations(n) { - let res = 0, sign = 1; + let res = 0, + sign = 1; while (n !== 0) { res += sign * (n ^ (n - 1)); - n &= (n - 1); + n &= n - 1; sign *= -1; } return Math.abs(res); @@ -242,8 +245,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ --- @@ -309,5 +312,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ diff --git a/articles/minimum-operations-to-reduce-x-to-zero.md b/articles/minimum-operations-to-reduce-x-to-zero.md index e3b3ca2eb..f9f19b49e 100644 --- a/articles/minimum-operations-to-reduce-x-to-zero.md +++ b/articles/minimum-operations-to-reduce-x-to-zero.md @@ -24,7 +24,7 @@ class Solution: suffixSum += nums[j] if prefixSum + suffixSum == x: res = min(res, i + 1 + n - j) - + return -1 if res == n + 1 else res ``` @@ -105,7 +105,9 @@ class Solution { */ minOperations(nums, x) { const n = nums.length; - let res = n + 1, suffixSum = 0, prefixSum = 0; + let res = n + 1, + suffixSum = 0, + prefixSum = 0; for (let i = n - 1; i >= 0; i--) { suffixSum += nums[i]; @@ -138,8 +140,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ extra space. --- @@ -154,7 +156,7 @@ class Solution: prefixSum = [0] * (n + 1) for i in range(n): prefixSum[i + 1] = prefixSum[i] + nums[i] - + if x > prefixSum[n]: return -1 @@ -170,9 +172,9 @@ class Solution: r = mid - 1 else: l = mid + 1 - + return index - + res = binarySearch(x, n) suffixSum = 0 for i in range(n - 1, 0, -1): @@ -182,7 +184,7 @@ class Solution: break if suffixSum > x: break res = min(res, binarySearch(x - suffixSum, i) + n - i) - + return -1 if res == n + 1 else res ``` @@ -194,11 +196,11 @@ public class Solution { for (int i = 0; i < n; i++) { prefixSum[i + 1] = prefixSum[i] + nums[i]; } - + if (x > prefixSum[n]) { return -1; } - + int res = binarySearch(prefixSum, x, n); int suffixSum = 0; for (int i = n - 1; i > 0; i--) { @@ -210,7 +212,7 @@ public class Solution { if (suffixSum > x) break; res = Math.min(res, binarySearch(prefixSum, x - suffixSum, i) + n - i); } - + return res == n + 1 ? -1 : res; } @@ -294,11 +296,12 @@ class Solution { for (let i = 0; i < n; i++) { prefixSum[i + 1] = prefixSum[i] + nums[i]; } - + if (x > prefixSum[n]) return -1; const binarySearch = (target, m) => { - let l = 1, r = m; + let l = 1, + r = m; let index = n + 1; while (l <= r) { let mid = Math.floor((l + r) / 2); @@ -335,8 +338,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -354,17 +357,17 @@ class Solution: target = total - x if target < 0: return -1 - + res = -1 prefixSum = 0 prefixMap = {0: -1} # prefixSum -> index - + for i, num in enumerate(nums): prefixSum += num if prefixSum - target in prefixMap: res = max(res, i - prefixMap[prefixSum - target]) prefixMap[prefixSum] = i - + return len(nums) - res if res != -1 else -1 ``` @@ -377,7 +380,7 @@ public class Solution { int target = total - x; if (target < 0) return -1; - + Map prefixMap = new HashMap<>(); prefixMap.put(0, -1); int prefixSum = 0, res = -1; @@ -389,7 +392,7 @@ public class Solution { } prefixMap.put(prefixSum, i); } - + return res == -1 ? -1 : nums.length - res; } } @@ -405,7 +408,7 @@ public: int target = total - x; if (target < 0) return -1; - + unordered_map prefixMap; prefixMap[0] = -1; int prefixSum = 0, res = -1; @@ -439,7 +442,8 @@ class Solution { const prefixMap = new Map(); prefixMap.set(0, -1); - let prefixSum = 0, res = -1; + let prefixSum = 0, + res = -1; for (let i = 0; i < nums.length; i++) { prefixSum += nums[i]; @@ -458,8 +462,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -549,7 +553,9 @@ class Solution { */ minOperations(nums, x) { const target = nums.reduce((acc, num) => acc + num, 0) - x; - let curSum = 0, maxWindow = -1, l = 0; + let curSum = 0, + maxWindow = -1, + l = 0; for (let r = 0; r < nums.length; r++) { curSum += nums[r]; @@ -573,5 +579,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/minimum-path-sum.md b/articles/minimum-path-sum.md index 21496ac0b..c05fa7f62 100644 --- a/articles/minimum-path-sum.md +++ b/articles/minimum-path-sum.md @@ -99,8 +99,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ {m + n})$ -* Space complexity: $O(m + n)$ for recursion stack. +- Time complexity: $O(2 ^ {m + n})$ +- Space complexity: $O(m + n)$ for recursion stack. > Where $m$ is the number of rows and $n$ is the number of columns. @@ -198,7 +198,8 @@ class Solution { * @return {number} */ minPathSum(grid) { - const m = grid.length, n = grid[0].length; + const m = grid.length, + n = grid[0].length; const dp = Array.from({ length: m }, () => Array(n).fill(-1)); const dfs = (r, c) => { @@ -259,8 +260,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns. @@ -334,8 +335,11 @@ class Solution { * @return {number} */ minPathSum(grid) { - const ROWS = grid.length, COLS = grid[0].length; - const dp = Array.from({ length: ROWS + 1 }, () => Array(COLS + 1).fill(Infinity)); + const ROWS = grid.length, + COLS = grid[0].length; + const dp = Array.from({ length: ROWS + 1 }, () => + Array(COLS + 1).fill(Infinity), + ); dp[ROWS - 1][COLS] = 0; for (let r = ROWS - 1; r >= 0; r--) { @@ -378,8 +382,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns. @@ -450,7 +454,8 @@ class Solution { * @return {number} */ minPathSum(grid) { - const ROWS = grid.length, COLS = grid[0].length; + const ROWS = grid.length, + COLS = grid[0].length; const dp = new Array(COLS + 1).fill(Infinity); dp[COLS - 1] = 0; @@ -490,7 +495,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(n)$ -> Where $m$ is the number of rows and $n$ is the number of columns. \ No newline at end of file +> Where $m$ is the number of rows and $n$ is the number of columns. diff --git a/articles/minimum-penalty-for-a-shop.md b/articles/minimum-penalty-for-a-shop.md index a3e506a88..5494b6bf6 100644 --- a/articles/minimum-penalty-for-a-shop.md +++ b/articles/minimum-penalty-for-a-shop.md @@ -17,7 +17,7 @@ class Solution: for j in range(i, n): if customers[j] == 'Y': penalty += 1 - + if penalty < minPenalty: minPenalty = penalty res = i @@ -49,7 +49,7 @@ public class Solution { res = i; } } - + return res; } } @@ -74,7 +74,7 @@ public: penalty++; } } - + if (penalty < minPenalty) { minPenalty = penalty; res = i; @@ -94,7 +94,8 @@ class Solution { */ bestClosingTime(customers) { const n = customers.length; - let res = n, minPenalty = n; + let res = n, + minPenalty = n; for (let i = 0; i <= n; i++) { let penalty = 0; @@ -124,8 +125,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -145,13 +146,13 @@ class Solution: if c == 'N': cnt += 1 prefixN.append(cnt) - + suffixY = [0] * (n + 1) for i in range(n - 1, -1, -1): suffixY[i] = suffixY[i + 1] if customers[i] == 'Y': suffixY[i] += 1 - + res = n minPenalty = n for i in range(n + 1): @@ -159,7 +160,7 @@ class Solution: if penalty < minPenalty: minPenalty = penalty res = i - + return res ``` @@ -264,7 +265,8 @@ class Solution { } } - let res = n, minPenalty = n; + let res = n, + minPenalty = n; for (let i = 0; i <= n; i++) { const penalty = prefixN[i] + suffixY[i]; if (penalty < minPenalty) { @@ -282,8 +284,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -345,7 +347,7 @@ class Solution { public: int bestClosingTime(string customers) { int cntY = count(customers.begin(), customers.end(), 'Y'); - + int minPenalty = cntY, res = 0, cntN = 0; for (int i = 0; i < customers.size(); i++) { if (customers[i] == 'Y') { @@ -378,7 +380,9 @@ class Solution { if (c === 'Y') cntY++; } - let minPenalty = cntY, res = 0, cntN = 0; + let minPenalty = cntY, + res = 0, + cntN = 0; for (let i = 0; i < customers.length; i++) { if (customers[i] === 'Y') { cntY--; @@ -402,8 +406,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -473,7 +477,9 @@ class Solution { * @return {number} */ bestClosingTime(customers) { - let res = 0, minPenalty = 0, penalty = 0; + let res = 0, + minPenalty = 0, + penalty = 0; for (let i = 0; i < customers.length; i++) { penalty += customers[i] === 'Y' ? 1 : -1; @@ -493,5 +499,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/minimum-remove-to-make-valid-parentheses.md b/articles/minimum-remove-to-make-valid-parentheses.md index 43c6d5981..bf7e8b5b0 100644 --- a/articles/minimum-remove-to-make-valid-parentheses.md +++ b/articles/minimum-remove-to-make-valid-parentheses.md @@ -165,8 +165,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -186,14 +186,14 @@ class Solution: cnt -= 1 elif c == ")": arr[i] = '' - + res = [] for c in reversed(arr): if c == '(' and cnt > 0: cnt -= 1 else: res.append(c) - + return ''.join(reversed(res)) ``` @@ -332,8 +332,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -354,7 +354,7 @@ class Solution: stack.pop() else: s[i] = '' - + while stack: s[stack.pop()] = '' return ''.join(s) @@ -495,8 +495,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -510,7 +510,7 @@ class Solution: openCnt = closeCnt = 0 for c in s: closeCnt += c == ')' - + res = [] for c in s: if c == '(': @@ -523,7 +523,7 @@ class Solution: continue openCnt -= 1 res.append(c) - + return ''.join(res) ``` @@ -534,7 +534,7 @@ public class Solution { for (char c : s.toCharArray()) { if (c == ')') closeCnt++; } - + StringBuilder res = new StringBuilder(); for (char c : s.toCharArray()) { if (c == '(') { @@ -547,7 +547,7 @@ public class Solution { } res.append(c); } - + return res.toString(); } } @@ -561,7 +561,7 @@ public: for (char& c : s) { if (c == ')') closeCnt++; } - + string res; for (char& c : s) { if (c == '(') { @@ -574,7 +574,7 @@ public: } res.push_back(c); } - + return res; } }; @@ -587,11 +587,12 @@ class Solution { * @return {string} */ minRemoveToMakeValid(s) { - let openCnt = 0, closeCnt = 0; + let openCnt = 0, + closeCnt = 0; for (const c of s) { if (c === ')') closeCnt++; } - + let res = []; for (const c of s) { if (c === '(') { @@ -604,7 +605,7 @@ class Solution { } res.push(c); } - + return res.join(''); } } @@ -640,7 +641,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ space for the output string. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ space for the output string. diff --git a/articles/minimum-score-of-a-path-between-two-cities.md b/articles/minimum-score-of-a-path-between-two-cities.md index 820b21739..24edf9c0b 100644 --- a/articles/minimum-score-of-a-path-between-two-cities.md +++ b/articles/minimum-score-of-a-path-between-two-cities.md @@ -132,8 +132,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ > Where $V$ is the number of vertices and $E$ is the number of edges. @@ -272,8 +272,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ > Where $V$ is the number of vertices and $E$ is the number of edges. @@ -412,8 +412,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ > Where $V$ is the number of vertices and $E$ is the number of edges. @@ -519,7 +519,7 @@ public class Solution { class DSU { public: vector parent, size; - + DSU(int n) { parent.resize(n + 1); size.resize(n + 1, 1); @@ -598,7 +598,8 @@ class DSU { * @return {boolean} */ union(u, v) { - let pu = this.find(u), pv = this.find(v); + let pu = this.find(u), + pv = this.find(v); if (pu === pv) return false; if (this.size[pu] >= this.size[pv]) { this.size[pu] += this.size[pv]; @@ -640,7 +641,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + (E * α(V)))$ -* Space complexity: $O(V)$ +- Time complexity: $O(V + (E * α(V)))$ +- Space complexity: $O(V)$ -> Where $V$ is the number of vertices and $E$ is the number of edges in the graph. $α()$ is used for amortized complexity. \ No newline at end of file +> Where $V$ is the number of vertices and $E$ is the number of edges in the graph. $α()$ is used for amortized complexity. diff --git a/articles/minimum-size-subarray-sum.md b/articles/minimum-size-subarray-sum.md index 683582184..0c56b14b5 100644 --- a/articles/minimum-size-subarray-sum.md +++ b/articles/minimum-size-subarray-sum.md @@ -15,7 +15,7 @@ class Solution: if curSum >= target: res = min(res, j - i + 1) break - + return 0 if res == float("inf") else res ``` @@ -24,7 +24,7 @@ public class Solution { public int minSubArrayLen(int target, int[] nums) { int n = nums.length; int res = Integer.MAX_VALUE; - + for (int i = 0; i < n; i++) { int curSum = 0, j = i; while (j < n) { @@ -36,7 +36,7 @@ public class Solution { j++; } } - + return res == Integer.MAX_VALUE ? 0 : res; } } @@ -48,7 +48,7 @@ public: int minSubArrayLen(int target, vector& nums) { int n = nums.size(); int res = INT_MAX; - + for (int i = 0; i < n; i++) { int curSum = 0, j = i; while (j < n) { @@ -60,7 +60,7 @@ public: j++; } } - + return res == INT_MAX ? 0 : res; } }; @@ -75,10 +75,11 @@ class Solution { */ minSubArrayLen(target, nums) { let n = nums.length; - let res = Infinity; - + let res = Infinity; + for (let i = 0; i < n; i++) { - let curSum = 0, j = i; + let curSum = 0, + j = i; while (j < n) { curSum += nums[j]; if (curSum >= target) { @@ -88,7 +89,7 @@ class Solution { j++; } } - + return res == Infinity ? 0 : res; } } @@ -120,8 +121,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ extra space. --- @@ -193,7 +194,8 @@ class Solution { * @return {number} */ minSubArrayLen(target, nums) { - let l = 0, total = 0; + let l = 0, + total = 0; let res = Infinity; for (let r = 0; r < nums.length; r++) { @@ -235,8 +237,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -251,7 +253,7 @@ class Solution: prefixSum = [0] * (n + 1) for i in range(n): prefixSum[i + 1] = prefixSum[i] + nums[i] - + res = n + 1 for i in range(n): l, r = i, n @@ -276,7 +278,7 @@ public class Solution { for (int i = 0; i < n; i++) { prefixSum[i + 1] = prefixSum[i] + nums[i]; } - + int res = n + 1; for (int i = 0; i < n; i++) { int l = i, r = n; @@ -308,7 +310,7 @@ public: for (int i = 0; i < n; i++) { prefixSum[i + 1] = prefixSum[i] + nums[i]; } - + int res = n + 1; for (int i = 0; i < n; i++) { int l = i, r = n; @@ -344,10 +346,11 @@ class Solution { for (let i = 0; i < n; i++) { prefixSum[i + 1] = prefixSum[i] + nums[i]; } - + let res = n + 1; for (let i = 0; i < n; i++) { - let l = i, r = n; + let l = i, + r = n; while (l < r) { const mid = Math.floor((l + r) / 2); const curSum = prefixSum[mid + 1] - prefixSum[i]; @@ -372,7 +375,7 @@ public class Solution { public int MinSubArrayLen(int target, int[] nums) { int n = nums.Length; int[] prefixSum = new int[n + 1]; - + for (int i = 0; i < n; i++) { prefixSum[i + 1] = prefixSum[i] + nums[i]; } @@ -404,5 +407,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ diff --git a/articles/minimum-stack.md b/articles/minimum-stack.md index 29041a02c..5fa5c90e5 100644 --- a/articles/minimum-stack.md +++ b/articles/minimum-stack.md @@ -24,10 +24,10 @@ class MinStack: while len(self.stack): mini = min(mini, self.stack[-1]) tmp.append(self.stack.pop()) - + while len(tmp): self.stack.append(tmp.pop()) - + return mini ``` @@ -39,19 +39,19 @@ class MinStack { public MinStack() { stack = new Stack<>(); } - + public void push(int val) { stack.push(val); } - + public void pop() { stack.pop(); } - + public int top() { return stack.peek(); } - + public int getMin() { Stack tmp = new Stack<>(); int mini = stack.peek(); @@ -60,11 +60,11 @@ class MinStack { mini = Math.min(mini, stack.peek()); tmp.push(stack.pop()); } - + while (!tmp.isEmpty()) { stack.push(tmp.pop()); } - + return mini; } } @@ -75,21 +75,21 @@ class MinStack { public: stack stk; MinStack() { - + } - + void push(int val) { stk.push(val); } - + void pop() { stk.pop(); } - + int top() { return stk.top(); } - + int getMin() { stack tmp; int mini = stk.top(); @@ -165,19 +165,19 @@ public class MinStack { public MinStack() { stack = new Stack(); } - + public void Push(int val) { stack.Push(val); } - + public void Pop() { stack.Pop(); } - + public int Top() { return stack.Peek(); } - + public int GetMin() { Stack tmp = new Stack(); int mini = stack.Peek(); @@ -186,11 +186,11 @@ public class MinStack { mini = System.Math.Min(mini, stack.Peek()); tmp.Push(stack.Pop()); } - + while (tmp.Count > 0) { stack.Push(tmp.Pop()); } - + return mini; } } @@ -318,8 +318,8 @@ class MinStack { ### Time & Space Complexity -* Time complexity: $O(n)$ for $getMin()$ and $O(1)$ for other operations. -* Space complexity: $O(n)$ for $getMin()$ and $O(1)$ for other operations. +- Time complexity: $O(n)$ for $getMin()$ and $O(1)$ for other operations. +- Space complexity: $O(n)$ for $getMin()$ and $O(1)$ for other operations. --- @@ -358,14 +358,14 @@ public class MinStack { stack = new Stack<>(); minStack = new Stack<>(); } - + public void push(int val) { stack.push(val); if (minStack.isEmpty() || val <= minStack.peek()) { minStack.push(val); } } - + public void pop() { if (stack.isEmpty()) return; int top = stack.pop(); @@ -373,11 +373,11 @@ public class MinStack { minStack.pop(); } } - + public int top() { return stack.peek(); } - + public int getMin() { return minStack.peek(); } @@ -462,7 +462,7 @@ class MinStack { ```csharp public class MinStack { - + private Stack stack; private Stack minStack; @@ -592,8 +592,8 @@ class MinStack { ### Time & Space Complexity -* Time complexity: $O(1)$ for all operations. -* Space complexity: $O(n)$ +- Time complexity: $O(1)$ for all operations. +- Space complexity: $O(n)$ --- @@ -619,9 +619,9 @@ class MinStack: def pop(self) -> None: if not self.stack: return - + pop = self.stack.pop() - + if pop < 0: self.min = self.min - pop @@ -644,7 +644,7 @@ public class MinStack { public MinStack() { stack = new Stack<>(); } - + public void push(int val) { if (stack.isEmpty()) { stack.push(0L); @@ -657,9 +657,9 @@ public class MinStack { public void pop() { if (stack.isEmpty()) return; - + long pop = stack.pop(); - + if (pop < 0) min = min - pop; } @@ -686,7 +686,7 @@ private: public: MinStack() {} - + void push(int val) { if (stack.empty()) { stack.push(0); @@ -696,21 +696,21 @@ public: if (val < min) min = val; } } - + void pop() { if (stack.empty()) return; - + long pop = stack.top(); stack.pop(); - + if (pop < 0) min = min - pop; } - + int top() { long top = stack.top(); return (top > 0) ? (top + min) : (int)min; } - + int getMin() { return (int)min; } @@ -913,9 +913,9 @@ class MinStack { if stack.isEmpty { return } - + let pop = stack.removeLast() - + if pop < 0 { minVal -= pop } @@ -936,5 +936,5 @@ class MinStack { ### Time & Space Complexity -* Time complexity: $O(1)$ for all operations. -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(1)$ for all operations. +- Space complexity: $O(n)$ diff --git a/articles/minimum-time-to-collect-all-apples-in-a-tree.md b/articles/minimum-time-to-collect-all-apples-in-a-tree.md index 2ea61fe99..8ad4a4804 100644 --- a/articles/minimum-time-to-collect-all-apples-in-a-tree.md +++ b/articles/minimum-time-to-collect-all-apples-in-a-tree.md @@ -116,10 +116,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ -> Where $V$ is the number of vertices and $E$ is the number of edges. +> Where $V$ is the number of vertices and $E$ is the number of edges. --- @@ -143,20 +143,20 @@ class Solution: if indegree[i] == 1: queue.append(i) indegree[i] = 0 - + time = [0] * n while queue: node = queue.popleft() for nei in adj[node]: if indegree[nei] <= 0: continue - + indegree[nei] -= 1 if hasApple[node] or time[node] > 0: time[nei] += time[node] + 2 if indegree[nei] == 1 and nei != 0: queue.append(nei) - + return time[0] ``` @@ -306,7 +306,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ -> Where $V$ is the number of vertices and $E$ is the number of edges. \ No newline at end of file +> Where $V$ is the number of vertices and $E$ is the number of edges. diff --git a/articles/minimum-time-to-make-rope-colorful.md b/articles/minimum-time-to-make-rope-colorful.md index a9d436a9d..785132df6 100644 --- a/articles/minimum-time-to-make-rope-colorful.md +++ b/articles/minimum-time-to-make-rope-colorful.md @@ -69,9 +69,12 @@ class Solution { */ minCost(colors, neededTime) { const n = neededTime.length; - let res = 0, i = 0; + let res = 0, + i = 0; while (i < n) { - let j = i, maxi = 0, curr = 0; + let j = i, + maxi = 0, + curr = 0; while (j < n && colors[j] === colors[i]) { maxi = Math.max(maxi, neededTime[j]); curr += neededTime[j]; @@ -89,8 +92,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -165,7 +168,8 @@ class Solution { * @return {number} */ minCost(colors, neededTime) { - let l = 0, res = 0; + let l = 0, + res = 0; for (let r = 1; r < colors.length; r++) { if (colors[l] === colors[r]) { if (neededTime[l] < neededTime[r]) { @@ -187,8 +191,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -249,7 +253,8 @@ class Solution { * @return {number} */ minCost(colors, neededTime) { - let res = 0, maxi = 0; + let res = 0, + maxi = 0; for (let i = 0; i < colors.length; i++) { if (i > 0 && colors[i] !== colors[i - 1]) { maxi = 0; @@ -266,5 +271,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/minimum-window-with-characters.md b/articles/minimum-window-with-characters.md index 887cb769c..3ea9bcd4c 100644 --- a/articles/minimum-window-with-characters.md +++ b/articles/minimum-window-with-characters.md @@ -23,7 +23,7 @@ class Solution: if countT[c] > countS.get(c, 0): flag = False break - + if flag and (j - i + 1) < resLen: resLen = j - i + 1 res = [i, j] @@ -118,7 +118,7 @@ class Solution { * @return {string} */ minWindow(s, t) { - if (t === "") return ""; + if (t === '') return ''; let countT = {}; for (let c of t) { @@ -141,14 +141,14 @@ class Solution { } } - if (flag && (j - i + 1) < resLen) { + if (flag && j - i + 1 < resLen) { resLen = j - i + 1; res = [i, j]; } } } - return resLen === Infinity ? "" : s.slice(res[0], res[1] + 1); + return resLen === Infinity ? '' : s.slice(res[0], res[1] + 1); } } ``` @@ -212,7 +212,7 @@ func minWindow(s string, t string) string { } res := []int{-1, -1} - resLen := int(^uint(0) >> 1) + resLen := int(^uint(0) >> 1) for i := 0; i < len(s); i++ { countS := make(map[rune]int) for j := i; j < len(s); j++ { @@ -252,7 +252,7 @@ class Solution { var res = IntArray(2) {-1} var resLen = Int.MAX_VALUE - + for (i in s.indices) { val countS = HashMap() for (j in i until s.length) { @@ -325,8 +325,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(m)$ > Where $n$ is the length of the string $s$ and $m$ is the total number of unique characters in the strings $t$ and $s$. @@ -360,7 +360,7 @@ class Solution: if (r - l + 1) < resLen: res = [l, r] resLen = r - l + 1 - + window[s[l]] -= 1 if s[l] in countT and window[s[l]] < countT[s[l]]: have -= 1 @@ -465,7 +465,7 @@ class Solution { * @return {string} */ minWindow(s, t) { - if (t === "") return ""; + if (t === '') return ''; let countT = {}; let window = {}; @@ -473,7 +473,8 @@ class Solution { countT[c] = (countT[c] || 0) + 1; } - let have = 0, need = Object.keys(countT).length; + let have = 0, + need = Object.keys(countT).length; let res = [-1, -1]; let resLen = Infinity; let l = 0; @@ -487,7 +488,7 @@ class Solution { } while (have === need) { - if ((r - l + 1) < resLen) { + if (r - l + 1 < resLen) { resLen = r - l + 1; res = [l, r]; } @@ -500,7 +501,7 @@ class Solution { } } - return resLen === Infinity ? "" : s.slice(res[0], res[1] + 1); + return resLen === Infinity ? '' : s.slice(res[0], res[1] + 1); } } ``` @@ -701,7 +702,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n)$ +- Space complexity: $O(m)$ -> Where $n$ is the length of the string $s$ and $m$ is the total number of unique characters in the strings $t$ and $s$. \ No newline at end of file +> Where $n$ is the length of the string $s$ and $m$ is the total number of unique characters in the strings $t$ and $s$. diff --git a/articles/missing-number.md b/articles/missing-number.md index 24844c099..1034fab68 100644 --- a/articles/missing-number.md +++ b/articles/missing-number.md @@ -125,8 +125,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -261,8 +261,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -274,7 +274,7 @@ class Solution { class Solution: def missingNumber(self, nums: List[int]) -> int: n = len(nums) - xorr = n + xorr = n for i in range(n): xorr ^= i ^ nums[i] return xorr @@ -284,7 +284,7 @@ class Solution: public class Solution { public int missingNumber(int[] nums) { int n = nums.length; - int xorr = n; + int xorr = n; for (int i = 0; i < n; i++) { xorr ^= i ^ nums[i]; } @@ -298,7 +298,7 @@ class Solution { public: int missingNumber(vector& nums) { int n = nums.size(); - int xorr = n; + int xorr = n; for (int i = 0; i < n; i++) { xorr ^= i ^ nums[i]; } @@ -315,7 +315,7 @@ class Solution { */ missingNumber(nums) { let n = nums.length; - let xorr = n; + let xorr = n; for (let i = 0; i < n; i++) { xorr ^= i ^ nums[i]; } @@ -328,7 +328,7 @@ class Solution { public class Solution { public int MissingNumber(int[] nums) { int n = nums.Length; - int xorr = n; + int xorr = n; for (int i = 0; i < n; i++) { xorr ^= i ^ nums[i]; } @@ -380,8 +380,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -496,5 +496,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/monotonic-array.md b/articles/monotonic-array.md index 317997838..8eb3d6d41 100644 --- a/articles/monotonic-array.md +++ b/articles/monotonic-array.md @@ -11,7 +11,7 @@ class Solution: if nums[i] < nums[i - 1]: increase = False break - + if increase: return True @@ -113,8 +113,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -216,8 +216,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -282,7 +282,8 @@ class Solution { * @return {boolean} */ isMonotonic(nums) { - let increase = true, decrease = true; + let increase = true, + decrease = true; for (let i = 0; i < nums.length - 1; i++) { if (!(nums[i] <= nums[i + 1])) { @@ -301,5 +302,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/move-zeroes.md b/articles/move-zeroes.md index c914bc968..4012e93ca 100644 --- a/articles/move-zeroes.md +++ b/articles/move-zeroes.md @@ -12,7 +12,7 @@ class Solution: for num in nums: if num != 0: tmp.append(num) - + for i in range(len(nums)): if i < len(tmp): nums[i] = tmp[i] @@ -76,7 +76,7 @@ class Solution { tmp.push(num); } } - + for (let i = 0; i < nums.length; i++) { if (i < tmp.length) { nums[i] = tmp[i]; @@ -112,12 +112,13 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- ## 2. Two Pointers (Two Pass) + ::tabs-start ```python @@ -131,7 +132,7 @@ class Solution: if nums[r] != 0: nums[l] = nums[r] l += 1 - + while l < len(nums): nums[l] = 0 l += 1 @@ -215,8 +216,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -248,7 +249,7 @@ public class Solution { nums[r] = temp; l++; } - } + } } } ``` @@ -303,5 +304,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/multiply-strings.md b/articles/multiply-strings.md index eb53364f1..19fc7cd99 100644 --- a/articles/multiply-strings.md +++ b/articles/multiply-strings.md @@ -7,18 +7,18 @@ class Solution: def multiply(self, num1: str, num2: str) -> str: if num1 == "0" or num2 == "0": return "0" - + if len(num1) < len(num2): return self.multiply(num2, num1) - + res, zero = "", 0 for i in range(len(num2) - 1, -1, -1): cur = self.mul(num1, num2[i], zero) res = self.add(res, cur) zero += 1 - + return res - + def mul(self, s: str, d: str, zero: int) -> str: i, carry = len(s) - 1, 0 d = int(d) @@ -30,7 +30,7 @@ class Solution: cur.append(str(prod % 10)) carry = prod // 10 i -= 1 - + return ''.join(cur[::-1]) + '0' * zero def add(self, num1: str, num2: str) -> str: @@ -45,7 +45,7 @@ class Solution: carry = total // 10 i -= 1 j -= 1 - + return ''.join(res[::-1]) ``` @@ -57,7 +57,7 @@ public class Solution { if (num1.length() < num2.length()) { return multiply(num2, num1); } - + String res = ""; int zero = 0; for (int i = num2.length() - 1; i >= 0; i--) { @@ -65,10 +65,10 @@ public class Solution { res = add(res, cur); zero++; } - + return res; } - + private String mul(String s, char d, int zero) { int i = s.length() - 1, carry = 0; int digit = d - '0'; @@ -81,7 +81,7 @@ public class Solution { carry = prod / 10; i--; } - + return cur.reverse().toString() + "0".repeat(zero); } @@ -98,7 +98,7 @@ public class Solution { i--; j--; } - + return res.reverse().toString(); } } @@ -109,11 +109,11 @@ class Solution { public: string multiply(string num1, string num2) { if (num1 == "0" || num2 == "0") return "0"; - + if (num1.size() < num2.size()) { return multiply(num2, num1); } - + string res = ""; int zero = 0; for (int i = num2.size() - 1; i >= 0; --i) { @@ -121,10 +121,10 @@ public: res = add(res, cur); zero++; } - + return res; } - + string mul(string s, char d, int zero) { int i = s.size() - 1, carry = 0; int digit = d - '0'; @@ -137,7 +137,7 @@ public: carry = prod / 10; i--; } - + reverse(cur.begin(), cur.end()); return cur + string(zero, '0'); } @@ -155,7 +155,7 @@ public: i--; j--; } - + reverse(res.begin(), res.end()); return res; } @@ -170,23 +170,23 @@ class Solution { * @return {string} */ multiply(num1, num2) { - if (num1 === "0" || num2 === "0") return "0"; + if (num1 === '0' || num2 === '0') return '0'; if (num1.length < num2.length) { return this.multiply(num2, num1); } - - let res = ""; + + let res = ''; let zero = 0; for (let i = num2.length - 1; i >= 0; i--) { const cur = this.mul(num1, num2[i], zero); res = this.add(res, cur); zero++; } - + return res; } - + /** * @param {string} s * @param {Character} d @@ -197,7 +197,7 @@ class Solution { let i = s.length - 1; let carry = 0; const digit = Number(d); - let cur = ""; + let cur = ''; while (i >= 0 || carry) { const n = i >= 0 ? Number(s[i]) : 0; @@ -206,8 +206,8 @@ class Solution { carry = Math.floor(prod / 10); i--; } - - return cur + "0".repeat(zero); + + return cur + '0'.repeat(zero); } /** @@ -216,8 +216,10 @@ class Solution { * @return {string} */ add(num1, num2) { - let i = num1.length - 1, j = num2.length - 1, carry = 0; - let res = ""; + let i = num1.length - 1, + j = num2.length - 1, + carry = 0; + let res = ''; while (i >= 0 || j >= 0 || carry) { const n1 = i >= 0 ? Number(num1[i]) : 0; @@ -228,7 +230,7 @@ class Solution { i--; j--; } - + return res; } } @@ -242,7 +244,7 @@ public class Solution { if (num1.Length < num2.Length) { return Multiply(num2, num1); } - + string res = ""; int zero = 0; for (int i = num2.Length - 1; i >= 0; i--) { @@ -250,10 +252,10 @@ public class Solution { res = Add(res, cur); zero++; } - + return res; } - + private string Mul(string s, char d, int zero) { int i = s.Length - 1, carry = 0; int digit = d - '0'; @@ -266,7 +268,7 @@ public class Solution { carry = prod / 10; i--; } - + cur.Reverse(); return new string(cur.ToArray()) + new string('0', zero); } @@ -284,7 +286,7 @@ public class Solution { i--; j--; } - + res.Reverse(); return new string(res.ToArray()); } @@ -296,18 +298,18 @@ func multiply(num1 string, num2 string) string { if num1 == "0" || num2 == "0" { return "0" } - + if len(num1) < len(num2) { return multiply(num2, num1) } - + res, zero := "", 0 for i := len(num2) - 1; i >= 0; i-- { cur := mul(num1, num2[i], zero) res = add(res, cur) zero++ } - + return res } @@ -315,7 +317,7 @@ func mul(s string, d byte, zero int) string { i, carry := len(s)-1, 0 d = d - '0' cur := make([]byte, 0) - + for i >= 0 || carry > 0 { var n int if i >= 0 { @@ -326,11 +328,11 @@ func mul(s string, d byte, zero int) string { carry = prod / 10 i-- } - + for i := 0; i < len(cur)/2; i++ { cur[i], cur[len(cur)-1-i] = cur[len(cur)-1-i], cur[i] } - + result := string(cur) for i := 0; i < zero; i++ { result += "0" @@ -341,7 +343,7 @@ func mul(s string, d byte, zero int) string { func add(num1 string, num2 string) string { i, j, carry := len(num1)-1, len(num2)-1, 0 res := make([]byte, 0) - + for i >= 0 || j >= 0 || carry > 0 { var n1, n2 int if i >= 0 { @@ -356,11 +358,11 @@ func add(num1 string, num2 string) string { i-- j-- } - + for i := 0; i < len(res)/2; i++ { res[i], res[len(res)-1-i] = res[len(res)-1-i], res[i] } - + return string(res) } ``` @@ -371,11 +373,11 @@ class Solution { if (num1 == "0" || num2 == "0") { return "0" } - + if (num1.length < num2.length) { return multiply(num2, num1) } - + var res = "" var zero = 0 for (i in num2.length - 1 downTo 0) { @@ -383,16 +385,16 @@ class Solution { res = add(res, cur) zero++ } - + return res } - + private fun mul(s: String, d: Char, zero: Int): String { var i = s.length - 1 var carry = 0 val dInt = d - '0' val cur = mutableListOf() - + while (i >= 0 || carry > 0) { val n = if (i >= 0) s[i] - '0' else 0 val prod = n * dInt + carry @@ -400,16 +402,16 @@ class Solution { carry = prod / 10 i-- } - + return cur.reversed().joinToString("") + "0".repeat(zero) } - + private fun add(num1: String, num2: String): String { var i = num1.length - 1 var j = num2.length - 1 var carry = 0 val res = mutableListOf() - + while (i >= 0 || j >= 0 || carry > 0) { val n1 = if (i >= 0) num1[i] - '0' else 0 val n2 = if (j >= 0) num2[j] - '0' else 0 @@ -419,7 +421,7 @@ class Solution { i-- j-- } - + return res.reversed().joinToString("") } } @@ -495,8 +497,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(min(m, n) * (m + n))$ -* Space complexity: $O(m + n)$ +- Time complexity: $O(min(m, n) * (m + n))$ +- Space complexity: $O(m + n)$ > Where $m$ is the length of the string $num1$ and $n$ is the length of the string $num2$. @@ -666,19 +668,19 @@ func multiply(num1 string, num2 string) string { if num1 == "0" || num2 == "0" { return "0" } - + res := make([]int, len(num1)+len(num2)) for i1 := len(num1) - 1; i1 >= 0; i1-- { for i2 := len(num2) - 1; i2 >= 0; i2-- { pos := len(num1) - 1 - i1 + len(num2) - 1 - i2 digit := int(num1[i1]-'0') * int(num2[i2]-'0') - + res[pos] += digit res[pos+1] += res[pos] / 10 res[pos] = res[pos] % 10 } } - + var result strings.Builder start := len(res) - 1 for start >= 0 && res[start] == 0 { @@ -687,11 +689,11 @@ func multiply(num1 string, num2 string) string { if start < 0 { return "0" } - + for i := start; i >= 0; i-- { result.WriteString(strconv.Itoa(res[i])) } - + return result.String() } ``` @@ -702,28 +704,28 @@ class Solution { if ("0" in listOf(num1, num2)) { return "0" } - + val res = IntArray(num1.length + num2.length) for (i1 in num1.indices.reversed()) { for (i2 in num2.indices.reversed()) { val pos = (num1.length - 1 - i1) + (num2.length - 1 - i2) val digit = (num1[i1] - '0') * (num2[i2] - '0') - + res[pos] += digit res[pos + 1] += res[pos] / 10 res[pos] = res[pos] % 10 } } - + var start = res.size - 1 while (start >= 0 && res[start] == 0) { start-- } - + if (start < 0) { return "0" } - + return buildString { for (i in start downTo 0) { append(res[i]) @@ -768,7 +770,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m + n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m + n)$ -> Where $m$ is the length of the string $num1$ and $n$ is the length of the string $num2$. \ No newline at end of file +> Where $m$ is the length of the string $num1$ and $n$ is the length of the string $num2$. diff --git a/articles/my-calendar-i.md b/articles/my-calendar-i.md index f926c9e13..e7f218291 100644 --- a/articles/my-calendar-i.md +++ b/articles/my-calendar-i.md @@ -12,7 +12,7 @@ class MyCalendar: for start, end in self.events: if startTime < end and start < endTime: return False - + self.events.append((startTime, endTime)) return True ``` @@ -63,8 +63,8 @@ class MyCalendar { this.events = []; } - /** - * @param {number} startTime + /** + * @param {number} startTime * @param {number} endTime * @return {boolean} */ @@ -84,8 +84,8 @@ class MyCalendar { ### Time & Space Complexity -* Time complexity: $O(n)$ for each $book()$ function call. -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ for each $book()$ function call. +- Space complexity: $O(n)$ --- @@ -217,9 +217,9 @@ public: ```javascript class TreeNode { - /** + /** * @constructor - * @param {number} start + * @param {number} start * @param {number} end */ constructor(start, end) { @@ -235,8 +235,8 @@ class MyCalendar { this.root = null; } - /** - * @param {TreeNode} node + /** + * @param {TreeNode} node * @param {number} start * @param {number} end * @return {boolean} @@ -258,8 +258,8 @@ class MyCalendar { return false; } - /** - * @param {number} startTime + /** + * @param {number} startTime * @param {number} endTime * @return {boolean} */ @@ -277,8 +277,8 @@ class MyCalendar { ### Time & Space Complexity -* Time complexity: $O(\log n)$ in average case, $O(n)$ in worst case for each $book()$ function call. -* Space complexity: $O(n)$ +- Time complexity: $O(\log n)$ in average case, $O(n)$ in worst case for each $book()$ function call. +- Space complexity: $O(n)$ --- @@ -328,15 +328,15 @@ public class MyCalendar { class MyCalendar { private: set> events; - + public: MyCalendar() {} - + bool book(int startTime, int endTime) { if (startTime >= endTime) { return false; } - + auto next = events.lower_bound({startTime, startTime}); if (next != events.end() && next->first < endTime) { return false; @@ -347,7 +347,7 @@ public: return false; } } - + events.insert({startTime, endTime}); return true; } @@ -360,8 +360,8 @@ class MyCalendar { this.events = []; } - /** - * @param {number} startTime + /** + * @param {number} startTime * @param {number} endTime * @return {boolean} */ @@ -371,8 +371,9 @@ class MyCalendar { } const binarySearch = (target) => { - let left = 0, right = this.events.length; - + let left = 0, + right = this.events.length; + while (left < right) { let mid = Math.floor((left + right) / 2); if (this.events[mid][0] < target) { @@ -401,5 +402,5 @@ class MyCalendar { ### Time & Space Complexity -* Time complexity: $O(\log n)$ for each $book()$ function call. -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(\log n)$ for each $book()$ function call. +- Space complexity: $O(n)$ diff --git a/articles/n-queens-ii.md b/articles/n-queens-ii.md index 16a94bd75..c29e85b70 100644 --- a/articles/n-queens-ii.md +++ b/articles/n-queens-ii.md @@ -21,14 +21,14 @@ class Solution: backtrack(0) return res - + def isSafe(self, r: int, c: int, board): row = r - 1 while row >= 0: if board[row][c] == "Q": return False row -= 1 - + row, col = r - 1, c - 1 while row >= 0 and col >= 0: if board[row][col] == "Q": @@ -137,8 +137,8 @@ class Solution { */ totalNQueens(n) { let res = 0; - let board = Array.from({length: n}, () => Array(n).fill('.')); - + let board = Array.from({ length: n }, () => Array(n).fill('.')); + const backtrack = (r) => { if (r === n) { res++; @@ -151,8 +151,8 @@ class Solution { board[r][c] = '.'; } } - } - + }; + backtrack(0); return res; } @@ -233,8 +233,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n!)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n!)$ +- Space complexity: $O(n ^ 2)$ --- @@ -280,7 +280,7 @@ public class Solution { Set posDiag = new HashSet<>(); Set negDiag = new HashSet<>(); int res; - + public int totalNQueens(int n) { res = 0; backtrack(0, n); @@ -374,8 +374,7 @@ class Solution { } for (let c = 0; c < n; c++) { - if (col.has(c) || posDiag.has(r + c) || - negDiag.has(r - c)) { + if (col.has(c) || posDiag.has(r + c) || negDiag.has(r - c)) { continue; } @@ -438,8 +437,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n!)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n!)$ +- Space complexity: $O(n)$ --- @@ -487,7 +486,7 @@ public class Solution { posDiag = new boolean[2 * n]; negDiag = new boolean[2 * n]; res = 0; - + backtrack(0, n); return res; } @@ -578,13 +577,13 @@ class Solution { for (let c = 0; c < n; c++) { if (col[c] || posDiag[r + c] || negDiag[r - c + n]) { continue; - } + } col[c] = true; posDiag[r + c] = true; negDiag[r - c + n] = true; backtrack(r + 1); - + col[c] = false; posDiag[r + c] = false; negDiag[r - c + n] = false; @@ -637,8 +636,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n!)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n!)$ +- Space complexity: $O(n)$ --- @@ -660,7 +659,7 @@ class Solution: res += 1 return for c in range(n): - if ((col & (1 << c)) or (posDiag & (1 << (r + c))) + if ((col & (1 << c)) or (posDiag & (1 << (r + c))) or (negDiag & (1 << (r - c + n)))): continue col ^= (1 << c) @@ -693,7 +692,7 @@ public class Solution { return; } for (int c = 0; c < n; c++) { - if ((col & (1 << c)) > 0 || (posDiag & (1 << (r + c))) > 0 || + if ((col & (1 << c)) > 0 || (posDiag & (1 << (r + c))) > 0 || (negDiag & (1 << (r - c + n))) > 0) { continue; } @@ -729,7 +728,7 @@ public: return; } for (int c = 0; c < n; c++) { - if ((col & (1 << c)) || (posDiag & (1 << (r + c))) || + if ((col & (1 << c)) || (posDiag & (1 << (r + c))) || (negDiag & (1 << (r - c + n)))) { continue; } @@ -754,7 +753,10 @@ class Solution { * @return {number} */ totalNQueens(n) { - let col = 0, posDiag = 0, negDiag = 0, res = 0; + let col = 0, + posDiag = 0, + negDiag = 0, + res = 0; /** * @param {number} r @@ -766,19 +768,22 @@ class Solution { return; } for (let c = 0; c < n; c++) { - if ((col & (1 << c)) > 0 || (posDiag & (1 << (r + c))) > 0 || - (negDiag & (1 << (r - c + n))) > 0) { + if ( + (col & (1 << c)) > 0 || + (posDiag & (1 << (r + c))) > 0 || + (negDiag & (1 << (r - c + n))) > 0 + ) { continue; } - col ^= (1 << c); - posDiag ^= (1 << (r + c)); - negDiag ^= (1 << (r - c + n)); + col ^= 1 << c; + posDiag ^= 1 << (r + c); + negDiag ^= 1 << (r - c + n); backtrack(r + 1); - - col ^= (1 << c); - posDiag ^= (1 << (r + c)); - negDiag ^= (1 << (r - c + n)); + + col ^= 1 << c; + posDiag ^= 1 << (r + c); + negDiag ^= 1 << (r - c + n); } } @@ -803,8 +808,8 @@ public class Solution { } for (int c = 0; c < n; c++) { - if (((col & (1 << c)) != 0) || - ((posDiag & (1 << (r + c))) != 0) || + if (((col & (1 << c)) != 0) || + ((posDiag & (1 << (r + c))) != 0) || ((negDiag & (1 << (r - c + n))) != 0)) continue; @@ -830,5 +835,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n!)$ -* Space complexity: $O(n)$ for recursion stack. \ No newline at end of file +- Time complexity: $O(n!)$ +- Space complexity: $O(n)$ for recursion stack. diff --git a/articles/n-queens.md b/articles/n-queens.md index e75cd714b..690ca72f2 100644 --- a/articles/n-queens.md +++ b/articles/n-queens.md @@ -28,7 +28,7 @@ class Solution: if board[row][c] == "Q": return False row -= 1 - + row, col = r - 1, c - 1 while row >= 0 and col >= 0: if board[row][col] == "Q": @@ -139,11 +139,11 @@ class Solution { */ solveNQueens(n) { let res = []; - let board = Array.from({length: n}, () => Array(n).fill('.')); - + let board = Array.from({ length: n }, () => Array(n).fill('.')); + const backtrack = (r) => { if (r === n) { - res.push(board.map(row => row.join(''))); + res.push(board.map((row) => row.join(''))); return; } for (let c = 0; c < n; c++) { @@ -153,8 +153,8 @@ class Solution { board[r][c] = '.'; } } - } - + }; + backtrack(0); return res; } @@ -339,7 +339,7 @@ class Solution { func solveNQueens(_ n: Int) -> [[String]] { var res = [[String]]() var board = Array(repeating: Array(repeating: ".", count: n), count: n) - + func backtrack(_ r: Int) { if r == n { let copy = board.map { $0.joined() } @@ -354,32 +354,32 @@ class Solution { } } } - + backtrack(0) return res } - + private func isSafe(_ r: Int, _ c: Int, _ board: [[String]]) -> Bool { var row = r - 1 while row >= 0 { if board[row][c] == "Q" { return false } row -= 1 } - + var row1 = r - 1, col1 = c - 1 while row1 >= 0, col1 >= 0 { if board[row1][col1] == "Q" { return false } row1 -= 1 col1 -= 1 } - + var row2 = r - 1, col2 = c + 1 while row2 >= 0, col2 < board.count { if board[row2][col2] == "Q" { return false } row2 -= 1 col2 += 1 } - + return true } } @@ -389,8 +389,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n!)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n!)$ +- Space complexity: $O(n ^ 2)$ --- @@ -440,7 +440,7 @@ public class Solution { Set posDiag = new HashSet<>(); Set negDiag = new HashSet<>(); List> res = new ArrayList<>(); - + public List> solveNQueens(int n) { char[][] board = new char[n][n]; for (char[] row : board) { @@ -462,7 +462,7 @@ public class Solution { } for (int c = 0; c < n; c++) { - if (col.contains(c) || posDiag.contains(r + c) + if (col.contains(c) || posDiag.contains(r + c) || negDiag.contains(r - c)) { continue; } @@ -506,7 +506,7 @@ private: } for (int c = 0; c < n; c++) { - if (col.count(c) || posDiag.count(r + c) || + if (col.count(c) || posDiag.count(r + c) || negDiag.count(r - c)) { continue; } @@ -539,8 +539,7 @@ class Solution { const negDiag = new Set(); const res = []; - const board = Array.from({ length: n }, - () => Array(n).fill('.')); + const board = Array.from({ length: n }, () => Array(n).fill('.')); /** * @param {number} r @@ -548,13 +547,12 @@ class Solution { */ function backtrack(r) { if (r === n) { - res.push(board.map(row => row.join(''))); + res.push(board.map((row) => row.join(''))); return; } for (let c = 0; c < n; c++) { - if (col.has(c) || posDiag.has(r + c) || - negDiag.has(r - c)) { + if (col.has(c) || posDiag.has(r + c) || negDiag.has(r - c)) { continue; } @@ -584,7 +582,7 @@ public class Solution { HashSet posDiag = new HashSet(); HashSet negDiag = new HashSet(); List> res = new List>(); - + public List> SolveNQueens(int n) { char[][] board = new char[n][]; for (int i = 0; i < n; i++) { @@ -762,8 +760,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n!)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n!)$ +- Space complexity: $O(n ^ 2)$ --- @@ -866,7 +864,7 @@ public: posDiag.resize(2 * n, false); negDiag.resize(2 * n, false); board.resize(n, string(n, '.')); - + backtrack(0, n); return res; } @@ -907,8 +905,7 @@ class Solution { const posDiag = Array(2 * n).fill(false); const negDiag = Array(2 * n).fill(false); const res = []; - const board = Array.from({ length: n }, - () => Array(n).fill('.')); + const board = Array.from({ length: n }, () => Array(n).fill('.')); /** * @param {number} r @@ -916,20 +913,20 @@ class Solution { */ function backtrack(r) { if (r === n) { - res.push(board.map(row => row.join(''))); + res.push(board.map((row) => row.join(''))); return; } for (let c = 0; c < n; c++) { if (col[c] || posDiag[r + c] || negDiag[r - c + n]) { continue; - } + } col[c] = true; posDiag[r + c] = true; negDiag[r - c + n] = true; board[r][c] = 'Q'; backtrack(r + 1); - + col[c] = false; posDiag[r + c] = false; negDiag[r - c + n] = false; @@ -974,7 +971,7 @@ public class Solution { for (int c = 0; c < n; c++) { if (col[c] || posDiag[r + c] || negDiag[r - c + n]) { continue; - } + } col[c] = true; posDiag[r + c] = true; negDiag[r - c + n] = true; @@ -1093,12 +1090,12 @@ class Solution { res.append(copy) return } - + for c in 0..> solveNQueens(int n) { board.resize(n, string(n, '.')); - + backtrack(0, n); return res; } @@ -1262,10 +1259,11 @@ class Solution { * @return {string[][]} */ solveNQueens(n) { - let col = 0, posDiag = 0, negDiag = 0; + let col = 0, + posDiag = 0, + negDiag = 0; const res = []; - const board = Array.from({ length: n }, - () => Array(n).fill('.')); + const board = Array.from({ length: n }, () => Array(n).fill('.')); /** * @param {number} r @@ -1273,24 +1271,27 @@ class Solution { */ function backtrack(r) { if (r === n) { - res.push(board.map(row => row.join(''))); + res.push(board.map((row) => row.join(''))); return; } for (let c = 0; c < n; c++) { - if ((col & (1 << c)) > 0 || (posDiag & (1 << (r + c))) > 0 - || (negDiag & (1 << (r - c + n))) > 0) { + if ( + (col & (1 << c)) > 0 || + (posDiag & (1 << (r + c))) > 0 || + (negDiag & (1 << (r - c + n))) > 0 + ) { continue; } - col ^= (1 << c); - posDiag ^= (1 << (r + c)); - negDiag ^= (1 << (r - c + n)); + col ^= 1 << c; + posDiag ^= 1 << (r + c); + negDiag ^= 1 << (r - c + n); board[r][c] = 'Q'; backtrack(r + 1); - - col ^= (1 << c); - posDiag ^= (1 << (r + c)); - negDiag ^= (1 << (r - c + n)); + + col ^= 1 << c; + posDiag ^= 1 << (r + c); + negDiag ^= 1 << (r - c + n); board[r][c] = '.'; } } @@ -1370,7 +1371,7 @@ func solveNQueens(n int) [][]string { } for c := 0; c < n; c++ { - if (col&(1< Where $n$ is the size of the array $ideas$ and $m$ is the average length of the strings. @@ -240,8 +240,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $n$ is the size of the array $ideas$ and $m$ is the average length of the strings. @@ -342,7 +342,10 @@ class Solution { intersect++; } } - res += 2 * (suffixes[i].size - intersect) * (suffixes[j].size - intersect); + res += + 2 * + (suffixes[i].size - intersect) * + (suffixes[j].size - intersect); } } return res; @@ -354,8 +357,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $n$ is the size of the array $ideas$ and $m$ is the average length of the strings. @@ -489,7 +492,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ -> Where $n$ is the size of the array $ideas$ and $m$ is the average length of the strings. \ No newline at end of file +> Where $n$ is the size of the array $ideas$ and $m$ is the average length of the strings. diff --git a/articles/network-delay-time.md b/articles/network-delay-time.md index ae9fb93fc..c9e76d51f 100644 --- a/articles/network-delay-time.md +++ b/articles/network-delay-time.md @@ -8,17 +8,17 @@ class Solution: adj = defaultdict(list) for u, v, w in times: adj[u].append((v, w)) - + dist = {node: float("inf") for node in range(1, n + 1)} def dfs(node, time): if time >= dist[node]: return - + dist[node] = time for nei, w in adj[node]: dfs(nei, time + w) - + dfs(k, 0) res = max(dist.values()) return res if res < float('inf') else -1 @@ -29,7 +29,7 @@ public class Solution { public int networkDelayTime(int[][] times, int n, int k) { Map> adj = new HashMap<>(); for (int[] time : times) { - adj.computeIfAbsent(time[0], + adj.computeIfAbsent(time[0], x -> new ArrayList<>()).add(new int[]{time[1], time[2]}); } @@ -41,8 +41,8 @@ public class Solution { return res == Integer.MAX_VALUE ? -1 : res; } - private void dfs(int node, int time, - Map> adj, + private void dfs(int node, int time, + Map> adj, Map dist) { if (time >= dist.get(node)) return; dist.put(node, time); @@ -65,14 +65,14 @@ public: vector dist(n + 1, INT_MAX); dfs(k, 0, adj, dist); - + int res = *max_element(dist.begin() + 1, dist.end()); return res == INT_MAX ? -1 : res; } private: - void dfs(int node, int time, - unordered_map>>& adj, + void dfs(int node, int time, + unordered_map>>& adj, vector& dist) { if (time >= dist[node]) return; dist[node] = time; @@ -106,7 +106,7 @@ class Solution { for (const [nei, w] of adj[node]) { dfs(nei, time + w); } - } + }; dfs(k, 0); const res = Math.max(...dist.slice(1)); @@ -134,8 +134,8 @@ public class Solution { return res == int.MaxValue ? -1 : res; } - private void Dfs(int node, int time, - Dictionary> adj, + private void Dfs(int node, int time, + Dictionary> adj, Dictionary dist) { if (time >= dist[node]) return; dist[node] = time; @@ -234,7 +234,7 @@ class Solution { if time >= dist[node]! { return } - + dist[node] = time if let neighbors = adj[node] { for (nei, w) in neighbors { @@ -254,8 +254,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V * E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V * E)$ +- Space complexity: $O(V + E)$ > Where $V$ is the number of vertices and $E$ is the number of edges. @@ -270,17 +270,17 @@ class Solution: def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: inf = float('inf') dist = [[inf] * n for _ in range(n)] - + for u, v, w in times: dist[u-1][v-1] = w for i in range(n): dist[i][i] = 0 - + for mid in range(n): for i in range(n): for j in range(n): dist[i][j] = min(dist[i][j], dist[i][mid] + dist[mid][j]) - + res = max(dist[k-1]) return res if res < inf else -1 ``` @@ -290,23 +290,23 @@ public class Solution { public int networkDelayTime(int[][] times, int n, int k) { int inf = Integer.MAX_VALUE / 2; int[][] dist = new int[n][n]; - + for (int i = 0; i < n; i++) { Arrays.fill(dist[i], inf); dist[i][i] = 0; } - + for (int[] time : times) { int u = time[0] - 1, v = time[1] - 1, w = time[2]; dist[u][v] = w; } - + for (int mid = 0; mid < n; mid++) for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) - dist[i][j] = Math.min(dist[i][j], + dist[i][j] = Math.min(dist[i][j], dist[i][mid] + dist[mid][j]); - + int res = Arrays.stream(dist[k-1]).max().getAsInt(); return res == inf ? -1 : res; } @@ -319,21 +319,21 @@ public: int networkDelayTime(vector>& times, int n, int k) { int inf = INT_MAX / 2; vector> dist(n, vector(n, inf)); - + for (int i = 0; i < n; i++) dist[i][i] = 0; - + for (auto& time : times) { int u = time[0] - 1, v = time[1] - 1, w = time[2]; dist[u][v] = w; } - + for (int mid = 0; mid < n; mid++) for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) - dist[i][j] = min(dist[i][j], + dist[i][j] = min(dist[i][j], dist[i][mid] + dist[mid][j]); - + int res = *max_element(dist[k-1].begin(), dist[k-1].end()); return res == inf ? -1 : res; } @@ -350,23 +350,24 @@ class Solution { */ networkDelayTime(times, n, k) { const inf = Infinity; - const dist = Array.from({ length: n }, () => - Array(n).fill(inf)); - + const dist = Array.from({ length: n }, () => Array(n).fill(inf)); + for (let i = 0; i < n; i++) { dist[i][i] = 0; } - + for (const [u, v, w] of times) { dist[u - 1][v - 1] = w; } - + for (let mid = 0; mid < n; mid++) for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) - dist[i][j] = Math.min(dist[i][j], - dist[i][mid] + dist[mid][j]); - + dist[i][j] = Math.min( + dist[i][j], + dist[i][mid] + dist[mid][j], + ); + const res = Math.max(...dist[k - 1]); return res === inf ? -1 : res; } @@ -378,24 +379,24 @@ public class Solution { public int NetworkDelayTime(int[][] times, int n, int k) { int inf = int.MaxValue / 2; int[,] dist = new int[n, n]; - + for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dist[i, j] = i == j ? 0 : inf; } } - + foreach (var time in times) { int u = time[0] - 1, v = time[1] - 1, w = time[2]; dist[u, v] = w; } - + for (int mid = 0; mid < n; mid++) for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) - dist[i, j] = Math.Min(dist[i, j], + dist[i, j] = Math.Min(dist[i, j], dist[i, mid] + dist[mid, j]); - + int res = Enumerable.Range(0, n).Select(i => dist[k-1, i]).Max(); return res == inf ? -1 : res; } @@ -489,7 +490,7 @@ class Solution { func networkDelayTime(_ times: [[Int]], _ n: Int, _ k: Int) -> Int { let inf = Int.max / 2 var dist = Array(repeating: Array(repeating: inf, count: n), count: n) - + for time in times { let u = time[0] - 1, v = time[1] - 1, w = time[2] dist[u][v] = w @@ -516,8 +517,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V ^ 3)$ -* Space complexity: $O(V ^ 2)$ +- Time complexity: $O(V ^ 3)$ +- Space complexity: $O(V ^ 2)$ > Where $V$ is the number of vertices. @@ -635,7 +636,7 @@ public class Solution { func networkDelayTime(times [][]int, n int, k int) int { dist := make([]int, n) for i := range dist { - dist[i] = 1 << 31 - 1 + dist[i] = 1 << 31 - 1 } dist[k-1] = 0 @@ -713,8 +714,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V * E)$ -* Space complexity: $O(V)$ +- Time complexity: $O(V * E)$ +- Space complexity: $O(V)$ > Where $V$ is the number of vertices and $E$ is the number of edges. @@ -730,7 +731,7 @@ class Solution: adj = defaultdict(list) for u, v, w in times: adj[u].append((v, w)) - + dist = {node: float("inf") for node in range(1, n + 1)} q = deque([(k, 0)]) dist[k] = 0 @@ -759,7 +760,7 @@ public class Solution { Map dist = new HashMap<>(); for (int i = 1; i <= n; i++) dist.put(i, Integer.MAX_VALUE); dist.put(k, 0); - + Queue q = new LinkedList<>(); q.offer(new int[] {k, 0}); @@ -792,7 +793,7 @@ public: for (const auto& time : times) { adj[time[0]].emplace_back(time[1], time[2]); } - + unordered_map dist; for (int i = 1; i <= n; ++i) dist[i] = INT_MAX; dist[k] = 0; @@ -867,7 +868,7 @@ public class Solution { foreach (var time in times) { adj[time[0]].Add(new int[] {time[1], time[2]}); } - + var dist = new Dictionary(); for (int i = 1; i <= n; i++) dist[i] = int.MaxValue; dist[k] = 0; @@ -889,7 +890,7 @@ public class Solution { } int res = 0; - foreach (var time in dist.Values) { + foreach (var time in dist.Values) { res = Math.Max(res, time); } return res == int.MaxValue ? -1 : res; @@ -1017,8 +1018,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ in average case, $O(V * E)$ in worst case. -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ in average case, $O(V * E)$ in worst case. +- Space complexity: $O(V + E)$ > Where $V$ is the number of vertices and $E$ is the number of edges. @@ -1056,7 +1057,7 @@ public class Solution { public int networkDelayTime(int[][] times, int n, int k) { Map> edges = new HashMap<>(); for (int[] time : times) { - edges.computeIfAbsent(time[0], + edges.computeIfAbsent(time[0], key -> new ArrayList<>()).add(new int[]{time[1], time[2]}); } @@ -1150,7 +1151,7 @@ class Solution { edges.get(u).push([v, w]); } - const minHeap = new MinPriorityQueue(entry => entry[0]); + const minHeap = new MinPriorityQueue((entry) => entry[0]); minHeap.enqueue([0, k]); const visit = new Set(); @@ -1353,7 +1354,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(E \log V)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(E \log V)$ +- Space complexity: $O(V + E)$ -> Where $V$ is the number of vertices and $E$ is the number of edges. \ No newline at end of file +> Where $V$ is the number of vertices and $E$ is the number of edges. diff --git a/articles/new-21-game.md b/articles/new-21-game.md index e65fcd1da..5d0bb1eb2 100644 --- a/articles/new-21-game.md +++ b/articles/new-21-game.md @@ -6,20 +6,20 @@ class Solution: def new21Game(self, n: int, k: int, maxPts: int) -> float: cache = {} - + def dfs(score): if score >= k: return 1 if score <= n else 0 if score in cache: return cache[score] - + prob = 0 for i in range(1, maxPts + 1): prob += dfs(score + i) cache[score] = prob / maxPts return cache[score] - + return dfs(0) ``` @@ -120,8 +120,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(k * m)$ -* Space complexity: $O(k)$ +- Time complexity: $O(k * m)$ +- Space complexity: $O(k)$ > Where $k$ is the threshold score, $m$ is the maximum points per draw and $n$ is the upper bound on score. @@ -135,7 +135,7 @@ class Solution { class Solution: def new21Game(self, n: int, k: int, maxPts: int) -> float: cache = {} - + def dfs(score): if score == k - 1: return min(n - k + 1, maxPts) / maxPts @@ -143,14 +143,14 @@ class Solution: return 0 if score >= k: return 1.0 - + if score in cache: return cache[score] - + cache[score] = dfs(score + 1) cache[score] -= (dfs(score + 1 + maxPts) - dfs(score + 1)) / maxPts return cache[score] - + return dfs(0) ``` @@ -257,8 +257,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(k + m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(k + m)$ +- Space complexity: $O(n)$ > Where $k$ is the threshold score, $m$ is the maximum points per draw and $n$ is the upper bound on score. @@ -365,8 +365,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n)$ > Where $k$ is the threshold score, $m$ is the maximum points per draw and $n$ is the upper bound on score. @@ -381,11 +381,11 @@ class Solution: def new21Game(self, n: int, k: int, maxPts: int) -> float: if k == 0: return 1.0 - + windowSum = 0 for i in range(k, k + maxPts): windowSum += 1 if i <= n else 0 - + dp = {} for i in range(k - 1, -1, -1): dp[i] = windowSum / maxPts @@ -459,14 +459,14 @@ class Solution { } let windowSum = 0.0; for (let i = k; i < k + maxPts; i++) { - windowSum += (i <= n) ? 1.0 : 0.0; + windowSum += i <= n ? 1.0 : 0.0; } let dp = {}; for (let i = k - 1; i >= 0; i--) { dp[i] = windowSum / maxPts; let remove = 0.0; if (i + maxPts <= n) { - remove = (dp[i + maxPts] !== undefined) ? dp[i + maxPts] : 1.0; + remove = dp[i + maxPts] !== undefined ? dp[i + maxPts] : 1.0; } windowSum += dp[i] - remove; } @@ -479,7 +479,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(k + m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(k + m)$ +- Space complexity: $O(n)$ -> Where $k$ is the threshold score, $m$ is the maximum points per draw and $n$ is the upper bound on score. \ No newline at end of file +> Where $k$ is the threshold score, $m$ is the maximum points per draw and $n$ is the upper bound on score. diff --git a/articles/next-greater-element-i.md b/articles/next-greater-element-i.md index b81ca977a..08db5bc94 100644 --- a/articles/next-greater-element-i.md +++ b/articles/next-greater-element-i.md @@ -91,8 +91,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(1)$ > Where $m$ is the size of the array $nums1$ and $n$ is the size of the array $nums2$. @@ -126,7 +126,7 @@ public class Solution { for (int i = 0; i < nums1.length; i++) { nums1Idx.put(nums1[i], i); } - + int[] res = new int[nums1.length]; Arrays.fill(res, -1); @@ -185,7 +185,7 @@ class Solution { nextGreaterElement(nums1, nums2) { const nums1Idx = new Map(); nums1.forEach((num, i) => nums1Idx.set(num, i)); - + const res = new Array(nums1.length).fill(-1); for (let i = 0; i < nums2.length; i++) { @@ -209,8 +209,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m)$ > Where $m$ is the size of the array $nums1$ and $n$ is the size of the array $nums2$. @@ -278,7 +278,7 @@ public: vector res(nums1.size(), -1); stack stack; - + for (int num : nums2) { while (!stack.empty() && num > stack.top()) { int val = stack.top(); @@ -305,7 +305,7 @@ class Solution { nextGreaterElement(nums1, nums2) { const nums1Idx = new Map(); nums1.forEach((num, i) => nums1Idx.set(num, i)); - + const res = new Array(nums1.length).fill(-1); const stack = []; @@ -328,7 +328,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n)$ -* Space complexity: $O(m)$ +- Time complexity: $O(m + n)$ +- Space complexity: $O(m)$ -> Where $m$ is the size of the array $nums1$ and $n$ is the size of the array $nums2$. \ No newline at end of file +> Where $m$ is the size of the array $nums1$ and $n$ is the size of the array $nums2$. diff --git a/articles/next-permutation.md b/articles/next-permutation.md index 29ed3afeb..664cf3c25 100644 --- a/articles/next-permutation.md +++ b/articles/next-permutation.md @@ -16,7 +16,7 @@ class Solution: for j in range(len(nums)): nums[j] = nextP[j] break - + def permute(self, nums: List[int]) -> List[List[int]]: res = [] @@ -25,14 +25,14 @@ class Solution: if i == len(nums): res.append(nums.copy()) return - + for j in range(i, len(nums)): if j > i and nums[i] == nums[j]: continue - + nums[i], nums[j] = nums[j], nums[i] dfs(i + 1) - + for j in range(len(nums) - 1, i, -1): nums[j], nums[i] = nums[i], nums[j] @@ -144,7 +144,7 @@ class Solution { * @return {void} Do not return anything, modify nums in-place instead. */ nextPermutation(nums) { - const permute = arr => { + const permute = (arr) => { const res = []; arr.sort((a, b) => a - b); const used = Array(arr.length).fill(false); @@ -156,7 +156,8 @@ class Solution { } for (let i = 0; i < arr.length; i++) { if (used[i]) continue; - if (i > 0 && arr[i] === arr[i - 1] && !used[i - 1]) continue; + if (i > 0 && arr[i] === arr[i - 1] && !used[i - 1]) + continue; used[i] = true; path.push(arr[i]); dfs(); @@ -247,8 +248,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n! * n)$ -* Space complexity: $O(n! * n)$ +- Time complexity: $O(n! * n)$ +- Space complexity: $O(n! * n)$ --- @@ -352,7 +353,8 @@ class Solution { } [nums[i], nums[j]] = [nums[j], nums[i]]; } - let l = i + 1, r = n - 1; + let l = i + 1, + r = n - 1; while (l < r) { [nums[l], nums[r]] = [nums[r], nums[l]]; l++; @@ -395,5 +397,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/non-cyclical-number.md b/articles/non-cyclical-number.md index 6b3053011..272eed2ca 100644 --- a/articles/non-cyclical-number.md +++ b/articles/non-cyclical-number.md @@ -240,8 +240,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(\log n)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(\log n)$ --- @@ -259,7 +259,7 @@ class Solution: fast = self.sumOfSquares(fast) slow = self.sumOfSquares(slow) return True if fast == 1 else False - + def sumOfSquares(self, n: int) -> int: output = 0 @@ -466,8 +466,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ --- @@ -480,7 +480,7 @@ class Solution: def isHappy(self, n: int) -> bool: slow, fast = n, self.sumOfSquares(n) power = lam = 1 - + while slow != fast: if power == lam: slow = fast @@ -489,7 +489,7 @@ class Solution: fast = self.sumOfSquares(fast) lam += 1 return True if fast == 1 else False - + def sumOfSquares(self, n: int) -> int: output = 0 @@ -571,7 +571,8 @@ class Solution { isHappy(n) { let slow = n; let fast = this.sumOfSquares(n); - let power = 1, lam = 1; + let power = 1, + lam = 1; while (slow !== fast) { if (power === lam) { @@ -732,5 +733,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ diff --git a/articles/non-decreasing-array.md b/articles/non-decreasing-array.md index aed007f6c..abdc4ad99 100644 --- a/articles/non-decreasing-array.md +++ b/articles/non-decreasing-array.md @@ -101,5 +101,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/non-overlapping-intervals.md b/articles/non-overlapping-intervals.md index 60f0b89a1..3833dfe87 100644 --- a/articles/non-overlapping-intervals.md +++ b/articles/non-overlapping-intervals.md @@ -6,7 +6,7 @@ class Solution: def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: intervals.sort() - + def dfs(i, prev): if i == len(intervals): return 0 @@ -14,7 +14,7 @@ class Solution: if prev == -1 or intervals[prev][1] <= intervals[i][0]: res = max(res, 1 + dfs(i + 1, i)) return res - + return len(intervals) - dfs(0, -1) ``` @@ -64,7 +64,7 @@ class Solution { */ eraseOverlapIntervals(intervals) { intervals.sort((a, b) => a[0] - b[0]); - + const dfs = (i, prev) => { if (i === intervals.length) return 0; let res = dfs(i + 1, prev); @@ -173,8 +173,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ --- @@ -210,9 +210,9 @@ public class Solution { public int eraseOverlapIntervals(int[][] intervals) { Arrays.sort(intervals, (a, b) -> Integer.compare(a[1], b[1])); int n = intervals.length; - memo = new int[n]; + memo = new int[n]; Arrays.fill(memo, -1); - + int maxNonOverlapping = dfs(intervals, 0); return n - maxNonOverlapping; } @@ -241,7 +241,7 @@ public: return a[1] < b[1]; }); int n = intervals.size(); - vector memo(n, -1); + vector memo(n, -1); int maxNonOverlapping = dfs(intervals, 0, memo); return n - maxNonOverlapping; @@ -273,7 +273,7 @@ class Solution { eraseOverlapIntervals(intervals) { intervals.sort((a, b) => a[1] - b[1]); const n = intervals.length; - let memo = new Array(n).fill(-1); + let memo = new Array(n).fill(-1); const dfs = (i) => { if (i >= n) return 0; @@ -302,7 +302,7 @@ public class Solution { public int EraseOverlapIntervals(int[][] intervals) { Array.Sort(intervals, (a, b) => a[1].CompareTo(b[1])); int n = intervals.Length; - memo = new int[n]; + memo = new int[n]; Array.Fill(memo, -1); int maxNonOverlapping = Dfs(intervals, 0); @@ -419,8 +419,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -433,15 +433,15 @@ class Solution: def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: intervals.sort(key=lambda x: x[1]) n = len(intervals) - dp = [0] * n + dp = [0] * n for i in range(n): - dp[i] = 1 + dp[i] = 1 for j in range(i): - if intervals[j][1] <= intervals[i][0]: + if intervals[j][1] <= intervals[i][0]: dp[i] = max(dp[i], 1 + dp[j]) - max_non_overlapping = max(dp) + max_non_overlapping = max(dp) return n - max_non_overlapping ``` @@ -450,18 +450,18 @@ public class Solution { public int eraseOverlapIntervals(int[][] intervals) { Arrays.sort(intervals, (a, b) -> Integer.compare(a[1], b[1])); int n = intervals.length; - int[] dp = new int[n]; + int[] dp = new int[n]; for (int i = 0; i < n; i++) { - dp[i] = 1; + dp[i] = 1; for (int j = 0; j < i; j++) { - if (intervals[j][1] <= intervals[i][0]) { + if (intervals[j][1] <= intervals[i][0]) { dp[i] = Math.max(dp[i], 1 + dp[j]); } } } - int maxNonOverlapping = Arrays.stream(dp).max().getAsInt(); + int maxNonOverlapping = Arrays.stream(dp).max().getAsInt(); return n - maxNonOverlapping; } } @@ -475,18 +475,18 @@ public: return a[1] < b[1]; }); int n = intervals.size(); - vector dp(n, 0); + vector dp(n, 0); for (int i = 0; i < n; i++) { - dp[i] = 1; + dp[i] = 1; for (int j = 0; j < i; j++) { - if (intervals[j][1] <= intervals[i][0]) { + if (intervals[j][1] <= intervals[i][0]) { dp[i] = max(dp[i], 1 + dp[j]); } } } - int maxNonOverlapping = *max_element(dp.begin(), dp.end()); + int maxNonOverlapping = *max_element(dp.begin(), dp.end()); return n - maxNonOverlapping; } }; @@ -501,18 +501,18 @@ class Solution { eraseOverlapIntervals(intervals) { intervals.sort((a, b) => a[1] - b[1]); const n = intervals.length; - const dp = new Array(n).fill(0); + const dp = new Array(n).fill(0); for (let i = 0; i < n; i++) { - dp[i] = 1; + dp[i] = 1; for (let j = 0; j < i; j++) { - if (intervals[j][1] <= intervals[i][0]) { + if (intervals[j][1] <= intervals[i][0]) { dp[i] = Math.max(dp[i], 1 + dp[j]); } } } - const maxNonOverlapping = Math.max(...dp); + const maxNonOverlapping = Math.max(...dp); return n - maxNonOverlapping; } } @@ -523,12 +523,12 @@ public class Solution { public int EraseOverlapIntervals(int[][] intervals) { Array.Sort(intervals, (a, b) => a[1].CompareTo(b[1])); int n = intervals.Length; - int[] dp = new int[n]; + int[] dp = new int[n]; for (int i = 0; i < n; i++) { - dp[i] = 1; + dp[i] = 1; for (int j = 0; j < i; j++) { - if (intervals[j][1] <= intervals[i][0]) { + if (intervals[j][1] <= intervals[i][0]) { dp[i] = Math.Max(dp[i], 1 + dp[j]); } } @@ -537,7 +537,7 @@ public class Solution { int maxNonOverlapping = 0; foreach (var count in dp) { maxNonOverlapping = Math.Max(maxNonOverlapping, count); - } + } return n - maxNonOverlapping; } } @@ -626,8 +626,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -756,7 +756,7 @@ class Solution { } } return l; - } + }; for (let i = 1; i < n; i++) { const idx = bs(i, intervals[i][0]); @@ -810,7 +810,7 @@ func eraseOverlapIntervals(intervals [][]int) int { sort.Slice(intervals, func(i, j int) bool { return intervals[i][1] < intervals[j][1] }) - + n := len(intervals) dp := make([]int, n) dp[0] = 1 @@ -921,8 +921,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -936,7 +936,7 @@ class Solution: intervals.sort() res = 0 prevEnd = intervals[0][1] - + for start, end in intervals[1:]: if start >= prevEnd: prevEnd = end @@ -952,7 +952,7 @@ public class Solution { Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0])); int res = 0; int prevEnd = intervals[0][1]; - + for (int i = 1; i < intervals.length; i++) { int start = intervals[i][0]; int end = intervals[i][1]; @@ -1023,7 +1023,7 @@ public class Solution { Array.Sort(intervals, (a, b) => a[0].CompareTo(b[0])); int res = 0; int prevEnd = intervals[0][1]; - + for (int i = 1; i < intervals.Length; i++) { int start = intervals[i][0]; int end = intervals[i][1]; @@ -1095,10 +1095,10 @@ class Solution { func eraseOverlapIntervals(_ intervals: [[Int]]) -> Int { var intervals = intervals intervals.sort { $0[0] < $1[0] } - + var res = 0 var prevEnd = intervals[0][1] - + for i in 1.. Integer.compare(a[1], b[1])); int res = 0; int prevEnd = intervals[0][1]; - + for (int i = 1; i < intervals.length; i++) { int start = intervals[i][0]; int end = intervals[i][1]; @@ -1220,7 +1220,7 @@ public class Solution { Array.Sort(intervals, (a, b) => a[1].CompareTo(b[1])); int res = 0; int prevEnd = intervals[0][1]; - + for (int i = 1; i < intervals.Length; i++) { int start = intervals[i][0]; int end = intervals[i][1]; @@ -1280,10 +1280,10 @@ class Solution { func eraseOverlapIntervals(_ intervals: [[Int]]) -> Int { var intervals = intervals intervals.sort { $0[1] < $1[1] } - + var prevEnd = intervals[0][1] var res = 0 - + for i in 1.. intervals[i][0] { res += 1 @@ -1291,7 +1291,7 @@ class Solution { prevEnd = intervals[i][1] } } - + return res } } @@ -1301,5 +1301,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. diff --git a/articles/number-of-closed-islands.md b/articles/number-of-closed-islands.md index d3ab68940..27bcab713 100644 --- a/articles/number-of-closed-islands.md +++ b/articles/number-of-closed-islands.md @@ -36,7 +36,7 @@ public class Solution { private int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; private boolean[][] visit; private int ROWS, COLS; - + public int closedIsland(int[][] grid) { ROWS = grid.length; COLS = grid[0].length; @@ -129,9 +129,12 @@ class Solution { * @return {number} */ closedIsland(grid) { - const ROWS = grid.length, COLS = grid[0].length; + const ROWS = grid.length, + COLS = grid[0].length; const directions = [0, 1, 0, -1, 0]; - const visit = Array.from({ length: ROWS }, () => Array(COLS).fill(false)); + const visit = Array.from({ length: ROWS }, () => + Array(COLS).fill(false), + ); const dfs = (r, c) => { if (r < 0 || c < 0 || r === ROWS || c === COLS) return false; @@ -164,8 +167,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns in the given grid. @@ -297,11 +300,13 @@ class Solution { * @return {number} */ closedIsland(grid) { - const ROWS = grid.length, COLS = grid[0].length; + const ROWS = grid.length, + COLS = grid[0].length; const directions = [0, 1, 0, -1, 0]; const dfs = (r, c) => { - if (r < 0 || c < 0 || r === ROWS || c === COLS || grid[r][c] === 1) return; + if (r < 0 || c < 0 || r === ROWS || c === COLS || grid[r][c] === 1) + return; grid[r][c] = 1; for (let d = 0; d < 4; d++) { dfs(r + directions[d], c + directions[d + 1]); @@ -335,8 +340,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns in the given grid. @@ -370,7 +375,7 @@ class Solution: continue visit.add((nx, ny)) q.append((nx, ny)) - + return is_closed for r in range(ROWS): @@ -484,9 +489,17 @@ class Solution { * @return {number} */ closedIsland(grid) { - const ROWS = grid.length, COLS = grid[0].length; - const directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]; - const visit = Array.from({ length: ROWS }, () => Array(COLS).fill(false)); + const ROWS = grid.length, + COLS = grid[0].length; + const directions = [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ]; + const visit = Array.from({ length: ROWS }, () => + Array(COLS).fill(false), + ); let res = 0; const bfs = (r, c) => { @@ -497,7 +510,8 @@ class Solution { while (!q.isEmpty()) { const [x, y] = q.pop(); for (const [dx, dy] of directions) { - const nx = x + dx, ny = y + dy; + const nx = x + dx, + ny = y + dy; if (nx < 0 || ny < 0 || nx >= ROWS || ny >= COLS) { isClosed = false; continue; @@ -526,8 +540,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns in the given grid. @@ -566,7 +580,7 @@ class Solution: N = ROWS * COLS def index(r, c): return r * COLS + c - + dsu = DSU(N) directions = [0, 1, 0, -1, 0] for r in range(ROWS): @@ -630,7 +644,7 @@ public class Solution { public int closedIsland(int[][] grid) { int ROWS = grid.length, COLS = grid[0].length; int N = ROWS * COLS; - + DSU dsu = new DSU(N); int[] directions = {0, 1, 0, -1, 0}; @@ -705,7 +719,7 @@ public: int closedIsland(vector>& grid) { int ROWS = grid.size(), COLS = grid[0].size(); int N = ROWS * COLS; - + DSU dsu(N); int directions[5] = {0, 1, 0, -1, 0}; @@ -769,7 +783,8 @@ class DSU { * @return {boolean} */ union(u, v) { - let pu = this.find(u), pv = this.find(v); + let pu = this.find(u), + pv = this.find(v); if (pu === pv) return false; if (this.size[pu] >= this.size[pv]) { this.size[pu] += this.size[pv]; @@ -788,9 +803,10 @@ class Solution { * @return {number} */ closedIsland(grid) { - const ROWS = grid.length, COLS = grid[0].length; + const ROWS = grid.length, + COLS = grid[0].length; const N = ROWS * COLS; - + const dsu = new DSU(N); const directions = [0, 1, 0, -1, 0]; @@ -798,7 +814,8 @@ class Solution { for (let c = 0; c < COLS; c++) { if (grid[r][c] === 0) { for (let d = 0; d < 4; d++) { - let nr = r + directions[d], nc = c + directions[d + 1]; + let nr = r + directions[d], + nc = c + directions[d + 1]; if (nr < 0 || nc < 0 || nr === ROWS || nc === COLS) { dsu.union(N, r * COLS + c); } else if (grid[nr][nc] === 0) { @@ -809,7 +826,8 @@ class Solution { } } - let res = 0, rootN = dsu.find(N); + let res = 0, + rootN = dsu.find(N); for (let r = 0; r < ROWS; r++) { for (let c = 0; c < COLS; c++) { if (grid[r][c] === 0) { @@ -830,7 +848,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ -> Where $m$ is the number of rows and $n$ is the number of columns in the given grid. \ No newline at end of file +> Where $m$ is the number of rows and $n$ is the number of columns in the given grid. diff --git a/articles/number-of-dice-rolls-with-target-sum.md b/articles/number-of-dice-rolls-with-target-sum.md index 442065a4a..e5dda8bfe 100644 --- a/articles/number-of-dice-rolls-with-target-sum.md +++ b/articles/number-of-dice-rolls-with-target-sum.md @@ -109,8 +109,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(k ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(k ^ n)$ +- Space complexity: $O(n)$ > Where $n$ is the number of dices, $k$ is the number of faces each dice have, and $t$ is the target value. @@ -224,7 +224,9 @@ class Solution { */ numRollsToTarget(n, k, target) { const MOD = 1e9 + 7; - const dp = Array.from({ length: n + 1 }, () => Array(target + 1).fill(-1)); + const dp = Array.from({ length: n + 1 }, () => + Array(target + 1).fill(-1), + ); const count = (n, target) => { if (n === 0) { @@ -253,8 +255,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * t * k)$ -* Space complexity: $O(n * t)$ +- Time complexity: $O(n * t * k)$ +- Space complexity: $O(n * t)$ > Where $n$ is the number of dices, $k$ is the number of faces each dice have, and $t$ is the target value. @@ -330,7 +332,9 @@ class Solution { */ numRollsToTarget(n, k, target) { const MOD = 1e9 + 7; - const dp = Array.from({ length: n + 1 }, () => Array(target + 1).fill(0)); + const dp = Array.from({ length: n + 1 }, () => + Array(target + 1).fill(0), + ); dp[0][0] = 1; for (let i = 1; i <= n; i++) { @@ -350,8 +354,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * t * k)$ -* Space complexity: $O(n * t)$ +- Time complexity: $O(n * t * k)$ +- Space complexity: $O(n * t)$ > Where $n$ is the number of dices, $k$ is the number of faces each dice have, and $t$ is the target value. @@ -455,8 +459,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * t * k)$ -* Space complexity: $O(t)$ +- Time complexity: $O(n * t * k)$ +- Space complexity: $O(t)$ > Where $n$ is the number of dices, $k$ is the number of faces each dice have, and $t$ is the target value. @@ -567,7 +571,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * t * k)$ -* Space complexity: $O(t)$ +- Time complexity: $O(n * t * k)$ +- Space complexity: $O(t)$ -> Where $n$ is the number of dices, $k$ is the number of faces each dice have, and $t$ is the target value. \ No newline at end of file +> Where $n$ is the number of dices, $k$ is the number of faces each dice have, and $t$ is the target value. diff --git a/articles/number-of-enclaves.md b/articles/number-of-enclaves.md index a5da06e58..8e153b1ac 100644 --- a/articles/number-of-enclaves.md +++ b/articles/number-of-enclaves.md @@ -10,8 +10,8 @@ class Solution: # Return num of land cells def dfs(r, c): - if (r < 0 or c < 0 or - r == ROWS or c == COLS or + if (r < 0 or c < 0 or + r == ROWS or c == COLS or not grid[r][c] or (r, c) in visit): return 0 visit.add((r, c)) @@ -25,7 +25,7 @@ class Solution: for r in range(ROWS): for c in range(COLS): land += grid[r][c] - if (grid[r][c] and (r, c) not in visit and + if (grid[r][c] and (r, c) not in visit and (c in [0, COLS - 1] or r in [0, ROWS - 1])): borderLand += dfs(r, c) @@ -37,7 +37,7 @@ public class Solution { private int ROWS, COLS; private boolean[][] visit; private int[][] direct = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; - + public int numEnclaves(int[][] grid) { this.ROWS = grid.length; this.COLS = grid[0].length; @@ -47,7 +47,7 @@ public class Solution { for (int r = 0; r < ROWS; r++) { for (int c = 0; c < COLS; c++) { land += grid[r][c]; - if (grid[r][c] == 1 && !visit[r][c] && + if (grid[r][c] == 1 && !visit[r][c] && (r == 0 || r == ROWS - 1 || c == 0 || c == COLS - 1)) { borderLand += dfs(r, c, grid); } @@ -57,7 +57,7 @@ public class Solution { } private int dfs(int r, int c, int[][] grid) { - if (r < 0 || c < 0 || r == ROWS || c == COLS || + if (r < 0 || c < 0 || r == ROWS || c == COLS || grid[r][c] == 0 || visit[r][c]) { return 0; } @@ -87,7 +87,7 @@ public: for (int r = 0; r < ROWS; r++) { for (int c = 0; c < COLS; c++) { land += grid[r][c]; - if (grid[r][c] == 1 && !visit[r][c] && + if (grid[r][c] == 1 && !visit[r][c] && (r == 0 || r == ROWS - 1 || c == 0 || c == COLS - 1)) { borderLand += dfs(r, c, grid); } @@ -98,7 +98,7 @@ public: private: int dfs(int r, int c, vector>& grid) { - if (r < 0 || c < 0 || r == ROWS || c == COLS || + if (r < 0 || c < 0 || r == ROWS || c == COLS || grid[r][c] == 0 || visit[r][c]) { return 0; } @@ -119,15 +119,22 @@ class Solution { * @return {number} */ numEnclaves(grid) { - const ROWS = grid.length, COLS = grid[0].length; - const visit = Array.from({ length: ROWS }, () => - Array(COLS).fill(false) + const ROWS = grid.length, + COLS = grid[0].length; + const visit = Array.from({ length: ROWS }, () => + Array(COLS).fill(false), ); const direct = [0, 1, 0, -1, 0]; const dfs = (r, c) => { - if (r < 0 || c < 0 || r === ROWS || c === COLS || - grid[r][c] === 0 || visit[r][c]) { + if ( + r < 0 || + c < 0 || + r === ROWS || + c === COLS || + grid[r][c] === 0 || + visit[r][c] + ) { return 0; } visit[r][c] = true; @@ -138,12 +145,16 @@ class Solution { return res; }; - let land = 0, borderLand = 0; + let land = 0, + borderLand = 0; for (let r = 0; r < ROWS; r++) { for (let c = 0; c < COLS; c++) { land += grid[r][c]; - if (grid[r][c] === 1 && !visit[r][c] && - (r === 0 || r === ROWS - 1 || c === 0 || c === COLS - 1)) { + if ( + grid[r][c] === 1 && + !visit[r][c] && + (r === 0 || r === ROWS - 1 || c === 0 || c === COLS - 1) + ) { borderLand += dfs(r, c); } } @@ -157,8 +168,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns in the given grid. @@ -175,12 +186,12 @@ class Solution: direct = [[0, 1], [0, -1], [1, 0], [-1, 0]] visit = [[False] * COLS for _ in range(ROWS)] q = deque() - + land, borderLand = 0, 0 for r in range(ROWS): for c in range(COLS): land += grid[r][c] - if (grid[r][c] == 1 and + if (grid[r][c] == 1 and (r in [0, ROWS - 1] or c in [0, COLS - 1]) ): q.append((r, c)) @@ -191,7 +202,7 @@ class Solution: borderLand += 1 for dr, dc in direct: nr, nc = r + dr, c + dc - if (0 <= nr < ROWS and 0 <= nc < COLS and + if (0 <= nr < ROWS and 0 <= nc < COLS and grid[nr][nc] == 1 and not visit[nr][nc] ): q.append((nr, nc)) @@ -212,7 +223,7 @@ public class Solution { for (int r = 0; r < ROWS; r++) { for (int c = 0; c < COLS; c++) { land += grid[r][c]; - if (grid[r][c] == 1 && (r == 0 || r == ROWS - 1 || + if (grid[r][c] == 1 && (r == 0 || r == ROWS - 1 || c == 0 || c == COLS - 1)) { q.offer(new int[]{r, c}); visit[r][c] = true; @@ -227,7 +238,7 @@ public class Solution { for (int[] d : direct) { int nr = r + d[0], nc = c + d[1]; - if (nr >= 0 && nc >= 0 && nr < ROWS && nc < COLS && + if (nr >= 0 && nc >= 0 && nr < ROWS && nc < COLS && grid[nr][nc] == 1 && !visit[nr][nc]) { q.offer(new int[]{nr, nc}); visit[nr][nc] = true; @@ -256,7 +267,7 @@ public: for (int r = 0; r < ROWS; r++) { for (int c = 0; c < COLS; c++) { land += grid[r][c]; - if (grid[r][c] == 1 && !visit[r][c] && + if (grid[r][c] == 1 && !visit[r][c] && (r == 0 || r == ROWS - 1 || c == 0 || c == COLS - 1)) { borderLand += dfs(r, c, grid); } @@ -267,7 +278,7 @@ public: private: int dfs(int r, int c, vector>& grid) { - if (r < 0 || c < 0 || r == ROWS || c == COLS || + if (r < 0 || c < 0 || r == ROWS || c == COLS || grid[r][c] == 0 || visit[r][c]) { return 0; } @@ -288,19 +299,23 @@ class Solution { * @return {number} */ numEnclaves(grid) { - const ROWS = grid.length, COLS = grid[0].length; + const ROWS = grid.length, + COLS = grid[0].length; const direct = [0, 1, 0, -1, 0]; - const visit = Array.from({ length: ROWS }, () => - Array(COLS).fill(false) + const visit = Array.from({ length: ROWS }, () => + Array(COLS).fill(false), ); const q = new Queue(); - let land = 0, borderLand = 0; + let land = 0, + borderLand = 0; for (let r = 0; r < ROWS; r++) { for (let c = 0; c < COLS; c++) { land += grid[r][c]; - if (grid[r][c] === 1 && (r === 0 || r === ROWS - 1 || - c === 0 || c === COLS - 1)) { + if ( + grid[r][c] === 1 && + (r === 0 || r === ROWS - 1 || c === 0 || c === COLS - 1) + ) { q.push([r, c]); visit[r][c] = true; } @@ -311,9 +326,16 @@ class Solution { let [r, c] = q.pop(); borderLand++; for (let d = 0; d < 4; d++) { - let nr = r + direct[d], nc = c + direct[d + 1]; - if (nr >= 0 && nc >= 0 && nr < ROWS && nc < COLS && - grid[nr][nc] === 1 && !visit[nr][nc]) { + let nr = r + direct[d], + nc = c + direct[d + 1]; + if ( + nr >= 0 && + nc >= 0 && + nr < ROWS && + nc < COLS && + grid[nr][nc] === 1 && + !visit[nr][nc] + ) { q.push([nr, nc]); visit[nr][nc] = true; } @@ -329,8 +351,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns in the given grid. @@ -549,7 +571,8 @@ class DSU { * @return {boolean} */ union(u, v) { - let pu = this.find(u), pv = this.find(v); + let pu = this.find(u), + pv = this.find(v); if (pu === pv) return false; if (this.size[pu] >= this.size[pv]) { this.size[pu] += this.size[pv]; @@ -568,7 +591,8 @@ class Solution { * @return {number} */ numEnclaves(grid) { - const ROWS = grid.length, COLS = grid[0].length; + const ROWS = grid.length, + COLS = grid[0].length; const N = ROWS * COLS; const dsu = new DSU(N); const directions = [0, 1, 0, -1, 0]; @@ -579,7 +603,8 @@ class Solution { if (grid[r][c] === 0) continue; land++; for (let d = 0; d < 4; d++) { - let nr = r + directions[d], nc = c + directions[d + 1]; + let nr = r + directions[d], + nc = c + directions[d + 1]; if (nr >= 0 && nc >= 0 && nr < ROWS && nc < COLS) { if (grid[nr][nc] === 1) { dsu.union(r * COLS + c, nr * COLS + nc); @@ -601,7 +626,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ -> Where $m$ is the number of rows and $n$ is the number of columns in the given grid. \ No newline at end of file +> Where $m$ is the number of rows and $n$ is the number of columns in the given grid. diff --git a/articles/number-of-flowers-in-full-bloom.md b/articles/number-of-flowers-in-full-bloom.md index 2b60ec927..f11f87559 100644 --- a/articles/number-of-flowers-in-full-bloom.md +++ b/articles/number-of-flowers-in-full-bloom.md @@ -89,8 +89,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m)$ for the output array. +- Time complexity: $O(m * n)$ +- Space complexity: $O(m)$ for the output array. > Where $n$ is the size of the array $flowers$, and $m$ is the size of the array $people$. @@ -109,7 +109,7 @@ class Solution: start = [f[0] for f in flowers] end = [f[1] for f in flowers] - + heapq.heapify(start) heapq.heapify(end) @@ -215,7 +215,7 @@ class Solution { fullBloomFlowers(flowers, people) { const m = people.length; const res = new Array(m).fill(0); - + const sortedPeople = people.map((p, i) => [p, i]); sortedPeople.sort((a, b) => a[0] - b[0]); @@ -248,8 +248,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m \log m + n \log n)$ -* Space complexity: $O(m + n)$ +- Time complexity: $O(m \log m + n \log n)$ +- Space complexity: $O(m + n)$ > Where $n$ is the size of the array $flowers$, and $m$ is the size of the array $people$. @@ -285,13 +285,13 @@ public class Solution { int m = people.length; int[] res = new int[m]; int[][] indexedPeople = new int[m][2]; - + for (int i = 0; i < m; i++) { indexedPeople[i] = new int[]{people[i], i}; } Arrays.sort(indexedPeople, Comparator.comparingInt(a -> a[0])); Arrays.sort(flowers, Comparator.comparingInt(a -> a[0])); - + PriorityQueue endHeap = new PriorityQueue<>(); int j = 0, n = flowers.length; @@ -325,7 +325,7 @@ public: } sort(indexedPeople.begin(), indexedPeople.end()); sort(flowers.begin(), flowers.end()); - + priority_queue, greater> endHeap; int j = 0, n = flowers.size(); @@ -361,7 +361,8 @@ class Solution { flowers.sort((a, b) => a[0] - b[0]); const endHeap = new MinPriorityQueue(); - let j = 0, n = flowers.length; + let j = 0, + n = flowers.length; for (const [p, index] of indexedPeople) { while (j < n && flowers[j][0] <= p) { @@ -382,8 +383,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m \log m + n \log n)$ -* Space complexity: $O(m + n)$ +- Time complexity: $O(m \log m + n \log n)$ +- Space complexity: $O(m + n)$ > Where $n$ is the size of the array $flowers$, and $m$ is the size of the array $people$. @@ -501,7 +502,8 @@ class Solution { * @return {number[]} */ fullBloomFlowers(flowers, people) { - const start = [], end = []; + const start = [], + end = []; for (let f of flowers) { start.push(f[0]); end.push(f[1]); @@ -510,7 +512,9 @@ class Solution { start.sort((a, b) => a - b); end.sort((a, b) => a - b); - let count = 0, i = 0, j = 0; + let count = 0, + i = 0, + j = 0; const peopleIndex = people.map((p, idx) => [p, idx]); peopleIndex.sort((a, b) => a[0] - b[0]); @@ -537,8 +541,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m \log m + n \log n)$ -* Space complexity: $O(m + n)$ +- Time complexity: $O(m \log m + n \log n)$ +- Space complexity: $O(m + n)$ > Where $n$ is the size of the array $flowers$, and $m$ is the size of the array $people$. @@ -605,9 +609,9 @@ public class Solution { class Solution { public: vector fullBloomFlowers(vector>& flowers, vector& people) { - vector> events; + vector> events; for (auto& f : flowers) { - events.emplace_back(f[0], 1); + events.emplace_back(f[0], 1); events.emplace_back(f[1] + 1, -1); } @@ -651,7 +655,8 @@ class Solution { let queries = people.map((p, i) => [p, i]).sort((a, b) => a[0] - b[0]); let res = new Array(people.length).fill(0); - let count = 0, j = 0; + let count = 0, + j = 0; for (let [time, index] of queries) { while (j < events.length && events[j][0] <= time) { count += events[j][1]; @@ -669,7 +674,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m \log m + n \log n)$ -* Space complexity: $O(m + n)$ +- Time complexity: $O(m \log m + n \log n)$ +- Space complexity: $O(m + n)$ -> Where $n$ is the size of the array $flowers$, and $m$ is the size of the array $people$. \ No newline at end of file +> Where $n$ is the size of the array $flowers$, and $m$ is the size of the array $people$. diff --git a/articles/number-of-good-pairs.md b/articles/number-of-good-pairs.md index ea3e819e8..e19097222 100644 --- a/articles/number-of-good-pairs.md +++ b/articles/number-of-good-pairs.md @@ -70,8 +70,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -135,7 +135,7 @@ class Solution { count[num] = (count[num] || 0) + 1; } for (const c of Object.values(count)) { - res += c * (c - 1) / 2; + res += (c * (c - 1)) / 2; } return res; } @@ -146,8 +146,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -217,5 +217,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/number-of-good-paths.md b/articles/number-of-good-paths.md index f0e16529f..2ec0e10ee 100644 --- a/articles/number-of-good-paths.md +++ b/articles/number-of-good-paths.md @@ -160,8 +160,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -329,8 +329,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -555,7 +555,8 @@ class DSU { * @return {boolean} */ union(u, v) { - let pu = this.find(u), pv = this.find(v); + let pu = this.find(u), + pv = this.find(v); if (pu === pv) return false; if (this.size[pu] >= this.size[pv]) { this.size[pu] += this.size[pv]; @@ -592,7 +593,9 @@ class Solution { const dsu = new DSU(n); let res = 0; - for (const [val, nodes] of [...valToIndex.entries()].sort((a, b) => a[0] - b[0])) { + for (const [val, nodes] of [...valToIndex.entries()].sort( + (a, b) => a[0] - b[0], + )) { for (const i of nodes) { for (const nei of adj[i]) { if (vals[nei] <= vals[i]) dsu.union(nei, i); @@ -615,8 +618,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -649,7 +652,7 @@ class DSU: result = self.count[pu] * self.count[pv] self.count[pu] += self.count[pv] return result - + return 0 @@ -714,7 +717,7 @@ public class Solution { DSU dsu = new DSU(n, vals); // Sort edges based on max value of the two nodes - Arrays.sort(edges, + Arrays.sort(edges, Comparator.comparingInt(edge -> Math.max(vals[edge[0]], vals[edge[1]])) ); @@ -789,7 +792,9 @@ class DSU { * @param {number[]} vals */ constructor(n, vals) { - this.parent = Array(n).fill(0).map((_, i) => i); + this.parent = Array(n) + .fill(0) + .map((_, i) => i); this.vals = vals; this.count = Array(n).fill(1); // count of nodes with max value of the component } @@ -811,7 +816,8 @@ class DSU { * @return {number} */ union(u, v) { - let pu = this.find(u), pv = this.find(v); + let pu = this.find(u), + pv = this.find(v); if (pu === pv) { return 0; } @@ -840,8 +846,10 @@ class Solution { let dsu = new DSU(n, vals); // Sort edges based on max value of the two nodes - edges.sort((a, b) => - Math.max(vals[a[0]], vals[a[1]]) - Math.max(vals[b[0]], vals[b[1]]) + edges.sort( + (a, b) => + Math.max(vals[a[0]], vals[a[1]]) - + Math.max(vals[b[0]], vals[b[1]]), ); let res = n; // Each node alone is a good path @@ -857,5 +865,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n\log n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n\log n)$ +- Space complexity: $O(n)$ diff --git a/articles/number-of-laser-beams-in-a-bank.md b/articles/number-of-laser-beams-in-a-bank.md index 598d7fbb2..f5d2bd0a8 100644 --- a/articles/number-of-laser-beams-in-a-bank.md +++ b/articles/number-of-laser-beams-in-a-bank.md @@ -104,7 +104,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(m * n)$ +- Space complexity: $O(1)$ extra space. -> Where $m$ is the number of rows and $n$ is the number of columns. \ No newline at end of file +> Where $m$ is the number of rows and $n$ is the number of columns. diff --git a/articles/number-of-longest-increasing-subsequence.md b/articles/number-of-longest-increasing-subsequence.md index f11ef6599..5a23a7430 100644 --- a/articles/number-of-longest-increasing-subsequence.md +++ b/articles/number-of-longest-increasing-subsequence.md @@ -20,7 +20,7 @@ class Solution: if nums[j] <= nums[i]: continue dfs(j, length + 1) - + for i in range(len(nums)): dfs(i, 1) return res @@ -123,8 +123,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ n)$ +- Space complexity: $O(n)$ --- @@ -208,7 +208,7 @@ public class Solution { } } } - + dp[i] = new int[]{maxLen, maxCnt}; } } @@ -273,7 +273,8 @@ class Solution { const dfs = (i) => { if (dp.has(i)) return; - let maxLen = 1, maxCnt = 1; + let maxLen = 1, + maxCnt = 1; for (let j = i + 1; j < nums.length; j++) { if (nums[j] > nums[i]) { dfs(j); @@ -289,7 +290,8 @@ class Solution { dp.set(i, [maxLen, maxCnt]); }; - let lenLIS = 0, res = 0; + let lenLIS = 0, + res = 0; for (let i = 0; i < nums.length; i++) { dfs(i); const [maxLen, maxCnt] = dp.get(i); @@ -309,8 +311,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -426,10 +428,12 @@ class Solution { findNumberOfLIS(nums) { const n = nums.length; const dp = Array.from({ length: n }, () => [0, 0]); - let lenLIS = 0, res = 0; + let lenLIS = 0, + res = 0; for (let i = n - 1; i >= 0; i--) { - let maxLen = 1, maxCnt = 1; + let maxLen = 1, + maxCnt = 1; for (let j = i + 1; j < n; j++) { if (nums[j] > nums[i]) { const [length, count] = dp[j]; @@ -459,8 +463,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -641,11 +645,18 @@ class Solution { * @return {number} */ findNumberOfLIS(nums) { - const dp = [[[0, 0], [nums[0], 1]]]; + const dp = [ + [ + [0, 0], + [nums[0], 1], + ], + ]; let LIS = 1; const bs1 = (num) => { - let l = 0, r = dp.length - 1, j = dp.length - 1; + let l = 0, + r = dp.length - 1, + j = dp.length - 1; while (l <= r) { const mid = Math.floor((l + r) / 2); if (dp[mid][dp[mid].length - 1][0] < num) { @@ -660,7 +671,9 @@ class Solution { const bs2 = (i, num) => { if (i < 0) return 1; - let l = 1, r = dp[i].length - 1, j = 0; + let l = 1, + r = dp[i].length - 1, + j = 0; while (l <= r) { const mid = Math.floor((l + r) / 2); if (dp[i][mid][0] >= num) { @@ -677,7 +690,10 @@ class Solution { const num = nums[i]; if (num > dp[dp.length - 1][dp[dp.length - 1].length - 1][0]) { const count = bs2(LIS - 1, num); - dp.push([[0, 0], [num, count]]); + dp.push([ + [0, 0], + [num, count], + ]); LIS++; } else { const j = bs1(num); @@ -695,5 +711,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n\log n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n\log n)$ +- Space complexity: $O(n)$ diff --git a/articles/number-of-music-playlists.md b/articles/number-of-music-playlists.md index 284e35bae..70dfcabaf 100644 --- a/articles/number-of-music-playlists.md +++ b/articles/number-of-music-playlists.md @@ -90,7 +90,9 @@ class Solution { */ numMusicPlaylists(n, goal, k) { const MOD = 1e9 + 7; - const dp = Array.from({ length: goal + 1 }, () => Array(n + 1).fill(-1)); + const dp = Array.from({ length: goal + 1 }, () => + Array(n + 1).fill(-1), + ); const count = (curGoal, oldSongs) => { if (curGoal === 0 && oldSongs === n) return 1; @@ -99,7 +101,11 @@ class Solution { let res = ((n - oldSongs) * count(curGoal - 1, oldSongs + 1)) % MOD; if (oldSongs > k) { - res = (res + ((oldSongs - k) * count(curGoal - 1, oldSongs)) % MOD) % MOD; + res = + (res + + (((oldSongs - k) * count(curGoal - 1, oldSongs)) % + MOD)) % + MOD; } dp[curGoal][oldSongs] = res; return res; @@ -114,8 +120,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(g * n)$ -* Space complexity: $O(g * n)$ +- Time complexity: $O(g * n)$ +- Space complexity: $O(g * n)$ > Where $g$ is the number of songs to listen and $n$ is the number of different songs. @@ -205,9 +211,12 @@ class Solution { for (let curGoal = 1; curGoal <= goal; curGoal++) { for (let oldSongs = 1; oldSongs <= n; oldSongs++) { - let res = (dp[curGoal - 1][oldSongs - 1] * (n - oldSongs + 1)) % MOD; + let res = + (dp[curGoal - 1][oldSongs - 1] * (n - oldSongs + 1)) % MOD; if (oldSongs > k) { - res = (res + dp[curGoal - 1][oldSongs] * (oldSongs - k)) % MOD; + res = + (res + dp[curGoal - 1][oldSongs] * (oldSongs - k)) % + MOD; } dp[curGoal][oldSongs] = res; } @@ -222,8 +231,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(g * n)$ -* Space complexity: $O(g * n)$ +- Time complexity: $O(g * n)$ +- Space complexity: $O(g * n)$ > Where $g$ is the number of songs to listen and $n$ is the number of different songs. @@ -334,7 +343,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(g * n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(g * n)$ +- Space complexity: $O(n)$ -> Where $g$ is the number of songs to listen and $n$ is the number of different songs. \ No newline at end of file +> Where $g$ is the number of songs to listen and $n$ is the number of different songs. diff --git a/articles/number-of-one-bits.md b/articles/number-of-one-bits.md index 4ea545b0d..7cab4d38a 100644 --- a/articles/number-of-one-bits.md +++ b/articles/number-of-one-bits.md @@ -117,8 +117,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ --- @@ -173,7 +173,7 @@ class Solution { let res = 0; while (n !== 0) { res += (n & 1) === 1 ? 1 : 0; - n >>= 1; + n >>= 1; } return res; } @@ -240,8 +240,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ --- @@ -359,8 +359,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ --- @@ -437,5 +437,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ diff --git a/articles/number-of-pairs-of-interchangeable-rectangles.md b/articles/number-of-pairs-of-interchangeable-rectangles.md index bbb73e152..03c2d7c30 100644 --- a/articles/number-of-pairs-of-interchangeable-rectangles.md +++ b/articles/number-of-pairs-of-interchangeable-rectangles.md @@ -56,7 +56,10 @@ class Solution { let res = 0; for (let i = 1; i < rectangles.length; i++) { for (let j = 0; j < i; j++) { - if (rectangles[i][0] / rectangles[i][1] === rectangles[j][0] / rectangles[j][1]) { + if ( + rectangles[i][0] / rectangles[i][1] === + rectangles[j][0] / rectangles[j][1] + ) { res++; } } @@ -70,8 +73,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -101,7 +104,7 @@ public class Solution { double ratio = (double) rect[0] / rect[1]; count.put(ratio, count.getOrDefault(ratio, 0) + 1); } - + long res = 0; for (int c : count.values()) { if (c > 1) { @@ -162,8 +165,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -224,7 +227,7 @@ class Solution { let res = 0; for (const [w, h] of rectangles) { const ratio = w / h; - res += count.get(ratio) || 0 + res += count.get(ratio) || 0; count.set(ratio, (count.get(ratio) || 0) + 1); } return res; @@ -236,8 +239,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -251,7 +254,7 @@ class Solution: mask = a mask |= (b << 31) return mask - + def interchangeableRectangles(self, rectangles: List[List[int]]) -> int: res = 0 count = {} @@ -270,7 +273,7 @@ public class Solution { mask |= ((long)b << 31); return mask; } - + public long interchangeableRectangles(int[][] rectangles) { long res = 0; Map count = new HashMap<>(); @@ -282,7 +285,7 @@ public class Solution { } return res; } - + private int gcd(int a, int b) { while (b != 0) { a %= b; @@ -303,7 +306,7 @@ public: mask |= ((long long)b << 31); return mask; } - + long long interchangeableRectangles(vector>& rectangles) { long long res = 0; unordered_map count; @@ -336,18 +339,21 @@ class Solution { interchangeableRectangles(rectangles) { let res = 0; const count = new Map(); - + const gcd = (a, b) => { while (b !== 0) { a %= b; - [a, b] = [b, a] + [a, b] = [b, a]; } return a; }; - + for (const rect of rectangles) { const g = gcd(rect[0], rect[1]); - const key = this.hash(Math.floor(rect[0] / g), Math.floor(rect[1] / g)); + const key = this.hash( + Math.floor(rect[0] / g), + Math.floor(rect[1] / g), + ); res += count.get(key) || 0; count.set(key, (count.get(key) || 0) + 1); } @@ -360,5 +366,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/number-of-senior-citizens.md b/articles/number-of-senior-citizens.md index 11a6b0d29..d0a647cbd 100644 --- a/articles/number-of-senior-citizens.md +++ b/articles/number-of-senior-citizens.md @@ -63,8 +63,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -145,5 +145,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/number-of-students-unable-to-eat-lunch.md b/articles/number-of-students-unable-to-eat-lunch.md index 6ccf1609d..32b33514b 100644 --- a/articles/number-of-students-unable-to-eat-lunch.md +++ b/articles/number-of-students-unable-to-eat-lunch.md @@ -58,7 +58,7 @@ public: int countStudents(vector& students, vector& sandwiches) { int n = students.size(); queue q; - + for (int student : students) { q.push(student); } @@ -121,8 +121,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -241,8 +241,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -262,7 +262,7 @@ class Solution: cnt[s] -= 1 else: break - + return res ``` @@ -344,5 +344,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.md b/articles/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.md index f99cc6f13..f12571b5a 100644 --- a/articles/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.md +++ b/articles/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.md @@ -7,16 +7,16 @@ class Solution: def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int: res = 0 l = 0 - + for r in range(k - 1, len(arr)): sum_ = 0 for i in range(l, r + 1): sum_ += arr[i] - + if sum_ / k >= threshold: res += 1 l += 1 - + return res ``` @@ -70,7 +70,8 @@ class Solution { * @return {number} */ numOfSubarrays(arr, k, threshold) { - let res = 0, l = 0; + let res = 0, + l = 0; for (let r = k - 1; r < arr.length; r++) { let sum = 0; @@ -91,8 +92,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * k)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n * k)$ +- Space complexity: $O(1)$ > Where $n$ is the size of the array $arr$ and $k$ is the size of the sub-array. @@ -115,7 +116,7 @@ class Solution: if sum_ / k >= threshold: res += 1 l += 1 - + return res ``` @@ -176,7 +177,8 @@ class Solution { prefixSum[i + 1] += prefixSum[i] + arr[i]; } - let res = 0, l = 0; + let res = 0, + l = 0; for (let r = k - 1; r < arr.length; r++) { const sum = prefixSum[r + 1] - prefixSum[l]; if (sum / k >= threshold) { @@ -193,8 +195,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ > Where $n$ is the size of the array $arr$ and $k$ is the size of the sub-array. @@ -282,7 +284,7 @@ class Solution { for (let L = 0; L <= arr.length - k; L++) { curSum += arr[L + k - 1]; - if ((curSum / k) >= threshold) { + if (curSum / k >= threshold) { res++; } curSum -= arr[L]; @@ -297,8 +299,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. > Where $n$ is the size of the array $arr$ and $k$ is the size of the sub-array. @@ -372,7 +374,8 @@ class Solution { */ numOfSubarrays(arr, k, threshold) { threshold *= k; - let res = 0, curSum = 0; + let res = 0, + curSum = 0; for (let R = 0; R < arr.length; R++) { curSum += arr[R]; @@ -392,7 +395,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. -> Where $n$ is the size of the array $arr$ and $k$ is the size of the sub-array. \ No newline at end of file +> Where $n$ is the size of the array $arr$ and $k$ is the size of the sub-array. diff --git a/articles/number-of-sub-arrays-with-odd-sum.md b/articles/number-of-sub-arrays-with-odd-sum.md index e13063014..b1af4583c 100644 --- a/articles/number-of-sub-arrays-with-odd-sum.md +++ b/articles/number-of-sub-arrays-with-odd-sum.md @@ -91,8 +91,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -206,7 +206,7 @@ class Solution { const newParity = (parity + arr[i]) % 2; const res = newParity + dp(i + 1, newParity); - return memo[i][parity] = res % mod; + return (memo[i][parity] = res % mod); }; let res = 0; @@ -223,8 +223,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -328,8 +328,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -407,7 +407,10 @@ class Solution { * @return {number} */ numOfSubarrays(arr) { - let curSum = 0, oddCnt = 0, evenCnt = 0, res = 0; + let curSum = 0, + oddCnt = 0, + evenCnt = 0, + res = 0; const MOD = 1e9 + 7; for (let n of arr) { @@ -430,8 +433,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -499,7 +502,8 @@ class Solution { */ numOfSubarrays(arr) { const count = [1, 0]; - let prefix = 0, res = 0; + let prefix = 0, + res = 0; const MOD = 1e9 + 7; for (const num of arr) { @@ -517,5 +521,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/number-of-submatrices-that-sum-to-target.md b/articles/number-of-submatrices-that-sum-to-target.md index 0fe84feca..4f99367e1 100644 --- a/articles/number-of-submatrices-that-sum-to-target.md +++ b/articles/number-of-submatrices-that-sum-to-target.md @@ -88,7 +88,8 @@ class Solution { * @return {number} */ numSubmatrixSumTarget(matrix, target) { - const ROWS = matrix.length, COLS = matrix[0].length; + const ROWS = matrix.length, + COLS = matrix[0].length; let res = 0; for (let r1 = 0; r1 < ROWS; r1++) { @@ -117,8 +118,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m ^ 3 * n ^ 3)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(m ^ 3 * n ^ 3)$ +- Space complexity: $O(1)$ extra space. > Where $m$ is the number of rows and $n$ is the number of columns of the given matrix. @@ -236,7 +237,8 @@ class Solution { * @return {number} */ numSubmatrixSumTarget(matrix, target) { - const ROWS = matrix.length, COLS = matrix[0].length; + const ROWS = matrix.length, + COLS = matrix[0].length; const subSum = Array.from({ length: ROWS }, () => Array(COLS).fill(0)); for (let r = 0; r < ROWS; r++) { @@ -255,7 +257,8 @@ class Solution { for (let c2 = c1; c2 < COLS; c2++) { let top = r1 > 0 ? subSum[r1 - 1][c2] : 0; let left = c1 > 0 ? subSum[r2][c1 - 1] : 0; - let topLeft = Math.min(r1, c1) > 0 ? subSum[r1 - 1][c1 - 1] : 0; + let topLeft = + Math.min(r1, c1) > 0 ? subSum[r1 - 1][c1 - 1] : 0; let curSum = subSum[r2][c2] - top - left + topLeft; if (curSum === target) { res++; @@ -273,8 +276,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m ^ 2 * n ^ 2)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m ^ 2 * n ^ 2)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns of the given matrix. @@ -383,7 +386,8 @@ class Solution { * @return {number} */ numSubmatrixSumTarget(matrix, target) { - let ROWS = matrix.length, COLS = matrix[0].length; + let ROWS = matrix.length, + COLS = matrix[0].length; let subSum = Array.from({ length: ROWS }, () => Array(COLS).fill(0)); for (let r = 0; r < ROWS; r++) { @@ -401,7 +405,8 @@ class Solution { let count = new Map(); count.set(0, 1); for (let c = 0; c < COLS; c++) { - let curSum = subSum[r2][c] - (r1 > 0 ? subSum[r1 - 1][c] : 0); + let curSum = + subSum[r2][c] - (r1 > 0 ? subSum[r1 - 1][c] : 0); res += count.get(curSum - target) || 0; count.set(curSum, (count.get(curSum) || 0) + 1); } @@ -416,8 +421,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m ^ 2 * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m ^ 2 * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns of the given matrix. @@ -514,7 +519,9 @@ class Solution { * @return {number} */ numSubmatrixSumTarget(matrix, target) { - let ROWS = matrix.length, COLS = matrix[0].length, res = 0; + let ROWS = matrix.length, + COLS = matrix[0].length, + res = 0; for (let c1 = 0; c1 < COLS; c1++) { let rowPrefix = new Array(ROWS).fill(0); @@ -543,7 +550,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n ^ 2)$ -* Space complexity: $O(m)$ +- Time complexity: $O(m * n ^ 2)$ +- Space complexity: $O(m)$ -> Where $m$ is the number of rows and $n$ is the number of columns of the given matrix. \ No newline at end of file +> Where $m$ is the number of rows and $n$ is the number of columns of the given matrix. diff --git a/articles/number-of-subsequences-that-satisfy-the-given-sum-condition.md b/articles/number-of-subsequences-that-satisfy-the-given-sum-condition.md index cc81b5ad0..d54c5e2c2 100644 --- a/articles/number-of-subsequences-that-satisfy-the-given-sum-condition.md +++ b/articles/number-of-subsequences-that-satisfy-the-given-sum-condition.md @@ -80,14 +80,18 @@ class Solution { const dfs = (maxi, mini, i) => { if (i === nums.length) { - if (mini !== Infinity && (maxi + mini) <= target) { + if (mini !== Infinity && maxi + mini <= target) { return 1; } return 0; } const skip = dfs(maxi, mini, i + 1); - const include = dfs(Math.max(maxi, nums[i]), Math.min(mini, nums[i]), i + 1); + const include = dfs( + Math.max(maxi, nums[i]), + Math.min(mini, nums[i]), + i + 1, + ); return (skip + include) % MOD; }; @@ -100,8 +104,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -115,11 +119,11 @@ class Solution: nums.sort() MOD = 1000000007 res = 0 - + for i in range(len(nums)): if nums[i] * 2 > target: break - + l, r = i, len(nums) - 1 while l <= r: mid = (l + r) // 2 @@ -127,10 +131,10 @@ class Solution: l = mid + 1 else: r = mid - 1 - + count = pow(2, r - i, MOD) res = (res + count) % MOD - + return res ``` @@ -226,7 +230,8 @@ class Solution { let res = 0n; const powerMod = (base, exp, mod) => { - let result = 1n, b = BigInt(base); + let result = 1n, + b = BigInt(base); while (exp > 0) { if (exp & 1) result = (result * b) % mod; b = (b * b) % mod; @@ -238,7 +243,8 @@ class Solution { for (let i = 0; i < nums.length; i++) { if (nums[i] * 2 > target) break; - let l = i, r = nums.length - 1; + let l = i, + r = nums.length - 1; while (l <= r) { const mid = Math.floor((l + r) / 2); if (nums[i] + nums[mid] <= target) { @@ -261,8 +267,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -276,7 +282,7 @@ class Solution: nums.sort() res = 0 mod = 10**9 + 7 - + r = len(nums) - 1 for i, left in enumerate(nums): while i <= r and left + nums[r] > target: @@ -284,7 +290,7 @@ class Solution: if i <= r: res += pow(2, r - i, mod) res %= mod - + return res ``` @@ -294,7 +300,7 @@ public class Solution { Arrays.sort(nums); int res = 0, mod = 1000000007; int r = nums.length - 1; - + for (int i = 0; i < nums.length; i++) { while (i <= r && nums[i] + nums[r] > target) { r--; @@ -305,7 +311,7 @@ public class Solution { } return res; } - + private int power(int base, int exp, int mod) { long result = 1, b = base; while (exp > 0) { @@ -325,7 +331,7 @@ public: sort(nums.begin(), nums.end()); int res = 0, mod = 1000000007; int r = nums.size() - 1; - + for (int i = 0; i < nums.size(); i++) { while (i <= r && nums[i] + nums[r] > target) { r--; @@ -336,7 +342,7 @@ public: } return res; } - + private: long long power(int base, int exp, int mod) { long long result = 1, b = base; @@ -363,7 +369,8 @@ class Solution { let res = 0n; const power = (base, exp, mod) => { - let result = 1n, b = BigInt(base); + let result = 1n, + b = BigInt(base); while (exp > 0) { if (exp & 1) result = (result * b) % mod; b = (b * b) % mod; @@ -390,8 +397,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -407,17 +414,17 @@ class Solution: res = 0 l, r = 0, len(nums) - 1 power = [1] * len(nums) - + for i in range(1, len(nums)): power[i] = (power[i - 1] * 2) % MOD - + while l <= r: if nums[l] + nums[r] <= target: res = (res + power[r - l]) % MOD l += 1 else: r -= 1 - + return res ``` @@ -485,7 +492,9 @@ class Solution { numSubseq(nums, target) { nums.sort((a, b) => a - b); const MOD = 1000000007; - let res = 0, l = 0, r = nums.length - 1; + let res = 0, + l = 0, + r = nums.length - 1; const power = Array(nums.length).fill(1); for (let i = 1; i < nums.length; i++) { @@ -510,5 +519,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ diff --git a/articles/number-of-visible-people-in-a-queue.md b/articles/number-of-visible-people-in-a-queue.md index 1d52b6b1a..6a10f8212 100644 --- a/articles/number-of-visible-people-in-a-queue.md +++ b/articles/number-of-visible-people-in-a-queue.md @@ -14,9 +14,9 @@ class Solution: if min(heights[i], heights[j]) > maxi: cnt += 1 maxi = max(maxi, heights[j]) - + res.append(cnt) - + return res ``` @@ -71,7 +71,8 @@ class Solution { const n = heights.length; const res = []; for (let i = 0; i < n; i++) { - let maxi = 0, cnt = 0; + let maxi = 0, + cnt = 0; for (let j = i + 1; j < n; j++) { if (Math.min(heights[i], heights[j]) > maxi) { cnt++; @@ -109,8 +110,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ for the output array. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ for the output array. --- @@ -229,8 +230,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -263,7 +264,7 @@ public class Solution { int n = heights.length; int[] res = new int[n]; Stack stack = new Stack<>(); - + for (int i = n - 1; i >= 0; i--) { while (!stack.isEmpty() && stack.peek() < heights[i]) { stack.pop(); @@ -274,7 +275,7 @@ public class Solution { } stack.push(heights[i]); } - + return res; } } @@ -287,7 +288,7 @@ public: int n = heights.size(); vector res(n, 0); stack st; - + for (int i = n - 1; i >= 0; --i) { while (!st.empty() && st.top() < heights[i]) { st.pop(); @@ -298,7 +299,7 @@ public: } st.push(heights[i]); } - + return res; } }; @@ -354,5 +355,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/number-of-ways-to-divide-a-long-corridor.md b/articles/number-of-ways-to-divide-a-long-corridor.md index cda191a27..36a9c7d81 100644 --- a/articles/number-of-ways-to-divide-a-long-corridor.md +++ b/articles/number-of-ways-to-divide-a-long-corridor.md @@ -68,7 +68,7 @@ public class Solution { res = dfs(i + 1, seats, corridor); } } - + return dp[i][seats] = res; } } @@ -156,8 +156,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -171,7 +171,7 @@ class Solution: MOD = 1000000007 n = len(corridor) dp = [[0] * 3 for _ in range(n + 1)] - dp[n][2] = 1 + dp[n][2] = 1 for i in range(n - 1, -1, -1): for seats in range(3): @@ -288,8 +288,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -374,9 +374,11 @@ class Solution { let new_dp = [0, 0, 0]; for (let seats = 0; seats < 3; seats++) { if (seats === 2) { - new_dp[seats] = corridor[i] === 'S' ? dp[1] : (dp[0] + dp[2]) % MOD; + new_dp[seats] = + corridor[i] === 'S' ? dp[1] : (dp[0] + dp[2]) % MOD; } else { - new_dp[seats] = corridor[i] === 'S' ? dp[seats + 1] : dp[seats]; + new_dp[seats] = + corridor[i] === 'S' ? dp[seats + 1] : dp[seats]; } } dp = new_dp; @@ -390,8 +392,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -449,7 +451,7 @@ public: int numberOfWays(string corridor) { int mod = 1'000'000'007; vector seats; - + for (int i = 0; i < corridor.size(); i++) { if (corridor[i] == 'S') { seats.push_back(i); @@ -506,8 +508,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -583,7 +585,9 @@ class Solution { */ numberOfWays(corridor) { const mod = 1_000_000_007; - let count = 0, res = 1, prev = -1; + let count = 0, + res = 1, + prev = -1; for (let i = 0; i < corridor.length; i++) { if (corridor[i] === 'S') { @@ -604,5 +608,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/number-of-ways-to-form-a-target-string-given-a-dictionary.md b/articles/number-of-ways-to-form-a-target-string-given-a-dictionary.md index 878690a7c..042982ad9 100644 --- a/articles/number-of-ways-to-form-a-target-string-given-a-dictionary.md +++ b/articles/number-of-ways-to-form-a-target-string-given-a-dictionary.md @@ -13,14 +13,14 @@ class Solution: return 1 if k == m: return 0 - + res = dfs(i, k + 1) for w in words: if w[k] != target[i]: continue res = (res + dfs(i + 1, k + 1)) % mod return res - + return dfs(0, 0) ``` @@ -112,8 +112,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(N ^ m)$ -* Space complexity: $O(m)$ +- Time complexity: $O(N ^ m)$ +- Space complexity: $O(m)$ > Where $N$ is the number of words, $m$ is the length of each word, and $n$ is the length of the $target$ string. @@ -233,7 +233,8 @@ class Solution { */ numWays(words, target) { const MOD = 1e9 + 7; - const n = target.length, m = words[0].length; + const n = target.length, + m = words[0].length; const cnt = Array.from({ length: m }, () => Array(26).fill(0)); for (const word of words) { @@ -250,7 +251,7 @@ class Solution { if (dp[i][k] !== -1) return dp[i][k]; const c = target.charCodeAt(i) - 97; - dp[i][k] = dfs(i, k + 1); // Skip k position + dp[i][k] = dfs(i, k + 1); // Skip k position dp[i][k] = (dp[i][k] + cnt[k][c] * dfs(i + 1, k + 1)) % MOD; return dp[i][k]; }; @@ -264,8 +265,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * (n + N))$ -* Space complexity: $O(n * m)$ +- Time complexity: $O(m * (n + N))$ +- Space complexity: $O(n * m)$ > Where $N$ is the number of words, $m$ is the length of each word, and $n$ is the length of the $target$ string. @@ -374,7 +375,8 @@ class Solution { */ numWays(words, target) { const MOD = 1e9 + 7; - const n = target.length, m = words[0].length; + const n = target.length, + m = words[0].length; const cnt = Array.from({ length: m }, () => Array(26).fill(0)); for (const word of words) { @@ -405,8 +407,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * (n + N))$ -* Space complexity: $O(n * m)$ +- Time complexity: $O(m * (n + N))$ +- Space complexity: $O(n * m)$ > Where $N$ is the number of words, $m$ is the length of each word, and $n$ is the length of the $target$ string. @@ -440,7 +442,7 @@ class Solution: dp[k] = (dp[k] + cnt[k][c] * nxt) % MOD nxt = cur dp[m] = 0 - + return dp[0] ``` @@ -527,7 +529,8 @@ class Solution { */ numWays(words, target) { const MOD = 1e9 + 7; - const n = target.length, m = words[0].length; + const n = target.length, + m = words[0].length; const cnt = Array.from({ length: m }, () => Array(26).fill(0)); for (const word of words) { @@ -562,7 +565,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * (n + N))$ -* Space complexity: $O(m)$ +- Time complexity: $O(m * (n + N))$ +- Space complexity: $O(m)$ -> Where $N$ is the number of words, $m$ is the length of each word, and $n$ is the length of the $target$ string. \ No newline at end of file +> Where $N$ is the number of words, $m$ is the length of each word, and $n$ is the length of the $target$ string. diff --git a/articles/number-of-ways-to-rearrange-sticks-with-k-sticks-visible.md b/articles/number-of-ways-to-rearrange-sticks-with-k-sticks-visible.md index d192c77b6..ede051484 100644 --- a/articles/number-of-ways-to-rearrange-sticks-with-k-sticks-visible.md +++ b/articles/number-of-ways-to-rearrange-sticks-with-k-sticks-visible.md @@ -76,8 +76,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -177,8 +177,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * k)$ -* Space complexity: $O(n * k)$ +- Time complexity: $O(n * k)$ +- Space complexity: $O(n * k)$ > Where $n$ represents the total number of sticks, and $k$ denotes the number of sticks that must be visible from the left side. @@ -267,8 +267,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * k)$ -* Space complexity: $O(n * k)$ +- Time complexity: $O(n * k)$ +- Space complexity: $O(n * k)$ > Where $n$ represents the total number of sticks, and $k$ denotes the number of sticks that must be visible from the left side. @@ -369,7 +369,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * k)$ -* Space complexity: $O(k)$ +- Time complexity: $O(n * k)$ +- Space complexity: $O(k)$ -> Where $n$ represents the total number of sticks, and $k$ denotes the number of sticks that must be visible from the left side. \ No newline at end of file +> Where $n$ represents the total number of sticks, and $k$ denotes the number of sticks that must be visible from the left side. diff --git a/articles/number-of-ways-to-split-array.md b/articles/number-of-ways-to-split-array.md index ca66c41c0..ee5a68257 100644 --- a/articles/number-of-ways-to-split-array.md +++ b/articles/number-of-ways-to-split-array.md @@ -112,8 +112,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -221,8 +221,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -297,7 +297,8 @@ class Solution { */ waysToSplitArray(nums) { let right = nums.reduce((a, b) => a + b, 0); - let left = 0, res = 0; + let left = 0, + res = 0; for (let i = 0; i < nums.length - 1; i++) { left += nums[i]; @@ -316,5 +317,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/number-of-ways-to-stay-in-the-same-place-after-some-steps.md b/articles/number-of-ways-to-stay-in-the-same-place-after-some-steps.md index 2c9577d2a..4a6961689 100644 --- a/articles/number-of-ways-to-stay-in-the-same-place-after-some-steps.md +++ b/articles/number-of-ways-to-stay-in-the-same-place-after-some-steps.md @@ -110,7 +110,9 @@ class Solution { numWays(steps, arrLen) { const MOD = 1e9 + 7; const maxPos = Math.min(steps, arrLen); - const dp = Array.from({ length: maxPos + 1 }, () => Array(steps + 1).fill(-1)); + const dp = Array.from({ length: maxPos + 1 }, () => + Array(steps + 1).fill(-1), + ); const dfs = (i, steps) => { if (steps === 0) return i === 0 ? 1 : 0; @@ -133,8 +135,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * min(n, m))$ -* Space complexity: $O(n * min(n, m))$ +- Time complexity: $O(n * min(n, m))$ +- Space complexity: $O(n * min(n, m))$ > Where $n$ is the number of steps and $m$ is the size of the array. @@ -227,7 +229,9 @@ class Solution { numWays(steps, arrLen) { const MOD = 1e9 + 7; arrLen = Math.min(arrLen, steps); - const dp = Array.from({ length: steps + 1 }, () => Array(arrLen + 1).fill(0)); + const dp = Array.from({ length: steps + 1 }, () => + Array(arrLen + 1).fill(0), + ); dp[0][0] = 1; for (let step = 1; step <= steps; step++) { @@ -252,8 +256,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * min(n, m))$ -* Space complexity: $O(n * min(n, m))$ +- Time complexity: $O(n * min(n, m))$ +- Space complexity: $O(n * min(n, m))$ > Where $n$ is the number of steps and $m$ is the size of the array. @@ -375,8 +379,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * min(n, m))$ -* Space complexity: $O(min(n, m))$ +- Time complexity: $O(n * min(n, m))$ +- Space complexity: $O(min(n, m))$ > Where $n$ is the number of steps and $m$ is the size of the array. @@ -497,7 +501,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * min(n, m))$ -* Space complexity: $O(min(n, m))$ +- Time complexity: $O(n * min(n, m))$ +- Space complexity: $O(min(n, m))$ -> Where $n$ is the number of steps and $m$ is the size of the array. \ No newline at end of file +> Where $n$ is the number of steps and $m$ is the size of the array. diff --git a/articles/number-of-zero-filled-subarrays.md b/articles/number-of-zero-filled-subarrays.md index 266353c04..b57e7262b 100644 --- a/articles/number-of-zero-filled-subarrays.md +++ b/articles/number-of-zero-filled-subarrays.md @@ -68,8 +68,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -137,7 +137,8 @@ class Solution { * @return {number} */ zeroFilledSubarray(nums) { - let res = 0, i = 0; + let res = 0, + i = 0; while (i < nums.length) { let count = 0; while (i < nums.length && nums[i] === 0) { @@ -156,8 +157,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -176,7 +177,7 @@ class Solution: else: count = 0 res += count - + return res ``` @@ -228,7 +229,8 @@ class Solution { * @return {number} */ zeroFilledSubarray(nums) { - let res = 0, count = 0; + let res = 0, + count = 0; for (let num of nums) { if (num === 0) { @@ -248,8 +250,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -315,7 +317,8 @@ class Solution { * @return {number} */ zeroFilledSubarray(nums) { - let res = 0, count = 0; + let res = 0, + count = 0; for (let num of nums) { if (num === 0) { count++; @@ -334,5 +337,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/ones-and-zeroes.md b/articles/ones-and-zeroes.md index 4d3e53b4d..88a3268d7 100644 --- a/articles/ones-and-zeroes.md +++ b/articles/ones-and-zeroes.md @@ -9,16 +9,16 @@ class Solution: for i, s in enumerate(strs): for c in s: arr[i][ord(c) - ord('0')] += 1 - + def dfs(i, m, n): if i == len(strs): return 0 - + res = dfs(i + 1, m, n) if m >= arr[i][0] and n >= arr[i][1]: res = max(res, 1 + dfs(i + 1, m - arr[i][0], n - arr[i][1])) return res - + return dfs(0, m, n) ``` @@ -89,7 +89,7 @@ class Solution { const arr = Array.from({ length: strs.length }, () => [0, 0]); for (let i = 0; i < strs.length; i++) { for (const c of strs[i]) { - arr[i][c - "0"]++; + arr[i][c - '0']++; } } @@ -100,7 +100,10 @@ class Solution { let res = dfs(i + 1, m, n); if (m >= arr[i][0] && n >= arr[i][1]) { - res = Math.max(res, 1 + dfs(i + 1, m - arr[i][0], n - arr[i][1])); + res = Math.max( + res, + 1 + dfs(i + 1, m - arr[i][0], n - arr[i][1]), + ); } return res; }; @@ -114,8 +117,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ N)$ -* Space complexity: $O(N)$ for recursion stack. +- Time complexity: $O(2 ^ N)$ +- Space complexity: $O(N)$ for recursion stack. > Where $N$ represents the number of binary strings, and $m$ and $n$ are the maximum allowable counts of zeros and ones, respectively. @@ -251,12 +254,12 @@ class Solution { const arr = Array.from({ length: strs.length }, () => [0, 0]); for (let i = 0; i < strs.length; i++) { for (const c of strs[i]) { - arr[i][c - "0"]++; + arr[i][c - '0']++; } } const dp = Array.from({ length: strs.length }, () => - Array.from({ length: m + 1 }, () => Array(n + 1).fill(-1)) + Array.from({ length: m + 1 }, () => Array(n + 1).fill(-1)), ); const dfs = (i, m, n) => { @@ -266,7 +269,10 @@ class Solution { let res = dfs(i + 1, m, n); if (m >= arr[i][0] && n >= arr[i][1]) { - res = Math.max(res, 1 + dfs(i + 1, m - arr[i][0], n - arr[i][1])); + res = Math.max( + res, + 1 + dfs(i + 1, m - arr[i][0], n - arr[i][1]), + ); } dp[i][m][n] = res; return res; @@ -281,8 +287,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n * N)$ -* Space complexity: $O(m * n * N)$ +- Time complexity: $O(m * n * N)$ +- Space complexity: $O(m * n * N)$ > Where $N$ represents the number of binary strings, and $m$ and $n$ are the maximum allowable counts of zeros and ones, respectively. @@ -378,14 +384,14 @@ class Solution { * @return {number} */ findMaxForm(strs, m, n) { - const arr = strs.map(s => { - const zeros = s.split('').filter(c => c === '0').length; + const arr = strs.map((s) => { + const zeros = s.split('').filter((c) => c === '0').length; const ones = s.length - zeros; return [zeros, ones]; }); const dp = Array.from({ length: strs.length + 1 }, () => - Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)) + Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)), ); for (let i = 1; i <= strs.length; i++) { @@ -393,7 +399,10 @@ class Solution { for (let k = 0; k <= n; k++) { dp[i][j][k] = dp[i - 1][j][k]; if (j >= arr[i - 1][0] && k >= arr[i - 1][1]) { - dp[i][j][k] = Math.max(dp[i][j][k], 1 + dp[i - 1][j - arr[i - 1][0]][k - arr[i - 1][1]]); + dp[i][j][k] = Math.max( + dp[i][j][k], + 1 + dp[i - 1][j - arr[i - 1][0]][k - arr[i - 1][1]], + ); } } } @@ -408,8 +417,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n * N)$ -* Space complexity: $O(m * n * N)$ +- Time complexity: $O(m * n * N)$ +- Space complexity: $O(m * n * N)$ > Where $N$ represents the number of binary strings, and $m$ and $n$ are the maximum allowable counts of zeros and ones, respectively. @@ -426,14 +435,14 @@ class Solution: for i, s in enumerate(strs): for c in s: arr[i][ord(c) - ord('0')] += 1 - + dp = [[0] * (n + 1) for _ in range(m + 1)] - + for zeros, ones in arr: for j in range(m, zeros - 1, -1): for k in range(n, ones - 1, -1): dp[j][k] = max(dp[j][k], 1 + dp[j - zeros][k - ones]) - + return dp[m][n] ``` @@ -502,7 +511,7 @@ class Solution { const arr = Array.from({ length: strs.length }, () => [0, 0]); for (let i = 0; i < strs.length; i++) { for (const c of strs[i]) { - arr[i][c - "0"]++; + arr[i][c - '0']++; } } @@ -525,7 +534,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n * N)$ -* Space complexity: $O(m * n + N)$ +- Time complexity: $O(m * n * N)$ +- Space complexity: $O(m * n + N)$ -> Where $N$ represents the number of binary strings, and $m$ and $n$ are the maximum allowable counts of zeros and ones, respectively. \ No newline at end of file +> Where $N$ represents the number of binary strings, and $m$ and $n$ are the maximum allowable counts of zeros and ones, respectively. diff --git a/articles/online-stock-span.md b/articles/online-stock-span.md index a86d71483..5127d99ae 100644 --- a/articles/online-stock-span.md +++ b/articles/online-stock-span.md @@ -99,8 +99,8 @@ public class StockSpanner { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ > Where $n$ is the number of function calls. @@ -175,7 +175,10 @@ class StockSpanner { */ next(price) { let span = 1; - while (this.stack.length && this.stack[this.stack.length - 1][0] <= price) { + while ( + this.stack.length && + this.stack[this.stack.length - 1][0] <= price + ) { span += this.stack.pop()[1]; } this.stack.push([price, span]); @@ -207,7 +210,7 @@ public class StockSpanner { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ -> Where $n$ is the number of function calls. \ No newline at end of file +> Where $n$ is the number of function calls. diff --git a/articles/open-the-lock.md b/articles/open-the-lock.md index 910704fd6..e811a94e6 100644 --- a/articles/open-the-lock.md +++ b/articles/open-the-lock.md @@ -109,7 +109,7 @@ private: string next = lock; next[i] = (next[i] - '0' + 1) % 10 + '0'; res.push_back(next); - + next = lock; next[i] = (next[i] - '0' - 1 + 10) % 10 + '0'; res.push_back(next); @@ -128,20 +128,26 @@ class Solution { */ openLock(deadends, target) { const visit = new Set(deadends); - if (visit.has("0000")) return -1; + if (visit.has('0000')) return -1; const children = (lock) => { const res = []; for (let i = 0; i < 4; i++) { - const up = lock.slice(0, i) + ((+lock[i] + 1) % 10) + lock.slice(i + 1); - const down = lock.slice(0, i) + ((+lock[i] - 1 + 10) % 10) + lock.slice(i + 1); + const up = + lock.slice(0, i) + + ((+lock[i] + 1) % 10) + + lock.slice(i + 1); + const down = + lock.slice(0, i) + + ((+lock[i] - 1 + 10) % 10) + + lock.slice(i + 1); res.push(up, down); } return res; }; - const queue = new Queue([["0000", 0]]); - visit.add("0000"); + const queue = new Queue([['0000', 0]]); + visit.add('0000'); while (!queue.isEmpty()) { const [lock, turns] = queue.pop(); @@ -201,8 +207,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(d ^ n + m)$ -* Space complexity: $O(d ^ n)$ +- Time complexity: $O(d ^ n + m)$ +- Space complexity: $O(d ^ n)$ > Where $d$ is the number of digits $(0 - 9)$, $n$ is the number of wheels $(4)$, and $m$ is the number of deadends. @@ -221,11 +227,11 @@ class Solution: visit = set(deadends) if "0000" in visit: return -1 - + q = deque(["0000"]) visit.add("0000") steps = 0 - + while q: steps += 1 for _ in range(len(q)): @@ -321,13 +327,13 @@ class Solution { * @return {number} */ openLock(deadends, target) { - if (target === "0000") return 0; + if (target === '0000') return 0; const visit = new Set(deadends); - if (visit.has("0000")) return -1; + if (visit.has('0000')) return -1; - const q = new Queue(["0000"]); - visit.add("0000"); + const q = new Queue(['0000']); + visit.add('0000'); let steps = 0; while (!q.isEmpty()) { @@ -337,7 +343,8 @@ class Solution { for (let j = 0; j < 4; j++) { for (let move of [1, -1]) { const digit = (parseInt(lock[j]) + move + 10) % 10; - const nextLock = lock.slice(0, j) + digit + lock.slice(j + 1); + const nextLock = + lock.slice(0, j) + digit + lock.slice(j + 1); if (visit.has(nextLock)) continue; if (nextLock === target) return steps; q.push(nextLock); @@ -391,8 +398,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(d ^ n + m)$ -* Space complexity: $O(d ^ n)$ +- Time complexity: $O(d ^ n + m)$ +- Space complexity: $O(d ^ n)$ > Where $d$ is the number of digits $(0 - 9)$, $n$ is the number of wheels $(4)$, and $m$ is the number of deadends. @@ -411,7 +418,7 @@ class Solution: visit = set(deadends) if "0000" in visit: return -1 - + begin = {"0000"} end = {target} steps = 0 @@ -419,7 +426,7 @@ class Solution: while begin and end: if len(begin) > len(end): begin, end = end, begin - + steps += 1 temp = set() for lock in begin: @@ -427,7 +434,7 @@ class Solution: for j in [-1, 1]: digit = str((int(lock[i]) + j + 10) % 10) nextLock = lock[:i] + digit + lock[i+1:] - + if nextLock in end: return steps if nextLock in visit: @@ -488,7 +495,7 @@ class Solution { public: int openLock(vector& deadends, string target) { if (target == "0000") return 0; - + unordered_set visit(deadends.begin(), deadends.end()); if (visit.count("0000")) return -1; @@ -529,12 +536,12 @@ class Solution { * @return {number} */ openLock(deadends, target) { - if (target === "0000") return 0; + if (target === '0000') return 0; const visit = new Set(deadends); - if (visit.has("0000")) return -1; + if (visit.has('0000')) return -1; - let begin = new Set(["0000"]); + let begin = new Set(['0000']); let end = new Set([target]); let steps = 0; @@ -548,7 +555,8 @@ class Solution { for (let i = 0; i < 4; i++) { for (const j of [-1, 1]) { const digit = (parseInt(lock[i]) + j + 10) % 10; - const nextLock = lock.slice(0, i) + digit + lock.slice(i + 1); + const nextLock = + lock.slice(0, i) + digit + lock.slice(i + 1); if (end.has(nextLock)) return steps; if (visit.has(nextLock)) continue; @@ -614,7 +622,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(d ^ n + m)$ -* Space complexity: $O(d ^ n)$ +- Time complexity: $O(d ^ n + m)$ +- Space complexity: $O(d ^ n)$ -> Where $d$ is the number of digits $(0 - 9)$, $n$ is the number of wheels $(4)$, and $m$ is the number of deadends. \ No newline at end of file +> Where $d$ is the number of digits $(0 - 9)$, $n$ is the number of wheels $(4)$, and $m$ is the number of deadends. diff --git a/articles/operations-on-tree.md b/articles/operations-on-tree.md index 682f18874..1cac6f328 100644 --- a/articles/operations-on-tree.md +++ b/articles/operations-on-tree.md @@ -194,10 +194,10 @@ class LockingTree { } } - /** - * @param {number} num - * @param {number} user - * @return {boolean} + /** + * @param {number} num + * @param {number} user + * @return {boolean} */ lock(num, user) { if (this.locked[num] !== 0) { @@ -207,7 +207,7 @@ class LockingTree { return true; } - /** + /** * @param {number} num * @param {number} user * @return {boolean} @@ -220,10 +220,10 @@ class LockingTree { return true; } - /** + /** * @param {number} num - * @param {number} user - * @return {boolean} + * @param {number} user + * @return {boolean} */ upgrade(num, user) { let node = num; @@ -259,11 +259,11 @@ class LockingTree { ### Time & Space Complexity -* Time complexity: - * $O(n)$ time for initialization. - * $O(1)$ time for each $lock()$ and $unlock()$ function call. - * $O(n)$ time for each $upgrade()$ function call. -* Space complexity: $O(n)$ +- Time complexity: + - $O(n)$ time for initialization. + - $O(1)$ time for each $lock()$ and $unlock()$ function call. + - $O(n)$ time for each $upgrade()$ function call. +- Space complexity: $O(n)$ --- @@ -462,10 +462,10 @@ class LockingTree { } } - /** - * @param {number} num - * @param {number} user - * @return {boolean} + /** + * @param {number} num + * @param {number} user + * @return {boolean} */ lock(num, user) { if (this.locked[num] !== 0) { @@ -475,7 +475,7 @@ class LockingTree { return true; } - /** + /** * @param {number} num * @param {number} user * @return {boolean} @@ -488,10 +488,10 @@ class LockingTree { return true; } - /** + /** * @param {number} num - * @param {number} user - * @return {boolean} + * @param {number} user + * @return {boolean} */ upgrade(num, user) { let node = num; @@ -529,11 +529,11 @@ class LockingTree { ### Time & Space Complexity -* Time complexity: - * $O(n)$ time for initialization. - * $O(1)$ time for each $lock()$ and $unlock()$ function call. - * $O(n)$ time for each $upgrade()$ function call. -* Space complexity: $O(n)$ +- Time complexity: + - $O(n)$ time for initialization. + - $O(1)$ time for each $lock()$ and $unlock()$ function call. + - $O(n)$ time for each $upgrade()$ function call. +- Space complexity: $O(n)$ --- @@ -734,10 +734,10 @@ class LockingTree { } } - /** - * @param {number} num - * @param {number} user - * @return {boolean} + /** + * @param {number} num + * @param {number} user + * @return {boolean} */ lock(num, user) { if (this.locked[num] !== 0) { @@ -747,7 +747,7 @@ class LockingTree { return true; } - /** + /** * @param {number} num * @param {number} user * @return {boolean} @@ -760,10 +760,10 @@ class LockingTree { return true; } - /** + /** * @param {number} num - * @param {number} user - * @return {boolean} + * @param {number} user + * @return {boolean} */ upgrade(num, user) { let node = num; @@ -799,8 +799,8 @@ class LockingTree { ### Time & Space Complexity -* Time complexity: - * $O(n)$ time for initialization. - * $O(1)$ time for each $lock()$ and $unlock()$ function call. - * $O(n)$ time for each $upgrade()$ function call. -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: + - $O(n)$ time for initialization. + - $O(1)$ time for each $lock()$ and $unlock()$ function call. + - $O(n)$ time for each $upgrade()$ function call. +- Space complexity: $O(n)$ diff --git a/articles/optimal-partition-of-string.md b/articles/optimal-partition-of-string.md index c4d89ab77..797474a48 100644 --- a/articles/optimal-partition-of-string.md +++ b/articles/optimal-partition-of-string.md @@ -75,8 +75,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ since we have at most $26$ different characters. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ since we have at most $26$ different characters. --- @@ -145,7 +145,8 @@ class Solution { */ partitionString(s) { const lastIdx = Array(26).fill(-1); - let res = 1, start = 0; + let res = 1, + start = 0; for (let i = 0; i < s.length; i++) { const j = s.charCodeAt(i) - 97; if (lastIdx[j] >= start) { @@ -163,8 +164,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ since we have at most $26$ different characters. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ since we have at most $26$ different characters. --- @@ -228,14 +229,15 @@ class Solution { * @return {number} */ partitionString(s) { - let res = 1, mask = 0; + let res = 1, + mask = 0; for (const c of s) { const i = c.charCodeAt(0) - 97; if (mask & (1 << i)) { mask = 0; res++; } - mask |= (1 << i); + mask |= 1 << i; } return res; } @@ -246,5 +248,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/out-of-boundary-paths.md b/articles/out-of-boundary-paths.md index ced7639b1..5a09fb085 100644 --- a/articles/out-of-boundary-paths.md +++ b/articles/out-of-boundary-paths.md @@ -84,9 +84,11 @@ class Solution { if (moves === 0) return 0; return ( - (dfs(r + 1, c, moves - 1) + dfs(r - 1, c, moves - 1)) % MOD + - (dfs(r, c + 1, moves - 1) + dfs(r, c - 1, moves - 1)) % MOD - ) % MOD; + (((dfs(r + 1, c, moves - 1) + dfs(r - 1, c, moves - 1)) % MOD) + + ((dfs(r, c + 1, moves - 1) + dfs(r, c - 1, moves - 1)) % + MOD)) % + MOD + ); }; return dfs(startRow, startColumn, maxMove); @@ -98,8 +100,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(4 ^ N)$ -* Space complexity: $O(N)$ +- Time complexity: $O(4 ^ N)$ +- Space complexity: $O(N)$ > Where $m$ is the number of rows, $n$ is the number of columns, and $N$ is the maximum number of allowed moves. @@ -202,8 +204,8 @@ class Solution { */ findPaths(m, n, maxMove, startRow, startColumn) { const MOD = 1_000_000_007; - const dp = Array.from({ length: m }, () => - Array.from({ length: n }, () => Array(maxMove + 1).fill(-1)) + const dp = Array.from({ length: m }, () => + Array.from({ length: n }, () => Array(maxMove + 1).fill(-1)), ); const dfs = (r, c, moves) => { @@ -211,10 +213,11 @@ class Solution { if (moves === 0) return 0; if (dp[r][c][moves] !== -1) return dp[r][c][moves]; - dp[r][c][moves] = ( - (dfs(r + 1, c, moves - 1) + dfs(r - 1, c, moves - 1)) % MOD + - (dfs(r, c + 1, moves - 1) + dfs(r, c - 1, moves - 1)) % MOD - ) % MOD; + dp[r][c][moves] = + (((dfs(r + 1, c, moves - 1) + dfs(r - 1, c, moves - 1)) % MOD) + + ((dfs(r, c + 1, moves - 1) + dfs(r, c - 1, moves - 1)) % + MOD)) % + MOD; return dp[r][c][moves]; }; @@ -227,8 +230,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n * N)$ -* Space complexity: $O(m * n * N)$ +- Time complexity: $O(m * n * N)$ +- Space complexity: $O(m * n * N)$ > Where $m$ is the number of rows, $n$ is the number of columns, and $N$ is the maximum number of allowed moves. @@ -319,18 +322,18 @@ class Solution { findPaths(m, n, maxMove, startRow, startColumn) { const MOD = 1_000_000_007; const dp = Array.from({ length: m }, () => - Array.from({ length: n }, () => Array(maxMove + 1).fill(0)) + Array.from({ length: n }, () => Array(maxMove + 1).fill(0)), ); for (let moves = 1; moves <= maxMove; moves++) { for (let r = 0; r < m; r++) { for (let c = 0; c < n; c++) { - dp[r][c][moves] = ( - (r > 0 ? dp[r - 1][c][moves - 1] : 1) + - (r < m - 1 ? dp[r + 1][c][moves - 1] : 1) + - (c > 0 ? dp[r][c - 1][moves - 1] : 1) + - (c < n - 1 ? dp[r][c + 1][moves - 1] : 1) - ) % MOD; + dp[r][c][moves] = + ((r > 0 ? dp[r - 1][c][moves - 1] : 1) + + (r < m - 1 ? dp[r + 1][c][moves - 1] : 1) + + (c > 0 ? dp[r][c - 1][moves - 1] : 1) + + (c < n - 1 ? dp[r][c + 1][moves - 1] : 1)) % + MOD; } } } @@ -344,8 +347,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n * N)$ -* Space complexity: $O(m * n * N)$ +- Time complexity: $O(m * n * N)$ +- Space complexity: $O(m * n * N)$ > Where $m$ is the number of rows, $n$ is the number of columns, and $N$ is the maximum number of allowed moves. @@ -519,7 +522,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n * N)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n * N)$ +- Space complexity: $O(m * n)$ -> Where $m$ is the number of rows, $n$ is the number of columns, and $N$ is the maximum number of allowed moves. \ No newline at end of file +> Where $m$ is the number of rows, $n$ is the number of columns, and $N$ is the maximum number of allowed moves. diff --git a/articles/pacific-atlantic-water-flow.md b/articles/pacific-atlantic-water-flow.md index 1245a570d..a34b84a19 100644 --- a/articles/pacific-atlantic-water-flow.md +++ b/articles/pacific-atlantic-water-flow.md @@ -149,10 +149,17 @@ class Solution { * @return {number[][]} */ pacificAtlantic(heights) { - let ROWS = heights.length, COLS = heights[0].length; - let directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; - - let pacific = false, atlantic = false; + let ROWS = heights.length, + COLS = heights[0].length; + let directions = [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + ]; + + let pacific = false, + atlantic = false; const dfs = (r, c, prevVal) => { if (r < 0 || c < 0) { @@ -252,9 +259,9 @@ func pacificAtlantic(heights [][]int) [][]int { rows, cols := len(heights), len(heights[0]) directions := [][]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}} result := make([][]int, 0) - + var pacific, atlantic bool - + var dfs func(r, c int, prevVal int) dfs = func(r, c int, prevVal int) { if r < 0 || c < 0 { @@ -268,10 +275,10 @@ func pacificAtlantic(heights [][]int) [][]int { if heights[r][c] > prevVal { return } - + tmp := heights[r][c] heights[r][c] = int(^uint(0) >> 1) - + for _, dir := range directions { dfs(r + dir[0], c + dir[1], tmp) if pacific && atlantic { @@ -280,7 +287,7 @@ func pacificAtlantic(heights [][]int) [][]int { } heights[r][c] = tmp } - + for r := 0; r < rows; r++ { for c := 0; c < cols; c++ { pacific = false @@ -291,7 +298,7 @@ func pacificAtlantic(heights [][]int) [][]int { } } } - + return result } ``` @@ -306,12 +313,12 @@ class Solution { intArrayOf(0, 1), intArrayOf(0, -1) ) - + fun pacificAtlantic(heights: Array): List> { val rows = heights.size val cols = heights[0].size val result = mutableListOf>() - + fun dfs(r: Int, c: Int, prevVal: Int) { when { r < 0 || c < 0 -> { @@ -324,17 +331,17 @@ class Solution { } heights[r][c] > prevVal -> return } - + val tmp = heights[r][c] heights[r][c] = Int.MAX_VALUE - + for (dir in directions) { dfs(r + dir[0], c + dir[1], tmp) if (pacific && atlantic) break } heights[r][c] = tmp } - + for (r in 0 until rows) { for (c in 0 until cols) { pacific = false @@ -345,7 +352,7 @@ class Solution { } } } - + return result } } @@ -406,8 +413,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n * 4 ^ {m * n})$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n * 4 ^ {m * n})$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns. @@ -424,9 +431,9 @@ class Solution: pac, atl = set(), set() def dfs(r, c, visit, prevHeight): - if ((r, c) in visit or - r < 0 or c < 0 or - r == ROWS or c == COLS or + if ((r, c) in visit or + r < 0 or c < 0 or + r == ROWS or c == COLS or heights[r][c] < prevHeight ): return @@ -454,7 +461,7 @@ class Solution: ```java public class Solution { - private int[][] directions = {{1, 0}, {-1, 0}, + private int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; public List> pacificAtlantic(int[][] heights) { int ROWS = heights.length, COLS = heights[0].length; @@ -485,8 +492,8 @@ public class Solution { ocean[r][c] = true; for (int[] d : directions) { int nr = r + d[0], nc = c + d[1]; - if (nr >= 0 && nr < heights.length && - nc >= 0 && nc < heights[0].length && + if (nr >= 0 && nr < heights.length && + nc >= 0 && nc < heights[0].length && !ocean[nr][nc] && heights[nr][nc] >= heights[r][c]) { dfs(nr, nc, ocean, heights); } @@ -497,7 +504,7 @@ public class Solution { ```cpp class Solution { - vector> directions = {{1, 0}, {-1, 0}, + vector> directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; public: vector> pacificAtlantic(vector>& heights) { @@ -530,8 +537,8 @@ private: ocean[r][c] = true; for (auto [dr, dc] : directions) { int nr = r + dr, nc = c + dc; - if (nr >= 0 && nr < heights.size() && - nc >= 0 && nc < heights[0].size() && + if (nr >= 0 && nr < heights.size() && + nc >= 0 && nc < heights[0].size() && !ocean[nr][nc] && heights[nr][nc] >= heights[r][c]) { dfs(nr, nc, ocean, heights); } @@ -547,24 +554,34 @@ class Solution { * @return {number[][]} */ pacificAtlantic(heights) { - let ROWS = heights.length, COLS = heights[0].length; - let pac = Array.from({ length: ROWS }, () => - Array(COLS).fill(false)); - let atl = Array.from({ length: ROWS }, () => - Array(COLS).fill(false)); + let ROWS = heights.length, + COLS = heights[0].length; + let pac = Array.from({ length: ROWS }, () => Array(COLS).fill(false)); + let atl = Array.from({ length: ROWS }, () => Array(COLS).fill(false)); const dfs = (r, c, ocean) => { ocean[r][c] = true; - let directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; + let directions = [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + ]; for (let [dr, dc] of directions) { - let nr = r + dr, nc = c + dc; - if (nr >= 0 && nr < ROWS && nc >= 0 && - nc < COLS && !ocean[nr][nc] && - heights[nr][nc] >= heights[r][c]) { + let nr = r + dr, + nc = c + dc; + if ( + nr >= 0 && + nr < ROWS && + nc >= 0 && + nc < COLS && + !ocean[nr][nc] && + heights[nr][nc] >= heights[r][c] + ) { dfs(nr, nc, ocean); } } - } + }; for (let c = 0; c < COLS; c++) { dfs(0, c, pac); @@ -590,9 +607,9 @@ class Solution { ```csharp public class Solution { - private int[][] directions = new int[][] { - new int[] { 1, 0 }, new int[] { -1, 0 }, - new int[] { 0, 1 }, new int[] { 0, -1 } + private int[][] directions = new int[][] { + new int[] { 1, 0 }, new int[] { -1, 0 }, + new int[] { 0, 1 }, new int[] { 0, -1 } }; public List> PacificAtlantic(int[][] heights) { int ROWS = heights.Length, COLS = heights[0].Length; @@ -623,8 +640,8 @@ public class Solution { ocean[r, c] = true; foreach (var dir in directions) { int nr = r + dir[0], nc = c + dir[1]; - if (nr >= 0 && nr < heights.Length && nc >= 0 && - nc < heights[0].Length && !ocean[nr, nc] && + if (nr >= 0 && nr < heights.Length && nc >= 0 && + nc < heights[0].Length && !ocean[nr, nc] && heights[nr][nc] >= heights[r][c]) { Dfs(nr, nc, ocean, heights); } @@ -638,7 +655,7 @@ func pacificAtlantic(heights [][]int) [][]int { rows, cols := len(heights), len(heights[0]) pac := make(map[[2]int]bool) atl := make(map[[2]int]bool) - + var dfs func(r, c int, visit map[[2]int]bool, prevHeight int) dfs = func(r, c int, visit map[[2]int]bool, prevHeight int) { coord := [2]int{r, c} @@ -648,25 +665,25 @@ func pacificAtlantic(heights [][]int) [][]int { heights[r][c] < prevHeight { return } - + visit[coord] = true - + dfs(r+1, c, visit, heights[r][c]) dfs(r-1, c, visit, heights[r][c]) dfs(r, c+1, visit, heights[r][c]) dfs(r, c-1, visit, heights[r][c]) } - + for c := 0; c < cols; c++ { dfs(0, c, pac, heights[0][c]) dfs(rows-1, c, atl, heights[rows-1][c]) } - + for r := 0; r < rows; r++ { dfs(r, 0, pac, heights[r][0]) dfs(r, cols-1, atl, heights[r][cols-1]) } - + result := make([][]int, 0) for r := 0; r < rows; r++ { for c := 0; c < cols; c++ { @@ -676,7 +693,7 @@ func pacificAtlantic(heights [][]int) [][]int { } } } - + return result } ``` @@ -688,7 +705,7 @@ class Solution { val cols = heights[0].size val pac = HashSet>() val atl = HashSet>() - + fun dfs(r: Int, c: Int, visit: HashSet>, prevHeight: Int) { val coord = r to c if (coord in visit || @@ -698,25 +715,25 @@ class Solution { ) { return } - + visit.add(coord) - + dfs(r + 1, c, visit, heights[r][c]) dfs(r - 1, c, visit, heights[r][c]) dfs(r, c + 1, visit, heights[r][c]) dfs(r, c - 1, visit, heights[r][c]) } - + for (c in 0 until cols) { dfs(0, c, pac, heights[0][c]) dfs(rows - 1, c, atl, heights[rows - 1][c]) } - + for (r in 0 until rows) { dfs(r, 0, pac, heights[r][0]) dfs(r, cols - 1, atl, heights[r][cols - 1]) } - + return (0 until rows).flatMap { r -> (0 until cols).mapNotNull { c -> if ((r to c) in pac && (r to c) in atl) { @@ -775,8 +792,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns. @@ -801,8 +818,8 @@ class Solution: ocean[r][c] = True for dr, dc in directions: nr, nc = r + dr, c + dc - if (0 <= nr < ROWS and 0 <= nc < COLS and - not ocean[nr][nc] and + if (0 <= nr < ROWS and 0 <= nc < COLS and + not ocean[nr][nc] and heights[nr][nc] >= heights[r][c] ): q.append((nr, nc)) @@ -816,7 +833,7 @@ class Solution: for r in range(ROWS): pacific.append((r, 0)) atlantic.append((r, COLS - 1)) - + bfs(pacific, pac) bfs(atlantic, atl) @@ -835,10 +852,10 @@ public class Solution { int ROWS = heights.length, COLS = heights[0].length; boolean[][] pac = new boolean[ROWS][COLS]; boolean[][] atl = new boolean[ROWS][COLS]; - + Queue pacQueue = new LinkedList<>(); Queue atlQueue = new LinkedList<>(); - + for (int c = 0; c < COLS; c++) { pacQueue.add(new int[]{0, c}); atlQueue.add(new int[]{ROWS - 1, c}); @@ -847,10 +864,10 @@ public class Solution { pacQueue.add(new int[]{r, 0}); atlQueue.add(new int[]{r, COLS - 1}); } - + bfs(pacQueue, pac, heights); bfs(atlQueue, atl, heights); - + List> res = new ArrayList<>(); for (int r = 0; r < ROWS; r++) { for (int c = 0; c < COLS; c++) { @@ -861,7 +878,7 @@ public class Solution { } return res; } - + private void bfs(Queue q, boolean[][] ocean, int[][] heights) { while (!q.isEmpty()) { int[] cur = q.poll(); @@ -869,8 +886,8 @@ public class Solution { ocean[r][c] = true; for (int[] d : directions) { int nr = r + d[0], nc = c + d[1]; - if (nr >= 0 && nr < heights.length && nc >= 0 && - nc < heights[0].length && !ocean[nr][nc] && + if (nr >= 0 && nr < heights.length && nc >= 0 && + nc < heights[0].length && !ocean[nr][nc] && heights[nr][nc] >= heights[r][c]) { q.add(new int[]{nr, nc}); } @@ -882,16 +899,16 @@ public class Solution { ```cpp class Solution { - vector> directions = {{1, 0}, {-1, 0}, + vector> directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; public: vector> pacificAtlantic(vector>& heights) { int ROWS = heights.size(), COLS = heights[0].size(); vector> pac(ROWS, vector(COLS, false)); vector> atl(ROWS, vector(COLS, false)); - + queue> pacQueue, atlQueue; - + for (int c = 0; c < COLS; ++c) { pacQueue.push({0, c}); atlQueue.push({ROWS - 1, c}); @@ -916,15 +933,15 @@ public: } private: - void bfs(queue>& q, vector>& ocean, + void bfs(queue>& q, vector>& ocean, vector>& heights) { while (!q.empty()) { auto [r, c] = q.front(); q.pop(); ocean[r][c] = true; for (auto [dr, dc] : directions) { int nr = r + dr, nc = c + dc; - if (nr >= 0 && nr < heights.size() && nc >= 0 && - nc < heights[0].size() && !ocean[nr][nc] && + if (nr >= 0 && nr < heights.size() && nc >= 0 && + nc < heights[0].size() && !ocean[nr][nc] && heights[nr][nc] >= heights[r][c]) { q.push({nr, nc}); } @@ -941,14 +958,18 @@ class Solution { * @return {number[][]} */ pacificAtlantic(heights) { - let ROWS = heights.length, COLS = heights[0].length; - let directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; - let pac = Array.from({ length: ROWS }, () => - Array(COLS).fill(false)); - let atl = Array.from({ length: ROWS }, () => - Array(COLS).fill(false)); - - let pacQueue = new Queue() + let ROWS = heights.length, + COLS = heights[0].length; + let directions = [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + ]; + let pac = Array.from({ length: ROWS }, () => Array(COLS).fill(false)); + let atl = Array.from({ length: ROWS }, () => Array(COLS).fill(false)); + + let pacQueue = new Queue(); let atlQueue = new Queue(); for (let c = 0; c < COLS; c++) { pacQueue.push([0, c]); @@ -964,15 +985,21 @@ class Solution { let [r, c] = queue.pop(); ocean[r][c] = true; for (let [dr, dc] of directions) { - let nr = r + dr, nc = c + dc; - if (nr >= 0 && nr < ROWS && nc >= 0 && - nc < COLS && !ocean[nr][nc] && - heights[nr][nc] >= heights[r][c]) { + let nr = r + dr, + nc = c + dc; + if ( + nr >= 0 && + nr < ROWS && + nc >= 0 && + nc < COLS && + !ocean[nr][nc] && + heights[nr][nc] >= heights[r][c] + ) { queue.push([nr, nc]); } } } - } + }; bfs(pacQueue, pac, heights); bfs(atlQueue, atl, heights); @@ -991,9 +1018,9 @@ class Solution { ```csharp public class Solution { - private int[][] directions = new int[][] { - new int[] { 1, 0 }, new int[] { -1, 0 }, - new int[] { 0, 1 }, new int[] { 0, -1 } + private int[][] directions = new int[][] { + new int[] { 1, 0 }, new int[] { -1, 0 }, + new int[] { 0, 1 }, new int[] { 0, -1 } }; public List> PacificAtlantic(int[][] heights) { int ROWS = heights.Length, COLS = heights[0].Length; @@ -1033,8 +1060,8 @@ public class Solution { ocean[r, c] = true; foreach (var dir in directions) { int nr = r + dir[0], nc = c + dir[1]; - if (nr >= 0 && nr < heights.Length && nc >= 0 && - nc < heights[0].Length && !ocean[nr, nc] && + if (nr >= 0 && nr < heights.Length && nc >= 0 && + nc < heights[0].Length && !ocean[nr, nc] && heights[nr][nc] >= heights[r][c]) { q.Enqueue(new int[] { nr, nc }); } @@ -1048,7 +1075,7 @@ public class Solution { func pacificAtlantic(heights [][]int) [][]int { rows, cols := len(heights), len(heights[0]) directions := [][]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}} - + pac := make([][]bool, rows) atl := make([][]bool, rows) for i := range pac { @@ -1107,11 +1134,11 @@ class Solution { fun pacificAtlantic(heights: Array): List> { val rows = heights.size val cols = heights[0].size - val directions = arrayOf(intArrayOf(1, 0), - intArrayOf(-1, 0), - intArrayOf(0, 1), + val directions = arrayOf(intArrayOf(1, 0), + intArrayOf(-1, 0), + intArrayOf(0, 1), intArrayOf(0, -1)) - + val pac = Array(rows) { BooleanArray(cols) } val atl = Array(rows) { BooleanArray(cols) } @@ -1177,7 +1204,7 @@ class Solution { for dir in directions { let nr = r + dir.0 let nc = c + dir.1 - if nr >= 0, nr < ROWS, nc >= 0, nc < COLS, + if nr >= 0, nr < ROWS, nc >= 0, nc < COLS, !ocean[nr][nc], heights[nr][nc] >= heights[r][c] { queue.append((nr, nc)) } @@ -1218,7 +1245,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ -> Where $m$ is the number of rows and $n$ is the number of columns. \ No newline at end of file +> Where $m$ is the number of rows and $n$ is the number of columns. diff --git a/articles/paint-house.md b/articles/paint-house.md index 91b9896cd..9960e4492 100644 --- a/articles/paint-house.md +++ b/articles/paint-house.md @@ -108,8 +108,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -246,8 +246,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -261,7 +261,7 @@ class Solution: n = len(costs) if n == 0: return 0 - + dp = [[0] * 3 for _ in range(n)] for c in range(3): dp[0][c] = costs[0][c] @@ -340,8 +340,9 @@ class Solution { for (let i = 1; i < n; i++) { for (let c = 0; c < 3; c++) { - dp[i][c] = costs[i][c] + - Math.min(dp[i - 1][(c + 1) % 3], dp[i - 1][(c + 2) % 3]); + dp[i][c] = + costs[i][c] + + Math.min(dp[i - 1][(c + 1) % 3], dp[i - 1][(c + 2) % 3]); } } @@ -354,8 +355,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -441,5 +442,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/painting-the-walls.md b/articles/painting-the-walls.md index 1942d0042..b7ea573e3 100644 --- a/articles/painting-the-walls.md +++ b/articles/painting-the-walls.md @@ -11,7 +11,7 @@ class Solution: return 0 if i == len(cost): return float("inf") - + paint = cost[i] + dfs(i + 1, remain - 1 - time[i]) skip = dfs(i + 1, remain) return min(paint, skip) @@ -59,7 +59,7 @@ private: int paint = dfs(cost, time, i + 1, remain - 1 - time[i]); if (paint != INT_MAX) paint += cost[i]; - + int skip = dfs(cost, time, i + 1, remain); return min(paint, skip); } @@ -96,8 +96,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -117,7 +117,7 @@ class Solution: return float("inf") if (i, remain) in dp: return dp[(i, remain)] - + paint = cost[i] + dfs(i + 1, remain - 1 - time[i]) skip = dfs(i + 1, remain) dp[(i, remain)] = min(paint, skip) @@ -182,7 +182,7 @@ private: int paint = dfs(cost, time, i + 1, remain - 1 - time[i]); if (paint != INT_MAX) paint += cost[i]; - + int skip = dfs(cost, time, i + 1, remain); return dp[i][remain] = min(paint, skip); } @@ -212,7 +212,7 @@ class Solution { const paint = cost[i] + dfs(i + 1, remain - 1 - time[i]); const skip = dfs(i + 1, remain); - return dp[i][remain] = Math.min(paint, skip); + return (dp[i][remain] = Math.min(paint, skip)); }; return dfs(0, cost.length); @@ -224,8 +224,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -246,7 +246,7 @@ class Solution: paint = cost[i] + dp[i + 1][max(remain - 1 - time[i], 0)] skip = dp[i + 1][remain] dp[i][remain] = min(paint, skip) - + return dp[0][n] ``` @@ -263,7 +263,7 @@ public class Solution { for (int remain = 1; remain <= n; remain++) { int paint = dp[i + 1][Math.max(remain - 1 - time[i], 0)]; if (paint != Integer.MAX_VALUE) paint += cost[i]; - + int skip = dp[i + 1][remain]; dp[i][remain] = Math.min(paint, skip); } @@ -289,7 +289,7 @@ public: for (int remain = 1; remain <= n; remain++) { int paint = dp[i + 1][max(remain - 1 - time[i], 0)]; if (paint != INT_MAX) paint += cost[i]; - + int skip = dp[i + 1][remain]; dp[i][remain] = min(paint, skip); } @@ -317,7 +317,8 @@ class Solution { for (let i = n - 1; i >= 0; i--) { for (let remain = 1; remain <= n; remain++) { - const paint = cost[i] + dp[i + 1][Math.max(remain - 1 - time[i], 0)]; + const paint = + cost[i] + dp[i + 1][Math.max(remain - 1 - time[i], 0)]; const skip = dp[i + 1][remain]; dp[i][remain] = Math.min(paint, skip); } @@ -332,8 +333,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -352,7 +353,7 @@ class Solution: for remain in range(n, 0, -1): paint = cost[i] + dp[max(remain - 1 - time[i], 0)] dp[remain] = min(paint, dp[remain]) - + return dp[n] ``` @@ -426,5 +427,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ diff --git a/articles/palindrome-linked-list.md b/articles/palindrome-linked-list.md index f4f73b7bc..4656304f3 100644 --- a/articles/palindrome-linked-list.md +++ b/articles/palindrome-linked-list.md @@ -118,7 +118,8 @@ class Solution { cur = cur.next; } - let l = 0, r = arr.length - 1; + let l = 0, + r = arr.length - 1; while (l < r) { if (arr[l] !== arr[r]) { return false; @@ -136,8 +137,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -276,8 +277,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -295,15 +296,15 @@ class Solution: def isPalindrome(self, head: Optional[ListNode]) -> bool: stack = [] cur = head - + while cur: stack.append(cur.val) cur = cur.next - + cur = head while cur and cur.val == stack.pop(): cur = cur.next - + return not cur ``` @@ -409,8 +410,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -449,7 +450,7 @@ class Solution: return False left = left.next right = right.next - + return True ``` @@ -560,7 +561,8 @@ class Solution { * @return {boolean} */ isPalindrome(head) { - let fast = head, slow = head; + let fast = head, + slow = head; // find middle (slow) while (fast && fast.next) { @@ -578,7 +580,8 @@ class Solution { } // check palindrome - let left = head, right = prev; + let left = head, + right = prev; while (right) { if (left.val !== right.val) { return false; @@ -596,5 +599,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/palindrome-number.md b/articles/palindrome-number.md index 445520930..ffbebc536 100644 --- a/articles/palindrome-number.md +++ b/articles/palindrome-number.md @@ -59,8 +59,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ > Where $n$ is the number of digits in the given integer. @@ -121,7 +121,7 @@ class Solution { isPalindrome(x) { const s = String(x); let n = s.length; - for (let i = 0; i < (n >> 1); i++) { + for (let i = 0; i < n >> 1; i++) { if (s.charAt(i) != s.charAt(n - i - 1)) { return false; } @@ -150,8 +150,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ > Where $n$ is the number of digits in the given integer. @@ -224,9 +224,10 @@ class Solution { return false; } - let rev = 0, num = x; + let rev = 0, + num = x; while (num !== 0) { - rev = (rev * 10) + (num % 10); + rev = rev * 10 + (num % 10); num = Math.floor(num / 10); } @@ -253,8 +254,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ > Where $n$ is the number of digits in the given integer. @@ -390,8 +391,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ > Where $n$ is the number of digits in the given integer. @@ -496,7 +497,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ -> Where $n$ is the number of digits in the given integer. \ No newline at end of file +> Where $n$ is the number of digits in the given integer. diff --git a/articles/palindrome-partitioning.md b/articles/palindrome-partitioning.md index 3e87916a5..1112bfbb5 100644 --- a/articles/palindrome-partitioning.md +++ b/articles/palindrome-partitioning.md @@ -12,14 +12,14 @@ class Solution: if i == j: res.append(part.copy()) return - + if self.isPali(s, j, i): part.append(s[j : i + 1]) dfs(i + 1, i + 1) part.pop() - + dfs(j, i + 1) - + dfs(0, 0) return res @@ -48,13 +48,13 @@ public class Solution { } return; } - + if (isPali(s, j, i)) { part.add(s.substring(j, i + 1)); dfs(i + 1, i + 1, s); part.remove(part.size() - 1); } - + dfs(j, i + 1, s); } @@ -88,13 +88,13 @@ public: } return; } - + if (isPali(s, j, i)) { part.push_back(s.substr(j, i - j + 1)); dfs(i + 1, i + 1, s, part); part.pop_back(); } - + dfs(j, i + 1, s, part); } @@ -328,10 +328,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 2 ^ n)$ -* Space complexity: - * $O(n)$ extra space. - * $O(n * 2 ^ n)$ space for the output list. +- Time complexity: $O(n * 2 ^ n)$ +- Space complexity: + - $O(n)$ extra space. + - $O(n * 2 ^ n)$ space for the output list. --- @@ -341,7 +341,7 @@ class Solution { ```python class Solution: - + def partition(self, s: str) -> List[List[str]]: res, part = [], [] @@ -368,7 +368,7 @@ class Solution: ```java public class Solution { - + public List> partition(String s) { List> res = new ArrayList<>(); List part = new ArrayList<>(); @@ -496,7 +496,7 @@ class Solution { ```csharp public class Solution { - + public List> Partition(string s) { List> res = new List>(); List part = new List(); @@ -649,10 +649,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 2 ^ n)$ -* Space complexity: - * $O(n)$ extra space. - * $O(n * 2 ^ n)$ space for the output list. +- Time complexity: $O(n * 2 ^ n)$ +- Space complexity: + - $O(n)$ extra space. + - $O(n * 2 ^ n)$ space for the output list. --- @@ -662,7 +662,7 @@ class Solution { ```python class Solution: - + def partition(self, s: str) -> List[List[str]]: n = len(s) dp = [[False] * n for _ in range(n)] @@ -695,12 +695,12 @@ public class Solution { dp = new boolean[n][n]; for (int l = 1; l <= n; l++) { for (int i = 0; i <= n - l; i++) { - dp[i][i + l - 1] = (s.charAt(i) == s.charAt(i + l - 1) && - (i + 1 > (i + l - 2) || + dp[i][i + l - 1] = (s.charAt(i) == s.charAt(i + l - 1) && + (i + 1 > (i + l - 2) || dp[i + 1][i + l - 2])); } } - + List> res = new ArrayList<>(); List part = new ArrayList<>(); dfs(0, s, part, res); @@ -732,8 +732,8 @@ public: dp.resize(n, vector(n)); for (int l = 1; l <= n; l++) { for (int i = 0; i <= n - l; i++) { - dp[i][i + l - 1] = (s[i] == s[i + l - 1] && - (i + 1 > (i + l - 2) || + dp[i][i + l - 1] = (s[i] == s[i + l - 1] && + (i + 1 > (i + l - 2) || dp[i + 1][i + l - 2])); } } @@ -772,9 +772,9 @@ class Solution { const dp = Array.from({ length: n }, () => Array(n).fill(false)); for (let l = 1; l <= n; l++) { for (let i = 0; i <= n - l; i++) { - dp[i][i + l - 1] = (s[i] === s[i + l - 1] && - (i + 1 > (i + l - 2) || - dp[i + 1][i + l - 2])); + dp[i][i + l - 1] = + s[i] === s[i + l - 1] && + (i + 1 > i + l - 2 || dp[i + 1][i + l - 2]); } } @@ -792,7 +792,7 @@ class Solution { part.pop(); } } - } + }; dfs(0); return res; } @@ -801,18 +801,18 @@ class Solution { ```csharp public class Solution { - + public List> Partition(string s) { int n = s.Length; bool[,] dp = new bool[n, n]; for (int l = 1; l <= n; l++) { for (int i = 0; i <= n - l; i++) { - dp[i, i + l - 1] = (s[i] == s[i + l - 1] && - (i + 1 > (i + l - 2) || + dp[i, i + l - 1] = (s[i] == s[i + l - 1] && + (i + 1 > (i + l - 2) || dp[i + 1, i + l - 2])); } } - + List> res = new List>(); List part = new List(); Dfs(0, s, part, res, dp); @@ -880,7 +880,7 @@ class Solution { for (l in 1..n) { for (i in 0..n - l) { - dp[i][i + l - 1] = s[i] == s[i + l - 1] && + dp[i][i + l - 1] = s[i] == s[i + l - 1] && (i + 1 > (i + l - 2) || dp[i + 1][i + l - 2]) } } @@ -914,7 +914,7 @@ class Solution { let n = s.count let sArray = Array(s) var dp = Array(repeating: Array(repeating: false, count: n), count: n) - + for l in 1...n { for i in 0...(n - l) { dp[i][i + l - 1] = (sArray[i] == sArray[i + l - 1] && @@ -949,10 +949,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 2 ^ n)$ -* Space complexity: - * $O(n ^ 2)$ extra space. - * $O(n * 2 ^ n)$ space for the output list. +- Time complexity: $O(n * 2 ^ n)$ +- Space complexity: + - $O(n ^ 2)$ extra space. + - $O(n * 2 ^ n)$ space for the output list. --- @@ -962,7 +962,7 @@ class Solution { ```python class Solution: - + def partition(self, s: str) -> List[List[str]]: n = len(s) dp = [[False] * n for _ in range(n)] @@ -971,37 +971,37 @@ class Solution: dp[i][i + l - 1] = (s[i] == s[i + l - 1] and (i + 1 > (i + l - 2) or dp[i + 1][i + l - 2])) - + def dfs(i): if i >= n: - return [[]] - + return [[]] + ret = [] for j in range(i, n): if dp[i][j]: nxt = dfs(j + 1) for part in nxt: - cur = [s[i : j + 1]] + part + cur = [s[i : j + 1]] + part ret.append(cur) return ret - + return dfs(0) ``` ```java public class Solution { - + public List> partition(String s) { int n = s.length(); boolean[][] dp = new boolean[n][n]; for (int l = 1; l <= n; l++) { for (int i = 0; i <= n - l; i++) { - dp[i][i + l - 1] = (s.charAt(i) == s.charAt(i + l - 1) && - (i + 1 > (i + l - 2) || + dp[i][i + l - 1] = (s.charAt(i) == s.charAt(i + l - 1) && + (i + 1 > (i + l - 2) || dp[i + 1][i + l - 2])); } } - + return dfs(s, dp, 0); } @@ -1035,12 +1035,12 @@ public: vector> dp(n, vector(n, false)); for (int l = 1; l <= n; l++) { for (int i = 0; i <= n - l; i++) { - dp[i][i + l - 1] = (s[i] == s[i + l - 1] && - (i + 1 > (i + l - 2) || + dp[i][i + l - 1] = (s[i] == s[i + l - 1] && + (i + 1 > (i + l - 2) || dp[i + 1][i + l - 2])); } } - + return dfs(s, dp, 0); } @@ -1077,12 +1077,12 @@ class Solution { const dp = Array.from({ length: n }, () => Array(n).fill(false)); for (let l = 1; l <= n; l++) { for (let i = 0; i <= n - l; i++) { - dp[i][i + l - 1] = (s[i] === s[i + l - 1] && - (i + 1 > (i + l - 2) || - dp[i + 1][i + l - 2])); + dp[i][i + l - 1] = + s[i] === s[i + l - 1] && + (i + 1 > i + l - 2 || dp[i + 1][i + l - 2]); } } - + const dfs = (i) => { if (i >= s.length) { return [[]]; @@ -1108,18 +1108,18 @@ class Solution { ```csharp public class Solution { - + public List> Partition(string s) { int n = s.Length; bool[,] dp = new bool[n, n]; for (int l = 1; l <= n; l++) { for (int i = 0; i <= n - l; i++) { - dp[i, i + l - 1] = (s[i] == s[i + l - 1] && - (i + 1 > (i + l - 2) || + dp[i, i + l - 1] = (s[i] == s[i + l - 1] && + (i + 1 > (i + l - 2) || dp[i + 1, i + l - 2])); } } - + return Dfs(s, dp, 0); } @@ -1154,7 +1154,7 @@ func partition(s string) [][]string { for l := 1; l <= n; l++ { for i := 0; i <= n-l; i++ { - dp[i][i+l-1] = (s[i] == s[i+l-1] && + dp[i][i+l-1] = (s[i] == s[i+l-1] && (i+1 > (i+l-2) || dp[i+1][i+l-2])) } } @@ -1190,7 +1190,7 @@ class Solution { for (l in 1..n) { for (i in 0..n - l) { - dp[i][i + l - 1] = s[i] == s[i + l - 1] && + dp[i][i + l - 1] = s[i] == s[i + l - 1] && (i + 1 > (i + l - 2) || dp[i + 1][i + l - 2]) } } @@ -1261,7 +1261,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 2 ^ n)$ -* Space complexity: - * $O(n ^ 2)$ extra space. - * $O(n * 2 ^ n)$ space for the output list. \ No newline at end of file +- Time complexity: $O(n * 2 ^ n)$ +- Space complexity: + - $O(n ^ 2)$ extra space. + - $O(n * 2 ^ n)$ space for the output list. diff --git a/articles/palindromic-substrings.md b/articles/palindromic-substrings.md index cd1dfa352..6fe6fb522 100644 --- a/articles/palindromic-substrings.md +++ b/articles/palindromic-substrings.md @@ -6,7 +6,7 @@ class Solution: def countSubstrings(self, s: str) -> int: res = 0 - + for i in range(len(s)): for j in range(i, len(s)): l, r = i, j @@ -14,7 +14,7 @@ class Solution: l += 1 r -= 1 res += (l >= r) - + return res ``` @@ -72,12 +72,13 @@ class Solution { for (let i = 0; i < s.length; i++) { for (let j = i; j < s.length; j++) { - let l = i, r = j; + let l = i, + r = j; while (l < r && s[l] === s[r]) { l++; r--; } - res += (l >= r) ? 1 : 0; + res += l >= r ? 1 : 0; } } @@ -176,8 +177,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 3)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 3)$ +- Space complexity: $O(1)$ --- @@ -208,9 +209,9 @@ public class Solution { for (int i = n - 1; i >= 0; i--) { for (int j = i; j < n; j++) { - if (s.charAt(i) == s.charAt(j) && + if (s.charAt(i) == s.charAt(j) && (j - i <= 2 || dp[i + 1][j - 1])) { - + dp[i][j] = true; res++; } @@ -231,7 +232,7 @@ public: for (int i = n - 1; i >= 0; i--) { for (int j = i; j < n; j++) { - if (s[i] == s[j] && + if (s[i] == s[j] && (j - i <= 2 || dp[i + 1][j - 1])) { dp[i][j] = true; @@ -258,9 +259,7 @@ class Solution { for (let i = n - 1; i >= 0; i--) { for (let j = i; j < n; j++) { - if (s[i] === s[j] && - (j - i <= 2 || dp[i + 1][j - 1])) { - + if (s[i] === s[j] && (j - i <= 2 || dp[i + 1][j - 1])) { dp[i][j] = true; res++; } @@ -280,9 +279,9 @@ public class Solution { for (int i = n - 1; i >= 0; i--) { for (int j = i; j < n; j++) { - if (s[i] == s[j] && + if (s[i] == s[j] && (j - i <= 2 || dp[i + 1, j - 1])) { - + dp[i, j] = true; res++; } @@ -363,8 +362,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -376,7 +375,7 @@ class Solution { class Solution: def countSubstrings(self, s: str) -> int: res = 0 - + for i in range(len(s)): # odd length l, r = i, i @@ -391,7 +390,7 @@ class Solution: res += 1 l -= 1 r += 1 - + return res ``` @@ -399,11 +398,11 @@ class Solution: public class Solution { public int countSubstrings(String s) { int res = 0; - + for (int i = 0; i < s.length(); i++) { // odd length int l = i, r = i; - while (l >= 0 && r < s.length() && + while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { res++; l--; @@ -413,7 +412,7 @@ public class Solution { // even length l = i; r = i + 1; - while (l >= 0 && r < s.length() && + while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) { res++; l--; @@ -466,13 +465,12 @@ class Solution { */ countSubstrings(s) { let res = 0; - + for (let i = 0; i < s.length; i++) { // odd length let l = i; - let r = i; - while (l >= 0 && r < s.length && - s.charAt(l) === s.charAt(r)) { + let r = i; + while (l >= 0 && r < s.length && s.charAt(l) === s.charAt(r)) { res++; l--; r++; @@ -481,8 +479,7 @@ class Solution { // even length l = i; r = i + 1; - while (l >= 0 && r < s.length && - s.charAt(l) === s.charAt(r)) { + while (l >= 0 && r < s.length && s.charAt(l) === s.charAt(r)) { res++; l--; r++; @@ -498,7 +495,7 @@ class Solution { public class Solution { public int CountSubstrings(string s) { int res = 0; - + for (int i = 0; i < s.Length; i++) { // odd length int l = i, r = i; @@ -586,7 +583,7 @@ class Solution { func countSubstrings(_ s: String) -> Int { let chars = Array(s) var res = 0 - + for i in 0.. int: res = 0 @@ -646,7 +643,7 @@ class Solution: ```java public class Solution { - + public int countSubstrings(String s) { int res = 0; for (int i = 0; i < s.length(); i++) { @@ -717,8 +714,7 @@ class Solution { */ countPali(s, l, r) { let res = 0; - while (l >= 0 && r < s.length && - s.charAt(l) === s.charAt(r)) { + while (l >= 0 && r < s.length && s.charAt(l) === s.charAt(r)) { res++; l--; r++; @@ -730,7 +726,7 @@ class Solution { ```csharp public class Solution { - + public int CountSubstrings(string s) { int res = 0; for (int i = 0; i < s.Length; i++) { @@ -756,8 +752,8 @@ public class Solution { func countSubstrings(s string) int { res := 0 for i := 0; i < len(s); i++ { - res += countPali(s, i, i) - res += countPali(s, i, i+1) + res += countPali(s, i, i) + res += countPali(s, i, i+1) } return res } @@ -778,8 +774,8 @@ class Solution { fun countSubstrings(s: String): Int { var res = 0 for (i in s.indices) { - res += countPali(s, i, i) - res += countPali(s, i, i + 1) + res += countPali(s, i, i) + res += countPali(s, i, i + 1) } return res } @@ -829,8 +825,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -849,13 +845,13 @@ class Solution: l, r = 0, 0 for i in range(n): p[i] = min(r - i, p[l + (r - i)]) if i < r else 0 - while (i + p[i] + 1 < n and i - p[i] - 1 >= 0 + while (i + p[i] + 1 < n and i - p[i] - 1 >= 0 and t[i + p[i] + 1] == t[i - p[i] - 1]): p[i] += 1 if i + p[i] > r: l, r = i - p[i], i + p[i] return p - + p = manacher(s) res = 0 for i in p: @@ -943,11 +939,15 @@ class Solution { const t = '#' + s.split('').join('#') + '#'; const n = t.length; const p = new Array(n).fill(0); - let l = 0, r = 0; + let l = 0, + r = 0; for (let i = 0; i < n; i++) { - p[i] = (i < r) ? Math.min(r - i, p[l + (r - i)]) : 0; - while (i + p[i] + 1 < n && i - p[i] - 1 >= 0 && - t[i + p[i] + 1] === t[i - p[i] - 1]) { + p[i] = i < r ? Math.min(r - i, p[l + (r - i)]) : 0; + while ( + i + p[i] + 1 < n && + i - p[i] - 1 >= 0 && + t[i + p[i] + 1] === t[i - p[i] - 1] + ) { p[i]++; } if (i + p[i] > r) { @@ -1025,7 +1025,7 @@ func countSubstrings(s string) int { } return p } - + p := manacher(s) res := 0 for _, val := range p { @@ -1063,7 +1063,7 @@ class Solution { if (i < r) { p[i] = minOf(r - i, p[l + (r - i)]) } - while (i + p[i] + 1 < n && i - p[i] - 1 >= 0 && + while (i + p[i] + 1 < n && i - p[i] - 1 >= 0 && t[i + p[i] + 1] == t[i - p[i] - 1]) { p[i]++ } @@ -1125,5 +1125,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/parallel-courses-iii.md b/articles/parallel-courses-iii.md index ca66a0769..6e73223d2 100644 --- a/articles/parallel-courses-iii.md +++ b/articles/parallel-courses-iii.md @@ -150,8 +150,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ > Where $V$ is the number of courses and $E$ is the number of prerequisites. @@ -322,8 +322,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ > Where $V$ is the number of courses and $E$ is the number of prerequisites. @@ -459,7 +459,10 @@ class Solution { while (!queue.isEmpty()) { let node = queue.pop(); for (let nei of adj[node]) { - maxTime[nei] = Math.max(maxTime[nei], maxTime[node] + time[nei]); + maxTime[nei] = Math.max( + maxTime[nei], + maxTime[node] + time[nei], + ); if (--indegree[nei] === 0) { queue.push(nei); } @@ -475,7 +478,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ -> Where $V$ is the number of courses and $E$ is the number of prerequisites. \ No newline at end of file +> Where $V$ is the number of courses and $E$ is the number of prerequisites. diff --git a/articles/partition-array-for-maximum-sum.md b/articles/partition-array-for-maximum-sum.md index a2fb52393..5b78a466d 100644 --- a/articles/partition-array-for-maximum-sum.md +++ b/articles/partition-array-for-maximum-sum.md @@ -83,7 +83,8 @@ class Solution { return 0; } - let cur_max = 0, res = 0; + let cur_max = 0, + res = 0; for (let j = i; j < Math.min(arr.length, i + k); j++) { cur_max = Math.max(cur_max, arr[j]); let window_size = j - i + 1; @@ -102,8 +103,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(k ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(k ^ n)$ +- Space complexity: $O(n)$ for recursion stack. > Where $k$ is the maximum length of the subarray and $n$ is the size of the array $arr$. @@ -205,7 +206,8 @@ class Solution { return cache[i]; } - let cur_max = 0, res = 0; + let cur_max = 0, + res = 0; for (let j = i; j < Math.min(arr.length, i + k); j++) { cur_max = Math.max(cur_max, arr[j]); let window_size = j - i + 1; @@ -224,8 +226,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * k)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * k)$ +- Space complexity: $O(n)$ > Where $k$ is the maximum length of the subarray and $n$ is the size of the array $arr$. @@ -321,8 +323,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * k)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * k)$ +- Space complexity: $O(n)$ > Where $k$ is the maximum length of the subarray and $n$ is the size of the array $arr$. @@ -419,13 +421,14 @@ class Solution { dp[0] = arr[0]; for (let i = 1; i < n; i++) { - let cur_max = 0, max_at_i = 0; + let cur_max = 0, + max_at_i = 0; for (let j = i; j > i - k; j--) { if (j < 0) break; cur_max = Math.max(cur_max, arr[j]); let window_size = i - j + 1; let cur_sum = cur_max * window_size; - let sub_sum = (j > 0) ? dp[(j - 1) % k] : 0; + let sub_sum = j > 0 ? dp[(j - 1) % k] : 0; max_at_i = Math.max(max_at_i, cur_sum + sub_sum); } dp[i % k] = max_at_i; @@ -440,7 +443,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * k)$ -* Space complexity: $O(k)$ +- Time complexity: $O(n * k)$ +- Space complexity: $O(k)$ -> Where $k$ is the maximum length of the subarray and $n$ is the size of the array $arr$. \ No newline at end of file +> Where $k$ is the maximum length of the subarray and $n$ is the size of the array $arr$. diff --git a/articles/partition-equal-subset-sum.md b/articles/partition-equal-subset-sum.md index 6d6fd0caa..d95805dc9 100644 --- a/articles/partition-equal-subset-sum.md +++ b/articles/partition-equal-subset-sum.md @@ -7,15 +7,15 @@ class Solution: def canPartition(self, nums: List[int]) -> bool: if sum(nums) % 2: return False - + def dfs(i, target): if i >= len(nums): return target == 0 if target < 0: return False - + return dfs(i + 1, target) or dfs(i + 1, target - nums[i]) - + return dfs(0, sum(nums) // 2) ``` @@ -30,7 +30,7 @@ public class Solution { if (sum % 2 != 0) { return false; } - + return dfs(nums, 0, sum / 2); } @@ -42,7 +42,7 @@ public class Solution { return false; } - return dfs(nums, i + 1, target) || + return dfs(nums, i + 1, target) || dfs(nums, i + 1, target - nums[i]); } } @@ -59,7 +59,7 @@ public: if (sum % 2 != 0) { return false; } - + return dfs(nums, 0, sum / 2); } @@ -71,7 +71,7 @@ public: return false; } - return dfs(nums, i + 1, target) || + return dfs(nums, i + 1, target) || dfs(nums, i + 1, target - nums[i]); } }; @@ -88,7 +88,7 @@ class Solution { if (sum % 2 !== 0) { return false; } - + return this.dfs(nums, 0, sum / 2); } @@ -106,8 +106,10 @@ class Solution { return false; } - return this.dfs(nums, i + 1, target) || - this.dfs(nums, i + 1, target - nums[i]); + return ( + this.dfs(nums, i + 1, target) || + this.dfs(nums, i + 1, target - nums[i]) + ); } } ``` @@ -122,7 +124,7 @@ public class Solution { if (sum % 2 != 0) { return false; } - + return Dfs(nums, 0, sum / 2); } @@ -134,7 +136,7 @@ public class Solution { return false; } - return Dfs(nums, i + 1, target) || + return Dfs(nums, i + 1, target) || Dfs(nums, i + 1, target - nums[i]); } } @@ -149,9 +151,9 @@ func canPartition(nums []int) bool { if sum%2 != 0 { return false } - + target := sum / 2 - + var dfs func(int, int) bool dfs = func(i int, target int) bool { if target == 0 { @@ -160,10 +162,10 @@ func canPartition(nums []int) bool { if i >= len(nums) || target < 0 { return false } - + return dfs(i+1, target) || dfs(i+1, target-nums[i]) } - + return dfs(0, target) } ``` @@ -175,9 +177,9 @@ class Solution { if (sum % 2 != 0) { return false } - + val target = sum / 2 - + fun dfs(i: Int, target: Int): Boolean { if (target == 0) { return true @@ -185,10 +187,10 @@ class Solution { if (i >= nums.size || target < 0) { return false } - + return dfs(i + 1, target) || dfs(i + 1, target - nums[i]) } - + return dfs(0, target) } } @@ -225,8 +227,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ --- @@ -240,7 +242,7 @@ class Solution: total = sum(nums) if total % 2 != 0: return False - + target = total // 2 n = len(nums) memo = [[-1] * (target + 1) for _ in range(n + 1)] @@ -252,8 +254,8 @@ class Solution: return False if memo[i][target] != -1: return memo[i][target] - - memo[i][target] = (dfs(i + 1, target) or + + memo[i][target] = (dfs(i + 1, target) or dfs(i + 1, target - nums[i])) return memo[i][target] @@ -273,7 +275,7 @@ public class Solution { return false; } memo = new Boolean[n][sum / 2 + 1]; - + return dfs(nums, 0, sum / 2); } @@ -288,7 +290,7 @@ public class Solution { return memo[i][target]; } - memo[i][target] = dfs(nums, i + 1, target) || + memo[i][target] = dfs(nums, i + 1, target) || dfs(nums, i + 1, target - nums[i]); return memo[i][target]; } @@ -308,7 +310,7 @@ public: return false; } memo.resize(nums.size(), vector(sum / 2 + 1, -1)); - + return dfs(nums, 0, sum / 2); } @@ -323,7 +325,7 @@ public: return memo[i][target]; } - memo[i][target] = dfs(nums, i + 1, target) || + memo[i][target] = dfs(nums, i + 1, target) || dfs(nums, i + 1, target - nums[i]); return memo[i][target]; } @@ -342,9 +344,10 @@ class Solution { return false; } const n = nums.length; - this.memo = Array.from(Array(n + 1), () => - Array(sum / 2 + 1).fill(null)); - + this.memo = Array.from(Array(n + 1), () => + Array(sum / 2 + 1).fill(null), + ); + return this.dfs(nums, 0, sum / 2); } @@ -365,8 +368,9 @@ class Solution { return this.memo[i][target]; } - this.memo[i][target] = this.dfs(nums, i + 1, target) || - this.dfs(nums, i + 1, target - nums[i]); + this.memo[i][target] = + this.dfs(nums, i + 1, target) || + this.dfs(nums, i + 1, target - nums[i]); return this.memo[i][target]; } } @@ -400,7 +404,7 @@ public class Solution { return memo[i, target] == true; } - bool result = Dfs(nums, i + 1, target) || + bool result = Dfs(nums, i + 1, target) || Dfs(nums, i + 1, target - nums[i]); memo[i, target] = result; @@ -418,7 +422,7 @@ func canPartition(nums []int) bool { if total%2 != 0 { return false } - + target := total / 2 n := len(nums) memo := make([][]int, n+1) @@ -440,14 +444,14 @@ func canPartition(nums []int) bool { if memo[i][target] != -1 { return memo[i][target] == 1 } - + found := dfs(i+1, target) || dfs(i+1, target-nums[i]) if found { memo[i][target] = 1 } else { memo[i][target] = 0 } - + return found } @@ -460,7 +464,7 @@ class Solution { fun canPartition(nums: IntArray): Boolean { val total = nums.sum() if (total % 2 != 0) return false - + val target = total / 2 val n = nums.size val memo = Array(n + 1) { IntArray(target + 1) { -1 } } @@ -469,10 +473,10 @@ class Solution { if (target == 0) return true if (i >= n || target < 0) return false if (memo[i][target] != -1) return memo[i][target] == 1 - + val found = dfs(i + 1, target) || dfs(i + 1, target - nums[i]) memo[i][target] = if (found) 1 else 0 - + return found } @@ -518,8 +522,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * target)$ -* Space complexity: $O(n * target)$ +- Time complexity: $O(n * target)$ +- Space complexity: $O(n * target)$ > Where $n$ is the length of the array $nums$ and $target$ is the sum of array elements divided by 2. @@ -546,7 +550,7 @@ class Solution: for i in range(1, n + 1): for j in range(1, target + 1): if nums[i - 1] <= j: - dp[i][j] = (dp[i - 1][j] or + dp[i][j] = (dp[i - 1][j] or dp[i - 1][j - nums[i - 1]]) else: dp[i][j] = dp[i - 1][j] @@ -565,7 +569,7 @@ public class Solution { if (sum % 2 != 0) { return false; } - + int target = sum / 2; boolean[][] dp = new boolean[n + 1][target + 1]; @@ -576,7 +580,7 @@ public class Solution { for (int i = 1; i <= n; i++) { for (int j = 1; j <= target; j++) { if (nums[i - 1] <= j) { - dp[i][j] = dp[i - 1][j] || + dp[i][j] = dp[i - 1][j] || dp[i - 1][j - nums[i - 1]]; } else { dp[i][j] = dp[i - 1][j]; @@ -600,19 +604,19 @@ public: if (sum % 2 != 0) { return false; } - + int target = sum / 2; int n = nums.size(); vector> dp(n + 1, vector(target + 1, false)); - + for (int i = 0; i <= n; i++) { - dp[i][0] = true; + dp[i][0] = true; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= target; j++) { if (nums[i - 1] <= j) { - dp[i][j] = dp[i - 1][j] || + dp[i][j] = dp[i - 1][j] || dp[i - 1][j - nums[i - 1]]; } else { dp[i][j] = dp[i - 1][j]; @@ -639,25 +643,25 @@ class Solution { const target = sum / 2; const n = nums.length; - const dp = Array.from(Array(n + 1), () => - Array(target + 1).fill(false)); + const dp = Array.from(Array(n + 1), () => + Array(target + 1).fill(false), + ); for (let i = 0; i <= n; i++) { - dp[i][0] = true; + dp[i][0] = true; } for (let i = 1; i <= n; i++) { for (let j = 1; j <= target; j++) { if (nums[i - 1] <= j) { - dp[i][j] = dp[i - 1][j] || - dp[i - 1][j - nums[i - 1]]; + dp[i][j] = dp[i - 1][j] || dp[i - 1][j - nums[i - 1]]; } else { dp[i][j] = dp[i - 1][j]; } } } - return dp[n][target]; + return dp[n][target]; } } ``` @@ -685,7 +689,7 @@ public class Solution { for (int i = 1; i <= n; i++) { for (int j = 1; j <= target; j++) { if (nums[i - 1] <= j) { - dp[i, j] = dp[i - 1, j] || + dp[i, j] = dp[i - 1, j] || dp[i - 1, j - nums[i - 1]]; } else { dp[i, j] = dp[i - 1, j]; @@ -693,7 +697,7 @@ public class Solution { } } - return dp[n, target]; + return dp[n, target]; } } ``` @@ -797,8 +801,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * target)$ -* Space complexity: $O(n * target)$ +- Time complexity: $O(n * target)$ +- Space complexity: $O(n * target)$ > Where $n$ is the length of the array $nums$ and $target$ is the sum of array elements divided by 2. @@ -818,7 +822,7 @@ class Solution: dp = [False] * (target + 1) nextDp = [False] * (target + 1) - dp[0] = True + dp[0] = True for i in range(len(nums)): for j in range(1, target + 1): if j >= nums[i]: @@ -826,7 +830,7 @@ class Solution: else: nextDp[j] = dp[j] dp, nextDp = nextDp, dp - + return dp[target] ``` @@ -854,7 +858,7 @@ public class Solution { dp = nextDp; nextDp = temp; } - + return dp[target]; } @@ -891,7 +895,7 @@ public: } swap(dp, nextDp); } - + return dp[target]; } @@ -932,7 +936,7 @@ class Solution { } [dp, nextDp] = [nextDp, dp]; } - + return dp[target]; } } @@ -962,7 +966,7 @@ public class Solution { dp = nextDp; nextDp = temp; } - + return dp[target]; } @@ -1063,8 +1067,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * target)$ -* Space complexity: $O(target)$ +- Time complexity: $O(n * target)$ +- Space complexity: $O(target)$ > Where $n$ is the length of the array $nums$ and $target$ is the sum of array elements divided by 2. @@ -1296,8 +1300,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * target)$ -* Space complexity: $O(target)$ +- Time complexity: $O(n * target)$ +- Space complexity: $O(target)$ > Where $n$ is the length of the array $nums$ and $target$ is the sum of array elements divided by 2. @@ -1320,7 +1324,7 @@ class Solution: for num in nums: for j in range(target, num - 1, -1): dp[j] = dp[j] or dp[j - num] - + return dp[target] ``` @@ -1340,7 +1344,7 @@ public class Solution { dp[j] = dp[j] || dp[j - nums[i]]; } } - + return dp[target]; } @@ -1371,7 +1375,7 @@ public: dp[j] = dp[j] || dp[j - nums[i]]; } } - + return dp[target]; } @@ -1406,7 +1410,7 @@ class Solution { dp[j] = dp[j] || dp[j - nums[i]]; } } - + return dp[target]; } } @@ -1428,7 +1432,7 @@ public class Solution { dp[j] = dp[j] || dp[j - nums[i]]; } } - + return dp[target]; } @@ -1513,8 +1517,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * target)$ -* Space complexity: $O(target)$ +- Time complexity: $O(n * target)$ +- Space complexity: $O(target)$ > Where $n$ is the length of the array $nums$ and $target$ is the sum of array elements divided by 2. @@ -1551,9 +1555,9 @@ public: if (sum % 2 != 0) { return false; } - + int target = sum / 2; - bitset<10001> dp; + bitset<10001> dp; dp[0] = 1; for (int num : nums) { @@ -1569,7 +1573,7 @@ public: ### Time & Space Complexity -* Time complexity: $O(n * target)$ -* Space complexity: $O(target)$ +- Time complexity: $O(n * target)$ +- Space complexity: $O(target)$ -> Where $n$ is the length of the array $nums$ and $target$ is the sum of array elements divided by 2. \ No newline at end of file +> Where $n$ is the length of the array $nums$ and $target$ is the sum of array elements divided by 2. diff --git a/articles/partition-labels.md b/articles/partition-labels.md index 1e4e2b3a1..75d799b9d 100644 --- a/articles/partition-labels.md +++ b/articles/partition-labels.md @@ -8,7 +8,7 @@ class Solution: lastIndex = {} for i, c in enumerate(s): lastIndex[c] = i - + res = [] size = end = 0 for i, c in enumerate(s): @@ -28,7 +28,7 @@ public class Solution { for (int i = 0; i < s.length(); i++) { lastIndex.put(s.charAt(i), i); } - + List res = new ArrayList<>(); int size = 0, end = 0; for (int i = 0; i < s.length(); i++) { @@ -83,7 +83,8 @@ class Solution { } let res = []; - let size = 0, end = 0; + let size = 0, + end = 0; for (let i = 0; i < S.length; i++) { size++; end = Math.max(end, lastIndex[S[i]]); @@ -198,7 +199,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n)$ +- Space complexity: $O(m)$ -> Where $n$ is the length of the string $s$ and $m$ is the number of unique characters in the string $s$. \ No newline at end of file +> Where $n$ is the length of the string $s$ and $m$ is the number of unique characters in the string $s$. diff --git a/articles/partition-list.md b/articles/partition-list.md index d3e69dd52..791ef3c05 100644 --- a/articles/partition-list.md +++ b/articles/partition-list.md @@ -12,7 +12,7 @@ class Solution: def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]: if not head: return None - + less, greater = [], [] cur = head while cur: @@ -95,7 +95,7 @@ class Solution { public: ListNode* partition(ListNode* head, int x) { if (!head) return nullptr; - + vector less, greater; ListNode* cur = head; @@ -143,7 +143,8 @@ class Solution { partition(head, x) { if (!head) return null; - let less = [], greater = []; + let less = [], + greater = []; let cur = head; while (cur) { @@ -175,8 +176,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -295,8 +296,10 @@ class Solution { * @return {ListNode} */ partition(head, x) { - let left = new ListNode(0), right = new ListNode(0); - let ltail = left, rtail = right; + let left = new ListNode(0), + right = new ListNode(0); + let ltail = left, + rtail = right; while (head) { if (head.val < x) { @@ -320,5 +323,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/partition-to-k-equal-sum-subsets.md b/articles/partition-to-k-equal-sum-subsets.md index d217736df..e4311864a 100644 --- a/articles/partition-to-k-equal-sum-subsets.md +++ b/articles/partition-to-k-equal-sum-subsets.md @@ -168,8 +168,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(k * 2 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(k * 2 ^ n)$ +- Space complexity: $O(n)$ > Where $n$ is the size of the array $nums$ and $k$ is the number of subsets. @@ -311,7 +311,8 @@ class Solution { used[j] = true; if (backtrack(j + 1, k, subsetSum + nums[j])) return true; used[j] = false; - if (subsetSum === 0) { // Pruning + if (subsetSum === 0) { + // Pruning return false; } } @@ -360,8 +361,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(k * 2 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(k * 2 ^ n)$ +- Space complexity: $O(n)$ > Where $n$ is the size of the array $nums$ and $k$ is the number of subsets. @@ -543,10 +544,10 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(k * 2 ^ n)$ -* Space complexity: - * $O(1)$ or $O(n)$ space depending on the sorting algorithm. - * $O(n)$ for the recursion stack. +- Time complexity: $O(k * 2 ^ n)$ +- Space complexity: + - $O(1)$ or $O(n)$ space depending on the sorting algorithm. + - $O(n)$ for the recursion stack. > Where $n$ is the size of the array $nums$ and $k$ is the number of subsets. @@ -789,8 +790,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 2 ^ n)$ -* Space complexity: $O(2 ^ n)$ +- Time complexity: $O(n * 2 ^ n)$ +- Space complexity: $O(2 ^ n)$ --- @@ -941,5 +942,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 2 ^ n)$ -* Space complexity: $O(2 ^ n)$ \ No newline at end of file +- Time complexity: $O(n * 2 ^ n)$ +- Space complexity: $O(2 ^ n)$ diff --git a/articles/pascals-triangle-ii.md b/articles/pascals-triangle-ii.md index 5a675a025..ffc0c7b7b 100644 --- a/articles/pascals-triangle-ii.md +++ b/articles/pascals-triangle-ii.md @@ -49,7 +49,7 @@ public: curRow.push_back(prevRow[i - 1] + prevRow[i]); } - curRow.push_back(1); + curRow.push_back(1); return curRow; } }; @@ -81,8 +81,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -139,7 +139,9 @@ class Solution { * @return {number[]} */ getRow(rowIndex) { - const res = Array.from({ length: rowIndex + 1 }, (_, i) => Array(i + 1).fill(1)); + const res = Array.from({ length: rowIndex + 1 }, (_, i) => + Array(i + 1).fill(1), + ); for (let i = 2; i <= rowIndex; i++) { for (let j = 1; j < i; j++) { res[i][j] = res[i - 1][j - 1] + res[i - 1][j]; @@ -154,8 +156,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -237,8 +239,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -307,8 +309,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -360,7 +362,9 @@ class Solution { getRow(rowIndex) { const row = [1]; for (let i = 1; i <= rowIndex; i++) { - row.push(Math.floor(row[row.length - 1] * (rowIndex - i + 1) / i)); + row.push( + Math.floor((row[row.length - 1] * (rowIndex - i + 1)) / i), + ); } return row; } @@ -371,5 +375,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/pascals-triangle.md b/articles/pascals-triangle.md index 79090ade0..2579a5220 100644 --- a/articles/pascals-triangle.md +++ b/articles/pascals-triangle.md @@ -99,8 +99,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -151,7 +151,7 @@ class Solution { public: vector> generate(int numRows) { vector> res = {{1}}; - + for (int i = 0; i < numRows - 1; i++) { vector temp = {0}; temp.insert(temp.end(), res.back().begin(), res.back().end()); @@ -194,22 +194,22 @@ public class Solution { public List> Generate(int numRows) { var res = new List>(); if (numRows <= 0) return res; - + res.Add(new List { 1 }); - + for (int i = 1; i < numRows; i++) { var prev = res[i - 1]; var temp = new List(prev); temp.Insert(0, 0); temp.Add(0); - + var row = new List(); for (int j = 0; j < prev.Count + 1; j++) { row.Add(temp[j] + temp[j + 1]); } res.Add(row); } - + return res; } } @@ -219,8 +219,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -284,7 +284,9 @@ class Solution { * @return {number[][]} */ generate(numRows) { - let res = Array.from({ length: numRows }, (_, i) => Array(i + 1).fill(1)); + let res = Array.from({ length: numRows }, (_, i) => + Array(i + 1).fill(1), + ); for (let i = 2; i < numRows; i++) { for (let j = 1; j < i; j++) { @@ -320,5 +322,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ \ No newline at end of file +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ diff --git a/articles/path-crossing.md b/articles/path-crossing.md index dd4abbaf2..958c7eb5c 100644 --- a/articles/path-crossing.md +++ b/articles/path-crossing.md @@ -11,7 +11,7 @@ class Solution: 'E': [1, 0], 'W': [-1, 0] } - + visit = set() x, y = 0, 0 @@ -55,18 +55,18 @@ public: unordered_set visit; int x = 0, y = 0; visit.insert(to_string(x) + "," + to_string(y)); - + for (char c : path) { if (c == 'N') y++; else if (c == 'S') y--; else if (c == 'E') x++; else if (c == 'W') x--; - + string pos = to_string(x) + "," + to_string(y); if (visit.count(pos)) return true; visit.insert(pos); } - + return false; } }; @@ -80,7 +80,8 @@ class Solution { */ isPathCrossing(path) { const visit = new Set(); - let x = 0, y = 0; + let x = 0, + y = 0; visit.add(`${x},${y}`); for (const c of path) { @@ -103,8 +104,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -162,7 +163,7 @@ public class Solution { } private long hash(long x, long y) { - return (x << 32) + y; + return (x << 32) + y; } } ``` @@ -206,7 +207,8 @@ class Solution { */ isPathCrossing(path) { const visit = new Set(); - let x = 0, y = 0; + let x = 0, + y = 0; visit.add(this.hash(x, y)); for (const c of path) { @@ -238,5 +240,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/path-sum.md b/articles/path-sum.md index ce01351cf..27da53c1e 100644 --- a/articles/path-sum.md +++ b/articles/path-sum.md @@ -14,13 +14,13 @@ class Solution: def dfs(node, curSum): if not node: return False - + curSum += node.val if not node.left and not node.right: return curSum == targetSum - + return dfs(node.left, curSum) or dfs(node.right, curSum) - + return dfs(root, 0) ``` @@ -128,8 +128,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -148,9 +148,9 @@ class Solution: def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool: if not root: return False - + targetSum -= root.val - return (self.hasPathSum(root.left, targetSum) or + return (self.hasPathSum(root.left, targetSum) or self.hasPathSum(root.right, targetSum) or (not targetSum and not root.left and not root.right)) ``` @@ -175,8 +175,8 @@ public class Solution { public boolean hasPathSum(TreeNode root, int targetSum) { if (root == null) return false; targetSum -= root.val; - return hasPathSum(root.left, targetSum) || - hasPathSum(root.right, targetSum) || + return hasPathSum(root.left, targetSum) || + hasPathSum(root.right, targetSum) || (targetSum == 0 && root.left == null && root.right == null); } } @@ -199,7 +199,7 @@ public: bool hasPathSum(TreeNode* root, int targetSum) { if (!root) return false; targetSum -= root->val; - return hasPathSum(root->left, targetSum) || + return hasPathSum(root->left, targetSum) || hasPathSum(root->right, targetSum) || (targetSum == 0 && !root->left && !root->right); } @@ -226,9 +226,11 @@ class Solution { hasPathSum(root, targetSum) { if (!root) return false; targetSum -= root.val; - return this.hasPathSum(root.left, targetSum) || - this.hasPathSum(root.right, targetSum) || - (targetSum === 0 && !root.left && !root.right); + return ( + this.hasPathSum(root.left, targetSum) || + this.hasPathSum(root.right, targetSum) || + (targetSum === 0 && !root.left && !root.right) + ); } } ``` @@ -237,8 +239,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -407,8 +409,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -577,5 +579,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/path-with-maximum-gold.md b/articles/path-with-maximum-gold.md index 81c3d201d..928f239ea 100644 --- a/articles/path-with-maximum-gold.md +++ b/articles/path-with-maximum-gold.md @@ -50,7 +50,7 @@ public class Solution { } private int dfs(int[][] grid, int r, int c, boolean[][] visit) { - if (r < 0 || c < 0 || r >= ROWS || c >= COLS || + if (r < 0 || c < 0 || r >= ROWS || c >= COLS || grid[r][c] == 0 || visit[r][c]) { return 0; } @@ -116,11 +116,24 @@ class Solution { * @return {number} */ getMaximumGold(grid) { - const ROWS = grid.length, COLS = grid[0].length; - const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; + const ROWS = grid.length, + COLS = grid[0].length; + const directions = [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + ]; const dfs = (r, c, visit) => { - if (r < 0 || c < 0 || r >= ROWS || c >= COLS || grid[r][c] === 0 || visit[r][c]) { + if ( + r < 0 || + c < 0 || + r >= ROWS || + c >= COLS || + grid[r][c] === 0 || + visit[r][c] + ) { return 0; } @@ -139,7 +152,9 @@ class Solution { for (let r = 0; r < ROWS; r++) { for (let c = 0; c < COLS; c++) { if (grid[r][c] !== 0) { - let visit = Array.from({ length: ROWS }, () => Array(COLS).fill(false)); + let visit = Array.from({ length: ROWS }, () => + Array(COLS).fill(false), + ); res = Math.max(res, dfs(r, c, visit)); } } @@ -153,8 +168,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(N * 3 ^ N)$ -* Space complexity: $O(N)$ +- Time complexity: $O(N * 3 ^ N)$ +- Space complexity: $O(N)$ > Where $N$ is the number of cells which contain gold. @@ -173,7 +188,7 @@ class Solution: def dfs(r, c): if min(r, c) < 0 or r == ROWS or c == COLS or grid[r][c] == 0: return 0 - + gold = grid[r][c] grid[r][c] = 0 res = 0 @@ -279,8 +294,14 @@ class Solution { * @return {number} */ getMaximumGold(grid) { - const ROWS = grid.length, COLS = grid[0].length; - const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; + const ROWS = grid.length, + COLS = grid[0].length; + const directions = [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + ]; const dfs = (r, c) => { if (r < 0 || c < 0 || r >= ROWS || c >= COLS || grid[r][c] === 0) { @@ -316,8 +337,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(N * 3 ^ N)$ -* Space complexity: $O(N)$ for recursion stack. +- Time complexity: $O(N * 3 ^ N)$ +- Space complexity: $O(N)$ for recursion stack. > Where $N$ is the number of cells which contain gold. @@ -458,7 +479,8 @@ class Solution { * @return {number} */ getMaximumGold(grid) { - const ROWS = grid.length, COLS = grid[0].length; + const ROWS = grid.length, + COLS = grid[0].length; const index = Array.from({ length: ROWS }, () => Array(COLS).fill(0)); let idx = 0; const directions = [1, 0, -1, 0, 1]; @@ -481,11 +503,23 @@ class Solution { const [row, col, gold, mask] = q.pop(); res = Math.max(res, gold); for (let i = 0; i < 4; i++) { - const nr = row + directions[i], nc = col + directions[i + 1]; - if (nr >= 0 && nr < ROWS && nc >= 0 && nc < COLS && grid[nr][nc] > 0) { + const nr = row + directions[i], + nc = col + directions[i + 1]; + if ( + nr >= 0 && + nr < ROWS && + nc >= 0 && + nc < COLS && + grid[nr][nc] > 0 + ) { const newIdx = index[nr][nc]; if (!(mask & (1 << newIdx))) { - q.push([nr, nc, gold + grid[nr][nc], mask | (1 << newIdx)]); + q.push([ + nr, + nc, + gold + grid[nr][nc], + mask | (1 << newIdx), + ]); } } } @@ -502,7 +536,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(N * 3 ^ N)$ -* Space complexity: $O(N)$ +- Time complexity: $O(N * 3 ^ N)$ +- Space complexity: $O(N)$ -> Where $N$ is the number of cells which contain gold. \ No newline at end of file +> Where $N$ is the number of cells which contain gold. diff --git a/articles/path-with-maximum-probability.md b/articles/path-with-maximum-probability.md index b16d1e43b..1ab0f16e8 100644 --- a/articles/path-with-maximum-probability.md +++ b/articles/path-with-maximum-probability.md @@ -133,7 +133,7 @@ class Solution { adj.get(dst).push([src, succProb[i]]); } - let pq = new MaxPriorityQueue({ priority: x => x[0] }); + let pq = new MaxPriorityQueue({ priority: (x) => x[0] }); pq.enqueue([1.0, start_node]); let visited = new Set(); @@ -159,8 +159,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O((V + E) \log V)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O((V + E) \log V)$ +- Space complexity: $O(V + E)$ > Where $V$ is the number nodes and $E$ is the number of edges. @@ -194,7 +194,7 @@ class Solution: for nei, edge_prob in adj[node]: new_prob = curr_prob * edge_prob - if new_prob > maxProb[nei]: + if new_prob > maxProb[nei]: maxProb[nei] = new_prob heapq.heappush(pq, (-new_prob, nei)) @@ -306,7 +306,7 @@ class Solution { let maxProb = Array(n).fill(0); maxProb[start_node] = 1.0; - let pq = new MaxPriorityQueue({ priority: x => x[1] }); + let pq = new MaxPriorityQueue({ priority: (x) => x[1] }); pq.enqueue([start_node, 1.0]); while (!pq.isEmpty()) { @@ -333,8 +333,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O((V + E) \log V)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O((V + E) \log V)$ +- Space complexity: $O(V + E)$ > Where $V$ is the number nodes and $E$ is the number of edges. @@ -378,12 +378,12 @@ public class Solution { boolean updated = false; for (int j = 0; j < edges.length; j++) { int src = edges[j][0], dst = edges[j][1]; - + if (maxProb[src] * succProb[j] > maxProb[dst]) { maxProb[dst] = maxProb[src] * succProb[j]; updated = true; } - + if (maxProb[dst] * succProb[j] > maxProb[src]) { maxProb[src] = maxProb[dst] * succProb[j]; updated = true; @@ -468,8 +468,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V * E)$ -* Space complexity: $O(V)$ +- Time complexity: $O(V * E)$ +- Space complexity: $O(V)$ > Where $V$ is the number nodes and $E$ is the number of edges. @@ -497,7 +497,7 @@ class Solution: for nei, edge_prob in adj[node]: new_prob = maxProb[node] * edge_prob - if new_prob > maxProb[nei]: + if new_prob > maxProb[nei]: maxProb[nei] = new_prob q.append(nei) @@ -626,7 +626,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V * E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V * E)$ +- Space complexity: $O(V + E)$ -> Where $V$ is the number nodes and $E$ is the number of edges. \ No newline at end of file +> Where $V$ is the number nodes and $E$ is the number of edges. diff --git a/articles/path-with-minimum-effort.md b/articles/path-with-minimum-effort.md index 5f151c2c8..5e5a6914d 100644 --- a/articles/path-with-minimum-effort.md +++ b/articles/path-with-minimum-effort.md @@ -127,17 +127,19 @@ class Solution { minimumEffortPath(heights) { const rows = heights.length; const cols = heights[0].length; - const dist = Array.from({ length: rows }, () => - Array(cols).fill(Infinity) + const dist = Array.from({ length: rows }, () => + Array(cols).fill(Infinity), ); dist[0][0] = 0; - const minHeap = new MinPriorityQueue(a => a[0]); + const minHeap = new MinPriorityQueue((a) => a[0]); minHeap.enqueue([0, 0, 0]); // [diff, row, col] const directions = [ - [0, 1], [0, -1], - [1, 0], [-1, 0], + [0, 1], + [0, -1], + [1, 0], + [-1, 0], ]; while (!minHeap.isEmpty()) { @@ -155,7 +157,7 @@ class Solution { const newDiff = Math.max( diff, - Math.abs(heights[r][c] - heights[newR][newC]) + Math.abs(heights[r][c] - heights[newR][newC]), ); if (newDiff < dist[newR][newC]) { dist[newR][newC] = newDiff; @@ -217,8 +219,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n * \log (m * n))$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n * \log (m * n))$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns in the given matrix. @@ -233,27 +235,27 @@ class Solution: def minimumEffortPath(self, heights: List[List[int]]) -> int: ROWS, COLS = len(heights), len(heights[0]) directions = [[0, 1], [0, -1], [1, 0], [-1, 0]] - + def dfs(r, c, limit, visited): if r == ROWS - 1 and c == COLS - 1: return True - + visited.add((r, c)) for dr, dc in directions: newR, newC = r + dr, c + dc - if (newR < 0 or newC < 0 or - newR >= ROWS or newC >= COLS or + if (newR < 0 or newC < 0 or + newR >= ROWS or newC >= COLS or (newR, newC) in visited or abs(heights[newR][newC] - heights[r][c]) > limit): continue - + if dfs(newR, newC, limit, visited): return True return False - + l, r = 0, 1000000 res = r - + while l <= r: mid = (l + r) // 2 if dfs(0, 0, mid, set()): @@ -261,7 +263,7 @@ class Solution: r = mid - 1 else: l = mid + 1 - + return res ``` @@ -384,11 +386,13 @@ class Solution { const ROWS = heights.length; const COLS = heights[0].length; const directions = [ - [0, 1], [0, -1], - [1, 0], [-1, 0] + [0, 1], + [0, -1], + [1, 0], + [-1, 0], ]; - let visited = Array.from({ length: ROWS }, () => - Array(COLS).fill(false) + let visited = Array.from({ length: ROWS }, () => + Array(COLS).fill(false), ); const dfs = (r, c, limit) => { @@ -401,9 +405,13 @@ class Solution { const newR = r + dr; const newC = c + dc; - if (newR < 0 || newC < 0 || - newR >= ROWS || newC >= COLS || - visited[newR][newC]) { + if ( + newR < 0 || + newC < 0 || + newR >= ROWS || + newC >= COLS || + visited[newR][newC] + ) { continue; } if (Math.abs(heights[newR][newC] - heights[r][c]) > limit) { @@ -416,7 +424,9 @@ class Solution { return false; }; - let l = 0, r = 1_000_000, res = r; + let l = 0, + r = 1_000_000, + res = r; while (l <= r) { const mid = Math.floor((l + r) / 2); for (const row of visited) { @@ -491,8 +501,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n * \log (m * n))$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n * \log (m * n))$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns in the given matrix. @@ -709,7 +719,8 @@ class DSU { * @return {boolean} */ union(u, v) { - let pu = this.find(u), pv = this.find(v); + let pu = this.find(u), + pv = this.find(v); if (pu === pv) return false; if (this.Size[pu] < this.Size[pv]) [pu, pv] = [pv, pu]; this.Size[pu] += this.Size[pv]; @@ -730,10 +741,18 @@ class Solution { for (let r = 0; r < ROWS; r++) { for (let c = 0; c < COLS; c++) { if (r + 1 < ROWS) { - edges.push([Math.abs(heights[r][c] - heights[r + 1][c]), r * COLS + c, (r + 1) * COLS + c]); + edges.push([ + Math.abs(heights[r][c] - heights[r + 1][c]), + r * COLS + c, + (r + 1) * COLS + c, + ]); } if (c + 1 < COLS) { - edges.push([Math.abs(heights[r][c] - heights[r][c + 1]), r * COLS + c, r * COLS + c + 1]); + edges.push([ + Math.abs(heights[r][c] - heights[r][c + 1]), + r * COLS + c, + r * COLS + c + 1, + ]); } } } @@ -826,8 +845,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n * \log (m * n))$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n * \log (m * n))$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns in the given matrix. @@ -844,10 +863,10 @@ class Solution: dist = [float('inf')] * (ROWS * COLS) dist[0] = 0 in_queue = [False] * (ROWS * COLS) - + def index(r, c): return r * COLS + c - + queue = deque([0]) in_queue[0] = True directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] @@ -868,7 +887,7 @@ class Solution: if not in_queue[v]: queue.append(v) in_queue[v] = True - + return dist[ROWS * COLS - 1] ``` @@ -966,7 +985,8 @@ class Solution { * @return {number} */ minimumEffortPath(heights) { - const ROWS = heights.length, COLS = heights[0].length; + const ROWS = heights.length, + COLS = heights[0].length; const dist = Array(ROWS * COLS).fill(Infinity); dist[0] = 0; @@ -976,20 +996,26 @@ class Solution { inQueue[0] = true; const directions = [ - [0, 1], [0, -1], - [1, 0], [-1, 0] + [0, 1], + [0, -1], + [1, 0], + [-1, 0], ]; while (!queue.isEmpty()) { const u = queue.pop(); inQueue[u] = false; - const r = Math.floor(u / COLS), c = u % COLS; + const r = Math.floor(u / COLS), + c = u % COLS; for (const [dr, dc] of directions) { - const newR = r + dr, newC = c + dc; + const newR = r + dr, + newC = c + dc; if (newR >= 0 && newC >= 0 && newR < ROWS && newC < COLS) { const v = newR * COLS + newC; - const weight = Math.abs(heights[r][c] - heights[newR][newC]); + const weight = Math.abs( + heights[r][c] - heights[newR][newC], + ); const newDist = Math.max(dist[u], weight); if (newDist < dist[v]) { dist[v] = newDist; @@ -1023,7 +1049,7 @@ public class Solution { inQueue[0] = true; int[][] directions = new int[][] { - new int[] {0, 1}, new int[] {0, -1}, + new int[] {0, 1}, new int[] {0, -1}, new int[] {1, 0}, new int[] {-1, 0} }; @@ -1058,9 +1084,9 @@ public class Solution { ### Time & Space Complexity -* Time complexity: - * $O(m * n)$ time in average case. - * $O(m ^ 2 * n ^ 2)$ time in worst case. -* Space complexity: $O(m * n)$ +- Time complexity: + - $O(m * n)$ time in average case. + - $O(m ^ 2 * n ^ 2)$ time in worst case. +- Space complexity: $O(m * n)$ -> Where $m$ is the number of rows and $n$ is the number of columns in the given matrix. \ No newline at end of file +> Where $m$ is the number of rows and $n$ is the number of columns in the given matrix. diff --git a/articles/perfect-squares.md b/articles/perfect-squares.md index eb92e5450..5af0a5a56 100644 --- a/articles/perfect-squares.md +++ b/articles/perfect-squares.md @@ -8,14 +8,14 @@ class Solution: def dfs(target): if target == 0: return 0 - + res = target for i in range(1, target): if i * i > target: break res = min(res, 1 + dfs(target - i * i)) return res - + return dfs(n) ``` @@ -29,7 +29,7 @@ public class Solution { if (target == 0) { return 0; } - + int res = target; for (int i = 1; i * i <= target; i++) { res = Math.min(res, 1 + dfs(target - i * i)); @@ -51,7 +51,7 @@ private: if (target == 0) { return 0; } - + int res = target; for (int i = 1; i * i <= target; i++) { res = min(res, 1 + dfs(target - i * i)); @@ -106,8 +106,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ {\sqrt {n}})$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n ^ {\sqrt {n}})$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -134,7 +134,7 @@ class Solution: memo[target] = res return res - + return dfs(n) ``` @@ -192,7 +192,7 @@ class Solution { */ numSquares(n) { const memo = new Map(); - + const dfs = (target) => { if (target === 0) return 0; if (memo.has(target)) { @@ -239,8 +239,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * \sqrt {n})$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * \sqrt {n})$ +- Space complexity: $O(n)$ --- @@ -253,14 +253,14 @@ class Solution: def numSquares(self, n: int) -> int: dp = [n] * (n + 1) dp[0] = 0 - + for target in range(1, n + 1): for s in range(1, target + 1): square = s * s if target - square < 0: break dp[target] = min(dp[target], 1 + dp[target - square]) - + return dp[n] ``` @@ -344,8 +344,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * \sqrt {n})$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * \sqrt {n})$ +- Space complexity: $O(n)$ --- @@ -358,7 +358,7 @@ class Solution: def numSquares(self, n: int) -> int: q = deque() seen = set() - + res = 0 q.append(0) while q: @@ -374,7 +374,7 @@ class Solution: seen.add(nxt) q.append(nxt) s += 1 - + return res ``` @@ -440,7 +440,7 @@ class Solution { * @return {number} */ numSquares(n) { - const q = new Queue; + const q = new Queue(); const seen = new Set(); let res = 0; @@ -469,10 +469,10 @@ public class Solution { public int NumSquares(int n) { Queue q = new Queue(); HashSet seen = new HashSet(); - + int res = 0; q.Enqueue(0); - + while (q.Count > 0) { res++; int size = q.Count; @@ -492,7 +492,7 @@ public class Solution { } } } - + return res; } } @@ -502,8 +502,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * \sqrt {n})$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * \sqrt {n})$ +- Space complexity: $O(n)$ --- @@ -516,23 +516,23 @@ class Solution: def numSquares(self, n: int) -> int: while n % 4 == 0: n //= 4 - + if n % 8 == 7: return 4 - + def isSquareNum(num): s = int(math.sqrt(num)) return s * s == num - + if isSquareNum(n): return 1 - + i = 1 while i * i <= n: if isSquareNum(n - i * i): return 2 i += 1 - + return 3 ``` @@ -542,24 +542,24 @@ public class Solution { while (n % 4 == 0) { n /= 4; } - + if (n % 8 == 7) { return 4; } - + if (isSquareNum(n)) { return 1; } - + for (int i = 1; i * i <= n; i++) { if (isSquareNum(n - i * i)) { return 2; } } - + return 3; } - + private boolean isSquareNum(int num) { int s = (int) Math.sqrt(num); return s * s == num; @@ -574,24 +574,24 @@ public: while (n % 4 == 0) { n /= 4; } - + if (n % 8 == 7) { return 4; } - + if (isSquareNum(n)) { return 1; } - + for (int i = 1; i * i <= n; i++) { if (isSquareNum(n - i * i)) { return 2; } } - + return 3; } - + private: bool isSquareNum(int num) { int s = (int) sqrt(num); @@ -610,26 +610,26 @@ class Solution { while (n % 4 === 0) { n = Math.floor(n / 4); } - + if (n % 8 === 7) { return 4; } - + const isSquareNum = (num) => { const s = Math.floor(Math.sqrt(num)); return s * s === num; }; - + if (isSquareNum(n)) { return 1; } - + for (let i = 1; i * i <= n; i++) { if (isSquareNum(n - i * i)) { return 2; } } - + return 3; } } @@ -670,5 +670,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(\sqrt {n})$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(\sqrt {n})$ +- Space complexity: $O(1)$ diff --git a/articles/permutation-string.md b/articles/permutation-string.md index 482890ee4..ee9eabce2 100644 --- a/articles/permutation-string.md +++ b/articles/permutation-string.md @@ -49,7 +49,7 @@ public: for (int j = i; j < s2.length(); j++) { string subStr = s2.substr(i, j - i + 1); sort(subStr.begin(), subStr.end()); - + if (subStr == s1) { return true; } @@ -72,7 +72,11 @@ class Solution { for (let i = 0; i < s2.length; i++) { for (let j = i; j < s2.length; j++) { - let subStr = s2.slice(i, j + 1).split('').sort().join(''); + let subStr = s2 + .slice(i, j + 1) + .split('') + .sort() + .join(''); if (subStr === s1) { return true; } @@ -172,8 +176,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 3 \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 3 \log n)$ +- Space complexity: $O(n)$ --- @@ -187,7 +191,7 @@ class Solution: count1 = {} for c in s1: count1[c] = 1 + count1.get(c, 0) - + need = len(count1) for i in range(len(s2)): count2, cur = {}, 0 @@ -217,15 +221,15 @@ public class Solution { for (int j = i; j < s2.length(); j++) { char c = s2.charAt(j); count2.put(c, count2.getOrDefault(c, 0) + 1); - + if (count1.getOrDefault(c, 0) < count2.get(c)) { break; } - + if (count1.getOrDefault(c, 0) == count2.get(c)) { cur++; } - + if (cur == need) { return true; } @@ -252,15 +256,15 @@ public: for (int j = i; j < s2.length(); j++) { char c = s2[j]; count2[c]++; - + if (count1[c] < count2[c]) { break; } - + if (count1[c] == count2[c]) { cur++; } - + if (cur == need) { return true; } @@ -417,7 +421,7 @@ class Solution { for c in s1 { count1[c, default: 0] += 1 } - + let need = count1.count let chars = Array(s2) @@ -447,8 +451,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(1)$ since we have at most $26$ different characters. +- Time complexity: $O(n * m)$ +- Space complexity: $O(1)$ since we have at most $26$ different characters. > Where $n$ is the length of the string1 and $m$ is the length of string2. @@ -463,21 +467,21 @@ class Solution: def checkInclusion(self, s1: str, s2: str) -> bool: if len(s1) > len(s2): return False - + s1Count, s2Count = [0] * 26, [0] * 26 for i in range(len(s1)): s1Count[ord(s1[i]) - ord('a')] += 1 s2Count[ord(s2[i]) - ord('a')] += 1 - + matches = 0 for i in range(26): matches += (1 if s1Count[i] == s2Count[i] else 0) - + l = 0 for r in range(len(s1), len(s2)): if matches == 26: return True - + index = ord(s2[r]) - ord('a') s2Count[index] += 1 if s1Count[index] == s2Count[index]: @@ -847,5 +851,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/permutations-ii.md b/articles/permutations-ii.md index 83aefec3b..af1011425 100644 --- a/articles/permutations-ii.md +++ b/articles/permutations-ii.md @@ -11,7 +11,7 @@ class Solution: if len(perm) == len(nums): res.add(tuple(perm)) return - + for i in range(len(nums)): if nums[i] != float("-inf"): perm.append(nums[i]) @@ -19,7 +19,7 @@ class Solution: backtrack(perm) nums[i] = perm[-1] perm.pop() - + backtrack([]) return list(res) ``` @@ -157,8 +157,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n! * n)$ -* Space complexity: $O(n! * n)$ for the hash set. +- Time complexity: $O(n! * n)$ +- Space complexity: $O(n! * n)$ for the hash set. --- @@ -179,7 +179,7 @@ class Solution: if len(perm) == len(nums): res.append(perm.copy()) return - + for num in count: if count[num] > 0: perm.append(num) @@ -196,7 +196,7 @@ class Solution: public class Solution { private Map count; private List> res; - + public List> permuteUnique(int[] nums) { res = new ArrayList<>(); count = new HashMap<>(); @@ -233,7 +233,7 @@ public class Solution { class Solution { vector> res; unordered_map count; - + public: vector> permuteUnique(vector& nums) { for (int& num : nums) { @@ -342,8 +342,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n! * n)$ -* Space complexity: $O(n! * n)$ for the output list. +- Time complexity: $O(n! * n)$ +- Space complexity: $O(n! * n)$ for the output list. --- @@ -362,11 +362,11 @@ class Solution: if len(perm) == n: res.append(perm.copy()) return - + for i in range(n): if visit[i]: continue - + if i and nums[i] == nums[i - 1] and not visit[i - 1]: continue visit[i] = True @@ -418,7 +418,7 @@ public class Solution { class Solution { vector> res; vector visit; - + public: vector> permuteUnique(vector& nums) { visit.assign(nums.size(), false); @@ -436,7 +436,7 @@ public: for (int i = 0; i < nums.size(); i++) { if (visit[i] || (i > 0 && nums[i] == nums[i - 1] && !visit[i - 1])) continue; - + visit[i] = true; perm.push_back(nums[i]); dfs(nums, perm); @@ -466,9 +466,12 @@ class Solution { } for (let i = 0; i < nums.length; i++) { - if (visit[i] || (i > 0 && nums[i] === nums[i - 1] && !visit[i - 1])) + if ( + visit[i] || + (i > 0 && nums[i] === nums[i - 1] && !visit[i - 1]) + ) continue; - + visit[i] = true; perm.push(nums[i]); dfs(); @@ -520,8 +523,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n! * n)$ -* Space complexity: $O(n! * n)$ for the output list. +- Time complexity: $O(n! * n)$ +- Space complexity: $O(n! * n)$ for the output list. --- @@ -538,14 +541,14 @@ class Solution: if i == len(nums): res.append(nums.copy()) return - + for j in range(i, len(nums)): if j > i and nums[i] == nums[j]: continue - + nums[i], nums[j] = nums[j], nums[i] dfs(i + 1) - + for j in range(len(nums) - 1, i, -1): nums[j], nums[i] = nums[i], nums[j] @@ -583,7 +586,7 @@ public class Solution { swap(nums, i, j); } } - + private void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; @@ -595,7 +598,7 @@ public class Solution { ```cpp class Solution { vector> res; - + public: vector> permuteUnique(vector& nums) { sort(nums.begin(), nums.end()); @@ -614,7 +617,7 @@ public: swap(nums[i], nums[j]); dfs(i + 1, nums); } - + for (int j = nums.size() - 1; j > i; --j) { swap(nums[i], nums[j]); } @@ -694,8 +697,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n! * n)$ -* Space complexity: $O(n! * n)$ for the output list. +- Time complexity: $O(n! * n)$ +- Space complexity: $O(n! * n)$ for the output list. --- @@ -714,22 +717,22 @@ class Solution: i = n - 2 while i >= 0 and nums[i] >= nums[i + 1]: i -= 1 - + if i < 0: break - + j = n - 1 while nums[j] <= nums[i]: - j -= 1 + j -= 1 nums[i], nums[j] = nums[j], nums[i] - + l, r = i + 1, n - 1 while l < r: nums[l], nums[r] = nums[r], nums[l] l, r = l + 1, r - 1 - + res.append(nums.copy()) - + return res ``` @@ -827,7 +830,8 @@ class Solution { [nums[i], nums[j]] = [nums[j], nums[i]]; - let l = i + 1, r = n - 1; + let l = i + 1, + r = n - 1; while (l < r) { [nums[l], nums[r]] = [nums[r], nums[l]]; l++; @@ -888,5 +892,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n! * n)$ -* Space complexity: $O(n! * n)$ for the output list. \ No newline at end of file +- Time complexity: $O(n! * n)$ +- Space complexity: $O(n! * n)$ for the output list. diff --git a/articles/permutations.md b/articles/permutations.md index 83dea1986..bb7f64f29 100644 --- a/articles/permutations.md +++ b/articles/permutations.md @@ -7,7 +7,7 @@ class Solution: def permute(self, nums: List[int]) -> List[List[int]]: if len(nums) == 0: return [[]] - + perms = self.permute(nums[1:]) res = [] for p in perms: @@ -24,7 +24,7 @@ public class Solution { if (nums.length == 0) { return Arrays.asList(new ArrayList<>()); } - + List> perms = permute(Arrays.copyOfRange(nums, 1, nums.length)); List> res = new ArrayList<>(); for (List p : perms) { @@ -46,7 +46,7 @@ public: if (nums.empty()) { return {{}}; } - + vector tmp = vector(nums.begin() + 1, nums.end()); vector> perms = permute(tmp); vector> res; @@ -93,7 +93,7 @@ public class Solution { if (nums.Length == 0) { return new List> { new List() }; } - + var perms = Permute(nums[1..]); var res = new List>(); foreach (var p in perms) { @@ -113,7 +113,7 @@ func permute(nums []int) [][]int { if len(nums) == 0 { return [][]int{{}} } - + perms := permute(nums[1:]) var res [][]int for _, p := range perms { @@ -131,7 +131,7 @@ func permute(nums []int) [][]int { class Solution { fun permute(nums: IntArray): List> { if (nums.isEmpty()) return listOf(listOf()) - + val perms = permute(nums.sliceArray(1 until nums.size)) val res = mutableListOf>() for (p in perms) { @@ -173,8 +173,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n! * n ^ 2)$ -* Space complexity: $O(n! * n)$ for the output list. +- Time complexity: $O(n! * n ^ 2)$ +- Space complexity: $O(n! * n)$ for the output list. --- @@ -287,7 +287,7 @@ public class Solution { ```go func permute(nums []int) [][]int { perms := [][]int{{}} - + for _, num := range nums { var newPerms [][]int for _, p := range perms { @@ -299,7 +299,7 @@ func permute(nums []int) [][]int { } perms = newPerms } - + return perms } ``` @@ -308,7 +308,7 @@ func permute(nums []int) [][]int { class Solution { fun permute(nums: IntArray): List> { var perms = mutableListOf(listOf()) - + for (num in nums) { val newPerms = mutableListOf>() for (p in perms) { @@ -320,7 +320,7 @@ class Solution { } perms = newPerms } - + return perms } } @@ -352,8 +352,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n! * n ^ 2)$ -* Space complexity: $O(n! * n)$ for the output list. +- Time complexity: $O(n! * n ^ 2)$ +- Space complexity: $O(n! * n)$ for the output list. --- @@ -447,7 +447,7 @@ class Solution { let res = []; backtrack([], nums, new Array(nums.length).fill(false)); return res; - + function backtrack(perm, nums, pick) { if (perm.length === nums.length) { res.push([...perm]); @@ -522,12 +522,12 @@ func backtrack(res *[][]int, perm []int, nums []int, pick []bool) { ```kotlin class Solution { private val res = mutableListOf>() - + fun permute(nums: IntArray): List> { backtrack(mutableListOf(), nums, BooleanArray(nums.size)) return res } - + private fun backtrack(perm: MutableList, nums: IntArray, pick: BooleanArray) { if (perm.size == nums.size) { res.add(ArrayList(perm)) @@ -579,8 +579,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n! * n)$ -* Space complexity: $O(n! * n)$ for the output list. +- Time complexity: $O(n! * n)$ +- Space complexity: $O(n! * n)$ for the output list. --- @@ -743,12 +743,12 @@ func backtrack(res *[][]int, perm []int, nums []int, mask int) { ```kotlin class Solution { private val res = mutableListOf>() - + fun permute(nums: IntArray): List> { backtrack(mutableListOf(), nums, 0) return res } - + private fun backtrack(perm: MutableList, nums: IntArray, mask: Int) { if (perm.size == nums.size) { res.add(ArrayList(perm)) @@ -795,8 +795,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n! * n)$ -* Space complexity: $O(n! * n)$ for the output list. +- Time complexity: $O(n! * n)$ +- Space complexity: $O(n! * n)$ for the output list. --- @@ -880,7 +880,7 @@ class Solution { constructor() { this.res = []; } - + /** * @param {number[]} nums * @return {number[][]} @@ -963,12 +963,12 @@ func backtrack(res *[][]int, nums []int, idx int) { ```kotlin class Solution { private val res = mutableListOf>() - + fun permute(nums: IntArray): List> { backtrack(nums, 0) return res } - + private fun backtrack(nums: IntArray, idx: Int) { if (idx == nums.size) { res.add(nums.toList()) @@ -980,7 +980,7 @@ class Solution { nums.swap(idx, i) } } - + private fun IntArray.swap(i: Int, j: Int) { val temp = this[i] this[i] = this[j] @@ -1017,5 +1017,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n! * n)$ -* Space complexity: $O(n! * n)$ for the output list. \ No newline at end of file +- Time complexity: $O(n! * n)$ +- Space complexity: $O(n! * n)$ for the output list. diff --git a/articles/plus-one.md b/articles/plus-one.md index a5b43fb09..2ecf1344b 100644 --- a/articles/plus-one.md +++ b/articles/plus-one.md @@ -152,8 +152,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -392,8 +392,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the language. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the language. --- @@ -410,7 +410,7 @@ class Solution: digits[i] += 1 return digits digits[i] = 0 - + return [1] + digits ``` @@ -546,5 +546,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/populating-next-right-pointers-in-each-node.md b/articles/populating-next-right-pointers-in-each-node.md index 1f7339287..facd98067 100644 --- a/articles/populating-next-right-pointers-in-each-node.md +++ b/articles/populating-next-right-pointers-in-each-node.md @@ -44,7 +44,7 @@ class Node { public Node next; public Node() {} - + public Node(int _val) { val = _val; } @@ -187,8 +187,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(\log n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(\log n)$ --- @@ -214,13 +214,13 @@ class Solution: def dfs(node, depth): if not node: return - + if depth not in mp: mp[depth] = node else: mp[depth].next = node mp[depth] = node - + dfs(node.left, depth + 1) dfs(node.right, depth + 1) @@ -238,7 +238,7 @@ class Node { public Node next; public Node() {} - + public Node(int _val) { val = _val; } @@ -261,7 +261,7 @@ public class Solution { private void dfs(Node node, int depth, Map mp) { if (node == null) return; - + if (!mp.containsKey(depth)) { mp.put(depth, node); } else { @@ -342,7 +342,7 @@ class Solution { const dfs = (node, depth) => { if (!node) return; - + if (!mp.has(depth)) { mp.set(depth, node); } else { @@ -364,8 +364,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(\log n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(\log n)$ --- @@ -410,7 +410,7 @@ class Node { public Node next; public Node() {} - + public Node(int _val) { val = _val; } @@ -522,8 +522,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(\log n)$ for the recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(\log n)$ for the recursion stack. --- @@ -569,7 +569,7 @@ class Node { public Node next; public Node() {} - + public Node(int _val) { val = _val; } @@ -672,7 +672,8 @@ class Solution { connect(root) { if (!root) return null; - let cur = root, nxt = root.left; + let cur = root, + nxt = root.left; while (cur && nxt) { cur.left.next = cur.right; @@ -696,5 +697,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/pow-x-n.md b/articles/pow-x-n.md index 50beeb0f4..95011e6c2 100644 --- a/articles/pow-x-n.md +++ b/articles/pow-x-n.md @@ -162,8 +162,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -364,8 +364,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(\log n)$ for recursion stack. +- Time complexity: $O(\log n)$ +- Space complexity: $O(\log n)$ for recursion stack. --- @@ -380,16 +380,16 @@ class Solution: return 0 if n == 0: return 1 - + res = 1 power = abs(n) - + while power: if power & 1: res *= x x *= x power >>= 1 - + return res if n >= 0 else 1 / res ``` @@ -572,5 +572,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ diff --git a/articles/power-of-four.md b/articles/power-of-four.md index dc54669cc..ef4cb1ed3 100644 --- a/articles/power-of-four.md +++ b/articles/power-of-four.md @@ -63,8 +63,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ --- @@ -82,7 +82,7 @@ class Solution: if n % 4: return False n //= 4 - + return n == 1 ``` @@ -140,8 +140,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ --- @@ -188,8 +188,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ --- @@ -202,11 +202,11 @@ class Solution: def isPowerOfFour(self, n: int) -> bool: if n < 0: return False - + for i in range(0, 32, 2): if n == (1 << i): return True - + return False ``` @@ -214,13 +214,13 @@ class Solution: public class Solution { public boolean isPowerOfFour(int n) { if (n < 0) return false; - + for (int i = 0; i < 32; i += 2) { if (n == (1 << i)) { return true; } } - + return false; } } @@ -253,7 +253,7 @@ class Solution { if (n < 0) return false; for (let i = 0; i < 32; i += 2) { - if (n === (1 << i)) { + if (n === 1 << i) { return true; } } @@ -267,8 +267,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ --- @@ -315,8 +315,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ --- @@ -354,7 +354,7 @@ class Solution { * @return {boolean} */ isPowerOfFour(n) { - return n > 0 && (n & (n - 1)) === 0 && (n % 3 == 1); + return n > 0 && (n & (n - 1)) === 0 && n % 3 == 1; } } ``` @@ -363,5 +363,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ diff --git a/articles/power-of-two.md b/articles/power-of-two.md index 5024ea27a..97b809d7d 100644 --- a/articles/power-of-two.md +++ b/articles/power-of-two.md @@ -7,7 +7,7 @@ class Solution: def isPowerOfTwo(self, n: int) -> bool: if n <= 0: return False - + x = 1 while x < n: x *= 2 @@ -65,8 +65,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ --- @@ -135,8 +135,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(\log n)$ for recursion stack. +- Time complexity: $O(\log n)$ +- Space complexity: $O(\log n)$ for recursion stack. --- @@ -149,7 +149,7 @@ class Solution: def isPowerOfTwo(self, n: int) -> bool: if n <= 0: return False - + while n % 2 == 0: n >>= 1 return n == 1 @@ -203,8 +203,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ --- @@ -242,7 +242,7 @@ class Solution { * @return {boolean} */ isPowerOfTwo(n) { - return n > 0 && (n & (-n)) === n; + return n > 0 && (n & -n) === n; } } ``` @@ -251,8 +251,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ --- @@ -299,8 +299,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ --- @@ -338,7 +338,7 @@ class Solution { * @return {boolean} */ isPowerOfTwo(n) { - return n > 0 && ((1 << 30) % n) === 0; + return n > 0 && (1 << 30) % n === 0; } } ``` @@ -347,5 +347,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ diff --git a/articles/prefix-and-suffix-search.md b/articles/prefix-and-suffix-search.md index a2674805b..acfc3bd51 100644 --- a/articles/prefix-and-suffix-search.md +++ b/articles/prefix-and-suffix-search.md @@ -20,7 +20,7 @@ class WordFilter: flag = False break j += 1 - + if not flag: continue @@ -30,10 +30,10 @@ class WordFilter: flag = False break j += 1 - + if flag: return i - + return -1 ``` @@ -139,8 +139,8 @@ class WordFilter { this.words = words; } - /** - * @param {string} pref + /** + * @param {string} pref * @param {string} suff * @return {number} */ @@ -185,8 +185,8 @@ class WordFilter { ### Time & Space Complexity -* Time complexity: $O(N * m * n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(N * m * n)$ +- Space complexity: $O(1)$ extra space. > Where $N$ is the number $f()$ function calls, $n$ is the number of words, and $m$ is the average length of each word. @@ -212,7 +212,7 @@ class WordFilter: s = pref + "$" + suff if s not in self.mp: return -1 - + return self.mp[s] ``` @@ -283,20 +283,20 @@ class WordFilter { for (let j = 0; j < w.length; j++) { const pref = w.slice(0, j + 1); for (let k = 0; k < w.length; k++) { - const cur = pref + "$" + w.slice(k); + const cur = pref + '$' + w.slice(k); this.mp.set(cur, i); } } } } - /** - * @param {string} pref + /** + * @param {string} pref * @param {string} suff * @return {number} */ f(pref, suff) { - const s = pref + "$" + suff; + const s = pref + '$' + suff; return this.mp.has(s) ? this.mp.get(s) : -1; } } @@ -306,10 +306,10 @@ class WordFilter { ### Time & Space Complexity -* Time complexity: - * $O(n * m ^ 3)$ time for initialization. - * $O(m)$ for each $f()$ function call. -* Space complexity: $O(n * m ^ 3)$ +- Time complexity: + - $O(n * m ^ 3)$ time for initialization. + - $O(m)$ for each $f()$ function call. +- Space complexity: $O(n * m ^ 3)$ > Where $n$ is the number of words and $m$ is the average length of each word. @@ -328,7 +328,7 @@ class TrieNode: class Trie: def __init__(self): self.root = TrieNode() - + def addWord(self, w, i): cur = self.root for ch in w: @@ -337,7 +337,7 @@ class Trie: cur.children[c] = TrieNode() cur = cur.children[c] cur.index = i - + def search(self, w): cur = self.root for ch in w: @@ -358,7 +358,7 @@ class WordFilter: for k in range(w_len + 1): prefix = w[:k] self.trie.addWord(suffix + self.CHAR + prefix, i) - + def f(self, pref: str, suff: str) -> int: return self.trie.search(suff + self.CHAR + pref) ``` @@ -573,8 +573,8 @@ class WordFilter { } } - /** - * @param {string} pref + /** + * @param {string} pref * @param {string} suff * @return {number} */ @@ -588,9 +588,9 @@ class WordFilter { ### Time & Space Complexity -* Time complexity: - * $O(n * m ^ 3)$ time for initialization. - * $O(m)$ for each $f()$ function call. -* Space complexity: $O(n * m ^ 3)$ +- Time complexity: + - $O(n * m ^ 3)$ time for initialization. + - $O(m)$ for each $f()$ function call. +- Space complexity: $O(n * m ^ 3)$ -> Where $n$ is the number of words and $m$ is the average length of each word. \ No newline at end of file +> Where $n$ is the number of words and $m$ is the average length of each word. diff --git a/articles/process-tasks-using-servers.md b/articles/process-tasks-using-servers.md index f79a9c753..ecc919621 100644 --- a/articles/process-tasks-using-servers.md +++ b/articles/process-tasks-using-servers.md @@ -68,7 +68,7 @@ public class Solution { int minIdx = -1; for (int i = 0; i < n; i++) { - if (available[i] && (minIdx == -1 || servers[i] < servers[minIdx] || + if (available[i] && (minIdx == -1 || servers[i] < servers[minIdx] || (servers[i] == servers[minIdx] && i < minIdx))) { minIdx = i; } @@ -119,7 +119,7 @@ public: int minIdx = -1; for (int i = 0; i < n; i++) { - if (available[i] && (minIdx == -1 || servers[i] < servers[minIdx] || + if (available[i] && (minIdx == -1 || servers[i] < servers[minIdx] || (servers[i] == servers[minIdx] && i < minIdx))) { minIdx = i; } @@ -142,7 +142,8 @@ class Solution { * @return {number[]} */ assignTasks(servers, tasks) { - const n = servers.length, m = tasks.length; + const n = servers.length, + m = tasks.length; const available = Array(n).fill(true); const finishTime = Array(n).fill(0); const res = []; @@ -157,7 +158,7 @@ class Solution { } } - if (!available.some(v => v)) { + if (!available.some((v) => v)) { time = Math.min(...finishTime); for (let i = 0; i < n; i++) { if (finishTime[i] <= time) { @@ -168,8 +169,12 @@ class Solution { let minIdx = -1; for (let i = 0; i < n; i++) { - if (available[i] && (minIdx === -1 || servers[i] < servers[minIdx] || - (servers[i] === servers[minIdx] && i < minIdx))) { + if ( + available[i] && + (minIdx === -1 || + servers[i] < servers[minIdx] || + (servers[i] === servers[minIdx] && i < minIdx)) + ) { minIdx = i; } } @@ -187,10 +192,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: - * $O(n)$ extra space. - * $O(m)$ space for the output array. +- Time complexity: $O(m * n)$ +- Space complexity: + - $O(n)$ extra space. + - $O(m)$ space for the output array. > Where $m$ is the number of tasks and $n$ is the number of servers. @@ -312,8 +317,8 @@ class Solution { */ assignTasks(servers, tasks) { const n = servers.length; - const available = new PriorityQueue( - (a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0] + const available = new PriorityQueue((a, b) => + a[0] === b[0] ? a[1] - b[1] : a[0] - b[0], ); const unavailable = new PriorityQueue((a, b) => a[0] - b[0]); const res = new Array(tasks.length); @@ -346,10 +351,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O((n + m) \log n)$ -* Space complexity: - * $O(n)$ extra space. - * $O(m)$ space for the output array. +- Time complexity: $O((n + m) \log n)$ +- Space complexity: + - $O(n)$ extra space. + - $O(m)$ space for the output array. > Where $m$ is the number of tasks and $n$ is the number of servers. @@ -384,23 +389,23 @@ public class Solution { public int[] assignTasks(int[] servers, int[] tasks) { int m = tasks.length, n = servers.length; int[] res = new int[m]; - + PriorityQueue available = new PriorityQueue<>((a, b) -> { if(a[0] != b[0]) return Integer.compare(a[0], b[0]); if(a[1] != b[1]) return Integer.compare(a[1], b[1]); return Integer.compare(a[2], b[2]); }); - + PriorityQueue unavailable = new PriorityQueue<>((a, b) -> { if(a[0] != b[0]) return Integer.compare(a[0], b[0]); if(a[1] != b[1]) return Integer.compare(a[1], b[1]); return Integer.compare(a[2], b[2]); }); - + for (int i = 0; i < n; i++) { available.offer(new int[]{servers[i], i, 0}); } - + for (int i = 0; i < m; i++) { while ((!unavailable.isEmpty() && unavailable.peek()[0] <= i) || available.isEmpty()) { @@ -413,7 +418,7 @@ public class Solution { Math.max(server[2], i) + tasks[i], server[0], server[1]} ); } - + return res; } } @@ -461,11 +466,19 @@ class Solution { */ assignTasks(servers, tasks) { const res = new Array(tasks.length); - const available = new PriorityQueue( - (a, b) => a[0] === b[0] ? (a[1] === b[1] ? a[2] - b[2] : a[1] - b[1]) : a[0] - b[0] + const available = new PriorityQueue((a, b) => + a[0] === b[0] + ? a[1] === b[1] + ? a[2] - b[2] + : a[1] - b[1] + : a[0] - b[0], ); - const unavailable = new PriorityQueue( - (a, b) => a[0] === b[0] ? (a[1] === b[1] ? a[2] - b[2] : a[1] - b[1]) : a[0] - b[0] + const unavailable = new PriorityQueue((a, b) => + a[0] === b[0] + ? a[1] === b[1] + ? a[2] - b[2] + : a[1] - b[1] + : a[0] - b[0], ); for (let i = 0; i < servers.length; i++) { @@ -473,15 +486,21 @@ class Solution { } for (let i = 0; i < tasks.length; i++) { - while ((!unavailable.isEmpty() && unavailable.front()[0] <= i) || - available.isEmpty()) { + while ( + (!unavailable.isEmpty() && unavailable.front()[0] <= i) || + available.isEmpty() + ) { const [timeFree, weight, index] = unavailable.dequeue(); available.enqueue([weight, index, timeFree]); } const [weight, index, timeFree] = available.dequeue(); res[i] = index; - unavailable.enqueue([Math.max(timeFree, i) + tasks[i], weight, index]); + unavailable.enqueue([ + Math.max(timeFree, i) + tasks[i], + weight, + index, + ]); } return res; @@ -493,9 +512,9 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O((n + m) \log n)$ -* Space complexity: - * $O(n)$ extra space. - * $O(m)$ space for the output array. +- Time complexity: $O((n + m) \log n)$ +- Space complexity: + - $O(n)$ extra space. + - $O(m)$ space for the output array. -> Where $m$ is the number of tasks and $n$ is the number of servers. \ No newline at end of file +> Where $m$ is the number of tasks and $n$ is the number of servers. diff --git a/articles/products-of-array-discluding-self.md b/articles/products-of-array-discluding-self.md index 1370fac97..c0a836cd5 100644 --- a/articles/products-of-array-discluding-self.md +++ b/articles/products-of-array-discluding-self.md @@ -12,9 +12,9 @@ class Solution: prod = 1 for j in range(n): if i == j: - continue + continue prod *= nums[j] - + res[i] = prod return res ``` @@ -36,7 +36,7 @@ public class Solution { } return res; } -} +} ``` ```cpp @@ -168,10 +168,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ space for the output array. +- Time complexity: $O(n ^ 2)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ space for the output array. --- @@ -208,9 +208,9 @@ public class Solution { zeroCount++; } } - + if (zeroCount > 1) { - return new int[nums.length]; + return new int[nums.length]; } int[] res = new int[nums.length]; @@ -223,7 +223,7 @@ public class Solution { } return res; } -} +} ``` ```cpp @@ -240,7 +240,7 @@ public: } if (zeroCount > 1) { - return vector(nums.size(), 0); + return vector(nums.size(), 0); } vector res(nums.size()); @@ -274,13 +274,13 @@ class Solution { } if (zeroCount > 1) { - return Array(nums.length).fill(0); + return Array(nums.length).fill(0); } const res = new Array(nums.length); for (let i = 0; i < nums.length; i++) { if (zeroCount > 0) { - res[i] = (nums[i] === 0) ? prod : 0; + res[i] = nums[i] === 0 ? prod : 0; } else { res[i] = prod / nums[i]; } @@ -303,7 +303,7 @@ public class Solution { } if (zeroCount > 1) { - return new int[nums.Length]; + return new int[nums.Length]; } int[] res = new int[nums.Length]; @@ -331,7 +331,7 @@ func productExceptSelf(nums []int) []int { zeroCount++ } } - + res := make([]int, len(nums)) if zeroCount > 1 { return res @@ -365,7 +365,7 @@ class Solution { zeroCount++ } } - + val res = IntArray(nums.size) if (zeroCount > 1) return res @@ -394,7 +394,7 @@ class Solution { zeroCount += 1 } } - + if zeroCount > 1 { return [Int](repeating: 0, count: nums.count) } @@ -417,14 +417,14 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ space for the output array. +- Time complexity: $O(n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ space for the output array. --- -## 3. Prefix & Suffix +## 3. Prefix & Suffix ::tabs-start @@ -442,7 +442,7 @@ class Solution: for i in range(n - 2, -1, -1): suff[i] = nums[i + 1] * suff[i + 1] for i in range(n): - res[i] = pref[i] * suff[i] + res[i] = pref[i] * suff[i] return res ``` @@ -467,7 +467,7 @@ public class Solution { } return res; } -} +} ``` ```cpp @@ -606,15 +606,15 @@ class Solution { for i in 1..= 0; i--) { res[i] *= postfix; @@ -667,7 +667,7 @@ public class Solution { } return res; } -} +} ``` ```cpp @@ -680,7 +680,7 @@ public: for (int i = 1; i < n; i++) { res[i] = res[i - 1] * nums[i - 1]; } - + int postfix = 1; for (int i = n - 1; i >= 0; i--) { res[i] *= postfix; @@ -704,7 +704,7 @@ class Solution { for (let i = 1; i < n; i++) { res[i] = res[i - 1] * nums[i - 1]; } - + let postfix = 1; for (let i = n - 1; i >= 0; i--) { res[i] *= postfix; @@ -725,7 +725,7 @@ public class Solution { for (int i = 1; i < n; i++) { res[i] = res[i - 1] * nums[i - 1]; } - + int postfix = 1; for (int i = n - 1; i >= 0; i--) { res[i] *= postfix; @@ -797,7 +797,7 @@ class Solution { res[i] *= postfix postfix *= nums[i] } - + return res } } @@ -807,7 +807,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ space for the output array. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ space for the output array. diff --git a/articles/profitable-schemes.md b/articles/profitable-schemes.md index 98986e70a..1b3ce4a65 100644 --- a/articles/profitable-schemes.md +++ b/articles/profitable-schemes.md @@ -10,13 +10,13 @@ class Solution: def dfs(i, n, p): if i == len(group): return 1 if p >= minProfit else 0 - + res = dfs(i + 1, n, p) if n - group[i] >= 0: res = (res + dfs(i + 1, n - group[i], p + profit[i])) % mod return res - + return dfs(0, n, 0) ``` @@ -103,8 +103,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ N)$ -* Space complexity: $O(N)$ +- Time complexity: $O(2 ^ N)$ +- Space complexity: $O(N)$ > Where $N$ is the size of the $group$ array. @@ -130,10 +130,10 @@ class Solution: if n - group[i] >= 0: nxtP = min(p + profit[i], minProfit) res = (res + dfs(i + 1, n - group[i], nxtP)) % mod - + dp[(i, n, p)] = res return res - + return dfs(0, n, 0) ``` @@ -217,7 +217,7 @@ class Solution { profitableSchemes(n, minProfit, group, profit) { const MOD = 1e9 + 7; const dp = Array.from({ length: group.length }, () => - Array.from({ length: n + 1 }, () => Array(minProfit + 1).fill(-1)) + Array.from({ length: n + 1 }, () => Array(minProfit + 1).fill(-1)), ); const dfs = (i, n, p) => { @@ -247,8 +247,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(N * m * n)$ -* Space complexity: $O(N * m * n)$ +- Time complexity: $O(N * m * n)$ +- Space complexity: $O(N * m * n)$ > Where $N$ is the size of the $group$ array, $m$ is the given minimum profit, and $n$ is the number of group members. @@ -275,8 +275,8 @@ class Solution: if j >= group[i]: nxtP = min(profit[i] + p, minProfit) res = (res + dp[i + 1][j - group[i]][nxtP]) % mod - dp[i][j][p] = res - + dp[i][j][p] = res + return dp[0][n][0] ``` @@ -356,7 +356,7 @@ class Solution { const N = group.length; const dp = Array.from({ length: N + 1 }, () => - Array.from({ length: n + 2 }, () => Array(minProfit + 1).fill(0)) + Array.from({ length: n + 2 }, () => Array(minProfit + 1).fill(0)), ); for (let j = 0; j <= n; j++) { @@ -385,8 +385,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(N * m * n)$ -* Space complexity: $O(N * m * n)$ +- Time complexity: $O(N * m * n)$ +- Space complexity: $O(N * m * n)$ > Where $N$ is the size of the $group$ array, $m$ is the given minimum profit, and $n$ is the number of group members. @@ -413,8 +413,8 @@ class Solution: if j >= group[i]: nxtP = min(profit[i] + p, minProfit) res = (res + dp[j - group[i]][nxtP]) % mod - dp[j][p] = res - + dp[j][p] = res + return dp[n][0] ``` @@ -493,8 +493,8 @@ class Solution { const MOD = 1e9 + 7; const N = group.length; - const dp = Array.from({ length: n + 2 }, () => - Array(minProfit + 1).fill(0) + const dp = Array.from({ length: n + 2 }, () => + Array(minProfit + 1).fill(0), ); for (let j = 0; j <= n; j++) { @@ -523,7 +523,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(N * m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(N * m * n)$ +- Space complexity: $O(m * n)$ -> Where $N$ is the size of the $group$ array, $m$ is the given minimum profit, and $n$ is the number of group members. \ No newline at end of file +> Where $N$ is the size of the $group$ array, $m$ is the given minimum profit, and $n$ is the number of group members. diff --git a/articles/pseudo-palindromic-paths-in-a-binary-tree.md b/articles/pseudo-palindromic-paths-in-a-binary-tree.md index 96bf58f3b..be39148af 100644 --- a/articles/pseudo-palindromic-paths-in-a-binary-tree.md +++ b/articles/pseudo-palindromic-paths-in-a-binary-tree.md @@ -146,12 +146,12 @@ class Solution { if (!cur) return 0; count.set(cur.val, (count.get(cur.val) || 0) + 1); - let odd_change = (count.get(cur.val) % 2 === 1) ? 1 : -1; + let odd_change = count.get(cur.val) % 2 === 1 ? 1 : -1; odd += odd_change; let res; if (!cur.left && !cur.right) { - res = (odd <= 1) ? 1 : 0; + res = odd <= 1 ? 1 : 0; } else { res = dfs(cur.left) + dfs(cur.right); } @@ -170,8 +170,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(h)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(h)$ for recursion stack. > Where $n$ is the number of nodes and $h$ is the height of the given tree. @@ -242,7 +242,7 @@ public class Solution { count[cur.val] ^= 1; odd += count[cur.val] == 1 ? 1 : -1; - int res = (cur.left == null && cur.right == null && odd <= 1) ? 1 + int res = (cur.left == null && cur.right == null && odd <= 1) ? 1 : dfs(cur.left, count, odd) + dfs(cur.right, count, odd); odd += count[cur.val] == 1 ? 1 : -1; @@ -279,7 +279,7 @@ private: count[cur->val] ^= 1; odd += (count[cur->val] == 1) ? 1 : -1; - int res = (!cur->left && !cur->right && odd <= 1) ? 1 + int res = (!cur->left && !cur->right && odd <= 1) ? 1 : dfs(cur->left, count, odd) + dfs(cur->right, count, odd); odd += (count[cur->val] == 1) ? 1 : -1; @@ -315,8 +315,10 @@ class Solution { count[cur.val] ^= 1; odd += count[cur.val] === 1 ? 1 : -1; - let res = (!cur.left && !cur.right && odd <= 1) - ? 1 : dfs(cur.left, odd) + dfs(cur.right, odd); + let res = + !cur.left && !cur.right && odd <= 1 + ? 1 + : dfs(cur.left, odd) + dfs(cur.right, odd); odd += count[cur.val] === 1 ? 1 : -1; count[cur.val] ^= 1; @@ -333,8 +335,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(h)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(h)$ for recursion stack. > Where $n$ is the number of nodes and $h$ is the height of the given tree. @@ -452,7 +454,7 @@ class Solution { const dfs = (node, path) => { if (!node) return 0; - path ^= (1 << node.val); + path ^= 1 << node.val; if (!node.left && !node.right) { return (path & (path - 1)) === 0 ? 1 : 0; } @@ -469,8 +471,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(h)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(h)$ for recursion stack. > Where $n$ is the number of nodes and $h$ is the height of the given tree. @@ -636,8 +638,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -800,7 +802,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(h)$ +- Time complexity: $O(n)$ +- Space complexity: $O(h)$ -> Where $n$ is the number of nodes and $h$ is the height of the given tree. \ No newline at end of file +> Where $n$ is the number of nodes and $h$ is the height of the given tree. diff --git a/articles/push-dominoes.md b/articles/push-dominoes.md index efe99877f..043e65116 100644 --- a/articles/push-dominoes.md +++ b/articles/push-dominoes.md @@ -11,15 +11,15 @@ class Solution: for i in range(n): if dominoes[i] != '.': continue - + l, r = i - 1, i + 1 - + while l >= 0 and dominoes[l] == '.': l -= 1 - + while r < n and dominoes[r] == '.': r += 1 - + left_force = dominoes[l] if l >= 0 else None right_force = dominoes[r] if r < n else None @@ -109,30 +109,31 @@ class Solution { */ pushDominoes(dominoes) { const n = dominoes.length; - const res = dominoes.split(""); + const res = dominoes.split(''); for (let i = 0; i < n; i++) { - if (dominoes[i] !== ".") continue; + if (dominoes[i] !== '.') continue; - let l = i - 1, r = i + 1; + let l = i - 1, + r = i + 1; - while (l >= 0 && dominoes[l] === ".") l--; - while (r < n && dominoes[r] === ".") r++; + while (l >= 0 && dominoes[l] === '.') l--; + while (r < n && dominoes[r] === '.') r++; const leftForce = l >= 0 ? dominoes[l] : null; const rightForce = r < n ? dominoes[r] : null; - if (leftForce === "R" && rightForce === "L") { - if ((i - l) < (r - i)) res[i] = "R"; - else if ((r - i) < (i - l)) res[i] = "L"; - } else if (leftForce === "R") { - res[i] = "R"; - } else if (rightForce === "L") { - res[i] = "L"; + if (leftForce === 'R' && rightForce === 'L') { + if (i - l < r - i) res[i] = 'R'; + else if (r - i < i - l) res[i] = 'L'; + } else if (leftForce === 'R') { + res[i] = 'R'; + } else if (rightForce === 'L') { + res[i] = 'L'; } } - return res.join(""); + return res.join(''); } } ``` @@ -141,8 +142,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ for only the output string. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ for only the output string. --- @@ -157,7 +158,7 @@ class Solution: left = [float('inf')] * n right = [float('inf')] * n res = list(dominoes) - + force = float('inf') for i in range(n): if dominoes[i] == 'R': @@ -167,7 +168,7 @@ class Solution: else: force += 1 right[i] = force - + force = float('inf') for i in range(n - 1, -1, -1): if dominoes[i] == 'L': @@ -177,13 +178,13 @@ class Solution: else: force += 1 left[i] = force - + for i in range(n): if left[i] < right[i]: res[i] = 'L' elif right[i] < left[i]: res[i] = 'R' - + return "".join(res) ``` @@ -288,13 +289,13 @@ class Solution { const n = dominoes.length; const left = new Array(n).fill(Infinity); const right = new Array(n).fill(Infinity); - const res = dominoes.split(""); + const res = dominoes.split(''); let force = Infinity; for (let i = 0; i < n; i++) { - if (dominoes[i] === "R") { + if (dominoes[i] === 'R') { force = 0; - } else if (dominoes[i] === "L") { + } else if (dominoes[i] === 'L') { force = Infinity; } else { force = force === Infinity ? Infinity : force + 1; @@ -304,9 +305,9 @@ class Solution { force = Infinity; for (let i = n - 1; i >= 0; i--) { - if (dominoes[i] === "L") { + if (dominoes[i] === 'L') { force = 0; - } else if (dominoes[i] === "R") { + } else if (dominoes[i] === 'R') { force = Infinity; } else { force = force === Infinity ? Infinity : force + 1; @@ -316,13 +317,13 @@ class Solution { for (let i = 0; i < n; i++) { if (left[i] < right[i]) { - res[i] = "L"; + res[i] = 'L'; } else if (right[i] < left[i]) { - res[i] = "R"; + res[i] = 'R'; } } - return res.join(""); + return res.join(''); } } ``` @@ -331,8 +332,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -448,11 +449,11 @@ class Solution { * @return {string} */ pushDominoes(dominoes) { - const dom = dominoes.split(""); + const dom = dominoes.split(''); const q = new Queue(); for (let i = 0; i < dom.length; i++) { - if (dom[i] !== ".") { + if (dom[i] !== '.') { q.push([i, dom[i]]); } } @@ -460,22 +461,22 @@ class Solution { while (!q.isEmpty()) { const [i, d] = q.pop(); - if (d === "L" && i > 0 && dom[i - 1] === ".") { - q.push([i - 1, "L"]); - dom[i - 1] = "L"; - } else if (d === "R") { - if (i + 1 < dom.length && dom[i + 1] === ".") { - if (i + 2 < dom.length && dom[i + 2] === "L") { + if (d === 'L' && i > 0 && dom[i - 1] === '.') { + q.push([i - 1, 'L']); + dom[i - 1] = 'L'; + } else if (d === 'R') { + if (i + 1 < dom.length && dom[i + 1] === '.') { + if (i + 2 < dom.length && dom[i + 2] === 'L') { q.pop(); } else { - q.push([i + 1, "R"]); - dom[i + 1] = "R"; + q.push([i + 1, 'R']); + dom[i + 1] = 'R'; } } } } - return dom.join(""); + return dom.join(''); } } ``` @@ -484,8 +485,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -527,7 +528,7 @@ class Solution: # Append half the dots as 'L'. res.append('L' * (dots // 2)) - + # Append the current 'L'. res.append('L') R, dots = False, 0 @@ -536,14 +537,14 @@ class Solution: # Append 'L' for all the dots and the current 'L'. res.append('L' * (dots + 1)) dots = 0 - + if R: # Trailing dots are affected by the last 'R'. res.append('R' * (dots + 1)) else: # Trailing dots remain unchanged as there is no previous 'R'. res.append('.' * dots) - + return ''.join(res) ``` @@ -745,5 +746,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for only the output string. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for only the output string. diff --git a/articles/put-marbles-in-bags.md b/articles/put-marbles-in-bags.md index a0abf8a29..67d8a650a 100644 --- a/articles/put-marbles-in-bags.md +++ b/articles/put-marbles-in-bags.md @@ -178,8 +178,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * k)$ -* Space complexity: $O(n * k)$ +- Time complexity: $O(n * k)$ +- Space complexity: $O(n * k)$ > Where $n$ is the number of marbles, and $k$ is the number of bags. @@ -253,7 +253,7 @@ public: for (int j = 0; j < i; ++j) minScore += splits[j]; for (int j = splits.size() - i; j < splits.size(); ++j) { maxScore += splits[j]; - } + } return maxScore - minScore; } @@ -278,7 +278,8 @@ class Solution { splits.sort((a, b) => a - b); const i = k - 1; - let minScore = 0, maxScore = 0; + let minScore = 0, + maxScore = 0; for (let j = 0; j < i; j++) minScore += splits[j]; for (let j = splits.length - i; j < splits.length; j++) { maxScore += splits[j]; @@ -319,8 +320,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ > Where $n$ is the number of marbles, and $k$ is the number of bags. @@ -453,7 +454,8 @@ class Solution { if (maxHeap.size() > k - 1) maxHeap.dequeue(); } - let maxScore = 0, minScore = 0; + let maxScore = 0, + minScore = 0; while (!minHeap.isEmpty()) maxScore += minHeap.dequeue(); while (!maxHeap.isEmpty()) minScore += maxHeap.dequeue(); @@ -495,7 +497,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log k)$ -* Space complexity: $O(k)$ +- Time complexity: $O(n \log k)$ +- Space complexity: $O(k)$ -> Where $n$ is the number of marbles, and $k$ is the number of bags. \ No newline at end of file +> Where $n$ is the number of marbles, and $k$ is the number of bags. diff --git a/articles/queue-reconstruction-by-height.md b/articles/queue-reconstruction-by-height.md index 72dbfcf5c..0829530eb 100644 --- a/articles/queue-reconstruction-by-height.md +++ b/articles/queue-reconstruction-by-height.md @@ -39,33 +39,33 @@ public class Solution { public int[][] reconstructQueue(int[][] people) { int n = people.length; Map> mp = new HashMap<>(); - + for (int[] p : people) { mp.computeIfAbsent(p[1], k -> new ArrayList<>()).add(p[0]); - } + } for (int key : mp.keySet()) { Collections.sort(mp.get(key), Collections.reverseOrder()); } - + List res = new ArrayList<>(); for (int i = 0; i < n; i++) { int mini = -1; for (int k : mp.keySet()) { if (k > i) continue; - + int cnt = 0; for (int j = res.size() - 1; j >= 0; j--) { if (res.get(j)[0] >= mp.get(k).get(mp.get(k).size() - 1)) { cnt++; } } - - if (cnt == k && (mini == -1 || mp.get(k).get(mp.get(k).size() - 1) < + + if (cnt == k && (mini == -1 || mp.get(k).get(mp.get(k).size() - 1) < mp.get(mini).get(mp.get(mini).size() - 1))) { mini = k; } } - + List list = mp.get(mini); res.add(new int[]{list.get(list.size() - 1), mini}); list.remove(list.size() - 1); @@ -73,7 +73,7 @@ public class Solution { mp.remove(mini); } } - + return res.toArray(new int[n][2]); } } @@ -85,40 +85,40 @@ public: vector> reconstructQueue(vector>& people) { int n = people.size(); unordered_map> mp; - + for (const auto& p : people) { mp[p[1]].push_back(p[0]); } for (auto& pair : mp) { sort(pair.second.rbegin(), pair.second.rend()); } - + vector> res; for (int i = 0; i < n; i++) { int mini = -1; for (const auto& pair : mp) { int k = pair.first; if (k > i) continue; - + int cnt = 0; for (int j = res.size() - 1; j >= 0; j--) { if (res[j][0] >= mp[k].back()) { cnt++; } } - + if (cnt == k && (mini == -1 || mp[k].back() < mp[mini].back())) { mini = k; } } - + res.push_back({mp[mini].back(), mini}); mp[mini].pop_back(); if (mp[mini].empty()) { mp.erase(mini); } } - + return res; } }; @@ -153,7 +153,12 @@ class Solution { if (res[j][0] >= heights[heights.length - 1]) cnt++; } - if (cnt === k && (mini === -1 || heights[heights.length - 1] < mp.get(mini)[mp.get(mini).length - 1])) { + if ( + cnt === k && + (mini === -1 || + heights[heights.length - 1] < + mp.get(mini)[mp.get(mini).length - 1]) + ) { mini = k; } } @@ -173,8 +178,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n + n ^ 3)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n + n ^ 3)$ +- Space complexity: $O(n)$ --- @@ -212,14 +217,14 @@ public: sort(people.begin(), people.end(), [](auto& a, auto& b) { return a[0] == b[0] ? a[1] < b[1] : a[0] > b[0]; }); - + list> res; for (const auto& p : people) { auto it = res.begin(); advance(it, p[1]); res.insert(it, p); } - + return vector>(res.begin(), res.end()); } }; @@ -246,8 +251,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n\log n + n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n\log n + n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -271,7 +276,7 @@ class Solution: cnt += 1 i += 1 res[i] = p - + return res ``` @@ -308,7 +313,7 @@ public: sort(people.begin(), people.end(), [](auto& a, auto& b) { return a[0] == b[0] ? a[1] > b[1] : a[0] < b[0]; }); - + vector> res(people.size(), vector()); for (const auto& p : people) { int cnt = 0, i = 0; @@ -321,7 +326,7 @@ public: } res[i] = p; } - + return res; } }; @@ -334,11 +339,12 @@ class Solution { * @return {number[][]} */ reconstructQueue(people) { - people.sort((a, b) => a[0] === b[0] ? b[1] - a[1] : a[0] - b[0]); + people.sort((a, b) => (a[0] === b[0] ? b[1] - a[1] : a[0] - b[0])); const res = Array(people.length).fill(null); for (const p of people) { - let cnt = 0, i = 0; + let cnt = 0, + i = 0; while (i < people.length) { if (res[i] === null) { @@ -359,8 +365,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n\log n + n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n\log n + n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -423,10 +429,10 @@ class Solution: r = mid - 1 else: l = mid + 1 - + res[idx] = p segTree.update(idx, 0) - + return res ``` @@ -548,7 +554,7 @@ public: return a[0] == b[0] ? a[1] > b[1] : a[0] < b[0]; }); vector> res(n, vector()); - + SegmentTree segTree(n); for (const auto& p : people) { int l = 0, r = n - 1, idx = 0; @@ -566,7 +572,7 @@ public: res[idx] = p; segTree.update(idx, 0); } - + return res; } }; @@ -576,7 +582,7 @@ public: class SegmentTree { /** * @constructor - * @param {number} N + * @param {number} N */ constructor(N) { this.n = N; @@ -585,7 +591,7 @@ class SegmentTree { } this.build(N); } - + /** * @param {number} N * @return {void} @@ -596,19 +602,19 @@ class SegmentTree { this.tree[this.n + i] = 1; } for (let i = this.n - 1; i > 0; i--) { - this.tree[i] = this.tree[i << 1] + this.tree[i << 1 | 1]; + this.tree[i] = this.tree[i << 1] + this.tree[(i << 1) | 1]; } } /** - * @param {number} i + * @param {number} i * @param {number} val * @return {void} */ update(i, val) { this.tree[this.n + i] = val; for (let j = (this.n + i) >> 1; j >= 1; j >>= 1) { - this.tree[j] = this.tree[j << 1] + this.tree[j << 1 | 1]; + this.tree[j] = this.tree[j << 1] + this.tree[(j << 1) | 1]; } } @@ -640,12 +646,14 @@ class Solution { */ reconstructQueue(people) { const n = people.length; - people.sort((a, b) => a[0] === b[0] ? b[1] - a[1] : a[0] - b[0]); + people.sort((a, b) => (a[0] === b[0] ? b[1] - a[1] : a[0] - b[0])); const res = Array(n).fill(null); - + const segTree = new SegmentTree(n); for (const p of people) { - let l = 0, r = n - 1, idx = 0; + let l = 0, + r = n - 1, + idx = 0; while (l <= r) { let mid = (l + r) >> 1; let cnt = segTree.query(0, mid); @@ -670,8 +678,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n\log ^ 2 n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n\log ^ 2 n)$ +- Space complexity: $O(n)$ --- @@ -721,10 +729,10 @@ class Solution: r = mid - 1 else: l = mid + 1 - + res[idx] = p bit.update(idx, -1) - + return res ``` @@ -836,7 +844,7 @@ public: return a[0] == b[0] ? a[1] > b[1] : a[0] < b[0]; }); vector> res(n, vector()); - + BIT bit(n); for (const auto& p : people) { int l = 0, r = n - 1, idx = 0; @@ -854,7 +862,7 @@ public: res[idx] = p; bit.update(idx, -1); } - + return res; } }; @@ -874,8 +882,8 @@ class BIT { } } - /** - * @param {number} index + /** + * @param {number} index * @param {number} val * @return {void} */ @@ -887,8 +895,8 @@ class BIT { } } - /** - * @param {number} index + /** + * @param {number} index * @return {number} */ prefixSum(index) { @@ -900,8 +908,8 @@ class BIT { return totalSum; } - /** - * @param {number} left + /** + * @param {number} left * @param {number} right * @return {number} */ @@ -917,12 +925,14 @@ class Solution { */ reconstructQueue(people) { const n = people.length; - people.sort((a, b) => a[0] === b[0] ? b[1] - a[1] : a[0] - b[0]); + people.sort((a, b) => (a[0] === b[0] ? b[1] - a[1] : a[0] - b[0])); const res = Array(n).fill(null); - + const bit = new BIT(n); for (const p of people) { - let l = 0, r = n - 1, idx = 0; + let l = 0, + r = n - 1, + idx = 0; while (l <= r) { let mid = (l + r) >> 1; let cnt = bit.query(0, mid); @@ -947,8 +957,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n\log ^ 2 n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n\log ^ 2 n)$ +- Space complexity: $O(n)$ --- @@ -992,7 +1002,7 @@ class Solution: idx = bit.getIdx(p[1], MSB) res[idx] = p bit.update(idx, -1) - + return res ``` @@ -1094,7 +1104,7 @@ public: return a[0] == b[0] ? a[1] > b[1] : a[0] < b[0]; }); vector> res(n, vector()); - + BIT bit(n); int MSB = 1 << (31 - __builtin_clz(n)); for (const auto& p : people) { @@ -1102,7 +1112,7 @@ public: res[idx] = p; bit.update(idx, -1); } - + return res; } }; @@ -1122,8 +1132,8 @@ class BIT { } } - /** - * @param {number} index + /** + * @param {number} index * @param {number} val * @return {void} */ @@ -1135,8 +1145,8 @@ class BIT { } } - /** - * @param {number} cnt + /** + * @param {number} cnt * @param {number} MSB * @return {number} */ @@ -1161,9 +1171,9 @@ class Solution { */ reconstructQueue(people) { const n = people.length; - people.sort((a, b) => a[0] === b[0] ? b[1] - a[1] : a[0] - b[0]); + people.sort((a, b) => (a[0] === b[0] ? b[1] - a[1] : a[0] - b[0])); const res = Array(n).fill(null); - + const bit = new BIT(n); const MSB = 1 << Math.floor(Math.log2(n)); for (const p of people) { @@ -1181,5 +1191,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n\log n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n\log n)$ +- Space complexity: $O(n)$ diff --git a/articles/range-sum-of-bst.md b/articles/range-sum-of-bst.md index c53b3f7e2..dcda43480 100644 --- a/articles/range-sum-of-bst.md +++ b/articles/range-sum-of-bst.md @@ -13,7 +13,7 @@ class Solution: def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int: if not root: return 0 - + res = root.val if low <= root.val <= high else 0 res += self.rangeSumBST(root.left, low, high) res += self.rangeSumBST(root.right, low, high) @@ -94,7 +94,7 @@ class Solution { rangeSumBST(root, low, high) { if (!root) return 0; - let res = (low <= root.val && root.val <= high) ? root.val : 0; + let res = low <= root.val && root.val <= high ? root.val : 0; res += this.rangeSumBST(root.left, low, high); res += this.rangeSumBST(root.right, low, high); return res; @@ -119,7 +119,7 @@ class Solution { public class Solution { public int RangeSumBST(TreeNode root, int low, int high) { if (root == null) return 0; - + int res = (root.val >= low && root.val <= high) ? root.val : 0; res += RangeSumBST(root.left, low, high); res += RangeSumBST(root.right, low, high); @@ -132,8 +132,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -192,7 +192,7 @@ public class Solution { return rangeSumBST(root.right, low, high); } - return root.val + rangeSumBST(root.left, low, high) + + return root.val + rangeSumBST(root.left, low, high) + rangeSumBST(root.right, low, high); } } @@ -222,7 +222,7 @@ public: return rangeSumBST(root->right, low, high); } - return root->val + rangeSumBST(root->left, low, high) + + return root->val + rangeSumBST(root->left, low, high) + rangeSumBST(root->right, low, high); } }; @@ -256,8 +256,11 @@ class Solution { return rangeSumBST(root.right, low, high); } - return root.val + this.rangeSumBST(root.left, low, high) + - this.rangeSumBST(root.right, low, high); + return ( + root.val + + this.rangeSumBST(root.left, low, high) + + this.rangeSumBST(root.right, low, high) + ); } } ``` @@ -279,14 +282,14 @@ class Solution { public class Solution { public int RangeSumBST(TreeNode root, int low, int high) { if (root == null) return 0; - + if (root.val > high) { return RangeSumBST(root.left, low, high); } if (root.val < low) { return RangeSumBST(root.right, low, high); } - + return root.val + RangeSumBST(root.left, low, high) + RangeSumBST(root.right, low, high); @@ -298,8 +301,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -502,5 +505,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/range-sum-query-2d-immutable.md b/articles/range-sum-query-2d-immutable.md index 0d34a2b30..9401b666f 100644 --- a/articles/range-sum-query-2d-immutable.md +++ b/articles/range-sum-query-2d-immutable.md @@ -68,10 +68,10 @@ class NumMatrix { this.matrix = matrix; } - /** - * @param {number} row1 - * @param {number} col1 - * @param {number} row2 + /** + * @param {number} row1 + * @param {number} col1 + * @param {number} row2 * @param {number} col2 * @return {number} */ @@ -111,8 +111,8 @@ public class NumMatrix { ### Time & Space Complexity -* Time complexity: $O(m * n)$ for each query. -* Space complexity: $O(1)$ +- Time complexity: $O(m * n)$ for each query. +- Space complexity: $O(1)$ > Where $m$ is the number of rows and $n$ is the number of columns in the matrix. @@ -127,7 +127,7 @@ class NumMatrix: def __init__(self, matrix: list[list[int]]): self.prefixSum = [[0] * len(matrix[0]) for _ in range(len(matrix))] - + for row in range(len(matrix)): self.prefixSum[row][0] = matrix[row][0] for col in range(1, len(matrix[0])): @@ -212,20 +212,23 @@ class NumMatrix { * @param {number[][]} matrix */ constructor(matrix) { - this.prefixSum = Array.from({ length: matrix.length }, () => Array(matrix[0].length).fill(0)); + this.prefixSum = Array.from({ length: matrix.length }, () => + Array(matrix[0].length).fill(0), + ); for (let row = 0; row < matrix.length; row++) { this.prefixSum[row][0] = matrix[row][0]; for (let col = 1; col < matrix[0].length; col++) { - this.prefixSum[row][col] = this.prefixSum[row][col - 1] + matrix[row][col]; + this.prefixSum[row][col] = + this.prefixSum[row][col - 1] + matrix[row][col]; } } } - /** - * @param {number} row1 - * @param {number} col1 - * @param {number} row2 + /** + * @param {number} row1 + * @param {number} col1 + * @param {number} row2 * @param {number} col2 * @return {number} */ @@ -233,7 +236,8 @@ class NumMatrix { let res = 0; for (let row = row1; row <= row2; row++) { if (col1 > 0) { - res += this.prefixSum[row][col2] - this.prefixSum[row][col1 - 1]; + res += + this.prefixSum[row][col2] - this.prefixSum[row][col1 - 1]; } else { res += this.prefixSum[row][col2]; } @@ -251,7 +255,7 @@ public class NumMatrix { int rows = matrix.Length; int cols = matrix[0].Length; prefixSum = new int[rows][]; - + for (int i = 0; i < rows; i++) { prefixSum[i] = new int[cols]; prefixSum[i][0] = matrix[i][0]; @@ -279,8 +283,8 @@ public class NumMatrix { ### Time & Space Complexity -* Time complexity: $O(m)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns in the matrix. @@ -380,8 +384,11 @@ class NumMatrix { * @param {number[][]} matrix */ constructor(matrix) { - const ROWS = matrix.length, COLS = matrix[0].length; - this.sumMat = Array.from({ length: ROWS + 1 }, () => Array(COLS + 1).fill(0)); + const ROWS = matrix.length, + COLS = matrix[0].length; + this.sumMat = Array.from({ length: ROWS + 1 }, () => + Array(COLS + 1).fill(0), + ); for (let r = 0; r < ROWS; r++) { let prefix = 0; @@ -393,15 +400,18 @@ class NumMatrix { } } - /** - * @param {number} row1 - * @param {number} col1 - * @param {number} row2 + /** + * @param {number} row1 + * @param {number} col1 + * @param {number} row2 * @param {number} col2 * @return {number} */ sumRegion(row1, col1, row2, col2) { - row1++; col1++; row2++; col2++; + row1++; + col1++; + row2++; + col2++; const bottomRight = this.sumMat[row2][col2]; const above = this.sumMat[row1 - 1][col2]; const left = this.sumMat[row2][col1 - 1]; @@ -445,7 +455,7 @@ public class NumMatrix { ### Time & Space Complexity -* Time complexity: $O(1)$ for each query. -* Space complexity: $O(m * n)$ +- Time complexity: $O(1)$ for each query. +- Space complexity: $O(m * n)$ -> Where $m$ is the number of rows and $n$ is the number of columns in the matrix. \ No newline at end of file +> Where $m$ is the number of rows and $n$ is the number of columns in the matrix. diff --git a/articles/range-sum-query-immutable.md b/articles/range-sum-query-immutable.md index f53012caa..dec6558e6 100644 --- a/articles/range-sum-query-immutable.md +++ b/articles/range-sum-query-immutable.md @@ -59,8 +59,8 @@ class NumArray { this.nums = nums; } - /** - * @param {number} left + /** + * @param {number} left * @param {number} right * @return {number} */ @@ -78,8 +78,8 @@ class NumArray { ### Time & Space Complexity -* Time complexity: $O(n)$ for each $sumRange()$ query. -* Space complexity: $O(1)$ since we only make a reference to the input array. +- Time complexity: $O(n)$ for each $sumRange()$ query. +- Space complexity: $O(1)$ since we only make a reference to the input array. --- @@ -159,8 +159,8 @@ class NumArray { } } - /** - * @param {number} left + /** + * @param {number} left * @param {number} right * @return {number} */ @@ -176,8 +176,8 @@ class NumArray { ### Time & Space Complexity -* Time complexity: $O(1)$ for each $sumRange()$ query, $O(n)$ for building the prefix sum array. -* Space complexity: $O(n)$ +- Time complexity: $O(1)$ for each $sumRange()$ query, $O(n)$ for building the prefix sum array. +- Space complexity: $O(n)$ --- @@ -191,7 +191,7 @@ class NumArray: self.prefix = [0] * (len(nums) + 1) for i in range(len(nums)): self.prefix[i + 1] = self.prefix[i] + nums[i] - + def sumRange(self, left, right): return self.prefix[right + 1] - self.prefix[left] @@ -245,8 +245,8 @@ class NumArray { } } - /** - * @param {number} left + /** + * @param {number} left * @param {number} right * @return {number} */ @@ -260,8 +260,8 @@ class NumArray { ### Time & Space Complexity -* Time complexity: $O(1)$ for each $sumRange()$ query, $O(n)$ for building the prefix sum array. -* Space complexity: $O(n)$ +- Time complexity: $O(1)$ for each $sumRange()$ query, $O(n)$ for building the prefix sum array. +- Space complexity: $O(n)$ --- @@ -433,8 +433,8 @@ class NumArray { this.segTree = new SegmentTree(nums); } - /** - * @param {number} left + /** + * @param {number} left * @param {number} right * @return {number} */ @@ -448,5 +448,5 @@ class NumArray { ### Time & Space Complexity -* Time complexity: $O(\log n)$ for each $sumRange()$ query, $O(n)$ for building the Segment Tree. -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(\log n)$ for each $sumRange()$ query, $O(n)$ for building the Segment Tree. +- Space complexity: $O(n)$ diff --git a/articles/range-sum-query-mutable.md b/articles/range-sum-query-mutable.md index 358921e03..7d694e093 100644 --- a/articles/range-sum-query-mutable.md +++ b/articles/range-sum-query-mutable.md @@ -73,8 +73,8 @@ class NumArray { this.nums = nums; } - /** - * @param {number} index + /** + * @param {number} index * @param {number} val * @return {void} */ @@ -82,8 +82,8 @@ class NumArray { this.nums[index] = val; } - /** - * @param {number} left + /** + * @param {number} left * @param {number} right * @return {number} */ @@ -101,11 +101,11 @@ class NumArray { ### Time & Space Complexity -* Time complexity: - * $O(n)$ for initializing the input array. - * $O(1)$ for each $update()$ function call. - * $O(n)$ for each $sumRange()$ function call. -* Space complexity: $O(n)$ +- Time complexity: + - $O(n)$ for initializing the input array. + - $O(1)$ for each $update()$ function call. + - $O(n)$ for each $sumRange()$ function call. +- Space complexity: $O(n)$ --- @@ -322,11 +322,11 @@ public: NumArray(vector& nums) { this->segTree = new SegmentTree(nums.size(), nums); } - + void update(int index, int val) { this->segTree->update(index, val); } - + int sumRange(int left, int right) { return this->segTree->query(left, right); } @@ -337,7 +337,7 @@ public: class SegmentTree { /** * @constructor - * @param {number} N + * @param {number} N * @param {number[]} A */ constructor(N, A) { @@ -348,12 +348,12 @@ class SegmentTree { this.tree = new Int32Array(2 * this.n); this.build(0, 0, this.n - 1, A); } - + /** - * @param {number} node - * @param {number} start - * @param {number} end - * @param {number[]} A + * @param {number} node + * @param {number} start + * @param {number} end + * @param {number[]} A */ build(node, start, end, A) { if (start === end) { @@ -389,11 +389,11 @@ class SegmentTree { } /** - * @param {number} node - * @param {number} start - * @param {number} end - * @param {number} l - * @param {number} r + * @param {number} node + * @param {number} start + * @param {number} end + * @param {number} l + * @param {number} r * @return {number} */ _query(node, start, end, l, r) { @@ -419,8 +419,8 @@ class SegmentTree { } /** - * @param {number} l - * @param {number} r + * @param {number} l + * @param {number} r * @return {number} */ query(l, r) { @@ -436,8 +436,8 @@ class NumArray { this.segTree = new SegmentTree(nums.length, nums); } - /** - * @param {number} index + /** + * @param {number} index * @param {number} val * @return {void} */ @@ -445,8 +445,8 @@ class NumArray { this.segTree.update(index, val); } - /** - * @param {number} left + /** + * @param {number} left * @param {number} right * @return {number} */ @@ -460,11 +460,11 @@ class NumArray { ### Time & Space Complexity -* Time complexity: - * $O(n)$ for initializing the input array. - * $O(\log n)$ for each $update()$ function call. - * $O(\log n)$ for each $sumRange()$ function call. -* Space complexity: $O(n)$ +- Time complexity: + - $O(n)$ for initializing the input array. + - $O(\log n)$ for each $update()$ function call. + - $O(\log n)$ for each $sumRange()$ function call. +- Space complexity: $O(n)$ --- @@ -627,11 +627,11 @@ public: NumArray(vector& nums) { this->segTree = new SegmentTree(nums.size(), nums); } - + void update(int index, int val) { this->segTree->update(index, val); } - + int sumRange(int left, int right) { return this->segTree->query(left, right); } @@ -642,7 +642,7 @@ public: class SegmentTree { /** * @constructor - * @param {number} N + * @param {number} N * @param {number[]} A */ constructor(N, A) { @@ -652,9 +652,9 @@ class SegmentTree { } this.build(N, A); } - + /** - * @param {number} N + * @param {number} N * @param {number[]} A * @return {void} */ @@ -664,7 +664,7 @@ class SegmentTree { this.tree[this.n + i] = A[i]; } for (let i = this.n - 1; i > 0; i--) { - this.tree[i] = this.tree[i << 1] + this.tree[i << 1 | 1]; + this.tree[i] = this.tree[i << 1] + this.tree[(i << 1) | 1]; } } @@ -676,7 +676,7 @@ class SegmentTree { update(i, val) { this.tree[this.n + i] = val; for (let j = (this.n + i) >> 1; j >= 1; j >>= 1) { - this.tree[j] = this.tree[j << 1] + this.tree[j << 1 | 1]; + this.tree[j] = this.tree[j << 1] + this.tree[(j << 1) | 1]; } } @@ -709,8 +709,8 @@ class NumArray { this.segTree = new SegmentTree(nums.length, nums); } - /** - * @param {number} index + /** + * @param {number} index * @param {number} val * @return {void} */ @@ -718,8 +718,8 @@ class NumArray { this.segTree.update(index, val); } - /** - * @param {number} left + /** + * @param {number} left * @param {number} right * @return {number} */ @@ -733,11 +733,11 @@ class NumArray { ### Time & Space Complexity -* Time complexity: - * $O(n)$ for initializing the input array. - * $O(\log n)$ for each $update()$ function call. - * $O(\log n)$ for each $sumRange()$ function call. -* Space complexity: $O(n)$ +- Time complexity: + - $O(n)$ for initializing the input array. + - $O(\log n)$ for each $update()$ function call. + - $O(\log n)$ for each $sumRange()$ function call. +- Space complexity: $O(n)$ --- @@ -747,7 +747,7 @@ class NumArray { ```python class SqrtDecomposition: - + def __init__(self, nums): self.A = nums[:] self.n = len(nums) @@ -926,8 +926,8 @@ class SqrtDecomposition { } } - /** - * @param {number} left + /** + * @param {number} left * @param {number} right * @return {number} */ @@ -949,8 +949,8 @@ class SqrtDecomposition { return totalSum; } - /** - * @param {number} index + /** + * @param {number} index * @param {number} val * @return {void} */ @@ -969,8 +969,8 @@ class NumArray { this.sq = new SqrtDecomposition(nums); } - /** - * @param {number} index + /** + * @param {number} index * @param {number} val * @return {void} */ @@ -978,8 +978,8 @@ class NumArray { this.sq.update(index, val); } - /** - * @param {number} left + /** + * @param {number} left * @param {number} right * @return {number} */ @@ -993,11 +993,11 @@ class NumArray { ### Time & Space Complexity -* Time complexity: - * $O(n)$ for initializing the input array. - * $O(1)$ for each $update()$ function call. - * $O(\sqrt {n})$ for each $sumRange()$ function call. -* Space complexity: $O(n)$ +- Time complexity: + - $O(n)$ for initializing the input array. + - $O(1)$ for each $update()$ function call. + - $O(\sqrt {n})$ for each $sumRange()$ function call. +- Space complexity: $O(n)$ --- @@ -1192,16 +1192,25 @@ class SqrtDecomposition { } } - /** - * @param {number} left + /** + * @param {number} left * @param {number} right * @return {number} */ query(left, right) { - let totalSum = (left % this.blockSize !== 0) ? -this.prefixSums[left - 1] : 0; - - while (Math.floor(left / this.blockSize) < Math.floor(right / this.blockSize)) { - const blockEnd = Math.min(this.n - 1, Math.floor(left / this.blockSize) * this.blockSize + this.blockSize - 1); + let totalSum = + left % this.blockSize !== 0 ? -this.prefixSums[left - 1] : 0; + + while ( + Math.floor(left / this.blockSize) < + Math.floor(right / this.blockSize) + ) { + const blockEnd = Math.min( + this.n - 1, + Math.floor(left / this.blockSize) * this.blockSize + + this.blockSize - + 1, + ); totalSum += this.prefixSums[blockEnd]; left = blockEnd + 1; } @@ -1210,8 +1219,8 @@ class SqrtDecomposition { return totalSum; } - /** - * @param {number} index + /** + * @param {number} index * @param {number} val * @return {void} */ @@ -1219,7 +1228,12 @@ class SqrtDecomposition { const diff = val - this.nums[index]; this.nums[index] = val; - const blockEnd = Math.min(this.n - 1, Math.floor(index / this.blockSize) * this.blockSize + this.blockSize - 1); + const blockEnd = Math.min( + this.n - 1, + Math.floor(index / this.blockSize) * this.blockSize + + this.blockSize - + 1, + ); for (let i = index; i <= blockEnd; i++) { this.prefixSums[i] += diff; } @@ -1234,8 +1248,8 @@ class NumArray { this.sq = new SqrtDecomposition(nums); } - /** - * @param {number} index + /** + * @param {number} index * @param {number} val * @return {void} */ @@ -1243,8 +1257,8 @@ class NumArray { this.sq.update(index, val); } - /** - * @param {number} left + /** + * @param {number} left * @param {number} right * @return {number} */ @@ -1258,11 +1272,11 @@ class NumArray { ### Time & Space Complexity -* Time complexity: - * $O(n)$ for initializing the input array. - * $O(\sqrt {n})$ for each $update()$ function call. - * $O(\sqrt {n})$ for each $sumRange()$ function call. -* Space complexity: $O(n)$ +- Time complexity: + - $O(n)$ for initializing the input array. + - $O(\sqrt {n})$ for each $update()$ function call. + - $O(\sqrt {n})$ for each $sumRange()$ function call. +- Space complexity: $O(n)$ --- @@ -1436,8 +1450,8 @@ class BIT { } } - /** - * @param {number} index + /** + * @param {number} index * @param {number} val * @return {void} */ @@ -1451,8 +1465,8 @@ class BIT { } } - /** - * @param {number} index + /** + * @param {number} index * @return {number} */ prefixSum(index) { @@ -1464,8 +1478,8 @@ class BIT { return totalSum; } - /** - * @param {number} left + /** + * @param {number} left * @param {number} right * @return {number} */ @@ -1482,8 +1496,8 @@ class NumArray { this.bit = new BIT(nums); } - /** - * @param {number} index + /** + * @param {number} index * @param {number} val * @return {void} */ @@ -1491,8 +1505,8 @@ class NumArray { this.bit.update(index, val); } - /** - * @param {number} left + /** + * @param {number} left * @param {number} right * @return {number} */ @@ -1506,8 +1520,8 @@ class NumArray { ### Time & Space Complexity -* Time complexity: - * $O(n)$ for initializing the input array. - * $O(\log n)$ for each $update()$ function call. - * $O(\log n)$ for each $sumRange()$ function call. -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: + - $O(n)$ for initializing the input array. + - $O(\log n)$ for each $update()$ function call. + - $O(\log n)$ for each $sumRange()$ function call. +- Space complexity: $O(n)$ diff --git a/articles/rearrange-array-elements-by-sign.md b/articles/rearrange-array-elements-by-sign.md index a634ed75b..02e465145 100644 --- a/articles/rearrange-array-elements-by-sign.md +++ b/articles/rearrange-array-elements-by-sign.md @@ -10,11 +10,11 @@ class Solution: if ((i % 2 == 0 and nums[i] > 0) or (i % 2 == 1 and nums[i] < 0)): continue - + j = i + 1 while j < n and ((nums[j] > 0) == (nums[i] > 0)): j += 1 - + tmp = nums[j] while j > i: nums[j] = nums[j - 1] @@ -31,12 +31,12 @@ public class Solution { if ((i % 2 == 0 && nums[i] > 0) || (i % 2 == 1 && nums[i] < 0)) { continue; } - + int j = i + 1; while (j < n && ((nums[j] > 0) == (nums[i] > 0))) { j++; } - + int temp = nums[j]; while (j > i) { nums[j] = nums[j - 1]; @@ -58,12 +58,12 @@ public: if ((i % 2 == 0 && nums[i] > 0) || (i % 2 == 1 && nums[i] < 0)) { continue; } - + int j = i + 1; while (j < n && ((nums[j] > 0) == (nums[i] > 0))) { j++; } - + int temp = nums[j]; while (j > i) { nums[j] = nums[j - 1]; @@ -88,12 +88,12 @@ class Solution { if ((i % 2 === 0 && nums[i] > 0) || (i % 2 === 1 && nums[i] < 0)) { continue; } - + let j = i + 1; - while (j < n && ((nums[j] > 0) === (nums[i] > 0))) { + while (j < n && nums[j] > 0 === nums[i] > 0) { j++; } - + let temp = nums[j]; while (j > i) { nums[j] = nums[j - 1]; @@ -110,8 +110,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ extra space. --- @@ -192,7 +192,8 @@ class Solution { * @return {number[]} */ rearrangeArray(nums) { - const pos = [], neg = []; + const pos = [], + neg = []; for (const num of nums) { if (num > 0) { pos.push(num); @@ -216,8 +217,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -286,7 +287,8 @@ class Solution { * @return {number[]} */ rearrangeArray(nums) { - let i = 0, j = 1; + let i = 0, + j = 1; const res = new Array(nums.length); for (let k = 0; k < nums.length; k++) { if (nums[k] > 0) { @@ -306,5 +308,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for the output array. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for the output array. diff --git a/articles/reconstruct-flight-path.md b/articles/reconstruct-flight-path.md index 26ca58784..571538aea 100644 --- a/articles/reconstruct-flight-path.md +++ b/articles/reconstruct-flight-path.md @@ -25,7 +25,7 @@ class Solution: adj[src].insert(i, v) res.pop() return False - + dfs("JFK") return res ``` @@ -37,31 +37,31 @@ public class Solution { for (List ticket : tickets) { adj.putIfAbsent(ticket.get(0), new ArrayList<>()); } - + tickets.sort((a, b) -> a.get(1).compareTo(b.get(1))); for (List ticket : tickets) { adj.get(ticket.get(0)).add(ticket.get(1)); } - + List res = new ArrayList<>(); res.add("JFK"); - + if (dfs("JFK", res, adj, tickets.size() + 1)) { return res; } return new ArrayList<>(); } - - private boolean dfs(String src, List res, + + private boolean dfs(String src, List res, Map> adj, int targetLen) { if (res.size() == targetLen) { return true; } - + if (!adj.containsKey(src)) { return false; } - + List temp = new ArrayList<>(adj.get(src)); for (int i = 0; i < temp.size(); i++) { String v = temp.get(i); @@ -96,7 +96,7 @@ public: } private: - bool dfs(const string& src, vector& res, + bool dfs(const string& src, vector& res, unordered_map>& adj, int targetLen) { if (res.size() == targetLen) { return true; @@ -137,7 +137,7 @@ class Solution { adj[src].push(dst); } - const res = ["JFK"]; + const res = ['JFK']; const dfs = (src) => { if (res.length === tickets.length + 1) return true; if (!adj[src]) return false; @@ -152,9 +152,9 @@ class Solution { adj[src].splice(i, 0, v); } return false; - } + }; - dfs("JFK"); + dfs('JFK'); return res; } } @@ -180,7 +180,7 @@ public class Solution { return res; } - private bool Dfs(string src, List res, + private bool Dfs(string src, List res, Dictionary> adj, int targetLen) { if (res.Count == targetLen) return true; if (!adj.ContainsKey(src)) return false; @@ -205,41 +205,41 @@ func findItinerary(tickets [][]string) []string { for _, ticket := range tickets { adj[ticket[0]] = append(adj[ticket[0]], ticket[1]) } - + for src := range adj { sort.Strings(adj[src]) } - + res := []string{"JFK"} - + var dfs func(string) bool dfs = func(src string) bool { if len(res) == len(tickets) + 1 { return true } - + destinations, exists := adj[src] if !exists { return false } - + temp := make([]string, len(destinations)) copy(temp, destinations) - + for i, v := range temp { adj[src] = append(adj[src][:i], adj[src][i+1:]...) res = append(res, v) - + if dfs(v) { return true } - + adj[src] = append(adj[src][:i], append([]string{v}, adj[src][i:]...)...) res = res[:len(res)-1] } return false } - + dfs("JFK") return res } @@ -249,34 +249,34 @@ func findItinerary(tickets [][]string) []string { class Solution { fun findItinerary(tickets: List>): List { val adj = HashMap>() - + tickets.sortedBy { it[1] }.forEach { (src, dst) -> adj.getOrPut(src) { mutableListOf() }.add(dst) } - + val res = mutableListOf("JFK") - + fun dfs(src: String): Boolean { if (res.size == tickets.size + 1) { return true } - + val destinations = adj[src] ?: return false - + for (i in destinations.indices) { val v = destinations.removeAt(i) res.add(v) - + if (dfs(v)) { return true } - + destinations.add(i, v) res.removeAt(res.lastIndex) } return false } - + dfs("JFK") return res } @@ -327,8 +327,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(E * V)$ -* Space complexity: $O(E * V)$ +- Time complexity: $O(E * V)$ +- Space complexity: $O(E * V)$ > Where $E$ is the number of tickets (edges) and $V$ is the number of airports (vertices). @@ -351,7 +351,7 @@ class Solution: dst = adj[src].pop() dfs(dst) res.append(src) - + dfs('JFK') return res[::-1] ``` @@ -396,7 +396,7 @@ public: for (auto& [src, dests] : adj) { sort(dests.rbegin(), dests.rend()); } - + vector res; dfs("JFK", adj, res); reverse(res.begin(), res.end()); @@ -404,7 +404,7 @@ public: } private: - void dfs(const string& src, unordered_map>& adj, vector& res) { while (!adj[src].empty()) { string dst = adj[src].back(); @@ -425,12 +425,15 @@ class Solution { findItinerary(tickets) { const adj = new Map(); const res = []; - - tickets.sort().reverse().forEach(([src, dst]) => { - if (!adj.has(src)) adj.set(src, []); - adj.get(src).push(dst); - }); - + + tickets + .sort() + .reverse() + .forEach(([src, dst]) => { + if (!adj.has(src)) adj.set(src, []); + adj.get(src).push(dst); + }); + function dfs(src) { while (adj.has(src) && adj.get(src).length > 0) { const dst = adj.get(src).pop(); @@ -438,8 +441,8 @@ class Solution { } res.push(src); } - - dfs("JFK"); + + dfs('JFK'); return res.reverse(); } } @@ -449,7 +452,7 @@ class Solution { public class Solution { private Dictionary> adj; private List res = new List(); - + public List FindItinerary(List> tickets) { adj = new Dictionary>(); var sortedTickets = tickets.OrderByDescending(t => t[1]).ToList(); @@ -459,12 +462,12 @@ public class Solution { } adj[ticket[0]].Add(ticket[1]); } - + Dfs("JFK"); res.Reverse(); return res; } - + private void Dfs(string src) { while (adj.ContainsKey(src) && adj[src].Count > 0) { var dst = adj[src][adj[src].Count - 1]; @@ -479,21 +482,21 @@ public class Solution { ```go func findItinerary(tickets [][]string) []string { adj := make(map[string][]string) - + sort.Slice(tickets, func(i, j int) bool { if tickets[i][0] == tickets[j][0] { return tickets[i][1] > tickets[j][1] } return tickets[i][0] > tickets[j][0] }) - + for _, ticket := range tickets { src, dst := ticket[0], ticket[1] adj[src] = append(adj[src], dst) } - + res := make([]string, 0) - + var dfs func(string) dfs = func(src string) { for len(adj[src]) > 0 { @@ -504,13 +507,13 @@ func findItinerary(tickets [][]string) []string { } res = append(res, src) } - + dfs("JFK") - + for i := 0; i < len(res)/2; i++ { res[i], res[len(res)-1-i] = res[len(res)-1-i], res[i] } - + return res } ``` @@ -519,15 +522,15 @@ func findItinerary(tickets [][]string) []string { class Solution { fun findItinerary(tickets: List>): List { val adj = HashMap>() - + tickets.sortedWith(compareBy({ it[0] }, { it[1] })) .reversed() .forEach { (src, dst) -> adj.getOrPut(src) { mutableListOf() }.add(dst) } - + val res = mutableListOf() - + fun dfs(src: String) { while (adj[src]?.isNotEmpty() == true) { val dst = adj[src]!!.removeAt(adj[src]!!.lastIndex) @@ -535,7 +538,7 @@ class Solution { } res.add(src) } - + dfs("JFK") return res.reversed() } @@ -570,8 +573,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(E\log E)$ -* Space complexity: $O(E)$ +- Time complexity: $O(E\log E)$ +- Space complexity: $O(E)$ > Where $E$ is the number of tickets (edges) and $V$ is the number of airports (vertices). @@ -587,17 +590,17 @@ class Solution: adj = defaultdict(list) for src, dst in sorted(tickets)[::-1]: adj[src].append(dst) - + stack = ["JFK"] res = [] - + while stack: curr = stack[-1] if not adj[curr]: res.append(stack.pop()) else: stack.append(adj[curr].pop()) - + return res[::-1] ``` @@ -606,14 +609,14 @@ public class Solution { public List findItinerary(List> tickets) { Map> adj = new HashMap<>(); for (List ticket : tickets) { - adj.computeIfAbsent(ticket.get(0), + adj.computeIfAbsent(ticket.get(0), k -> new PriorityQueue<>()).add(ticket.get(1)); } - + LinkedList res = new LinkedList<>(); Stack stack = new Stack<>(); stack.push("JFK"); - + while (!stack.isEmpty()) { String curr = stack.peek(); if (!adj.containsKey(curr) || adj.get(curr).isEmpty()) { @@ -622,7 +625,7 @@ public class Solution { stack.push(adj.get(curr).poll()); } } - + return res; } } @@ -639,11 +642,11 @@ public: for (auto& [src, destinations] : adj) { sort(destinations.rbegin(), destinations.rend()); } - + vector res; stack stk; stk.push("JFK"); - + while (!stk.empty()) { string curr = stk.top(); if (adj[curr].empty()) { @@ -655,7 +658,7 @@ public: stk.push(next); } } - + reverse(res.begin(), res.end()); return res; } @@ -670,14 +673,17 @@ class Solution { */ findItinerary(tickets) { const adj = new Map(); - tickets.sort().reverse().forEach(([src, dst]) => { - if (!adj.has(src)) adj.set(src, []); - adj.get(src).push(dst); - }); - + tickets + .sort() + .reverse() + .forEach(([src, dst]) => { + if (!adj.has(src)) adj.set(src, []); + adj.get(src).push(dst); + }); + const res = []; - const stack = ["JFK"]; - + const stack = ['JFK']; + while (stack.length > 0) { let curr = stack[stack.length - 1]; if (!adj.has(curr) || adj.get(curr).length === 0) { @@ -686,7 +692,7 @@ class Solution { stack.push(adj.get(curr).pop()); } } - + return res; } } @@ -702,11 +708,11 @@ public class Solution { } adj[ticket[0]].Add(ticket[1]); } - + var res = new List(); var stack = new Stack(); stack.Push("JFK"); - + while (stack.Count > 0) { var curr = stack.Peek(); if (!adj.ContainsKey(curr) || adj[curr].Count == 0) { @@ -717,7 +723,7 @@ public class Solution { stack.Push(next); } } - + return res; } } @@ -776,7 +782,7 @@ class Solution { stack.add(adj[curr]!!.removeLast()) } } - + return res.asReversed() } } @@ -811,7 +817,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(E\log E)$ -* Space complexity: $O(E)$ +- Time complexity: $O(E\log E)$ +- Space complexity: $O(E)$ -> Where $E$ is the number of tickets (edges) and $V$ is the number of airports (vertices). \ No newline at end of file +> Where $E$ is the number of tickets (edges) and $V$ is the number of airports (vertices). diff --git a/articles/redistribute-characters-to-make-all-strings-equal.md b/articles/redistribute-characters-to-make-all-strings-equal.md index b825a3786..d503fb3d7 100644 --- a/articles/redistribute-characters-to-make-all-strings-equal.md +++ b/articles/redistribute-characters-to-make-all-strings-equal.md @@ -10,7 +10,7 @@ class Solution: for w in words: for c in w: char_cnt[c] += 1 - + for c in char_cnt: if char_cnt[c] % len(words): return False @@ -89,8 +89,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(1)$ since we have at most $26$ different characters. +- Time complexity: $O(n * m)$ +- Space complexity: $O(1)$ since we have at most $26$ different characters. > Where $n$ is the number of words and $m$ is the average length of each word. @@ -119,7 +119,7 @@ class Solution: if freq[i] % n != 0: flag -= 1 freq[i] %= n - + return flag == 0 ``` @@ -147,7 +147,7 @@ public class Solution { freq[i] %= n; } } - + return flag == 0; } } @@ -178,7 +178,7 @@ public: freq[i] %= n; } } - + return flag == 0; } }; @@ -222,7 +222,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(1)$ since we have at most $26$ different characters. +- Time complexity: $O(n * m)$ +- Space complexity: $O(1)$ since we have at most $26$ different characters. -> Where $n$ is the number of words and $m$ is the average length of each word. \ No newline at end of file +> Where $n$ is the number of words and $m$ is the average length of each word. diff --git a/articles/redundant-connection.md b/articles/redundant-connection.md index 154493da7..bedd63762 100644 --- a/articles/redundant-connection.md +++ b/articles/redundant-connection.md @@ -11,7 +11,7 @@ class Solution: def dfs(node, par): if visit[node]: return True - + visit[node] = True for nei in adj[node]: if nei == par: @@ -19,12 +19,12 @@ class Solution: if dfs(nei, node): return True return False - + for u, v in edges: adj[u].append(v) adj[v].append(u) visit = [False] * (n + 1) - + if dfs(u, -1): return [u, v] return [] @@ -52,7 +52,7 @@ public class Solution { return new int[0]; } - private boolean dfs(int node, int parent, + private boolean dfs(int node, int parent, List> adj, boolean[] visit) { if (visit[node]) { return true; @@ -93,7 +93,7 @@ public: } private: - bool dfs(int node, int parent, + bool dfs(int node, int parent, vector>& adj, vector& visit) { if (visit[node]) return true; visit[node] = true; @@ -161,7 +161,7 @@ public class Solution { return new int[0]; } - private bool Dfs(int node, int parent, + private bool Dfs(int node, int parent, List> adj, bool[] visit) { if (visit[node]) return true; visit[node] = true; @@ -204,7 +204,7 @@ func findRedundantConnection(edges [][]int) []int { for i := 0; i <= n; i++ { visit[i] = false } - + if dfs(u, -1) { return []int{u, v} } @@ -290,8 +290,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(E * (V + E))$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(E * (V + E))$ +- Space complexity: $O(V + E)$ > Where $V$ is the number of vertices and $E$ is the number of edges in the graph. @@ -313,13 +313,13 @@ class Solution: visit = [False] * (n + 1) cycle = set() cycleStart = -1 - + def dfs(node, par): nonlocal cycleStart if visit[node]: cycleStart = node - return True - + return True + visit[node] = True for nei in adj[node]: if nei == par: @@ -331,9 +331,9 @@ class Solution: cycleStart = -1 return True return False - + dfs(1, -1) - + for u, v in reversed(edges): if u in cycle and v in cycle: return [u, v] @@ -351,7 +351,7 @@ public class Solution { public int[] findRedundantConnection(int[][] edges) { int n = edges.length; adj = new ArrayList<>(); - for (int i = 0; i <= n; i++) + for (int i = 0; i <= n; i++) adj.add(new ArrayList<>()); for (int[] edge : edges) { @@ -566,7 +566,7 @@ func findRedundantConnection(edges [][]int) []int { cycleStart = node return true } - + visit[node] = true for _, nei := range adj[node] { if nei == par { @@ -650,7 +650,7 @@ class Solution { func findRedundantConnection(_ edges: [[Int]]) -> [Int] { let n = edges.count var adj = Array(repeating: [Int](), count: n + 1) - + for edge in edges { let u = edge[0] let v = edge[1] @@ -667,7 +667,7 @@ class Solution { cycleStart = node return true } - + visit[node] = true for nei in adj[node] { if nei == par { @@ -705,8 +705,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ > Where $V$ is the number of vertices and $E$ is the number of edges in the graph. @@ -727,7 +727,7 @@ class Solution: adj[v].append(u) indegree[u] += 1 indegree[v] += 1 - + q = deque() for i in range(1, n + 1): if indegree[i] == 1: @@ -778,7 +778,7 @@ public class Solution { for (int i = edges.length - 1; i >= 0; i--) { int u = edges[i][0], v = edges[i][1]; - if (indegree[u] == 2 && indegree[v] > 0) + if (indegree[u] == 2 && indegree[v] > 0) return new int[]{u, v}; } return new int[0]; @@ -817,7 +817,7 @@ public: for (int i = edges.size() - 1; i >= 0; i--) { int u = edges[i][0], v = edges[i][1]; - if (indegree[u] == 2 && indegree[v]) + if (indegree[u] == 2 && indegree[v]) return {u, v}; } return {}; @@ -858,8 +858,7 @@ class Solution { for (let i = edges.length - 1; i >= 0; i--) { const [u, v] = edges[i]; - if (indegree[u] === 2 && indegree[v]) - return [u, v]; + if (indegree[u] === 2 && indegree[v]) return [u, v]; } return []; } @@ -897,7 +896,7 @@ public class Solution { for (int i = edges.Length - 1; i >= 0; i--) { int u = edges[i][0], v = edges[i][1]; - if (indegree[u] == 2 && indegree[v] > 0) + if (indegree[u] == 2 && indegree[v] > 0) return new int[] {u, v}; } return new int[0]; @@ -1040,8 +1039,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ > Where $V$ is the number of vertices and $E$ is the number of edges in the graph. @@ -1227,7 +1226,7 @@ class Solution { ```csharp public class Solution { - + public int[] FindRedundantConnection(int[][] edges) { int[] par = new int[edges.Length + 1]; int[] rank = new int[edges.Length + 1]; @@ -1275,7 +1274,7 @@ func findRedundantConnection(edges [][]int) []int { n := len(edges) par := make([]int, n+1) rank := make([]int, n+1) - + for i := 0; i <= n; i++ { par[i] = i rank[i] = 1 @@ -1401,7 +1400,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + (E * α(V)))$ -* Space complexity: $O(V)$ +- Time complexity: $O(V + (E * α(V)))$ +- Space complexity: $O(V)$ -> Where $V$ is the number of vertices and $E$ is the number of edges in the graph. $α()$ is used for amortized complexity. \ No newline at end of file +> Where $V$ is the number of vertices and $E$ is the number of edges in the graph. $α()$ is used for amortized complexity. diff --git a/articles/regular-expression-matching.md b/articles/regular-expression-matching.md index fd4bfda86..30ec007ac 100644 --- a/articles/regular-expression-matching.md +++ b/articles/regular-expression-matching.md @@ -10,15 +10,15 @@ class Solution: def dfs(i, j): if j == n: return i == m - + match = i < m and (s[i] == p[j] or p[j] == ".") if (j + 1) < n and p[j + 1] == "*": - return (dfs(i, j + 2) or # don't use * + return (dfs(i, j + 2) or # don't use * (match and dfs(i + 1, j))) # use * if match: return dfs(i + 1, j + 1) return False - + return dfs(0, 0) ``` @@ -32,17 +32,17 @@ public class Solution { private boolean dfs(int i, int j, String s, String p, int m, int n) { if (j == n) return i == m; - boolean match = i < m && (s.charAt(i) == p.charAt(j) || + boolean match = i < m && (s.charAt(i) == p.charAt(j) || p.charAt(j) == '.'); if (j + 1 < n && p.charAt(j + 1) == '*') { - return dfs(i, j + 2, s, p, m, n) || + return dfs(i, j + 2, s, p, m, n) || (match && dfs(i + 1, j, s, p, m, n)); } if (match) { return dfs(i + 1, j + 1, s, p, m, n); } - + return false; } } @@ -61,7 +61,7 @@ public: bool match = (i < m && (s[i] == p[j] || p[j] == '.')); if (j + 1 < n && p[j + 1] == '*') { - return dfs(i, j + 2, s, p, m, n) || + return dfs(i, j + 2, s, p, m, n) || (match && dfs(i + 1, j, s, p, m, n)); } @@ -82,7 +82,8 @@ class Solution { * @return {boolean} */ isMatch(s, p) { - let m = s.length, n = p.length; + let m = s.length, + n = p.length; const dfs = (i, j) => { if (j === n) { @@ -91,8 +92,7 @@ class Solution { let match = i < m && (s[i] === p[j] || p[j] === '.'); if (j + 1 < n && p[j + 1] === '*') { - return dfs(i, j + 2) || - (match && dfs(i + 1, j)); + return dfs(i, j + 2) || (match && dfs(i + 1, j)); } if (match) { @@ -100,7 +100,7 @@ class Solution { } return false; - } + }; return dfs(0, 0); } @@ -121,7 +121,7 @@ public class Solution { bool match = i < m && (s[i] == p[j] || p[j] == '.'); if (j + 1 < n && p[j + 1] == '*') { - return Dfs(i, j + 2, s, p, m, n) || + return Dfs(i, j + 2, s, p, m, n) || (match && Dfs(i + 1, j, s, p, m, n)); } @@ -145,11 +145,11 @@ func isMatch(s string, p string) bool { } match := i < m && (s[i] == p[j] || p[j] == '.') - + if (j+1) < n && p[j+1] == '*' { return dfs(i, j+2) || (match && dfs(i+1, j)) } - + if match { return dfs(i+1, j+1) } @@ -169,13 +169,13 @@ class Solution { fun dfs(i: Int, j: Int): Boolean { if (j == n) return i == m - + val match = i < m && (s[i] == p[j] || p[j] == '.') - + if ((j + 1) < n && p[j + 1] == '*') { return dfs(i, j + 2) || (match && dfs(i + 1, j)) } - + return match && dfs(i + 1, j + 1) } @@ -217,8 +217,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ {m + n})$ -* Space complexity: $O(m + n)$ +- Time complexity: $O(2 ^ {m + n})$ +- Space complexity: $O(m + n)$ > Where $m$ is the length of the string $s$ and $n$ is the length of the string $p$. @@ -242,17 +242,17 @@ class Solution: match = i < m and (s[i] == p[j] or p[j] == ".") if (j + 1) < n and p[j + 1] == "*": - cache[(i, j)] = (dfs(i, j + 2) or + cache[(i, j)] = (dfs(i, j + 2) or (match and dfs(i + 1, j))) return cache[(i, j)] if match: cache[(i, j)] = dfs(i + 1, j + 1) return cache[(i, j)] - + cache[(i, j)] = False return False - + return dfs(0, 0) ``` @@ -274,10 +274,10 @@ public class Solution { return dp[i][j]; } - boolean match = i < m && (s.charAt(i) == p.charAt(j) || + boolean match = i < m && (s.charAt(i) == p.charAt(j) || p.charAt(j) == '.'); if (j + 1 < n && p.charAt(j + 1) == '*') { - dp[i][j] = dfs(i, j + 2, s, p, m, n) || + dp[i][j] = dfs(i, j + 2, s, p, m, n) || (match && dfs(i + 1, j, s, p, m, n)); } else { dp[i][j] = match && dfs(i + 1, j + 1, s, p, m, n); @@ -309,7 +309,7 @@ private: } bool match = i < m && (s[i] == p[j] || p[j] == '.'); if (j + 1 < n && p[j + 1] == '*') { - dp[i][j] = dfs(i, j + 2, s, p, m, n) || + dp[i][j] = dfs(i, j + 2, s, p, m, n) || (match && dfs(i + 1, j, s, p, m, n)); } else { dp[i][j] = match && dfs(i + 1, j + 1, s, p, m, n); @@ -327,10 +327,12 @@ class Solution { * @return {boolean} */ isMatch(s, p) { - const m = s.length, n = p.length; - let dp = Array(m + 1).fill().map(() => - Array(n + 1).fill(null)); - + const m = s.length, + n = p.length; + let dp = Array(m + 1) + .fill() + .map(() => Array(n + 1).fill(null)); + const dfs = (i, j) => { if (j === n) { return i === m; @@ -340,13 +342,12 @@ class Solution { } const match = i < m && (s[i] === p[j] || p[j] === '.'); if (j + 1 < n && p[j + 1] === '*') { - dp[i][j] = dfs(i, j + 2) || - (match && dfs(i + 1, j)); + dp[i][j] = dfs(i, j + 2) || (match && dfs(i + 1, j)); } else { dp[i][j] = match && dfs(i + 1, j + 1); } return dp[i][j]; - } + }; return dfs(0, 0); } @@ -372,7 +373,7 @@ public class Solution { } bool match = i < m && (s[i] == p[j] || p[j] == '.'); if (j + 1 < n && p[j + 1] == '*') { - dp[i, j] = Dfs(i, j + 2, s, p, m, n) || + dp[i, j] = Dfs(i, j + 2, s, p, m, n) || (match && Dfs(i + 1, j, s, p, m, n)); } else { dp[i, j] = match && Dfs(i + 1, j + 1, s, p, m, n); @@ -389,7 +390,7 @@ func isMatch(s string, p string) bool { for i := range dp { dp[i] = make([]int, n+1) for j := range dp[i] { - dp[i][j] = -1 + dp[i][j] = -1 } } @@ -403,17 +404,17 @@ func isMatch(s string, p string) bool { } match := i < m && (s[i] == p[j] || p[j] == '.') - + if (j+1) < n && p[j+1] == '*' { dp[i][j] = boolToInt(dfs(i, j+2) || (match && dfs(i+1, j))) return dp[i][j] == 1 } - + if match { dp[i][j] = boolToInt(dfs(i+1, j+1)) return dp[i][j] == 1 } - + dp[i][j] = 0 return false } @@ -434,24 +435,24 @@ class Solution { fun isMatch(s: String, p: String): Boolean { val m = s.length val n = p.length - val dp = Array(m + 1) { IntArray(n + 1) { -1 } } + val dp = Array(m + 1) { IntArray(n + 1) { -1 } } fun dfs(i: Int, j: Int): Boolean { if (j == n) return i == m if (dp[i][j] != -1) return dp[i][j] == 1 val match = i < m && (s[i] == p[j] || p[j] == '.') - + if ((j + 1) < n && p[j + 1] == '*') { dp[i][j] = if (dfs(i, j + 2) || (match && dfs(i + 1, j))) 1 else 0 return dp[i][j] == 1 } - + if (match) { dp[i][j] = if (dfs(i + 1, j + 1)) 1 else 0 return dp[i][j] == 1 } - + dp[i][j] = 0 return false } @@ -501,8 +502,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the length of the string $s$ and $n$ is the length of the string $p$. @@ -603,8 +604,7 @@ class Solution { for (let i = s.length; i >= 0; i--) { for (let j = p.length - 1; j >= 0; j--) { - const match = i < s.length && - (s[i] === p[j] || p[j] === '.'); + const match = i < s.length && (s[i] === p[j] || p[j] === '.'); if (j + 1 < p.length && p[j + 1] === '*') { dp[i][j] = dp[i][j + 2]; @@ -630,7 +630,7 @@ public class Solution { for (int i = s.Length; i >= 0; i--) { for (int j = p.Length - 1; j >= 0; j--) { - bool match = i < s.Length && + bool match = i < s.Length && (s[i] == p[j] || p[j] == '.'); if ((j + 1) < p.Length && p[j + 1] == '*') { @@ -661,7 +661,7 @@ func isMatch(s, p string) bool { for i := m; i >= 0; i-- { for j := n - 1; j >= 0; j-- { match := i < m && (s[i] == p[j] || p[j] == '.') - + if j+1 < n && p[j+1] == '*' { dp[i][j] = dp[i][j+2] if match { @@ -687,7 +687,7 @@ class Solution { for (i in m downTo 0) { for (j in n - 1 downTo 0) { val match = i < m && (s[i] == p[j] || p[j] == '.') - + if (j + 1 < n && p[j + 1] == '*') { dp[i][j] = dp[i][j + 2] || (match && dp[i + 1][j]) } else if (match) { @@ -732,8 +732,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the length of the string $s$ and $n$ is the length of the string $p$. @@ -748,23 +748,23 @@ class Solution: def isMatch(self, s: str, p: str) -> bool: dp = [False] * (len(p) + 1) dp[len(p)] = True - + for i in range(len(s), -1, -1): nextDp = [False] * (len(p) + 1) nextDp[len(p)] = (i == len(s)) for j in range(len(p) - 1, -1, -1): match = i < len(s) and (s[i] == p[j] or p[j] == ".") - + if (j + 1) < len(p) and p[j + 1] == "*": nextDp[j] = nextDp[j + 2] if match: nextDp[j] |= dp[j] elif match: nextDp[j] = dp[j + 1] - + dp = nextDp - + return dp[0] ``` @@ -779,8 +779,8 @@ public class Solution { nextDp[p.length()] = (i == s.length()); for (int j = p.length() - 1; j >= 0; j--) { - boolean match = i < s.length() && - (s.charAt(i) == p.charAt(j) || + boolean match = i < s.length() && + (s.charAt(i) == p.charAt(j) || p.charAt(j) == '.'); if (j + 1 < p.length() && p.charAt(j + 1) == '*') { @@ -813,7 +813,7 @@ public: nextDp[p.length()] = (i == s.length()); for (int j = p.length() - 1; j >= 0; j--) { - bool match = i < s.length() && + bool match = i < s.length() && (s[i] == p[j] || p[j] == '.'); if (j + 1 < p.length() && p[j + 1] == '*') { @@ -847,13 +847,12 @@ class Solution { for (let i = s.length; i >= 0; i--) { let nextDp = new Array(p.length + 1).fill(false); - nextDp[p.length] = (i === s.length); + nextDp[p.length] = i === s.length; for (let j = p.length - 1; j >= 0; j--) { - const match = i < s.length && - (s[i] === p[j] || p[j] === "."); + const match = i < s.length && (s[i] === p[j] || p[j] === '.'); - if (j + 1 < p.length && p[j + 1] === "*") { + if (j + 1 < p.length && p[j + 1] === '*') { nextDp[j] = nextDp[j + 2]; if (match) { nextDp[j] = nextDp[j] || dp[j]; @@ -914,7 +913,7 @@ func isMatch(s, p string) bool { for j := n - 1; j >= 0; j-- { match := i < m && (s[i] == p[j] || p[j] == '.') - + if j+1 < n && p[j+1] == '*' { nextDp[j] = nextDp[j+2] || (match && dp[j]) } else if match { @@ -961,7 +960,7 @@ class Solution { let sArr = Array(s), pArr = Array(p) var dp = Array(repeating: false, count: pArr.count + 1) dp[pArr.count] = true - + for i in stride(from: sArr.count, through: 0, by: -1) { var nextDp = Array(repeating: false, count: pArr.count + 1) nextDp[pArr.count] = (i == sArr.count) @@ -981,7 +980,7 @@ class Solution { dp = nextDp } - + return dp[0] } } @@ -991,8 +990,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(n)$ > Where $m$ is the length of the string $s$ and $n$ is the length of the string $p$. @@ -1007,11 +1006,11 @@ class Solution: def isMatch(self, s: str, p: str) -> bool: dp = [False] * (len(p) + 1) dp[len(p)] = True - + for i in range(len(s), -1, -1): dp1 = dp[len(p)] dp[len(p)] = (i == len(s)) - + for j in range(len(p) - 1, -1, -1): match = i < len(s) and (s[i] == p[j] or p[j] == ".") res = False @@ -1037,8 +1036,8 @@ public class Solution { dp[p.length()] = (i == s.length()); for (int j = p.length() - 1; j >= 0; j--) { - boolean match = i < s.length() && - (s.charAt(i) == p.charAt(j) || + boolean match = i < s.length() && + (s.charAt(i) == p.charAt(j) || p.charAt(j) == '.'); boolean res = false; if (j + 1 < p.length() && p.charAt(j + 1) == '*') { @@ -1071,7 +1070,7 @@ public: dp[p.length()] = (i == s.length()); for (int j = p.length() - 1; j >= 0; j--) { - bool match = i < s.length() && + bool match = i < s.length() && (s[i] == p[j] || p[j] == '.'); bool res = false; if (j + 1 < p.length() && p[j + 1] == '*') { @@ -1105,13 +1104,12 @@ class Solution { for (let i = s.length; i >= 0; i--) { let dp1 = dp[p.length]; - dp[p.length] = (i == s.length); + dp[p.length] = i == s.length; for (let j = p.length - 1; j >= 0; j--) { - const match = i < s.length && - (s[i] === p[j] || p[j] === "."); + const match = i < s.length && (s[i] === p[j] || p[j] === '.'); let res = false; - if (j + 1 < p.length && p[j + 1] === "*") { + if (j + 1 < p.length && p[j + 1] === '*') { res = dp[j + 2]; if (match) { res = res || dp[j]; @@ -1258,7 +1256,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(n)$ -> Where $m$ is the length of the string $s$ and $n$ is the length of the string $p$. \ No newline at end of file +> Where $m$ is the length of the string $s$ and $n$ is the length of the string $p$. diff --git a/articles/relative-sort-array.md b/articles/relative-sort-array.md index 8681e3fba..f7596a24d 100644 --- a/articles/relative-sort-array.md +++ b/articles/relative-sort-array.md @@ -102,10 +102,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n + n \log n)$ -* Space complexity: - * $O(1)$ or $O(n)$ depending on the sorting algorithm. - * $O(n)$ space for the output list. +- Time complexity: $O(m * n + n \log n)$ +- Space complexity: + - $O(1)$ or $O(n)$ depending on the sorting algorithm. + - $O(n)$ space for the output list. > Where $n$ is the size of the array $arr1$, and $m$ is the size of the array $arr2$. @@ -224,8 +224,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m + n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n + m + n \log n)$ +- Space complexity: $O(n)$ > Where $n$ is the size of the array $arr1$, and $m$ is the size of the array $arr2$. @@ -335,7 +335,9 @@ class Solution { delete count[num]; } - const remaining = Object.keys(count).map(Number).sort((a, b) => a - b); + const remaining = Object.keys(count) + .map(Number) + .sort((a, b) => a - b); for (let num of remaining) { for (let i = 0; i < count[num]; i++) { res.push(num); @@ -351,8 +353,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m + n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n + m + n \log n)$ +- Space complexity: $O(n)$ > Where $n$ is the size of the array $arr1$, and $m$ is the size of the array $arr2$. @@ -459,10 +461,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m + M)$ -* Space complexity: - * $O(M)$ extra space. - * $O(n)$ space for the output list. +- Time complexity: $O(n + m + M)$ +- Space complexity: + - $O(M)$ extra space. + - $O(n)$ space for the output list. > Where $n$ is the size of the array $arr1$, $m$ is the size of the array $arr2$, and $M$ is the maximum value in the array $arr1$. @@ -543,9 +545,9 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m + n \log n)$ -* Space complexity: - * $O(m)$ extra space. - * $O(n)$ space for the output list. +- Time complexity: $O(n + m + n \log n)$ +- Space complexity: + - $O(m)$ extra space. + - $O(n)$ space for the output list. -> Where $n$ is the size of the array $arr1$, and $m$ is the size of the array $arr2$. \ No newline at end of file +> Where $n$ is the size of the array $arr1$, and $m$ is the size of the array $arr2$. diff --git a/articles/remove-all-adjacent-duplicates-in-string-ii.md b/articles/remove-all-adjacent-duplicates-in-string-ii.md index 7c4ae8a82..3e6d60c3f 100644 --- a/articles/remove-all-adjacent-duplicates-in-string-ii.md +++ b/articles/remove-all-adjacent-duplicates-in-string-ii.md @@ -128,8 +128,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\frac {n ^ 2}{k})$ -* Space complexity: $O(n)$ +- Time complexity: $O(\frac {n ^ 2}{k})$ +- Space complexity: $O(n)$ --- @@ -144,7 +144,7 @@ class Solution: n = len(s) i = 0 s = list(s) - + while i < n: if i == 0 or s[i] != s[i - 1]: stack.append(1) @@ -155,9 +155,9 @@ class Solution: del s[i - k + 1:i + 1] i -= k n -= k - + i += 1 - + return ''.join(s) ``` @@ -167,7 +167,7 @@ public class Solution { StringBuilder sb = new StringBuilder(s); Stack stack = new Stack<>(); int i = 0; - + while (i < sb.length()) { if (i == 0 || sb.charAt(i) != sb.charAt(i - 1)) { stack.push(1); @@ -181,7 +181,7 @@ public class Solution { } i++; } - + return sb.toString(); } } @@ -249,8 +249,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -349,7 +349,7 @@ class Solution { } } - let res = ""; + let res = ''; for (const [char, count] of stack) { res += char.repeat(count); } @@ -363,8 +363,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -463,5 +463,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/remove-colored-pieces-if-both-neighbors-are-the-same-color.md b/articles/remove-colored-pieces-if-both-neighbors-are-the-same-color.md index 156cbb636..a86e56cac 100644 --- a/articles/remove-colored-pieces-if-both-neighbors-are-the-same-color.md +++ b/articles/remove-colored-pieces-if-both-neighbors-are-the-same-color.md @@ -83,7 +83,7 @@ class Solution { * @return {boolean} */ winnerOfGame(colors) { - let s = colors.split(""); + let s = colors.split(''); const removeChar = (c) => { for (let i = 1; i < s.length - 1; i++) { @@ -109,8 +109,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -195,7 +195,9 @@ class Solution { * @return {boolean} */ winnerOfGame(colors) { - let alice = 0, bob = 0, l = 0; + let alice = 0, + bob = 0, + l = 0; for (let r = 0; r < colors.length; r++) { if (colors[l] !== colors[r]) { @@ -221,8 +223,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -251,7 +253,7 @@ public class Solution { int alice = 0, bob = 0; for (int i = 1; i < colors.length() - 1; i++) { - if (colors.charAt(i - 1) == colors.charAt(i) && + if (colors.charAt(i - 1) == colors.charAt(i) && colors.charAt(i) == colors.charAt(i + 1)) { if (colors.charAt(i) == 'A') { alice++; @@ -296,7 +298,8 @@ class Solution { * @return {boolean} */ winnerOfGame(colors) { - let alice = 0, bob = 0; + let alice = 0, + bob = 0; for (let i = 1; i < colors.length - 1; i++) { if (colors[i - 1] === colors[i] && colors[i] === colors[i + 1]) { @@ -318,5 +321,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/remove-covered-intervals.md b/articles/remove-covered-intervals.md index f71a0cfcc..f06632921 100644 --- a/articles/remove-covered-intervals.md +++ b/articles/remove-covered-intervals.md @@ -10,7 +10,7 @@ class Solution: for i in range(n): for j in range(n): - if (i != j and intervals[j][0] <= intervals[i][0] and + if (i != j and intervals[j][0] <= intervals[i][0] and intervals[j][1] >= intervals[i][1] ): res -= 1 @@ -27,7 +27,7 @@ public class Solution { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { - if (i != j && intervals[j][0] <= intervals[i][0] && + if (i != j && intervals[j][0] <= intervals[i][0] && intervals[j][1] >= intervals[i][1]) { res--; break; @@ -48,7 +48,7 @@ public: for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { - if (i != j && intervals[j][0] <= intervals[i][0] && + if (i != j && intervals[j][0] <= intervals[i][0] && intervals[j][1] >= intervals[i][1]) { res--; break; @@ -72,8 +72,11 @@ class Solution { for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { - if (i !== j && intervals[j][0] <= intervals[i][0] && - intervals[j][1] >= intervals[i][1]) { + if ( + i !== j && + intervals[j][0] <= intervals[i][0] && + intervals[j][1] >= intervals[i][1] + ) { res--; break; } @@ -88,8 +91,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ extra space. --- @@ -115,7 +118,7 @@ class Solution: ```java public class Solution { public int removeCoveredIntervals(int[][] intervals) { - Arrays.sort(intervals, (a, b) -> + Arrays.sort(intervals, (a, b) -> a[0] == b[0] ? Integer.compare(b[1], a[1]) : Integer.compare(a[0], b[0]) ); int res = 1, prevL = intervals[0][0], prevR = intervals[0][1]; @@ -163,8 +166,9 @@ class Solution { * @return {number} */ removeCoveredIntervals(intervals) { - intervals.sort((a, b) => a[0] === b[0] ? b[1] - a[1] : a[0] - b[0]); - let res = 1, [prevL, prevR] = intervals[0]; + intervals.sort((a, b) => (a[0] === b[0] ? b[1] - a[1] : a[0] - b[0])); + let res = 1, + [prevL, prevR] = intervals[0]; for (const [l, r] of intervals) { if (prevL <= l && prevR >= r) { continue; @@ -182,8 +186,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n\log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n\log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -253,7 +257,9 @@ class Solution { */ removeCoveredIntervals(intervals) { intervals.sort((a, b) => a[0] - b[0]); - let res = 1, start = intervals[0][0], end = intervals[0][1]; + let res = 1, + start = intervals[0][0], + end = intervals[0][1]; for (const [l, r] of intervals) { if (start < l && end < r) { @@ -271,5 +277,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. diff --git a/articles/remove-duplicates-from-sorted-array-ii.md b/articles/remove-duplicates-from-sorted-array-ii.md index 8fff8a2d4..678e6c93d 100644 --- a/articles/remove-duplicates-from-sorted-array-ii.md +++ b/articles/remove-duplicates-from-sorted-array-ii.md @@ -97,7 +97,8 @@ class Solution { let i = 0; while (i < n - 1) { if (nums[i] === nums[i + 1]) { - let j = i + 2, cnt = 0; + let j = i + 2, + cnt = 0; while (j < n && nums[i] === nums[j]) { j++; cnt++; @@ -121,8 +122,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ extra space. --- @@ -136,7 +137,7 @@ class Solution: n = len(nums) if n <= 2: return n - + count = Counter(nums) i = 0 for num in count: @@ -234,8 +235,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -258,7 +259,7 @@ class Solution: nums[l] = nums[r] l += 1 r += 1 - + return l ``` @@ -280,7 +281,7 @@ public class Solution { } r++; } - + return l; } } @@ -305,7 +306,7 @@ public: } r++; } - + return l; } }; @@ -318,7 +319,8 @@ class Solution { * @return {number} */ removeDuplicates(nums) { - let l = 0, r = 0; + let l = 0, + r = 0; while (r < nums.length) { let count = 1; @@ -333,7 +335,7 @@ class Solution { } r++; } - + return l; } } @@ -343,8 +345,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -417,5 +419,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/remove-duplicates-from-sorted-array.md b/articles/remove-duplicates-from-sorted-array.md index 7629a2ff3..4f5f95a85 100644 --- a/articles/remove-duplicates-from-sorted-array.md +++ b/articles/remove-duplicates-from-sorted-array.md @@ -70,8 +70,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -132,7 +132,9 @@ class Solution { * @return {number} */ removeDuplicates(nums) { - let n = nums.length, l = 0, r = 0; + let n = nums.length, + l = 0, + r = 0; while (r < n) { nums[l] = nums[r]; while (r < n && nums[r] === nums[l]) { @@ -168,8 +170,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -255,5 +257,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/remove-duplicates-from-sorted-list.md b/articles/remove-duplicates-from-sorted-list.md index 9184c3e9c..3fabf8439 100644 --- a/articles/remove-duplicates-from-sorted-list.md +++ b/articles/remove-duplicates-from-sorted-list.md @@ -12,7 +12,7 @@ class Solution: def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]: if not head or not head.next: return head - + head.next = self.deleteDuplicates(head.next) return head if head.val != head.next.val else head.next ``` @@ -31,7 +31,7 @@ class Solution: public class Solution { public ListNode deleteDuplicates(ListNode head) { if (head == null || head.next == null) return head; - + head.next = deleteDuplicates(head.next); return head.val != head.next.val ? head : head.next; } @@ -53,7 +53,7 @@ class Solution { public: ListNode* deleteDuplicates(ListNode* head) { if (!head || !head->next) return head; - + head->next = deleteDuplicates(head->next); return head->val != head->next->val ? head : head->next; } @@ -88,8 +88,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -196,8 +196,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -308,5 +308,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/remove-element.md b/articles/remove-element.md index 14d2c78b4..b53bb57ee 100644 --- a/articles/remove-element.md +++ b/articles/remove-element.md @@ -95,8 +95,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -181,8 +181,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -245,7 +245,8 @@ class Solution { * @return {number} */ removeElement(nums, val) { - let i = 0, n = nums.length; + let i = 0, + n = nums.length; while (i < n) { if (nums[i] == val) { nums[i] = nums[--n]; @@ -278,5 +279,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/remove-k-digits.md b/articles/remove-k-digits.md index 19ccf59dc..93374679b 100644 --- a/articles/remove-k-digits.md +++ b/articles/remove-k-digits.md @@ -93,7 +93,7 @@ class Solution { } num = num.slice(i); - return num.length === 0 ? "0" : num.join(''); + return num.length === 0 ? '0' : num.join(''); } } ``` @@ -102,8 +102,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * k)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the language. +- Time complexity: $O(n * k)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the language. --- @@ -218,7 +218,7 @@ class Solution { } let res = stack.slice(i).join(''); - return res === '' ? "0" : res; + return res === '' ? '0' : res; } } ``` @@ -227,8 +227,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -331,7 +331,7 @@ class Solution { i++; } let res = numArray.slice(i, l).join(''); - return res.length === 0 ? "0" : res; + return res.length === 0 ? '0' : res; } } ``` @@ -340,5 +340,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the language. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the language. diff --git a/articles/remove-linked-list-elements.md b/articles/remove-linked-list-elements.md index 30e4a5e94..629ae21de 100644 --- a/articles/remove-linked-list-elements.md +++ b/articles/remove-linked-list-elements.md @@ -17,7 +17,7 @@ class Solution: if cur.val != val: arr.append(cur.val) cur = cur.next - + if not arr: return None @@ -27,7 +27,7 @@ class Solution: node = ListNode(arr[i]) cur.next = node cur = cur.next - + return res ``` @@ -160,8 +160,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -252,8 +252,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -308,7 +308,7 @@ public class Solution { } curr = nxt; } - + return dummy.next; } } @@ -330,7 +330,7 @@ public: ListNode* removeElements(ListNode* head, int val) { ListNode dummy(0, head); ListNode *prev = &dummy, *curr = head; - + while (curr) { ListNode* nxt = curr->next; if (curr->val == val) { @@ -340,7 +340,7 @@ public: } curr = nxt; } - + return dummy.next; } }; @@ -364,7 +364,8 @@ class Solution { */ removeElements(head, val) { let dummy = new ListNode(0, head); - let prev = dummy, curr = head; + let prev = dummy, + curr = head; while (curr) { let nxt = curr.next; @@ -385,8 +386,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -437,7 +438,7 @@ public class Solution { curr = curr.next; } } - + return dummy.next; } } @@ -459,7 +460,7 @@ public: ListNode* removeElements(ListNode* head, int val) { ListNode dummy(-1, head); ListNode *curr = &dummy; - + while (curr->next) { if (curr->next->val == val) { curr->next = curr->next->next; @@ -467,7 +468,7 @@ public: curr = curr->next; } } - + return dummy.next; } }; @@ -510,5 +511,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/remove-max-number-of-edges-to-keep-graph-fully-traversable.md b/articles/remove-max-number-of-edges-to-keep-graph-fully-traversable.md index 04c3da1ac..11f1ff3bd 100644 --- a/articles/remove-max-number-of-edges-to-keep-graph-fully-traversable.md +++ b/articles/remove-max-number-of-edges-to-keep-graph-fully-traversable.md @@ -193,7 +193,9 @@ class DSU { */ constructor(n) { this.n = n; - this.parent = Array(n + 1).fill(0).map((_, i) => i); + this.parent = Array(n + 1) + .fill(0) + .map((_, i) => i); this.size = Array(n + 1).fill(1); } @@ -214,7 +216,8 @@ class DSU { * @return {number} */ union(u, v) { - let pu = this.find(u), pv = this.find(v); + let pu = this.find(u), + pv = this.find(v); if (pu === pv) { return 0; } @@ -242,12 +245,13 @@ class Solution { * @return {number} */ maxNumEdgesToRemove(n, edges) { - let alice = new DSU(n), bob = new DSU(n); + let alice = new DSU(n), + bob = new DSU(n); let cnt = 0; for (let [type, src, dst] of edges) { if (type === 3) { - cnt += (alice.union(src, dst) | bob.union(src, dst)); + cnt += alice.union(src, dst) | bob.union(src, dst); } } @@ -259,7 +263,9 @@ class Solution { } } - return alice.isConnected() && bob.isConnected() ? edges.length - cnt : -1; + return alice.isConnected() && bob.isConnected() + ? edges.length - cnt + : -1; } } ``` @@ -268,7 +274,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(E * α(V))$ -* Space complexity: $O(V)$ +- Time complexity: $O(E * α(V))$ +- Space complexity: $O(V)$ -> Where $V$ is the number of verticies and $E$ is the number of edges. \ No newline at end of file +> Where $V$ is the number of verticies and $E$ is the number of edges. diff --git a/articles/remove-node-from-end-of-linked-list.md b/articles/remove-node-from-end-of-linked-list.md index ee936f416..4d919436e 100644 --- a/articles/remove-node-from-end-of-linked-list.md +++ b/articles/remove-node-from-end-of-linked-list.md @@ -16,11 +16,11 @@ class Solution: while cur: nodes.append(cur) cur = cur.next - + removeIndex = len(nodes) - n if removeIndex == 0: return head.next - + nodes[removeIndex - 1].next = nodes[removeIndex].next return head ``` @@ -199,7 +199,7 @@ class Solution { fun removeNthFromEnd(head: ListNode?, n: Int): ListNode? { val nodes = mutableListOf() var cur = head - + while (cur != null) { nodes.add(cur) cur = cur.next @@ -252,8 +252,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(N)$ -* Space complexity: $O(N)$ +- Time complexity: $O(N)$ +- Space complexity: $O(N)$ --- @@ -275,11 +275,11 @@ class Solution: while cur: N += 1 cur = cur.next - + removeIndex = N - n if removeIndex == 0: return head.next - + cur = head for i in range(N - 1): if (i + 1) == removeIndex: @@ -564,8 +564,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(N)$ -* Space complexity: $O(1)$ +- Time complexity: $O(N)$ +- Space complexity: $O(1)$ --- @@ -650,7 +650,7 @@ public: n--; if (n == 0) { return head -> next; - } + } return head; } @@ -748,16 +748,16 @@ func rec(head *ListNode, n *int) *ListNode { } head.Next = rec(head.Next, n) - (*n)-- + (*n)-- if *n == 0 { - return head.Next + return head.Next } - return head + return head } func removeNthFromEnd(head *ListNode, n int) *ListNode { - return rec(head, &n) + return rec(head, &n) } ``` @@ -781,9 +781,9 @@ class Solution { n[0]-- return if (n[0] == 0) { - head.next + head.next } else { - head + head } } @@ -829,8 +829,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(N)$ -* Space complexity: $O(N)$ for recursion stack. +- Time complexity: $O(N)$ +- Space complexity: $O(N)$ for recursion stack. --- @@ -1104,5 +1104,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(N)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(N)$ +- Space complexity: $O(1)$ diff --git a/articles/remove-nodes-from-linked-list.md b/articles/remove-nodes-from-linked-list.md index b629d4760..b03300e26 100644 --- a/articles/remove-nodes-from-linked-list.md +++ b/articles/remove-nodes-from-linked-list.md @@ -14,14 +14,14 @@ class Solution: while cur: arr.append(cur) cur = cur.next - + rightMaxi = ListNode(0, None) for i in range(len(arr) - 1, 0, -1): if rightMaxi.val > arr[i].val: arr[i - 1].next = rightMaxi else: rightMaxi = arr[i] - + return arr[0].next ``` @@ -114,7 +114,8 @@ class Solution { * @return {ListNode} */ removeNodes(head) { - let cur = head, arr = [{ val: 0, next: head }]; + let cur = head, + arr = [{ val: 0, next: head }]; while (cur) { arr.push(cur); cur = cur.next; @@ -138,8 +139,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -293,8 +294,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -312,7 +313,7 @@ class Solution: def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]: if not head: return None - + head.next = self.removeNodes(head.next) if head.next and head.val < head.next.val: return head.next @@ -399,8 +400,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -434,7 +435,7 @@ class Solution: else: cur_max = cur.next.val cur = cur.next - + return reverse(head) ``` @@ -503,7 +504,7 @@ public: } return prev; } - + ListNode* removeNodes(ListNode* head) { head = reverse(head); ListNode* cur = head; @@ -539,7 +540,8 @@ class Solution { */ removeNodes(head) { const reverse = (head) => { - let prev = null, cur = head; + let prev = null, + cur = head; while (cur) { let tmp = cur.next; cur.next = prev; @@ -570,5 +572,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/removing-stars-from-a-string.md b/articles/removing-stars-from-a-string.md index 108454bae..54964a0bb 100644 --- a/articles/removing-stars-from-a-string.md +++ b/articles/removing-stars-from-a-string.md @@ -91,8 +91,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -177,8 +177,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -248,13 +248,13 @@ class Solution { removeStars(s) { const stack = []; for (const c of s) { - if (c === "*") { + if (c === '*') { if (stack.length > 0) stack.pop(); } else { stack.push(c); } } - return stack.join(""); + return stack.join(''); } } ``` @@ -263,8 +263,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -284,7 +284,7 @@ class Solution: else: s[l] = s[r] l += 1 - + return ''.join(s[:l]) ``` @@ -353,5 +353,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the language. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the language. diff --git a/articles/reorder-linked-list.md b/articles/reorder-linked-list.md index 75e0ef82c..7f87f29ec 100644 --- a/articles/reorder-linked-list.md +++ b/articles/reorder-linked-list.md @@ -13,13 +13,13 @@ class Solution: def reorderList(self, head: Optional[ListNode]) -> None: if not head: return - + nodes = [] cur = head while cur: nodes.append(cur) cur = cur.next - + i, j = 0, len(nodes) - 1 while i < j: nodes[i].next = nodes[j] @@ -28,7 +28,7 @@ class Solution: break nodes[j].next = nodes[i] j -= 1 - + nodes[i].next = None ``` @@ -89,14 +89,14 @@ class Solution { public: void reorderList(ListNode* head) { if (!head) return; - + vector nodes; ListNode* cur = head; while (cur) { nodes.push_back(cur); cur = cur->next; } - + int i = 0, j = nodes.size() - 1; while (i < j) { nodes[i]->next = nodes[j]; @@ -105,7 +105,7 @@ public: nodes[j]->next = nodes[i]; j--; } - + nodes[i]->next = nullptr; } }; @@ -137,7 +137,8 @@ class Solution { cur = cur.next; } - let i = 0, j = nodes.length - 1; + let i = 0, + j = nodes.length - 1; while (i < j) { nodes[i].next = nodes[j]; i++; @@ -276,15 +277,15 @@ class Solution { if head == nil { return } - + var nodes: [ListNode] = [] var cur = head - + while cur != nil { nodes.append(cur!) cur = cur?.next } - + var i = 0, j = nodes.count - 1 while i < j { nodes[i].next = nodes[j] @@ -295,7 +296,7 @@ class Solution { nodes[j].next = nodes[i] j -= 1 } - + nodes[i].next = nil } } @@ -305,8 +306,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -635,7 +636,7 @@ class Solution { return tmp } - + rec(head, head?.next) } } @@ -645,8 +646,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -1000,5 +1001,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/reorder-routes-to-make-all-paths-lead-to-the-city-zero.md b/articles/reorder-routes-to-make-all-paths-lead-to-the-city-zero.md index ae2727f84..2ca0dcc12 100644 --- a/articles/reorder-routes-to-make-all-paths-lead-to-the-city-zero.md +++ b/articles/reorder-routes-to-make-all-paths-lead-to-the-city-zero.md @@ -134,8 +134,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -158,7 +158,7 @@ class Solution: continue changes += dfs(abs(nei), node) + (nei > 0) return changes - + return dfs(0, -1) ``` @@ -197,7 +197,7 @@ public: adj[u].push_back(v); adj[v].push_back(-u); } - + return dfs(0, -1, adj); } @@ -245,8 +245,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -261,12 +261,12 @@ class Solution: for u, v in connections: adj[u].append((v, 1)) adj[v].append((u, 0)) - + visit = [False] * n queue = deque([0]) visit[0] = True changes = 0 - + while queue: node = queue.popleft() for neighbor, isForward in adj[node]: @@ -319,13 +319,13 @@ public: adj[conn[0]].push_back({conn[1], 1}); adj[conn[1]].push_back({conn[0], 0}); } - + vector visit(n, false); queue q; q.push(0); visit[0] = true; int changes = 0; - + while (!q.empty()) { int node = q.front(); q.pop(); @@ -381,5 +381,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/reorganize-string.md b/articles/reorganize-string.md index 868c78dca..bf57f927e 100644 --- a/articles/reorganize-string.md +++ b/articles/reorganize-string.md @@ -8,11 +8,11 @@ class Solution: freq = [0] * 26 for char in s: freq[ord(char) - ord('a')] += 1 - + max_freq = max(freq) if max_freq > (len(s) + 1) // 2: return "" - + res = [] while len(res) < len(s): maxIdx = freq.index(max(freq)) @@ -21,7 +21,7 @@ class Solution: freq[maxIdx] -= 1 if freq[maxIdx] == 0: continue - + tmp = freq[maxIdx] freq[maxIdx] = float("-inf") nextMaxIdx = freq.index(max(freq)) @@ -29,7 +29,7 @@ class Solution: res.append(char) freq[maxIdx] = tmp freq[nextMaxIdx] -= 1 - + return ''.join(res) ``` @@ -145,7 +145,7 @@ class Solution { const maxFreq = Math.max(...freq); if (maxFreq > Math.floor((s.length + 1) / 2)) { - return ""; + return ''; } const findMaxIndex = () => { @@ -172,7 +172,9 @@ class Solution { const tmp = freq[maxIdx]; freq[maxIdx] = -Infinity; const nextMaxIdx = findMaxIndex(); - const nextMaxChar = String.fromCharCode(nextMaxIdx + 'a'.charCodeAt(0)); + const nextMaxChar = String.fromCharCode( + nextMaxIdx + 'a'.charCodeAt(0), + ); res.push(nextMaxChar); freq[maxIdx] = tmp; freq[nextMaxIdx]--; @@ -223,10 +225,10 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(1)$ extra space, since we have at most $26$ different characters. - * $O(n)$ space for the output string. +- Time complexity: $O(n)$ +- Space complexity: + - $O(1)$ extra space, since we have at most $26$ different characters. + - $O(n)$ space for the output string. --- @@ -240,13 +242,13 @@ class Solution: count = Counter(s) maxHeap = [[-cnt, char] for char, cnt in count.items()] heapq.heapify(maxHeap) - + prev = None res = "" while maxHeap or prev: if prev and not maxHeap: return "" - + cnt, char = heapq.heappop(maxHeap) res += char cnt += 1 @@ -254,10 +256,10 @@ class Solution: if prev: heapq.heappush(maxHeap, prev) prev = None - + if cnt != 0: prev = [cnt, char] - + return res ``` @@ -359,7 +361,10 @@ class Solution { }); for (let i = 0; i < 26; i++) { if (freq[i] > 0) { - maxHeap.enqueue([freq[i], String.fromCharCode(i + 'a'.charCodeAt(0))]); + maxHeap.enqueue([ + freq[i], + String.fromCharCode(i + 'a'.charCodeAt(0)), + ]); } } @@ -431,10 +436,10 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(1)$ extra space, since we have at most $26$ different characters. - * $O(n)$ space for the output string. +- Time complexity: $O(n)$ +- Space complexity: + - $O(1)$ extra space, since we have at most $26$ different characters. + - $O(n)$ space for the output string. --- @@ -453,7 +458,7 @@ class Solution: max_freq = freq[max_idx] if max_freq > (len(s) + 1) // 2: return "" - + res = [''] * len(s) idx = 0 max_char = chr(max_idx + ord('a')) @@ -462,7 +467,7 @@ class Solution: res[idx] = max_char idx += 2 freq[max_idx] -= 1 - + for i in range(26): while freq[i] > 0: if idx >= len(s): @@ -470,7 +475,7 @@ class Solution: res[idx] = chr(i + ord('a')) idx += 2 freq[i] -= 1 - + return ''.join(res) ``` @@ -657,7 +662,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(1)$ extra space, since we have at most $26$ different characters. - * $O(n)$ space for the output string. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: + - $O(1)$ extra space, since we have at most $26$ different characters. + - $O(n)$ space for the output string. diff --git a/articles/repeated-dna-sequences.md b/articles/repeated-dna-sequences.md index 6976f8850..de3a9938b 100644 --- a/articles/repeated-dna-sequences.md +++ b/articles/repeated-dna-sequences.md @@ -78,8 +78,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -182,8 +182,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -316,9 +316,14 @@ class Solution { const cnt = new Map(); const res = []; - const base1 = 31, base2 = 37; - let hash1 = 0, hash2 = 0, power1 = 1, power2 = 1; - const MOD1 = 685683731, MOD2 = 768258391; + const base1 = 31, + base2 = 37; + let hash1 = 0, + hash2 = 0, + power1 = 1, + power2 = 1; + const MOD1 = 685683731, + MOD2 = 768258391; for (let i = 0; i < 9; i++) { power1 = (power1 * base1) % MOD1; @@ -336,8 +341,12 @@ class Solution { res.push(s.substring(i - 9, i + 1)); } - hash1 = (hash1 - power1 * s.charCodeAt(i - 9) % MOD1 + MOD1) % MOD1; - hash2 = (hash2 - power2 * s.charCodeAt(i - 9) % MOD2 + MOD2) % MOD2; + hash1 = + (hash1 - ((power1 * s.charCodeAt(i - 9)) % MOD1) + MOD1) % + MOD1; + hash2 = + (hash2 - ((power2 * s.charCodeAt(i - 9)) % MOD2) + MOD2) % + MOD2; } } @@ -350,8 +359,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -375,7 +384,7 @@ class Solution: res.add(s[i - 9: i + 1]) else: seen.add(mask) - + return list(res) ``` @@ -410,7 +419,7 @@ public: vector findRepeatedDnaSequences(string s) { if (s.length() < 10) return {}; - unordered_map mp = {{'A', 0}, {'C', 1}, + unordered_map mp = {{'A', 0}, {'C', 1}, {'G', 2}, {'T', 3}}; unordered_map cnt; vector res; @@ -441,13 +450,13 @@ class Solution { findRepeatedDnaSequences(s) { if (s.length < 10) return []; - const mp = { 'A': 0, 'C': 1, 'G': 2, 'T': 3 }; + const mp = { A: 0, C: 1, G: 2, T: 3 }; const cnt = new Map(); const res = []; let mask = 0; for (let i = 0; i < s.length; i++) { - mask = ((mask << 2) | mp[s[i]]) & 0xFFFFF; + mask = ((mask << 2) | mp[s[i]]) & 0xfffff; if (i >= 9) { cnt.set(mask, (cnt.get(mask) || 0) + 1); @@ -466,5 +475,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/replace-elements-with-greatest-element-on-right-side.md b/articles/replace-elements-with-greatest-element-on-right-side.md index 1825436a7..30217a747 100644 --- a/articles/replace-elements-with-greatest-element-on-right-side.md +++ b/articles/replace-elements-with-greatest-element-on-right-side.md @@ -75,8 +75,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -93,7 +93,7 @@ class Solution: for i in range(n - 1, -1, -1): ans[i] = rightMax rightMax = max(arr[i], rightMax) - return ans + return ans ``` ```java @@ -150,5 +150,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/restore-ip-addresses.md b/articles/restore-ip-addresses.md index a0a6fd2b6..2c00656c9 100644 --- a/articles/restore-ip-addresses.md +++ b/articles/restore-ip-addresses.md @@ -8,20 +8,20 @@ class Solution: res = [] if len(s) > 12: return res - + def backtrack(i, dots, curIP): if dots == 4 and i == len(s): res.append(curIP[:-1]) return if dots > 4: return - + for j in range(i, min(i + 3, len(s))): if i != j and s[i] == "0": continue if int(s[i: j + 1]) < 256: backtrack(j + 1, dots + 1, curIP + s[i: j + 1] + ".") - + backtrack(0, 0, "") return res ``` @@ -107,7 +107,7 @@ class Solution { } }; - backtrack(0, 0, ""); + backtrack(0, 0, ''); return res; } } @@ -117,8 +117,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m ^ n * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m ^ n * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is equals to $3$ as there are at most three digits in a valid segment and $n$ is equals to $4$ as there are four segments in a valid IP. @@ -134,27 +134,27 @@ class Solution: res = [] if len(s) > 12: return res - + def valid(num): return len(num) == 1 or (int(num) < 256 and num[0] != "0") - + def add(s1, s2, s3, s4): if s1 + s2 + s3 + s4 != len(s): return - + num1 = s[:s1] num2 = s[s1:s1+s2] num3 = s[s1+s2:s1+s2+s3] num4 = s[s1+s2+s3:] if valid(num1) and valid(num2) and valid(num3) and valid(num4): res.append(num1 + "." + num2 + "." + num3 + "." + num4) - + for seg1 in range(1, 4): for seg2 in range(1, 4): for seg3 in range(1, 4): for seg4 in range(1, 4): add(seg1, seg2, seg3, seg4) - + return res ``` @@ -163,13 +163,13 @@ public class Solution { public List restoreIpAddresses(String s) { List res = new ArrayList<>(); if (s.length() > 12) return res; - + for (int seg1 = 1; seg1 < 4; seg1++) { for (int seg2 = 1; seg2 < 4; seg2++) { for (int seg3 = 1; seg3 < 4; seg3++) { for (int seg4 = 1; seg4 < 4; seg4++) { if (seg1 + seg2 + seg3 + seg4 != s.length()) continue; - + String num1 = s.substring(0, seg1); String num2 = s.substring(seg1, seg1 + seg2); String num3 = s.substring(seg1 + seg2, seg1 + seg2 + seg3); @@ -211,7 +211,7 @@ public: for (int seg3 = 1; seg3 < 4; ++seg3) { for (int seg4 = 1; seg4 < 4; ++seg4) { if (seg1 + seg2 + seg3 + seg4 != s.size()) continue; - + string num1 = s.substr(0, seg1); string num2 = s.substr(seg1, seg2); string num3 = s.substr(seg1 + seg2, seg3); @@ -238,7 +238,7 @@ class Solution { restoreIpAddresses(s) { const res = []; if (s.length > 12) return res; - + const isValid = (num) => { if (num.length > 1 && num[0] === '0') return false; const value = parseInt(num, 10); @@ -253,10 +253,18 @@ class Solution { const num1 = s.substring(0, seg1); const num2 = s.substring(seg1, seg1 + seg2); - const num3 = s.substring(seg1 + seg2, seg1 + seg2 + seg3); + const num3 = s.substring( + seg1 + seg2, + seg1 + seg2 + seg3, + ); const num4 = s.substring(seg1 + seg2 + seg3); - if (isValid(num1) && isValid(num2) && isValid(num3) && isValid(num4)) { + if ( + isValid(num1) && + isValid(num2) && + isValid(num3) && + isValid(num4) + ) { res.push(`${num1}.${num2}.${num3}.${num4}`); } } @@ -272,7 +280,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m ^ n * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m ^ n * n)$ +- Space complexity: $O(m * n)$ -> Where $m$ is equals to $3$ as there are at most three digits in a valid segment and $n$ is equals to $4$ as there are four segments in a valid IP. \ No newline at end of file +> Where $m$ is equals to $3$ as there are at most three digits in a valid segment and $n$ is equals to $4$ as there are four segments in a valid IP. diff --git a/articles/reveal-cards-in-increasing-order.md b/articles/reveal-cards-in-increasing-order.md index 4759af658..473876c16 100644 --- a/articles/reveal-cards-in-increasing-order.md +++ b/articles/reveal-cards-in-increasing-order.md @@ -104,8 +104,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -198,8 +198,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -285,8 +285,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -377,7 +377,8 @@ class Solution { let n = deck.length; let res = new Array(n).fill(0); let skip = false; - let deckIndex = 0, i = 0; + let deckIndex = 0, + i = 0; deck.sort((a, b) => a - b); @@ -400,7 +401,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: - * $O(1)$ or $O(n)$ space depending on the sorting algorithm. - * $O(n)$ space for the output array. \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: + - $O(1)$ or $O(n)$ space depending on the sorting algorithm. + - $O(n)$ space for the output array. diff --git a/articles/reverse-a-linked-list.md b/articles/reverse-a-linked-list.md index 3a205a543..128f9269b 100644 --- a/articles/reverse-a-linked-list.md +++ b/articles/reverse-a-linked-list.md @@ -19,7 +19,7 @@ class Solution: newHead = self.reverseList(head.next) head.next.next = head head.next = None - + return newHead ``` @@ -129,7 +129,7 @@ class Solution { * } * } */ - + public class Solution { public ListNode ReverseList(ListNode head) { if (head == null) { @@ -160,14 +160,14 @@ func reverseList(head *ListNode) *ListNode { if head == nil { return nil } - + newHead := head if head.Next != nil { newHead = reverseList(head.Next) head.Next.Next = head } head.Next = nil - + return newHead } ``` @@ -233,8 +233,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -361,7 +361,7 @@ class Solution { * } * } */ - + public class Solution { public ListNode ReverseList(ListNode head) { ListNode prev = null; @@ -457,5 +457,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/reverse-bits.md b/articles/reverse-bits.md index 84cbe88ce..d77b73092 100644 --- a/articles/reverse-bits.md +++ b/articles/reverse-bits.md @@ -11,12 +11,12 @@ class Solution: binary += "1" else: binary += "0" - + res = 0 for i, bit in enumerate(binary[::-1]): if bit == "1": res |= (1 << i) - + return res ``` @@ -31,7 +31,7 @@ public class Solution { binary.append("0"); } } - + int res = 0; String reversedBinary = binary.reverse().toString(); for (int i = 0; i < 32; i++) { @@ -39,7 +39,7 @@ public class Solution { res |= (1 << i); } } - + return res; } } @@ -57,14 +57,14 @@ public: binary += '0'; } } - + uint32_t res = 0; for (int i = 0; i < 32; i++) { - if (binary[31 - i] == '1') { + if (binary[31 - i] == '1') { res |= (1 << i); } } - + return res; } }; @@ -77,22 +77,22 @@ class Solution { * @return {number} - a positive integer */ reverseBits(n) { - let binary = ""; + let binary = ''; for (let i = 0; i < 32; i++) { if (n & (1 << i)) { - binary += "1"; + binary += '1'; } else { - binary += "0"; + binary += '0'; } } - + let res = 0; for (let i = 0; i < 32; i++) { - if (binary[31 - i] === "1") { - res |= (1 << i); + if (binary[31 - i] === '1') { + res |= 1 << i; } } - + return res >>> 0; } } @@ -109,14 +109,14 @@ public class Solution { binary += "0"; } } - + uint res = 0; for (int i = 0; i < 32; i++) { - if (binary[31 - i] == '1') { + if (binary[31 - i] == '1') { res |= (1u << i); } } - + return res; } } @@ -190,8 +190,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ --- @@ -308,8 +308,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ --- @@ -365,7 +365,7 @@ class Solution { * @return {number} - a positive integer */ reverseBits(n) { - let ret = n >>> 0; + let ret = n >>> 0; ret = (ret >>> 16) | (ret << 16); ret = ((ret & 0xff00ff00) >>> 8) | ((ret & 0x00ff00ff) << 8); ret = ((ret & 0xf0f0f0f0) >>> 4) | ((ret & 0x0f0f0f0f) << 4); @@ -434,5 +434,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ diff --git a/articles/reverse-integer.md b/articles/reverse-integer.md index c388a821f..8eb02eb59 100644 --- a/articles/reverse-integer.md +++ b/articles/reverse-integer.md @@ -42,7 +42,7 @@ public: x = abs(x); string strX = to_string(x); std::reverse(strX.begin(), strX.end()); - long long res = stoll(strX); + long long res = stoll(strX); if (org < 0) { res *= -1; } @@ -67,7 +67,7 @@ class Solution { if (org < 0) { res *= -1; } - if (res < -(2 ** 31) || res > (2 ** 31) - 1) { + if (res < -(2 ** 31) || res > 2 ** 31 - 1) { return 0; } return res; @@ -82,16 +82,16 @@ public class Solution { x = Math.Abs(x); char[] arr = x.ToString().ToCharArray(); Array.Reverse(arr); - - long res = long.Parse(new string(arr)); + + long res = long.Parse(new string(arr)); if (org < 0) { - res *= -1; + res *= -1; } - + if (res < int.MinValue || res > int.MaxValue) { - return 0; + return 0; } - return (int)res; + return (int)res; } } ``` @@ -170,8 +170,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ --- @@ -185,17 +185,17 @@ class Solution: def rec(n: int, rev: int) -> int: if n == 0: return rev - + rev = rev * 10 + n % 10 return rec(n // 10, rev) - + sign = -1 if x < 0 else 1 - x = abs(x) + x = abs(x) reversed_num = rec(x, 0) - reversed_num *= sign + reversed_num *= sign if reversed_num < -(1 << 31) or reversed_num > (1 << 31) - 1: return 0 - + return reversed_num ``` @@ -249,7 +249,7 @@ class Solution { */ reverse(x) { let res = this.rec(Math.abs(x), 0) * (x < 0 ? -1 : 1); - if (res < -(2 ** 31) || res > (2 ** 31) - 1) { + if (res < -(2 ** 31) || res > 2 ** 31 - 1) { return 0; } return res; @@ -264,7 +264,7 @@ class Solution { if (n === 0) { return rev; } - rev = rev * 10 + n % 10; + rev = rev * 10 + (n % 10); return this.rec(Math.floor(n / 10), rev); } } @@ -355,8 +355,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ --- @@ -561,5 +561,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ diff --git a/articles/reverse-linked-list-ii.md b/articles/reverse-linked-list-ii.md index 98f00e838..cd0845c1f 100644 --- a/articles/reverse-linked-list-ii.md +++ b/articles/reverse-linked-list-ii.md @@ -38,7 +38,7 @@ class Solution: newHead = self.reverseList(head.next) head.next.next = head head.next = None - + return newHead ``` @@ -249,8 +249,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -277,7 +277,7 @@ class Solution: if left == 1: new_head, _ = reverseList(head, right) return new_head - + head.next = self.reverseBetween(head.next, left - 1, right - 1) return head ``` @@ -425,8 +425,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -604,7 +604,7 @@ class Solution { } return prev; }; - + const dummy = new ListNode(0, head); let prev = dummy; for (let i = 0; i < left - 1; i++) { @@ -683,8 +683,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -815,7 +815,8 @@ class Solution { */ reverseBetween(head, left, right) { const dummy = new ListNode(0, head); - let leftPrev = dummy, cur = head; + let leftPrev = dummy, + cur = head; for (let i = 0; i < left - 1; i++) { leftPrev = cur; @@ -880,5 +881,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/reverse-nodes-in-k-group.md b/articles/reverse-nodes-in-k-group.md index f5836142d..8a073e130 100644 --- a/articles/reverse-nodes-in-k-group.md +++ b/articles/reverse-nodes-in-k-group.md @@ -45,18 +45,18 @@ public class Solution { public ListNode reverseKGroup(ListNode head, int k) { ListNode cur = head; int group = 0; - while (cur != null && group < k) { + while (cur != null && group < k) { cur = cur.next; group++; } - if (group == k) { - cur = reverseKGroup(cur, k); - while (group-- > 0) { - ListNode tmp = head.next; - head.next = cur; - cur = head; - head = tmp; + if (group == k) { + cur = reverseKGroup(cur, k); + while (group-- > 0) { + ListNode tmp = head.next; + head.next = cur; + cur = head; + head = tmp; } head = cur; } @@ -243,9 +243,9 @@ class Solution { tempHead = tmp group-- } - cur + cur } else { - head + head } } } @@ -296,8 +296,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(\frac{n}{k})$ +- Time complexity: $O(n)$ +- Space complexity: $O(\frac{n}{k})$ --- @@ -355,7 +355,7 @@ class Solution: */ class Solution { - + public ListNode reverseKGroup(ListNode head, int k) { ListNode dummy = new ListNode(0, head); ListNode groupPrev = dummy; @@ -699,5 +699,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/reverse-string.md b/articles/reverse-string.md index 6c671dd5f..acebe2477 100644 --- a/articles/reverse-string.md +++ b/articles/reverse-string.md @@ -83,8 +83,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -102,7 +102,7 @@ class Solution: if l < r: reverse(l + 1, r - 1) s[l], s[r] = s[r], s[l] - + reverse(0, len(s) - 1) ``` @@ -111,7 +111,7 @@ public class Solution { public void reverseString(char[] s) { reverse(s, 0, s.length - 1); } - + private void reverse(char[] s, int l, int r) { if (l < r) { reverse(s, l + 1, r - 1); @@ -129,7 +129,7 @@ public: void reverseString(vector& s) { reverse(s, 0, s.size() - 1); } - + private: void reverse(vector& s, int l, int r) { if (l < r) { @@ -179,8 +179,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -274,8 +274,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -300,7 +300,7 @@ public class Solution { list.add(c); } Collections.reverse(list); - + for (int i = 0; i < s.length; i++) { s[i] = list.get(i); } @@ -341,8 +341,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -397,7 +397,8 @@ class Solution { * @return {void} Do not return anything, modify s in-place instead. */ reverseString(s) { - let l = 0, r = s.length - 1; + let l = 0, + r = s.length - 1; while (l < r) { [s[l], s[r]] = [s[r], s[l]]; l++; @@ -426,5 +427,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/reverse-words-in-a-string-iii.md b/articles/reverse-words-in-a-string-iii.md index b9fb3b3cb..96514518a 100644 --- a/articles/reverse-words-in-a-string-iii.md +++ b/articles/reverse-words-in-a-string-iii.md @@ -27,7 +27,7 @@ public: stringstream ss(s); string word, res; bool first = true; - + while (ss >> word) { reverse(word.begin(), word.end()); if (first) { @@ -37,7 +37,7 @@ public: res += " " + word; } } - + return res; } }; @@ -50,7 +50,10 @@ class Solution { * @return {string} */ reverseWords(s) { - return s.split(' ').map(w => w.split('').reverse().join('')).join(' '); + return s + .split(' ') + .map((w) => w.split('').reverse().join('')) + .join(' '); } } ``` @@ -59,8 +62,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -137,15 +140,15 @@ class Solution { * @return {string} */ reverseWords(s) { - let tmpStr = ""; - let res = ""; + let tmpStr = ''; + let res = ''; for (let r = 0; r <= s.length; r++) { if (r === s.length || s[r] === ' ') { res += tmpStr; - tmpStr = ""; + tmpStr = ''; if (r !== s.length) { - res += " "; + res += ' '; } } else { tmpStr = s[r] + tmpStr; @@ -160,8 +163,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -240,7 +243,8 @@ class Solution { let l = 0; for (let r = 0; r <= chars.length; r++) { if (r === chars.length || chars[r] === ' ') { - let tempL = l, tempR = r - 1; + let tempL = l, + tempR = r - 1; while (tempL < tempR) { [chars[tempL], chars[tempR]] = [chars[tempR], chars[tempL]]; tempL++; @@ -258,8 +262,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -285,7 +289,7 @@ class Solution: j += 1 reverse(i, j - 1) i = j + 1 - return ''.join(s) + return ''.join(s) ``` ```java @@ -383,5 +387,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/robot-bounded-in-circle.md b/articles/robot-bounded-in-circle.md index 76ec62fc9..464883cc9 100644 --- a/articles/robot-bounded-in-circle.md +++ b/articles/robot-bounded-in-circle.md @@ -80,8 +80,10 @@ class Solution { * @return {boolean} */ isRobotBounded(instructions) { - let dirX = 0, dirY = 1; - let x = 0, y = 0; + let dirX = 0, + dirY = 1; + let x = 0, + y = 0; for (const d of instructions) { if (d === 'G') { @@ -94,7 +96,7 @@ class Solution { } } - return (x === 0 && y === 0) || (dirX !== 0 || dirY !== 1); + return (x === 0 && y === 0) || dirX !== 0 || dirY !== 1; } } ``` @@ -103,5 +105,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/roman-to-integer.md b/articles/roman-to-integer.md index 2848187cb..6cd1e98df 100644 --- a/articles/roman-to-integer.md +++ b/articles/roman-to-integer.md @@ -70,8 +70,13 @@ class Solution { */ romanToInt(s) { const roman = { - "I": 1, "V": 5, "X": 10, - "L": 50, "C": 100, "D": 500, "M": 1000 + I: 1, + V: 5, + X: 10, + L: 50, + C: 100, + D: 500, + M: 1000, }; let res = 0; @@ -112,5 +117,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ since we have $7$ characters in the hash map. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ since we have $7$ characters in the hash map. diff --git a/articles/rotate-array.md b/articles/rotate-array.md index 790679e20..1a6d2365c 100644 --- a/articles/rotate-array.md +++ b/articles/rotate-array.md @@ -97,8 +97,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * k)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n * k)$ +- Space complexity: $O(1)$ extra space. --- @@ -116,7 +116,7 @@ class Solution: tmp = [0] * n for i in range(n): tmp[(i + k) % n] = nums[i] - + nums[:] = tmp ``` @@ -176,7 +176,7 @@ public class Solution { public void Rotate(int[] nums, int k) { int n = nums.Length; int[] tmp = new int[n]; - + for (int i = 0; i < n; i++) { tmp[(i + k) % n] = nums[i]; } @@ -192,8 +192,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ extra space. --- @@ -209,7 +209,7 @@ class Solution: """ n = len(nums) k %= n - count = start = 0 + count = start = 0 while count < n: current = start @@ -231,7 +231,7 @@ public class Solution { int n = nums.length; k %= n; int count = 0; - + for (int start = 0; count < n; start++) { int current = start; int prev = nums[start]; @@ -255,7 +255,7 @@ public: int n = nums.size(); k %= n; int count = 0; - + for (int start = 0; count < n; start++) { int current = start; int prev = nums[start]; @@ -283,7 +283,7 @@ class Solution { const n = nums.length; k %= n; let count = 0; - + for (let start = 0; count < n; start++) { let current = start; let prev = nums[start]; @@ -328,8 +328,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -455,8 +455,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -525,5 +525,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the language. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the language. diff --git a/articles/rotate-list.md b/articles/rotate-list.md index 675821f82..a954129f6 100644 --- a/articles/rotate-list.md +++ b/articles/rotate-list.md @@ -155,8 +155,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -300,7 +300,8 @@ class Solution { return head; } - let length = 1, tail = head; + let length = 1, + tail = head; while (tail.next) { tail = tail.next; length++; @@ -328,8 +329,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -459,7 +460,8 @@ class Solution { return head; } - let cur = head, n = 1; + let cur = head, + n = 1; while (cur.next) { n++; cur = cur.next; @@ -482,5 +484,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/rotate-matrix.md b/articles/rotate-matrix.md index c7ea787f1..493bc1d54 100644 --- a/articles/rotate-matrix.md +++ b/articles/rotate-matrix.md @@ -7,11 +7,11 @@ class Solution: def rotate(self, matrix: List[List[int]]) -> None: n = len(matrix) rotated = [[0] * n for _ in range(n)] - + for i in range(n): for j in range(n): rotated[j][n - 1 - i] = matrix[i][j] - + for i in range(n): for j in range(n): matrix[i][j] = rotated[i][j] @@ -64,8 +64,7 @@ class Solution { */ rotate(matrix) { const n = matrix.length; - const rotated = Array.from({ length: n }, () => - Array(n).fill(0)); + const rotated = Array.from({ length: n }, () => Array(n).fill(0)); for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { @@ -86,16 +85,16 @@ class Solution { public class Solution { public void Rotate(int[][] matrix) { int n = matrix.Length; - int[][] rotated = new int[n][]; + int[][] rotated = new int[n][]; for (int i = 0; i < n; i++) { - rotated[i] = new int[n]; + rotated[i] = new int[n]; for (int j = 0; j < n; j++) { - rotated[i][j] = matrix[n - 1 - j][i]; + rotated[i][j] = matrix[n - 1 - j][i]; } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { - matrix[i][j] = rotated[i][j]; + matrix[i][j] = rotated[i][j]; } } } @@ -170,8 +169,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -210,7 +209,7 @@ public class Solution { public void rotate(int[][] matrix) { int l = 0; int r = matrix.length - 1; - + while ( l < r ) { for(int i = 0; i < r - l; i++) { int top = l; @@ -229,7 +228,7 @@ public class Solution { // move top left into top right matrix[top + i][r] = topLeft; - + } r--; l++; @@ -244,7 +243,7 @@ public: void rotate(vector>& matrix) { int l = 0; int r = matrix.size() - 1; - + while ( l < r ) { for(int i = 0; i < r - l; i++) { int top = l; @@ -264,7 +263,7 @@ public: // move top left into top right matrix[top + i][r] = topLeft; - + } r--; l++; @@ -314,32 +313,32 @@ class Solution { public class Solution { public void Rotate(int[][] matrix) { (int left, int right) = (0, matrix.Length -1); - + while(left < right) { var limit = right - left; for(var i = 0; i < limit; i++) { (int top, int bottom) = (left, right); - + // save the top left position var topLeft = matrix[top][left + i]; - + // put the bottom left value to the top left position matrix[top][left + i] = matrix[bottom - i][left]; - + // put the bottom right value to the bottom left position matrix[bottom - i][left] = matrix[bottom][right - i]; - + // put the top right value to the bottom right position - matrix[bottom][right - i] = matrix[top + i][right]; + matrix[bottom][right - i] = matrix[top + i][right]; // put the saved top left value to the top right position - matrix[top + i][right] = topLeft; + matrix[top + i][right] = topLeft; } left++; right--; } - + return; } } @@ -441,8 +440,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -595,5 +594,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ diff --git a/articles/rotating-the-box.md b/articles/rotating-the-box.md index 3dac527fa..f7f5f16f4 100644 --- a/articles/rotating-the-box.md +++ b/articles/rotating-the-box.md @@ -13,10 +13,10 @@ class Solution: c2 = c1 + 1 while c2 < COLS and boxGrid[r][c2] == '.': c2 += 1 - + boxGrid[r][c1] = '.' boxGrid[r][c2 - 1] = '#' - + res = [] for c in range(COLS): @@ -93,7 +93,8 @@ class Solution { * @return {character[][]} */ rotateTheBox(boxGrid) { - const ROWS = boxGrid.length, COLS = boxGrid[0].length; + const ROWS = boxGrid.length, + COLS = boxGrid[0].length; const res = Array.from({ length: COLS }, () => Array(ROWS).fill('.')); for (let r = 0; r < ROWS; r++) { let i = COLS - 1; @@ -146,8 +147,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n ^ 2)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n ^ 2)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns. @@ -243,12 +244,16 @@ class Solution { * @return {character[][]} */ rotateTheBox(boxGrid) { - const ROWS = boxGrid.length, COLS = boxGrid[0].length; + const ROWS = boxGrid.length, + COLS = boxGrid[0].length; for (let r = 0; r < ROWS; r++) { let i = COLS - 1; for (let c = COLS - 1; c >= 0; c--) { if (boxGrid[r][c] === '#') { - [boxGrid[r][c], boxGrid[r][i]] = [boxGrid[r][i], boxGrid[r][c]]; + [boxGrid[r][c], boxGrid[r][i]] = [ + boxGrid[r][i], + boxGrid[r][c], + ]; i--; } else if (boxGrid[r][c] === '*') { i = c - 1; @@ -301,8 +306,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns. @@ -390,7 +395,8 @@ class Solution { * @return {character[][]} */ rotateTheBox(boxGrid) { - const ROWS = boxGrid.length, COLS = boxGrid[0].length; + const ROWS = boxGrid.length, + COLS = boxGrid[0].length; const res = Array.from({ length: COLS }, () => Array(ROWS).fill('.')); for (let r = 0; r < ROWS; r++) { let i = COLS - 1; @@ -442,7 +448,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ -> Where $m$ is the number of rows and $n$ is the number of columns. \ No newline at end of file +> Where $m$ is the number of rows and $n$ is the number of columns. diff --git a/articles/rotting-fruit.md b/articles/rotting-fruit.md index 62345eea7..656ce8d15 100644 --- a/articles/rotting-fruit.md +++ b/articles/rotting-fruit.md @@ -64,7 +64,7 @@ public class Solution { for (int[] dir : directions) { int row = r + dir[0]; int col = c + dir[1]; - if (row >= 0 && row < grid.length && + if (row >= 0 && row < grid.length && col >= 0 && col < grid[0].length && grid[row][col] == 1) { grid[row][col] = 2; @@ -111,7 +111,7 @@ public: for (const auto& dir : directions) { int row = r + dir.first; int col = c + dir.second; - if (row >= 0 && row < grid.size() && + if (row >= 0 && row < grid.size() && col >= 0 && col < grid[0].size() && grid[row][col] == 1) { grid[row][col] = 2; @@ -163,9 +163,13 @@ class Solution { for (const [dr, dc] of directions) { const row = currR + dr; const col = currC + dc; - if (row >= 0 && row < grid.length && - col >= 0 && col < grid[0].length && - grid[row][col] === 1) { + if ( + row >= 0 && + row < grid.length && + col >= 0 && + col < grid[0].length && + grid[row][col] === 1 + ) { grid[row][col] = 2; q.push([row, col]); fresh--; @@ -208,7 +212,7 @@ public class Solution { foreach (int[] dir in directions) { int row = r + dir[0]; int col = c + dir[1]; - if (row >= 0 && row < grid.Length && + if (row >= 0 && row < grid.Length && col >= 0 && col < grid[0].Length && grid[row][col] == 1) { grid[row][col] = 2; @@ -234,7 +238,7 @@ func orangesRotting(grid [][]int) int { queue := make([]Pair, 0) fresh := 0 time := 0 - + for r := 0; r < rows; r++ { for c := 0; c < cols; c++ { if grid[r][c] == 1 { @@ -245,20 +249,20 @@ func orangesRotting(grid [][]int) int { } } } - + directions := [][]int{{0, 1}, {0, -1}, {1, 0}, {-1, 0}} - + for fresh > 0 && len(queue) > 0 { length := len(queue) - + for i := 0; i < length; i++ { current := queue[0] - queue = queue[1:] - + queue = queue[1:] + for _, dir := range directions { newRow := current.row + dir[0] newCol := current.col + dir[1] - + if newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols && grid[newRow][newCol] == 1 { @@ -270,7 +274,7 @@ func orangesRotting(grid [][]int) int { } time++ } - + if fresh == 0 { return time } @@ -281,14 +285,14 @@ func orangesRotting(grid [][]int) int { ```kotlin class Solution { data class Pair(val row: Int, val col: Int) - + fun orangesRotting(grid: Array): Int { val rows = grid.size val cols = grid[0].size val queue = ArrayDeque() var fresh = 0 var time = 0 - + for (r in 0 until rows) { for (c in 0 until cols) { if (grid[r][c] == 1) { @@ -299,24 +303,24 @@ class Solution { } } } - + val directions = arrayOf( intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0) ) - + while (fresh > 0 && queue.isNotEmpty()) { val length = queue.size - + repeat(length) { val current = queue.removeFirst() - + for (dir in directions) { val newRow = current.row + dir[0] val newCol = current.col + dir[1] - + if (newRow in 0 until rows && newCol in 0 until cols && grid[newRow][newCol] == 1) { @@ -328,7 +332,7 @@ class Solution { } time++ } - + return if (fresh == 0) time else -1 } } @@ -386,14 +390,14 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns in the $grid$. --- -## 2. Breadth First Search (No Queue) +## 2. Breadth First Search (No Queue) ::tabs-start @@ -418,10 +422,10 @@ class Solution: if grid[r][c] == 2: for dr, dc in directions: row, col = r + dr, c + dc - if (row in range(ROWS) and - col in range(COLS) and + if (row in range(ROWS) and + col in range(COLS) and grid[row][col] == 1): - grid[row][col] = 3 + grid[row][col] = 3 fresh -= 1 flag = True @@ -431,7 +435,7 @@ class Solution: for r in range(ROWS): for c in range(COLS): if grid[r][c] == 3: - grid[r][c] = 2 + grid[r][c] = 2 time += 1 @@ -459,8 +463,8 @@ public class Solution { if (grid[r][c] == 2) { for (int[] d : directions) { int row = r + d[0], col = c + d[1]; - if (row >= 0 && col >= 0 && - row < ROWS && col < COLS && + if (row >= 0 && col >= 0 && + row < ROWS && col < COLS && grid[row][col] == 1) { grid[row][col] = 3; fresh--; @@ -500,7 +504,7 @@ public: } } - vector> directions = {{0, 1}, {0, -1}, + vector> directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; while (fresh > 0) { @@ -510,8 +514,8 @@ public: if (grid[r][c] == 2) { for (auto& d : directions) { int row = r + d[0], col = c + d[1]; - if (row >= 0 && col >= 0 && - row < ROWS && col < COLS && + if (row >= 0 && col >= 0 && + row < ROWS && col < COLS && grid[row][col] == 1) { grid[row][col] = 3; fresh--; @@ -545,8 +549,10 @@ class Solution { * @return {number} */ orangesRotting(grid) { - let ROWS = grid.length, COLS = grid[0].length; - let fresh = 0, time = 0; + let ROWS = grid.length, + COLS = grid[0].length; + let fresh = 0, + time = 0; for (let r = 0; r < ROWS; r++) { for (let c = 0; c < COLS; c++) { @@ -554,7 +560,12 @@ class Solution { } } - let directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]; + let directions = [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ]; while (fresh > 0) { let flag = false; @@ -562,10 +573,15 @@ class Solution { for (let c = 0; c < COLS; c++) { if (grid[r][c] === 2) { for (let [dr, dc] of directions) { - let row = r + dr, col = c + dc; - if (row >= 0 && col >= 0 && - row < ROWS && col < COLS && - grid[row][col] === 1) { + let row = r + dr, + col = c + dc; + if ( + row >= 0 && + col >= 0 && + row < ROWS && + col < COLS && + grid[row][col] === 1 + ) { grid[row][col] = 3; fresh--; flag = true; @@ -604,7 +620,7 @@ public class Solution { } int[][] directions = new int[][] { - new int[] {0, 1}, new int[] {0, -1}, + new int[] {0, 1}, new int[] {0, -1}, new int[] {1, 0}, new int[] {-1, 0} }; @@ -615,8 +631,8 @@ public class Solution { if (grid[r][c] == 2) { foreach (var d in directions) { int row = r + d[0], col = c + d[1]; - if (row >= 0 && col >= 0 && - row < ROWS && col < COLS && + if (row >= 0 && col >= 0 && + row < ROWS && col < COLS && grid[row][col] == 1) { grid[row][col] = 3; fresh--; @@ -648,7 +664,7 @@ func orangesRotting(grid [][]int) int { rows, cols := len(grid), len(grid[0]) fresh := 0 time := 0 - + for r := 0; r < rows; r++ { for c := 0; c < cols; c++ { if grid[r][c] == 1 { @@ -656,9 +672,9 @@ func orangesRotting(grid [][]int) int { } } } - + directions := [][]int{{0, 1}, {0, -1}, {1, 0}, {-1, 0}} - + for fresh > 0 { flag := false for r := 0; r < rows; r++ { @@ -666,8 +682,8 @@ func orangesRotting(grid [][]int) int { if grid[r][c] == 2 { for _, d := range directions { row, col := r+d[0], c+d[1] - if row >= 0 && row < rows && - col >= 0 && col < cols && + if row >= 0 && row < rows && + col >= 0 && col < cols && grid[row][col] == 1 { grid[row][col] = 3 fresh-- @@ -677,11 +693,11 @@ func orangesRotting(grid [][]int) int { } } } - + if !flag { return -1 } - + for r := 0; r < rows; r++ { for c := 0; c < cols; c++ { if grid[r][c] == 3 { @@ -691,7 +707,7 @@ func orangesRotting(grid [][]int) int { } time++ } - + return time } ``` @@ -703,20 +719,20 @@ class Solution { val cols = grid[0].size var fresh = 0 var time = 0 - + for (r in 0 until rows) { for (c in 0 until cols) { if (grid[r][c] == 1) fresh++ } } - + val directions = arrayOf( intArrayOf(0, 1), intArrayOf(0, -1), intArrayOf(1, 0), intArrayOf(-1, 0) ) - + while (fresh > 0) { var flag = false for (r in 0 until rows) { @@ -725,8 +741,8 @@ class Solution { for (d in directions) { val row = r + d[0] val col = c + d[1] - if (row in 0 until rows && - col in 0 until cols && + if (row in 0 until rows && + col in 0 until cols && grid[row][col] == 1) { grid[row][col] = 3 fresh-- @@ -736,9 +752,9 @@ class Solution { } } } - + if (!flag) return -1 - + for (r in 0 until rows) { for (c in 0 until cols) { if (grid[r][c] == 3) grid[r][c] = 2 @@ -746,7 +762,7 @@ class Solution { } time++ } - + return time } } @@ -814,7 +830,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O((m * n) ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O((m * n) ^ 2)$ +- Space complexity: $O(1)$ -> Where $m$ is the number of rows and $n$ is the number of columns in the $grid$. \ No newline at end of file +> Where $m$ is the number of rows and $n$ is the number of columns in the $grid$. diff --git a/articles/russian-doll-envelopes.md b/articles/russian-doll-envelopes.md index 2c638fc6c..5f61e6e8f 100644 --- a/articles/russian-doll-envelopes.md +++ b/articles/russian-doll-envelopes.md @@ -25,7 +25,7 @@ class Solution: return LIS return max(dfs(i) for i in range(n)) - + return lis([e[1] for e in envelopes]) ``` @@ -34,9 +34,9 @@ public class Solution { public int maxEnvelopes(int[][] envelopes) { int n = envelopes.length; if (n == 0) return 0; - Arrays.sort(envelopes, (a, b) -> - a[0] != b[0] - ? Integer.compare(a[0], b[0]) + Arrays.sort(envelopes, (a, b) -> + a[0] != b[0] + ? Integer.compare(a[0], b[0]) : Integer.compare(b[1], a[1]) ); @@ -113,7 +113,7 @@ class Solution { maxEnvelopes(envelopes) { const n = envelopes.length; envelopes.sort((a, b) => a[0] - b[0] || b[1] - a[1]); - const nums = envelopes.map(e => e[1]); + const nums = envelopes.map((e) => e[1]); const memo = new Array(n).fill(-1); const dfs = (i) => { @@ -173,8 +173,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -260,7 +260,7 @@ class Solution { */ maxEnvelopes(envelopes) { envelopes.sort((a, b) => a[0] - b[0] || b[1] - a[1]); - const heights = envelopes.map(e => e[1]); + const heights = envelopes.map((e) => e[1]); const n = heights.length; if (n === 0) return 0; const LIS = new Array(n).fill(1); @@ -307,8 +307,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -327,13 +327,13 @@ class Solution: LIS = 1 for i in range(1, len(nums)): - if dp[-1] < nums[i]: + if dp[-1] < nums[i]: dp.append(nums[i]) LIS += 1 continue idx = bisect_left(dp, nums[i]) - dp[idx] = nums[i] + dp[idx] = nums[i] return LIS @@ -344,9 +344,9 @@ class Solution: public class Solution { public int maxEnvelopes(int[][] envelopes) { int n = envelopes.length; - Arrays.sort(envelopes, (a, b) -> - a[0] != b[0] - ? Integer.compare(a[0], b[0]) + Arrays.sort(envelopes, (a, b) -> + a[0] != b[0] + ? Integer.compare(a[0], b[0]) : Integer.compare(b[1], a[1]) ); @@ -360,15 +360,15 @@ public class Solution { int LIS = 1; for (int i = 1; i < n; i++) { - if (dp.get(dp.size() - 1) < nums[i]) { + if (dp.get(dp.size() - 1) < nums[i]) { dp.add(nums[i]); LIS++; continue; } int idx = Collections.binarySearch(dp, nums[i]); - if (idx < 0) idx = -idx - 1; - dp.set(idx, nums[i]); + if (idx < 0) idx = -idx - 1; + dp.set(idx, nums[i]); } return LIS; @@ -393,15 +393,15 @@ public: int LIS = 1; for (int i = 1; i < n; i++) { - if (dp.back() < nums[i]) { + if (dp.back() < nums[i]) { dp.push_back(nums[i]); LIS++; continue; } - int idx = lower_bound(dp.begin(), + int idx = lower_bound(dp.begin(), dp.end(), nums[i]) - dp.begin(); - dp[idx] = nums[i]; + dp[idx] = nums[i]; } return LIS; @@ -418,19 +418,20 @@ class Solution { maxEnvelopes(envelopes) { const n = envelopes.length; envelopes.sort((a, b) => a[0] - b[0] || b[1] - a[1]); - const nums = envelopes.map(e => e[1]); + const nums = envelopes.map((e) => e[1]); const dp = []; dp.push(nums[0]); let LIS = 1; for (let i = 1; i < n; i++) { - if (dp[dp.length - 1] < nums[i]) { + if (dp[dp.length - 1] < nums[i]) { dp.push(nums[i]); LIS++; continue; } - let left = 0, right = dp.length - 1; + let left = 0, + right = dp.length - 1; while (left < right) { const mid = Math.floor((left + right) / 2); if (dp[mid] < nums[i]) { @@ -439,7 +440,7 @@ class Solution { right = mid; } } - dp[left] = nums[i]; + dp[left] = nums[i]; } return LIS; @@ -462,15 +463,15 @@ public class Solution { int LIS = 1; for (int i = 1; i < n; i++) { - if (dp[dp.Count - 1] < nums[i]) { + if (dp[dp.Count - 1] < nums[i]) { dp.Add(nums[i]); LIS++; continue; } int idx = dp.BinarySearch(nums[i]); - if (idx < 0) idx = ~idx; - dp[idx] = nums[i]; + if (idx < 0) idx = ~idx; + dp[idx] = nums[i]; } return LIS; @@ -482,8 +483,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -535,7 +536,7 @@ class Solution: for num in arr: order.append(bisect_left(sortedArr, num)) return order - + nums = compress(nums) n = len(nums) segTree = SegmentTree(n) @@ -611,7 +612,7 @@ public class Solution { segTree.update(num, curLIS); LIS = Math.max(LIS, curLIS); } - return LIS; + return LIS; } public int maxEnvelopes(int[][] envelopes) { @@ -677,7 +678,7 @@ class Solution { int lis(vector& nums) { vector sortedArr = nums; sort(sortedArr.begin(), sortedArr.end()); - sortedArr.erase(unique(sortedArr.begin(), + sortedArr.erase(unique(sortedArr.begin(), sortedArr.end()), sortedArr.end()); vector order(nums.size()); @@ -731,7 +732,7 @@ class SegmentTree { this.tree[this.n + i] = val; let j = (this.n + i) >> 1; while (j >= 1) { - this.tree[j] = Math.max(this.tree[j << 1], this.tree[j << 1 | 1]); + this.tree[j] = Math.max(this.tree[j << 1], this.tree[(j << 1) | 1]); j >>= 1; } } @@ -771,17 +772,17 @@ class Solution { */ maxEnvelopes(envelopes) { envelopes.sort((a, b) => a[0] - b[0] || b[1] - a[1]); - const heights = envelopes.map(e => e[1]); - + const heights = envelopes.map((e) => e[1]); + const lis = (nums) => { const sortedArr = Array.from(new Set(nums)).sort((a, b) => a - b); const map = new Map(); - + sortedArr.forEach((num, index) => { map.set(num, index); }); - - const order = nums.map(num => map.get(num)); + + const order = nums.map((num) => map.get(num)); const n = sortedArr.length; const segTree = new SegmentTree(n, order); @@ -845,14 +846,14 @@ public class Solution { public int Lis(int[] nums) { var sortedArr = nums.Distinct().OrderBy(x => x).ToArray(); var map = new Dictionary(); - + for (int i = 0; i < sortedArr.Length; i++) { map[sortedArr[i]] = i; } - + int n = sortedArr.Length; var segTree = new SegmentTree(n); - + int LIS = 0; foreach (var num in nums) { int compressedIndex = map[num]; @@ -879,5 +880,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ diff --git a/articles/same-binary-tree.md b/articles/same-binary-tree.md index b07d14e35..84877698c 100644 --- a/articles/same-binary-tree.md +++ b/articles/same-binary-tree.md @@ -220,10 +220,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ - * Best Case ([balanced tree](https://www.geeksforgeeks.org/balanced-binary-tree/)): $O(log(n))$ - * Worst Case ([degenerate tree](https://www.geeksforgeeks.org/introduction-to-degenerate-binary-tree/)): $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ + - Best Case ([balanced tree](https://www.geeksforgeeks.org/balanced-binary-tree/)): $O(log(n))$ + - Worst Case ([degenerate tree](https://www.geeksforgeeks.org/introduction-to-degenerate-binary-tree/)): $O(n)$ > Where $n$ is the number of nodes in the tree and $h$ is the height of the tree. @@ -244,18 +244,18 @@ class Solution { class Solution: def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: stack = [(p, q)] - + while stack: node1, node2 = stack.pop() - + if not node1 and not node2: continue if not node1 or not node2 or node1.val != node2.val: return False - + stack.append((node1.right, node2.right)) stack.append((node1.left, node2.left)) - + return True ``` @@ -280,11 +280,11 @@ public class Solution { public boolean isSameTree(TreeNode p, TreeNode q) { Stack stack = new Stack<>(); stack.push(new TreeNode[]{p, q}); - + while (!stack.isEmpty()) { TreeNode[] nodes = stack.pop(); TreeNode node1 = nodes[0], node2 = nodes[1]; - + if (node1 == null && node2 == null) continue; if (node1 == null || node2 == null || node1.val != node2.val) { return false; @@ -292,7 +292,7 @@ public class Solution { stack.push(new TreeNode[]{node1.right, node2.right}); stack.push(new TreeNode[]{node1.left, node2.left}); } - + return true; } } @@ -316,18 +316,18 @@ public: bool isSameTree(TreeNode* p, TreeNode* q) { stack> stk; stk.push({p, q}); - + while (!stk.empty()) { auto [node1, node2] = stk.top(); stk.pop(); - + if (!node1 && !node2) continue; if (!node1 || !node2 || node1->val != node2->val) return false; - + stk.push({node1->right, node2->right}); stk.push({node1->left, node2->left}); } - + return true; } }; @@ -353,10 +353,10 @@ class Solution { */ isSameTree(p, q) { const stack = [[p, q]]; - + while (stack.length) { const [node1, node2] = stack.pop(); - + if (!node1 && !node2) continue; if (!node1 || !node2 || node1.val !== node2.val) { return false; @@ -364,7 +364,7 @@ class Solution { stack.push([node1.right, node2.right]); stack.push([node1.left, node2.left]); } - + return true; } } @@ -389,10 +389,10 @@ public class Solution { public bool IsSameTree(TreeNode p, TreeNode q) { var stack = new Stack<(TreeNode, TreeNode)>(); stack.Push((p, q)); - + while (stack.Count > 0) { var (node1, node2) = stack.Pop(); - + if (node1 == null && node2 == null) continue; if (node1 == null || node2 == null || node1.val != node2.val) { return false; @@ -400,7 +400,7 @@ public class Solution { stack.Push((node1.right, node2.right)); stack.Push((node1.left, node2.left)); } - + return true; } } @@ -419,25 +419,25 @@ func isSameTree(p *TreeNode, q *TreeNode) bool { type Pair struct { first, second *TreeNode } - + stack := []Pair{{p, q}} - + for len(stack) > 0 { lastIdx := len(stack) - 1 node1, node2 := stack[lastIdx].first, stack[lastIdx].second stack = stack[:lastIdx] - + if node1 == nil && node2 == nil { continue } if node1 == nil || node2 == nil || node1.Val != node2.Val { return false } - + stack = append(stack, Pair{node1.Right, node2.Right}) stack = append(stack, Pair{node1.Left, node2.Left}) } - + return true } ``` @@ -457,10 +457,10 @@ class Solution { fun isSameTree(p: TreeNode?, q: TreeNode?): Boolean { val stack = ArrayDeque>() stack.addLast(Pair(p, q)) - + while (stack.isNotEmpty()) { val (node1, node2) = stack.removeLast() - + if (node1 == null && node2 == null) continue if (node1 == null || node2 == null || node1.`val` != node2.`val`) { return false @@ -468,7 +468,7 @@ class Solution { stack.addLast(Pair(node1.right, node2.right)) stack.addLast(Pair(node1.left, node2.left)) } - + return true } } @@ -517,8 +517,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -554,7 +554,7 @@ class Solution: q2.append(nodeQ.left) q2.append(nodeQ.right) - return True + return True ``` ```java @@ -629,7 +629,7 @@ public: TreeNode* nodeQ = q2.front(); q2.pop(); if (!nodeP && !nodeQ) continue; - if (!nodeP || !nodeQ || nodeP->val != nodeQ->val) + if (!nodeP || !nodeQ || nodeP->val != nodeQ->val) return false; q1.push(nodeP->left); @@ -667,17 +667,21 @@ class Solution { const q2 = new Queue(); q1.push(p); q2.push(q); - + while (!q1.isEmpty() && !q2.isEmpty()) { for (let i = q1.size(); i > 0; i--) { let nodeP = q1.pop(); let nodeQ = q2.pop(); if (nodeP === null && nodeQ === null) continue; - if (nodeP === null || nodeQ === null || nodeP.val !== nodeQ.val) { + if ( + nodeP === null || + nodeQ === null || + nodeP.val !== nodeQ.val + ) { return false; } - + q1.push(nodeP.left); q1.push(nodeP.right); q2.push(nodeQ.left); @@ -860,5 +864,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/score-after-flipping-matrix.md b/articles/score-after-flipping-matrix.md index 83c222266..2136f3a3c 100644 --- a/articles/score-after-flipping-matrix.md +++ b/articles/score-after-flipping-matrix.md @@ -108,7 +108,8 @@ class Solution { * @return {number} */ matrixScore(grid) { - let ROWS = grid.length, COLS = grid[0].length; + let ROWS = grid.length, + COLS = grid[0].length; for (let r = 0; r < ROWS; r++) { if (grid[r][0] === 0) { @@ -146,8 +147,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(m * n)$ +- Space complexity: $O(1)$ extra space. > Where $m$ is the number of rows and $n$ is the number of columns. @@ -225,7 +226,8 @@ class Solution { * @return {number} */ matrixScore(grid) { - const ROWS = grid.length, COLS = grid[0].length; + const ROWS = grid.length, + COLS = grid[0].length; let res = ROWS * (1 << (COLS - 1)); for (let c = 1; c < COLS; c++) { @@ -247,7 +249,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(m * n)$ +- Space complexity: $O(1)$ extra space. -> Where $m$ is the number of rows and $n$ is the number of columns. \ No newline at end of file +> Where $m$ is the number of rows and $n$ is the number of columns. diff --git a/articles/score-of-a-string.md b/articles/score-of-a-string.md index 9a5bf9bdf..925bc174a 100644 --- a/articles/score-of-a-string.md +++ b/articles/score-of-a-string.md @@ -56,5 +56,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/search-2d-matrix.md b/articles/search-2d-matrix.md index 45181e5df..7a9c1baf4 100644 --- a/articles/search-2d-matrix.md +++ b/articles/search-2d-matrix.md @@ -125,8 +125,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(1)$ > Where $m$ is the number of rows and $n$ is the number of columns of matrix. @@ -201,8 +201,10 @@ class Solution { * @return {boolean} */ searchMatrix(matrix, target) { - const m = matrix.length, n = matrix[0].length; - let r = 0, c = n - 1; + const m = matrix.length, + n = matrix[0].length; + let r = 0, + c = n - 1; while (r < m && c >= 0) { if (matrix[r][c] > target) { @@ -303,8 +305,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(m + n)$ +- Space complexity: $O(1)$ > Where $m$ is the number of rows and $n$ is the number of columns of matrix. @@ -624,8 +626,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log m + \log n)$ (which reduces to $O(\log(m * n))$) -* Space complexity: $O(1)$ +- Time complexity: $O(\log m + \log n)$ (which reduces to $O(\log(m * n))$) +- Space complexity: $O(1)$ > Where $m$ is the number of rows and $n$ is the number of columns of matrix. @@ -706,12 +708,15 @@ class Solution { * @return {boolean} */ searchMatrix(matrix, target) { - let ROWS = matrix.length, COLS = matrix[0].length; + let ROWS = matrix.length, + COLS = matrix[0].length; - let l = 0, r = ROWS * COLS - 1; + let l = 0, + r = ROWS * COLS - 1; while (l <= r) { let m = l + Math.floor((r - l) / 2); - let row = Math.floor(m / COLS), col = m % COLS; + let row = Math.floor(m / COLS), + col = m % COLS; if (target > matrix[row][col]) { l = m + 1; } else if (target < matrix[row][col]) { @@ -821,7 +826,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log(m * n))$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log(m * n))$ +- Space complexity: $O(1)$ -> Where $m$ is the number of rows and $n$ is the number of columns of matrix. \ No newline at end of file +> Where $m$ is the number of rows and $n$ is the number of columns of matrix. diff --git a/articles/search-for-word-ii.md b/articles/search-for-word-ii.md index 519307f04..9451914a1 100644 --- a/articles/search-for-word-ii.md +++ b/articles/search-for-word-ii.md @@ -11,7 +11,7 @@ class Solution: def backtrack(r, c, i): if i == len(word): return True - if (r < 0 or c < 0 or r >= ROWS or + if (r < 0 or c < 0 or r >= ROWS or c >= COLS or board[r][c] != word[i] ): return False @@ -63,7 +63,7 @@ public class Solution { private boolean backtrack(char[][] board, int r, int c, String word, int i) { if (i == word.length()) return true; - if (r < 0 || c < 0 || r >= board.length || + if (r < 0 || c < 0 || r >= board.length || c >= board[0].length || board[r][c] != word.charAt(i)) return false; @@ -104,7 +104,7 @@ public: private: bool backtrack(vector>& board, int r, int c, string& word, int i) { if (i == word.length()) return true; - if (r < 0 || c < 0 || r >= board.size() || + if (r < 0 || c < 0 || r >= board.size() || c >= board[0].size() || board[r][c] != word[i]) return false; @@ -127,20 +127,28 @@ class Solution { * @return {string[]} */ findWords(board, words) { - const ROWS = board.length, COLS = board[0].length; + const ROWS = board.length, + COLS = board[0].length; const res = []; const backtrack = (r, c, word, i) => { if (i === word.length) return true; - if (r < 0 || c < 0 || r >= ROWS || - c >= COLS || board[r][c] !== word[i]) return false; + if ( + r < 0 || + c < 0 || + r >= ROWS || + c >= COLS || + board[r][c] !== word[i] + ) + return false; const temp = board[r][c]; board[r][c] = '*'; - const ret = backtrack(r + 1, c, word, i + 1) || - backtrack(r - 1, c, word, i + 1) || - backtrack(r, c + 1, word, i + 1) || - backtrack(r, c - 1, word, i + 1); + const ret = + backtrack(r + 1, c, word, i + 1) || + backtrack(r - 1, c, word, i + 1) || + backtrack(r, c + 1, word, i + 1) || + backtrack(r, c - 1, word, i + 1); board[r][c] = temp; return ret; }; @@ -188,7 +196,7 @@ public class Solution { private bool Backtrack(char[][] board, int r, int c, string word, int i) { if (i == word.Length) return true; - if (r < 0 || c < 0 || r >= board.Length || + if (r < 0 || c < 0 || r >= board.Length || c >= board[0].Length || board[r][c] != word[i]) return false; @@ -333,10 +341,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n * 4 ^ t + s)$ -* Space complexity: $O(t)$ +- Time complexity: $O(m * n * 4 ^ t + s)$ +- Space complexity: $O(t)$ -> Where $m$ is the number of rows, $n$ is the number of columns, $t$ is the maximum length of any word in the array $words$ and $s$ is the sum of the lengths of all the words. +> Where $m$ is the number of rows, $n$ is the number of columns, $t$ is the maximum length of any word in the array $words$ and $s$ is the sum of the lengths of all the words. --- @@ -368,8 +376,8 @@ class Solution: res, visit = set(), set() def dfs(r, c, node, word): - if (r < 0 or c < 0 or r >= ROWS or - c >= COLS or (r, c) in visit or + if (r < 0 or c < 0 or r >= ROWS or + c >= COLS or (r, c) in visit or board[r][c] not in node.children ): return @@ -416,7 +424,7 @@ class TrieNode { public class Solution { private Set res; private boolean[][] visit; - + public List findWords(char[][] board, String[] words) { TrieNode root = new TrieNode(); for (String word : words) { @@ -437,8 +445,8 @@ public class Solution { private void dfs(char[][] board, int r, int c, TrieNode node, String word) { int ROWS = board.length, COLS = board[0].length; - if (r < 0 || c < 0 || r >= ROWS || - c >= COLS || visit[r][c] || + if (r < 0 || c < 0 || r >= ROWS || + c >= COLS || visit[r][c] || !node.children.containsKey(board[r][c])) { return; } @@ -504,8 +512,8 @@ public: private: void dfs(vector>& board, int r, int c, TrieNode* node, string word) { int ROWS = board.size(), COLS = board[0].size(); - if (r < 0 || c < 0 || r >= ROWS || - c >= COLS || visit[r][c] || + if (r < 0 || c < 0 || r >= ROWS || + c >= COLS || visit[r][c] || !node->children.count(board[r][c])) { return; } @@ -562,13 +570,20 @@ class Solution { root.addWord(word); } - const ROWS = board.length, COLS = board[0].length; - const res = new Set(), visit = new Set(); + const ROWS = board.length, + COLS = board[0].length; + const res = new Set(), + visit = new Set(); const dfs = (r, c, node, word) => { - if (r < 0 || c < 0 || r >= ROWS || - c >= COLS || visit.has(`${r},${c}`) || - !(board[r][c] in node.children)) { + if ( + r < 0 || + c < 0 || + r >= ROWS || + c >= COLS || + visit.has(`${r},${c}`) || + !(board[r][c] in node.children) + ) { return; } @@ -589,7 +604,7 @@ class Solution { for (let r = 0; r < ROWS; r++) { for (let c = 0; c < COLS; c++) { - dfs(r, c, root, ""); + dfs(r, c, root, ''); } } @@ -637,8 +652,8 @@ public class Solution { private void Dfs(char[][] board, int r, int c, TrieNode node, string word) { int ROWS = board.Length, COLS = board[0].Length; - if (r < 0 || c < 0 || r >= ROWS || - c >= COLS || visit[r, c] || + if (r < 0 || c < 0 || r >= ROWS || + c >= COLS || visit[r, c] || !node.Children.ContainsKey(board[r][c])) { return; } @@ -759,7 +774,7 @@ class Solution { val visit = HashSet>() fun dfs(r: Int, c: Int, node: TrieNode, word: String) { - if (r < 0 || c < 0 || r >= rows || c >= cols || + if (r < 0 || c < 0 || r >= rows || c >= cols || (r to c) in visit || board[r][c] !in node.children) { return } @@ -794,7 +809,7 @@ class Solution { class TrieNode { var children: [Character: TrieNode] = [:] var isWord: Bool = false - + func addWord(_ word: String) { var current = self for char in word { @@ -813,40 +828,40 @@ class Solution { for word in words { root.addWord(word) } - + let ROWS = board.count let COLS = board[0].count var result = Set() var visited = Set<[Int]>() - + func dfs(_ r: Int, _ c: Int, _ node: TrieNode, _ word: String) { - if r < 0 || c < 0 || r >= ROWS || c >= COLS || + if r < 0 || c < 0 || r >= ROWS || c >= COLS || visited.contains([r, c]) || node.children[board[r][c]] == nil { return } - + visited.insert([r, c]) let nextNode = node.children[board[r][c]]! let newWord = word + String(board[r][c]) - + if nextNode.isWord { result.insert(newWord) } - + dfs(r + 1, c, nextNode, newWord) dfs(r - 1, c, nextNode, newWord) dfs(r, c + 1, nextNode, newWord) dfs(r, c - 1, nextNode, newWord) - + visited.remove([r, c]) } - + for r in 0.. Where $m$ is the number of rows, $n$ is the number of columns, $t$ is the maximum length of any word in the array $words$ and $s$ is the sum of the lengths of all the words. +> Where $m$ is the number of rows, $n$ is the number of columns, $t$ is the maximum length of any word in the array $words$ and $s$ is the sum of the lengths of all the words. --- @@ -899,11 +914,11 @@ class Solution: return index def dfs(r, c, node): - if (r < 0 or c < 0 or r >= ROWS or - c >= COLS or board[r][c] == '*' or + if (r < 0 or c < 0 or r >= ROWS or + c >= COLS or board[r][c] == '*' or not node.children[getIndex(board[r][c])]): return - + tmp = board[r][c] board[r][c] = '*' prev = node @@ -972,8 +987,8 @@ public class Solution { } private void dfs(char[][] board, TrieNode node, int r, int c, String[] words) { - if (r < 0 || c < 0 || r >= board.length || - c >= board[0].length || board[r][c] == '*' || + if (r < 0 || c < 0 || r >= board.length || + c >= board[0].length || board[r][c] == '*' || node.children[board[r][c] - 'a'] == null) { return; } @@ -1054,8 +1069,8 @@ public: } void dfs(auto& board, TrieNode* node, int r, int c, auto& words) { - if (r < 0 || c < 0 || r >= board.size() || - c >= board[0].size() || board[r][c] == '*' || + if (r < 0 || c < 0 || r >= board.size() || + c >= board[0].size() || board[r][c] == '*' || !node->children[board[r][c] - 'a']) { return; } @@ -1093,7 +1108,7 @@ class TrieNode { this.idx = -1; this.refs = 0; } - + /** * @param {string} word * @param {number} i @@ -1126,16 +1141,22 @@ class Solution { root.addWord(words[i], i); } - const ROWS = board.length, COLS = board[0].length; + const ROWS = board.length, + COLS = board[0].length; const res = []; const dfs = (r, c, node) => { - if (r < 0 || c < 0 || r >= ROWS || - c >= COLS || board[r][c] === '*' || - node.children[this.getId(board[r][c])] === null) { + if ( + r < 0 || + c < 0 || + r >= ROWS || + c >= COLS || + board[r][c] === '*' || + node.children[this.getId(board[r][c])] === null + ) { return; } - + let tmp = board[r][c]; board[r][c] = '*'; let prev = node; @@ -1148,7 +1169,7 @@ class Solution { prev.children[this.getId(tmp)] = null; node = null; board[r][c] = tmp; - return ; + return; } } @@ -1156,7 +1177,7 @@ class Solution { dfs(r - 1, c, node); dfs(r, c + 1, node); dfs(r, c - 1, node); - + board[r][c] = tmp; }; @@ -1219,8 +1240,8 @@ public class Solution { } private void Dfs(char[][] board, TrieNode node, int r, int c, string[] words) { - if (r < 0 || c < 0 || r >= board.Length || - c >= board[0].Length || board[r][c] == '*' || + if (r < 0 || c < 0 || r >= board.Length || + c >= board[0].Length || board[r][c] == '*' || node.children[board[r][c] - 'a'] == null) { return; } @@ -1289,7 +1310,7 @@ func findWords(board [][]byte, words []string) []string { var dfs func(r, c int, node *TrieNode) dfs = func(r, c int, node *TrieNode) { - if r < 0 || c < 0 || r >= rows || c >= cols || + if r < 0 || c < 0 || r >= rows || c >= cols || board[r][c] == '*' || node.children[getIndex(board[r][c])] == nil { return } @@ -1360,7 +1381,7 @@ class Solution { fun getIndex(c: Char): Int = c - 'a' fun dfs(r: Int, c: Int, node: TrieNode?) { - if (r < 0 || c < 0 || r >= rows || c >= cols || board[r][c] == '*' || + if (r < 0 || c < 0 || r >= rows || c >= cols || board[r][c] == '*' || node?.children?.get(getIndex(board[r][c])) == null) { return } @@ -1405,7 +1426,7 @@ class TrieNode { var children: [TrieNode?] = Array(repeating: nil, count: 26) var idx: Int = -1 var refs: Int = 0 - + func addWord(_ word: String, _ i: Int) { var cur = self cur.refs += 1 @@ -1427,28 +1448,28 @@ class Solution { for i in 0.. Int { return Int(c.asciiValue! - Character("a").asciiValue!) } - + func dfs(_ r: Int, _ c: Int, _ node: TrieNode) { - if r < 0 || c < 0 || r >= ROWS || c >= COLS || - boardCopy[r][c] == "*" || + if r < 0 || c < 0 || r >= ROWS || c >= COLS || + boardCopy[r][c] == "*" || node.children[getIndex(boardCopy[r][c])] == nil { return } - + let tmp = boardCopy[r][c] boardCopy[r][c] = "*" let prev = node let nextNode = node.children[getIndex(tmp)]! - + if nextNode.idx != -1 { res.append(words[nextNode.idx]) nextNode.idx = -1 @@ -1459,21 +1480,21 @@ class Solution { return } } - + dfs(r + 1, c, nextNode) dfs(r - 1, c, nextNode) dfs(r, c + 1, nextNode) dfs(r, c - 1, nextNode) - + boardCopy[r][c] = tmp } - + for r in 0.. Where $m$ is the number of rows, $n$ is the number of columns, $t$ is the maximum length of any word in the array $words$ and $s$ is the sum of the lengths of all the words. \ No newline at end of file +> Where $m$ is the number of rows, $n$ is the number of columns, $t$ is the maximum length of any word in the array $words$ and $s$ is the sum of the lengths of all the words. diff --git a/articles/search-for-word.md b/articles/search-for-word.md index bb2895568..d0c1b0f6c 100644 --- a/articles/search-for-word.md +++ b/articles/search-for-word.md @@ -11,13 +11,13 @@ class Solution: def dfs(r, c, i): if i == len(word): return True - + if (min(r, c) < 0 or r >= ROWS or c >= COLS or word[i] != board[r][c] or (r, c) in path): return False - + path.add((r, c)) res = (dfs(r + 1, c, i + 1) or dfs(r - 1, c, i + 1) or @@ -25,7 +25,7 @@ class Solution: dfs(r, c - 1, i + 1)) path.remove((r, c)) return res - + for r in range(ROWS): for c in range(COLS): if dfs(r, c, 0): @@ -57,16 +57,16 @@ public class Solution { return true; } - if (r < 0 || c < 0 || r >= ROWS || c >= COLS || - board[r][c] != word.charAt(i) || + if (r < 0 || c < 0 || r >= ROWS || c >= COLS || + board[r][c] != word.charAt(i) || path.contains(new Pair<>(r, c))) { return false; } path.add(new Pair<>(r, c)); - boolean res = dfs(board, word, r + 1, c, i + 1) || + boolean res = dfs(board, word, r + 1, c, i + 1) || dfs(board, word, r - 1, c, i + 1) || - dfs(board, word, r, c + 1, i + 1) || + dfs(board, word, r, c + 1, i + 1) || dfs(board, word, r, c - 1, i + 1); path.remove(new Pair<>(r, c)); @@ -100,15 +100,15 @@ public: return true; } - if (r < 0 || c < 0 || r >= ROWS || c >= COLS || + if (r < 0 || c < 0 || r >= ROWS || c >= COLS || board[r][c] != word[i] || path.count({r, c})) { return false; } path.insert({r, c}); - bool res = dfs(board, word, r + 1, c, i + 1) || + bool res = dfs(board, word, r + 1, c, i + 1) || dfs(board, word, r - 1, c, i + 1) || - dfs(board, word, r, c + 1, i + 1) || + dfs(board, word, r, c + 1, i + 1) || dfs(board, word, r, c - 1, i + 1); path.erase({r, c}); @@ -131,16 +131,23 @@ class Solution { const dfs = (r, c, i) => { if (i === word.length) return true; - if (r < 0 || c < 0 || r >= ROWS || c >= COLS || - board[r][c] !== word[i] || path.has(`${r},${c}`)) { + if ( + r < 0 || + c < 0 || + r >= ROWS || + c >= COLS || + board[r][c] !== word[i] || + path.has(`${r},${c}`) + ) { return false; } path.add(`${r},${c}`); - const res = dfs(r + 1, c, i + 1) || - dfs(r - 1, c, i + 1) || - dfs(r, c + 1, i + 1) || - dfs(r, c - 1, i + 1); + const res = + dfs(r + 1, c, i + 1) || + dfs(r - 1, c, i + 1) || + dfs(r, c + 1, i + 1) || + dfs(r, c - 1, i + 1); path.delete(`${r},${c}`); return res; }; @@ -179,15 +186,15 @@ public class Solution { return true; } - if (r < 0 || c < 0 || r >= ROWS || c >= COLS || + if (r < 0 || c < 0 || r >= ROWS || c >= COLS || board[r][c] != word[i] || path.Contains((r, c))) { return false; } path.Add((r, c)); - bool res = DFS(board, word, r + 1, c, i + 1) || + bool res = DFS(board, word, r + 1, c, i + 1) || DFS(board, word, r - 1, c, i + 1) || - DFS(board, word, r, c + 1, i + 1) || + DFS(board, word, r, c + 1, i + 1) || DFS(board, word, r, c - 1, i + 1); path.Remove((r, c)); @@ -206,15 +213,15 @@ func exist(board [][]byte, word string) bool { if i == len(word) { return true } - if r < 0 || c < 0 || r >= rows || c >= cols || + if r < 0 || c < 0 || r >= rows || c >= cols || board[r][c] != word[i] || path[[2]int{r, c}] { return false } path[[2]int{r, c}] = true - res := dfs(r+1, c, i+1) || - dfs(r-1, c, i+1) || - dfs(r, c+1, i+1) || + res := dfs(r+1, c, i+1) || + dfs(r-1, c, i+1) || + dfs(r, c+1, i+1) || dfs(r, c-1, i+1) delete(path, [2]int{r, c}) @@ -241,7 +248,7 @@ class Solution { fun dfs(r: Int, c: Int, i: Int): Boolean { if (i == word.length) return true - if (r < 0 || c < 0 || r >= rows || c >= cols || + if (r < 0 || c < 0 || r >= rows || c >= cols || board[r][c] != word[i] || Pair(r, c) in path) { return false } @@ -310,8 +317,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * 4 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(m * 4 ^ n)$ +- Space complexity: $O(n)$ > Where $m$ is the number of cells in the $board$ and $n$ is the length of the $word$. @@ -374,15 +381,15 @@ public class Solution { return true; } - if (r < 0 || c < 0 || r >= ROWS || c >= COLS || + if (r < 0 || c < 0 || r >= ROWS || c >= COLS || board[r][c] != word.charAt(i) || visited[r][c]) { return false; } visited[r][c] = true; - boolean res = dfs(board, word, r + 1, c, i + 1) || + boolean res = dfs(board, word, r + 1, c, i + 1) || dfs(board, word, r - 1, c, i + 1) || - dfs(board, word, r, c + 1, i + 1) || + dfs(board, word, r, c + 1, i + 1) || dfs(board, word, r, c - 1, i + 1); visited[r][c] = false; @@ -417,15 +424,15 @@ public: return true; } - if (r < 0 || c < 0 || r >= ROWS || c >= COLS || + if (r < 0 || c < 0 || r >= ROWS || c >= COLS || board[r][c] != word[i] || visited[r][c]) { return false; } visited[r][c] = true; - bool res = dfs(board, word, r + 1, c, i + 1) || + bool res = dfs(board, word, r + 1, c, i + 1) || dfs(board, word, r - 1, c, i + 1) || - dfs(board, word, r, c + 1, i + 1) || + dfs(board, word, r, c + 1, i + 1) || dfs(board, word, r, c - 1, i + 1); visited[r][c] = false; @@ -444,20 +451,29 @@ class Solution { exist(board, word) { const ROWS = board.length; const COLS = board[0].length; - const visited = Array.from({ length: ROWS }, () => Array(COLS).fill(false)); + const visited = Array.from({ length: ROWS }, () => + Array(COLS).fill(false), + ); const dfs = (r, c, i) => { if (i === word.length) return true; - if (r < 0 || c < 0 || r >= ROWS || c >= COLS || - board[r][c] !== word[i] || visited[r][c]) { + if ( + r < 0 || + c < 0 || + r >= ROWS || + c >= COLS || + board[r][c] !== word[i] || + visited[r][c] + ) { return false; } visited[r][c] = true; - const res = dfs(r + 1, c, i + 1) || - dfs(r - 1, c, i + 1) || - dfs(r, c + 1, i + 1) || - dfs(r, c - 1, i + 1); + const res = + dfs(r + 1, c, i + 1) || + dfs(r - 1, c, i + 1) || + dfs(r, c + 1, i + 1) || + dfs(r, c - 1, i + 1); visited[r][c] = false; return res; }; @@ -497,15 +513,15 @@ public class Solution { return true; } - if (r < 0 || c < 0 || r >= ROWS || c >= COLS || + if (r < 0 || c < 0 || r >= ROWS || c >= COLS || board[r][c] != word[i] || visited[r, c]) { return false; } visited[r, c] = true; - bool res = DFS(board, word, r + 1, c, i + 1) || + bool res = DFS(board, word, r + 1, c, i + 1) || DFS(board, word, r - 1, c, i + 1) || - DFS(board, word, r, c + 1, i + 1) || + DFS(board, word, r, c + 1, i + 1) || DFS(board, word, r, c - 1, i + 1); visited[r, c] = false; @@ -527,15 +543,15 @@ func exist(board [][]byte, word string) bool { if i == len(word) { return true } - if r < 0 || c < 0 || r >= rows || c >= cols || + if r < 0 || c < 0 || r >= rows || c >= cols || board[r][c] != word[i] || visited[r][c] { return false } visited[r][c] = true - res := dfs(r+1, c, i+1) || - dfs(r-1, c, i+1) || - dfs(r, c+1, i+1) || + res := dfs(r+1, c, i+1) || + dfs(r-1, c, i+1) || + dfs(r, c+1, i+1) || dfs(r, c-1, i+1) visited[r][c] = false @@ -562,15 +578,15 @@ class Solution { fun dfs(r: Int, c: Int, i: Int): Boolean { if (i == word.length) return true - if (r < 0 || c < 0 || r >= rows || c >= cols || + if (r < 0 || c < 0 || r >= rows || c >= cols || board[r][c] != word[i] || visited[r][c]) { return false } visited[r][c] = true - val res = dfs(r + 1, c, i + 1) || + val res = dfs(r + 1, c, i + 1) || dfs(r - 1, c, i + 1) || - dfs(r, c + 1, i + 1) || + dfs(r, c + 1, i + 1) || dfs(r, c - 1, i + 1) visited[r][c] = false @@ -631,8 +647,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * 4 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(m * 4 ^ n)$ +- Space complexity: $O(n)$ > Where $m$ is the number of cells in the $board$ and $n$ is the length of the $word$. @@ -691,7 +707,7 @@ public class Solution { if (i == word.length()) { return true; } - if (r < 0 || c < 0 || r >= ROWS || c >= COLS || + if (r < 0 || c < 0 || r >= ROWS || c >= COLS || board[r][c] != word.charAt(i) || board[r][c] == '#') { return false; } @@ -730,7 +746,7 @@ public: if (i == word.size()) { return true; } - if (r < 0 || c < 0 || r >= ROWS || c >= COLS || + if (r < 0 || c < 0 || r >= ROWS || c >= COLS || board[r][c] != word[i] || board[r][c] == '#') { return false; } @@ -759,16 +775,23 @@ class Solution { const dfs = (r, c, i) => { if (i === word.length) return true; - if (r < 0 || c < 0 || r >= ROWS || c >= COLS || - board[r][c] !== word[i] || board[r][c] === '#') { + if ( + r < 0 || + c < 0 || + r >= ROWS || + c >= COLS || + board[r][c] !== word[i] || + board[r][c] === '#' + ) { return false; } board[r][c] = '#'; - const res = dfs(r + 1, c, i + 1) || - dfs(r - 1, c, i + 1) || - dfs(r, c + 1, i + 1) || - dfs(r, c - 1, i + 1); + const res = + dfs(r + 1, c, i + 1) || + dfs(r - 1, c, i + 1) || + dfs(r, c + 1, i + 1) || + dfs(r, c - 1, i + 1); board[r][c] = word[i]; return res; }; @@ -805,7 +828,7 @@ public class Solution { if (i == word.Length) { return true; } - if (r < 0 || c < 0 || r >= ROWS || c >= COLS || + if (r < 0 || c < 0 || r >= ROWS || c >= COLS || board[r][c] != word[i] || board[r][c] == '#') { return false; } @@ -830,16 +853,16 @@ func exist(board [][]byte, word string) bool { if i == len(word) { return true } - if r < 0 || c < 0 || r >= rows || c >= cols || + if r < 0 || c < 0 || r >= rows || c >= cols || board[r][c] != word[i] || board[r][c] == '#' { return false } temp := board[r][c] board[r][c] = '#' - res := dfs(r+1, c, i+1) || - dfs(r-1, c, i+1) || - dfs(r, c+1, i+1) || + res := dfs(r+1, c, i+1) || + dfs(r-1, c, i+1) || + dfs(r, c+1, i+1) || dfs(r, c-1, i+1) board[r][c] = temp @@ -865,16 +888,16 @@ class Solution { fun dfs(r: Int, c: Int, i: Int): Boolean { if (i == word.length) return true - if (r < 0 || c < 0 || r >= rows || c >= cols || + if (r < 0 || c < 0 || r >= rows || c >= cols || board[r][c] != word[i] || board[r][c] == '#') { return false } val temp = board[r][c] board[r][c] = '#' - val res = dfs(r + 1, c, i + 1) || + val res = dfs(r + 1, c, i + 1) || dfs(r - 1, c, i + 1) || - dfs(r, c + 1, i + 1) || + dfs(r, c + 1, i + 1) || dfs(r, c - 1, i + 1) board[r][c] = temp @@ -936,7 +959,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * 4 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(m * 4 ^ n)$ +- Space complexity: $O(n)$ -> Where $m$ is the number of cells in the $board$ and $n$ is the length of the $word$. \ No newline at end of file +> Where $m$ is the number of cells in the $board$ and $n$ is the length of the $word$. diff --git a/articles/search-in-a-binary-search-tree.md b/articles/search-in-a-binary-search-tree.md index 548c56821..b60dc3de6 100644 --- a/articles/search-in-a-binary-search-tree.md +++ b/articles/search-in-a-binary-search-tree.md @@ -86,7 +86,9 @@ class Solution { if (!root || root.val === val) { return root; } - return val < root.val ? this.searchBST(root.left, val) : this.searchBST(root.right, val); + return val < root.val + ? this.searchBST(root.left, val) + : this.searchBST(root.right, val); } } ``` @@ -95,8 +97,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(H)$ -* Space complexity: $O(H)$ for recursion stack. +- Time complexity: $O(H)$ +- Space complexity: $O(H)$ for recursion stack. > Where $H$ is the height of the given tree. @@ -199,7 +201,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(H)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(H)$ +- Space complexity: $O(1)$ extra space. -> Where $H$ is the height of the given tree. \ No newline at end of file +> Where $H$ is the height of the given tree. diff --git a/articles/search-in-rotated-sorted-array-ii.md b/articles/search-in-rotated-sorted-array-ii.md index 04af02db0..507bd0a81 100644 --- a/articles/search-in-rotated-sorted-array-ii.md +++ b/articles/search-in-rotated-sorted-array-ii.md @@ -65,8 +65,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -176,7 +176,8 @@ class Solution { * @return {boolean} */ search(nums, target) { - let l = 0, r = nums.length - 1; + let l = 0, + r = nums.length - 1; while (l <= r) { const m = Math.floor(l + (r - l) / 2); @@ -185,13 +186,15 @@ class Solution { return true; } - if (nums[l] < nums[m]) { // Left portion + if (nums[l] < nums[m]) { + // Left portion if (nums[l] <= target && target < nums[m]) { r = m - 1; } else { l = m + 1; } - } else if (nums[l] > nums[m]) { // Right portion + } else if (nums[l] > nums[m]) { + // Right portion if (nums[m] < target && target <= nums[r]) { l = m + 1; } else { @@ -242,5 +245,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ in average case, $O(n)$ in worst case. -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(\log n)$ in average case, $O(n)$ in worst case. +- Space complexity: $O(1)$ diff --git a/articles/search-insert-position.md b/articles/search-insert-position.md index 7e6cbd60e..4277480df 100644 --- a/articles/search-insert-position.md +++ b/articles/search-insert-position.md @@ -73,8 +73,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -153,7 +153,8 @@ class Solution { */ searchInsert(nums, target) { let res = nums.length; - let l = 0, r = nums.length - 1; + let l = 0, + r = nums.length - 1; while (l <= r) { const mid = Math.floor((l + r) / 2); if (nums[mid] === target) { @@ -199,8 +200,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ extra space. --- @@ -272,7 +273,8 @@ class Solution { * @return {number} */ searchInsert(nums, target) { - let l = 0, r = nums.length - 1; + let l = 0, + r = nums.length - 1; while (l <= r) { const mid = Math.floor((l + r) / 2); if (nums[mid] === target) { @@ -315,8 +317,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ extra space. --- @@ -329,7 +331,7 @@ class Solution: def searchInsert(self, nums: List[int], target: int) -> int: l, r = 0, len(nums) while l < r: - m = l + ((r - l) // 2) + m = l + ((r - l) // 2) if nums[m] >= target: r = m elif nums[m] < target: @@ -380,7 +382,8 @@ class Solution { * @return {number} */ searchInsert(nums, target) { - let l = 0, r = nums.length; + let l = 0, + r = nums.length; while (l < r) { let m = l + Math.floor((r - l) / 2); if (nums[m] >= target) { @@ -417,8 +420,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ --- @@ -460,8 +463,8 @@ class Solution { */ searchInsert(nums, target) { // There is no built in Binary Search function for JS. - let index = nums.findIndex(x => x >= target); - return index !== -1 ? index : nums.length + let index = nums.findIndex((x) => x >= target); + return index !== -1 ? index : nums.length; } } ``` @@ -479,5 +482,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ diff --git a/articles/search-suggestions-system.md b/articles/search-suggestions-system.md index 87325be56..03b06ed5f 100644 --- a/articles/search-suggestions-system.md +++ b/articles/search-suggestions-system.md @@ -25,7 +25,7 @@ class Solution: cur.append(w) if len(cur) == 3: break - + if not cur: for j in range(i, m): res.append([]) @@ -171,10 +171,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n + m * n)$ -* Space complexity: - * $O(n)$ or $O(1)$ space for the sorting algorithm. - * $O(m * w)$ space for the output array. +- Time complexity: $O(n \log n + m * n)$ +- Space complexity: + - $O(n)$ or $O(1)$ space for the sorting algorithm. + - $O(m * w)$ space for the output array. > Where $n$ is the total number of characters in the string array $products$, $m$ is the length of the string $searchWord$, and $w$ is the average length of each word in the given string array. @@ -327,11 +327,11 @@ class Solution { for (let i = 0; i < m; i++) { prefix.push(searchWord[i]); - start = this.binarySearch(products, prefix.join(""), start); + start = this.binarySearch(products, prefix.join(''), start); let cur = []; for (let j = start; j < Math.min(start + 3, products.length); j++) { - if (products[j].startsWith(prefix.join(""))) { + if (products[j].startsWith(prefix.join(''))) { cur.push(products[j]); } else { break; @@ -351,7 +351,8 @@ class Solution { * @return {number} */ binarySearch(products, target, start) { - let l = start, r = products.length; + let l = start, + r = products.length; while (l < r) { let mid = Math.floor(l + (r - l) / 2); if (products[mid] >= target) { @@ -369,10 +370,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n + m * w * \log N)$ -* Space complexity: - * $O(n)$ or $O(1)$ space for the sorting algorithm. - * $O(m * w)$ space for the output array. +- Time complexity: $O(n \log n + m * w * \log N)$ +- Space complexity: + - $O(n)$ or $O(1)$ space for the sorting algorithm. + - $O(m * w)$ space for the output array. > Where $n$ is the total number of characters in the string array $products$, $N$ is the size of the array $products$, $m$ is the length of the string $searchWord$, and $w$ is the average length of each word in the given string array. @@ -394,7 +395,7 @@ class Solution: for i in range(m): prefix += searchWord[i] start = bisect_left(products, prefix, start) - + cur = [] for j in range(start, min(start + 3, len(products))): if products[j].startswith(prefix): @@ -442,10 +443,10 @@ public: ### Time & Space Complexity -* Time complexity: $O(n \log n + m * w * \log N)$ -* Space complexity: - * $O(n)$ or $O(1)$ space for the sorting algorithm. - * $O(m * w)$ space for the output array. +- Time complexity: $O(n \log n + m * w * \log N)$ +- Space complexity: + - $O(n)$ or $O(1)$ space for the sorting algorithm. + - $O(m * w)$ space for the output array. > Where $n$ is the total number of characters in the string array $products$, $N$ is the size of the array $products$, $m$ is the length of the string $searchWord$, and $w$ is the average length of each word in the given string array. @@ -552,14 +553,21 @@ class Solution { let res = []; products.sort(); - let l = 0, r = products.length - 1; + let l = 0, + r = products.length - 1; for (let i = 0; i < searchWord.length; i++) { let c = searchWord[i]; - while (l <= r && (products[l].length <= i || products[l][i] !== c)) { + while ( + l <= r && + (products[l].length <= i || products[l][i] !== c) + ) { l++; } - while (l <= r && (products[r].length <= i || products[r][i] !== c)) { + while ( + l <= r && + (products[r].length <= i || products[r][i] !== c) + ) { r--; } @@ -581,9 +589,9 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n + m * w + N)$ -* Space complexity: - * $O(n)$ or $O(1)$ space for the sorting algorithm. - * $O(m * w)$ space for the output array. +- Time complexity: $O(n \log n + m * w + N)$ +- Space complexity: + - $O(n)$ or $O(1)$ space for the sorting algorithm. + - $O(m * w)$ space for the output array. -> Where $n$ is the total number of characters in the string array $products$, $N$ is the size of the array $products$, $m$ is the length of the string $searchWord$, and $w$ is the average length of each word in the given string array. \ No newline at end of file +> Where $n$ is the total number of characters in the string array $products$, $N$ is the size of the array $products$, $m$ is the length of the string $searchWord$, and $w$ is the average length of each word in the given string array. diff --git a/articles/seat-reservation-manager.md b/articles/seat-reservation-manager.md index c546e1be8..6280f7f6f 100644 --- a/articles/seat-reservation-manager.md +++ b/articles/seat-reservation-manager.md @@ -101,11 +101,11 @@ class SeatManager { ### Time & Space Complexity -* Time complexity: - * $O(n)$ time for initialization. - * $O(n)$ time for each $reserve()$ function call. - * $O(1)$ time for each $unreserve()$ function call. -* Space complexity: $O(n)$ +- Time complexity: + - $O(n)$ time for initialization. + - $O(n)$ time for each $reserve()$ function call. + - $O(1)$ time for each $unreserve()$ function call. +- Space complexity: $O(n)$ --- @@ -204,11 +204,11 @@ class SeatManager { ### Time & Space Complexity -* Time complexity: - * $O(n \log n)$ time for initialization. - * $O(\log n)$ time for each $reserve()$ function call. - * $O(\log n)$ time for each $unreserve()$ function call. -* Space complexity: $O(n)$ +- Time complexity: + - $O(n \log n)$ time for initialization. + - $O(\log n)$ time for each $reserve()$ function call. + - $O(\log n)$ time for each $unreserve()$ function call. +- Space complexity: $O(n)$ --- @@ -225,7 +225,7 @@ class SeatManager: def reserve(self) -> int: if self.minHeap: return heapq.heappop(self.minHeap) - + seat = self.nextSeat self.nextSeat += 1 return seat @@ -317,11 +317,11 @@ class SeatManager { ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for initialization. - * $O(\log n)$ time for each $reserve()$ function call. - * $O(\log n)$ time for each $unreserve()$ function call. -* Space complexity: $O(n)$ +- Time complexity: + - $O(1)$ time for initialization. + - $O(\log n)$ time for each $reserve()$ function call. + - $O(\log n)$ time for each $unreserve()$ function call. +- Space complexity: $O(n)$ --- @@ -338,7 +338,7 @@ class SeatManager: def reserve(self) -> int: if self.available: return self.available.pop(0) - + seat = self.nextSeat self.nextSeat += 1 return seat @@ -400,8 +400,8 @@ public: ### Time & Space Complexity -* Time complexity: - * $O(1)$ time for initialization. - * $O(\log n)$ time for each $reserve()$ function call. - * $O(\log n)$ time for each $unreserve()$ function call. -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: + - $O(1)$ time for initialization. + - $O(\log n)$ time for each $reserve()$ function call. + - $O(\log n)$ time for each $unreserve()$ function call. +- Space complexity: $O(n)$ diff --git a/articles/sequential-digits.md b/articles/sequential-digits.md index b1f6bb8b8..60f54c763 100644 --- a/articles/sequential-digits.md +++ b/articles/sequential-digits.md @@ -96,8 +96,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -110,7 +110,7 @@ class Solution: def sequentialDigits(self, low: int, high: int) -> List[int]: res = [] low_digit, high_digit = len(str(low)), len(str(high)) - + for digits in range(low_digit, high_digit + 1): for start in range(1, 10): if start + digits > 10: @@ -132,7 +132,7 @@ public class Solution { List res = new ArrayList<>(); int lowDigit = String.valueOf(low).length(); int highDigit = String.valueOf(high).length(); - + for (int digits = lowDigit; digits <= highDigit; digits++) { for (int start = 1; start < 10; start++) { if (start + digits > 10) { @@ -160,7 +160,7 @@ public: vector res; int lowDigit = to_string(low).length(); int highDigit = to_string(high).length(); - + for (int digits = lowDigit; digits <= highDigit; digits++) { for (int start = 1; start < 10; start++) { if (start + digits > 10) { @@ -192,7 +192,7 @@ class Solution { const res = []; const lowDigit = low.toString().length; const highDigit = high.toString().length; - + for (let digits = lowDigit; digits <= highDigit; digits++) { for (let start = 1; start < 10; start++) { if (start + digits > 10) { @@ -201,7 +201,7 @@ class Solution { let num = start; let prev = start; for (let i = 1; i < digits; i++) { - num = num * 10 + (++prev); + num = num * 10 + ++prev; } if (num >= low && num <= high) { res.push(num); @@ -217,8 +217,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ > Since, we have at most $36$ valid numbers as per the given constraints. @@ -233,7 +233,7 @@ class Solution: def sequentialDigits(self, low: int, high: int) -> List[int]: res = [] queue = deque(range(1, 10)) - + while queue: n = queue.popleft() if n > high: @@ -243,7 +243,7 @@ class Solution: ones = n % 10 if ones < 9: queue.append(n * 10 + (ones + 1)) - + return res ``` @@ -252,11 +252,11 @@ public class Solution { public List sequentialDigits(int low, int high) { List res = new ArrayList<>(); Queue queue = new LinkedList<>(); - + for (int i = 1; i < 10; i++) { queue.add(i); } - + while (!queue.isEmpty()) { int n = queue.poll(); if (n > high) { @@ -270,7 +270,7 @@ public class Solution { queue.add(n * 10 + (ones + 1)); } } - + return res; } } @@ -282,15 +282,15 @@ public: vector sequentialDigits(int low, int high) { vector res; queue queue; - + for (int i = 1; i < 10; i++) { queue.push(i); } - + while (!queue.empty()) { int n = queue.front(); queue.pop(); - + if (n > high) { continue; } @@ -302,7 +302,7 @@ public: queue.push(n * 10 + (ones + 1)); } } - + return res; } }; @@ -321,7 +321,7 @@ class Solution { for (let i = 1; i < 9; i++) { queue.push(i); } - + while (!queue.isEmpty()) { const n = queue.pop(); if (n > high) { @@ -335,7 +335,7 @@ class Solution { queue.push(n * 10 + (ones + 1)); } } - + return res; } } @@ -345,8 +345,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ > Since, we have at most $36$ valid numbers as per the given constraints. @@ -468,8 +468,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ > Since, we have at most $36$ valid numbers as per the given constraints. @@ -499,7 +499,7 @@ public class Solution { public List sequentialDigits(int low, int high) { String nums = "123456789"; List res = new ArrayList<>(); - + for (int d = 2; d <= 9; d++) { for (int i = 0; i <= 9 - d; i++) { int num = Integer.parseInt(nums.substring(i, i + d)); @@ -511,7 +511,7 @@ public class Solution { } } } - + return res; } } @@ -549,7 +549,7 @@ class Solution { * @return {number[]} */ sequentialDigits(low, high) { - const nums = "123456789"; + const nums = '123456789'; const res = []; for (let d = 2; d <= 9; d++) { @@ -573,7 +573,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ -> Since, we have at most $36$ valid numbers as per the given constraints. \ No newline at end of file +> Since, we have at most $36$ valid numbers as per the given constraints. diff --git a/articles/serialize-and-deserialize-binary-tree.md b/articles/serialize-and-deserialize-binary-tree.md index ad965e002..9d53a481b 100644 --- a/articles/serialize-and-deserialize-binary-tree.md +++ b/articles/serialize-and-deserialize-binary-tree.md @@ -11,7 +11,7 @@ # self.right = right class Codec: - + # Encodes a tree to a single string. def serialize(self, root: Optional[TreeNode]) -> str: res = [] @@ -26,7 +26,7 @@ class Codec: dfs(root) return ",".join(res) - + # Decodes your encoded data to tree. def deserialize(self, data: str) -> Optional[TreeNode]: vals = data.split(",") @@ -63,7 +63,7 @@ class Codec: */ public class Codec { - + // Encodes a tree to a single string. public String serialize(TreeNode root) { List res = new ArrayList<>(); @@ -253,7 +253,7 @@ class Codec { */ public class Codec { - + // Encodes a tree to a single string. public string Serialize(TreeNode root) { List res = new List(); @@ -460,8 +460,8 @@ class Codec { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -478,7 +478,7 @@ class Codec { # self.right = right class Codec: - + # Encodes a tree to a single string. def serialize(self, root: Optional[TreeNode]) -> str: if not root: @@ -494,7 +494,7 @@ class Codec: queue.append(node.left) queue.append(node.right) return ",".join(res) - + # Decodes your encoded data to tree. def deserialize(self, data: str) -> Optional[TreeNode]: vals = data.split(",") @@ -541,7 +541,7 @@ public class Codec { StringBuilder res = new StringBuilder(); Queue queue = new LinkedList<>(); queue.add(root); - + while (!queue.isEmpty()) { TreeNode node = queue.poll(); if (node == null) { @@ -667,7 +667,7 @@ class Codec { * @return {string} */ serialize(root) { - if (!root) return "N"; + if (!root) return 'N'; const res = []; const queue = new Queue(); queue.push(root); @@ -675,14 +675,14 @@ class Codec { while (!queue.isEmpty()) { const node = queue.pop(); if (!node) { - res.push("N"); + res.push('N'); } else { res.push(node.val); queue.push(node.left); queue.push(node.right); } } - return res.join(","); + return res.join(','); } /** @@ -692,20 +692,20 @@ class Codec { * @return {TreeNode} */ deserialize(data) { - const vals = data.split(","); - if (vals[0] === "N") return null; + const vals = data.split(','); + if (vals[0] === 'N') return null; const root = new TreeNode(parseInt(vals[0])); const queue = new Queue([root]); let index = 1; while (!queue.isEmpty()) { const node = queue.pop(); - if (vals[index] !== "N") { + if (vals[index] !== 'N') { node.left = new TreeNode(parseInt(vals[index])); queue.push(node.left); } index++; - if (vals[index] !== "N") { + if (vals[index] !== 'N') { node.right = new TreeNode(parseInt(vals[index])); queue.push(node.right); } @@ -826,7 +826,7 @@ func (this *Codec) deserialize(data string) *TreeNode { if vals[0] == "N" { return nil } - + rootVal, _ := strconv.Atoi(vals[0]) root := &TreeNode{Val: rootVal} queue := []*TreeNode{root} @@ -969,7 +969,7 @@ class Codec { while !queue.isEmpty { let node = queue.popFirst()! - + if vals[index] != "N" { node.left = TreeNode(Int(vals[index])!) queue.append(node.left!) @@ -992,5 +992,5 @@ class Codec { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/set-mismatch.md b/articles/set-mismatch.md index f29e54444..8b5f7037a 100644 --- a/articles/set-mismatch.md +++ b/articles/set-mismatch.md @@ -13,12 +13,12 @@ class Solution: for num in nums: if num == i: cnt += 1 - + if cnt == 0: res[1] = i elif cnt == 2: res[0] = i - + return res ``` @@ -109,8 +109,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -129,9 +129,9 @@ class Solution: res[0] = nums[i] elif nums[i] - nums[i - 1] == 2: res[1] = nums[i] - 1 - + if nums[-1] != len(nums): - res[1] = len(nums) + res[1] = len(nums) return res ``` @@ -210,8 +210,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -230,7 +230,7 @@ class Solution: res[1] = i if count[i] == 2: res[0] = i - + return res ``` @@ -318,8 +318,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -337,7 +337,7 @@ class Solution: nums[num - 1] *= -1 if nums[num - 1] > 0: res[0] = num - + for i, num in enumerate(nums): if num > 0 and i + 1 != res[0]: res[1] = i + 1 @@ -431,8 +431,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -450,7 +450,7 @@ class Solution: for i in range(1, N + 1): x += nums[i - 1] - i y += nums[i - 1]**2 - i**2 - + missing = (y - x**2) // (2 * x) duplicate = missing + x return [duplicate, missing] @@ -522,9 +522,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ - +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -539,11 +538,11 @@ class Solution: # a ^ a = 0 # xorr = (1 ^ 2 ^ ... N) ^ (nums[0] ^ nums[1] ^ ... nums[N - 1]) # xorr = missing ^ duplicate - xorr = 0 + xorr = 0 for i in range(1, N + 1): xorr ^= i xorr ^= nums[i - 1] - + # bit that is set in only one number among (duplicate, missing), # will be set in (duplicate ^ missing) # take rightMost set bit for simplicity @@ -557,12 +556,12 @@ class Solution: x ^= i else: y ^= i - + if nums[i - 1] & rightMostBit: x ^= nums[i - 1] else: y ^= nums[i - 1] - + # identify the duplicate number from x and y for num in nums: if num == x: @@ -577,7 +576,7 @@ public class Solution { // a ^ a = 0 // xorr = (1 ^ 2 ^ ... N) ^ (nums[0] ^ nums[1] ^ ... nums[N - 1]) // xorr = missing ^ duplicate - int xorr = 0; + int xorr = 0; for (int i = 1; i <= N; i++) { xorr ^= i; xorr ^= nums[i - 1]; @@ -624,7 +623,7 @@ public: // a ^ a = 0 // xorr = (1 ^ 2 ^ ... N) ^ (nums[0] ^ nums[1] ^ ... nums[N - 1]) // xorr = missing ^ duplicate - int xorr = 0; + int xorr = 0; for (int i = 1; i <= N; i++) { xorr ^= i; xorr ^= nums[i - 1]; @@ -687,7 +686,8 @@ class Solution { // divide numbers (from nums, from [1, N]) into two sets w.r.t the rightMostBit // xorr the numbers of these sets independently - let x = 0, y = 0; + let x = 0, + y = 0; for (let i = 1; i <= N; i++) { if (i & rightMostBit) { x ^= i; @@ -717,5 +717,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/set-zeroes-in-matrix.md b/articles/set-zeroes-in-matrix.md index 72cef4283..262d6b526 100644 --- a/articles/set-zeroes-in-matrix.md +++ b/articles/set-zeroes-in-matrix.md @@ -87,8 +87,9 @@ class Solution { * @return {void} */ setZeroes(matrix) { - const ROWS = matrix.length, COLS = matrix[0].length; - const mark = matrix.map(row => [...row]); + const ROWS = matrix.length, + COLS = matrix[0].length; + const mark = matrix.map((row) => [...row]); for (let r = 0; r < ROWS; r++) { for (let c = 0; c < COLS; c++) { @@ -241,8 +242,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O((m * n) * (m + n))$ -* Space complexity: $O(m * n)$ +- Time complexity: $O((m * n) * (m + n))$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns. @@ -332,7 +333,8 @@ class Solution { * @return {void} */ setZeroes(matrix) { - const rows = matrix.length, cols = matrix[0].length; + const rows = matrix.length, + cols = matrix[0].length; const rowZero = Array(rows).fill(false); const colZero = Array(cols).fill(false); @@ -468,8 +470,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m + n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m + n)$ > Where $m$ is the number of rows and $n$ is the number of columns. @@ -601,7 +603,7 @@ class Solution { */ setZeroes(matrix) { const ROWS = matrix.length; - const COLS = matrix[0].length; + const COLS = matrix[0].length; let rowZero = false; for (let r = 0; r < ROWS; r++) { @@ -812,7 +814,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(1)$ -> Where $m$ is the number of rows and $n$ is the number of columns. \ No newline at end of file +> Where $m$ is the number of rows and $n$ is the number of columns. diff --git a/articles/shift-2d-grid.md b/articles/shift-2d-grid.md index 78f570a31..ec5a6301b 100644 --- a/articles/shift-2d-grid.md +++ b/articles/shift-2d-grid.md @@ -13,13 +13,13 @@ class Solution: for r in range(m): for c in range(n - 1): cur[r][c + 1] = grid[r][c] - + for r in range(m): cur[(r + 1) % m][0] = grid[r][n - 1] - + grid = cur k -= 1 - + return grid ``` @@ -94,7 +94,8 @@ class Solution { * @return {number[][]} */ shiftGrid(grid, k) { - const m = grid.length, n = grid[0].length; + const m = grid.length, + n = grid[0].length; while (k > 0) { const cur = Array.from({ length: m }, () => Array(n).fill(0)); @@ -122,8 +123,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(k * m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(k * m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows in the grid, $n$ is the number of columns in the grid, and $k$ is the shift count. @@ -144,7 +145,7 @@ class Solution: for c in range(n): grid[r][c], prev = prev, grid[r][c] k -= 1 - + return grid ``` @@ -207,7 +208,8 @@ class Solution { * @return {number[][]} */ shiftGrid(grid, k) { - const m = grid.length, n = grid[0].length; + const m = grid.length, + n = grid[0].length; while (k > 0) { let prev = grid[m - 1][n - 1]; @@ -228,8 +230,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(k * m * n)$ -* Space complexity: $O(m * n)$ for the output matrix. +- Time complexity: $O(k * m * n)$ +- Space complexity: $O(m * n)$ for the output matrix. > Where $m$ is the number of rows in the grid, $n$ is the number of columns in the grid, and $k$ is the shift count. @@ -250,13 +252,13 @@ class Solution: for r in range(m): for c in range(n): arr[r * n + c] = grid[r][c] - + def reverse(l, r): while l < r: arr[l], arr[r] = arr[r], arr[l] l += 1 r -= 1 - + reverse(0, N - 1) reverse(0, k - 1) reverse(k, N - 1) @@ -264,7 +266,7 @@ class Solution: for r in range(m): for c in range(n): grid[r][c] = arr[r * n + c] - + return grid ``` @@ -347,7 +349,8 @@ class Solution { * @return {number[][]} */ shiftGrid(grid, k) { - const m = grid.length, n = grid[0].length; + const m = grid.length, + n = grid[0].length; const N = m * n; k %= N; @@ -385,8 +388,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows in the grid and $n$ is the number of columns in the grid. @@ -473,7 +476,8 @@ class Solution { * @return {number[][]} */ shiftGrid(grid, k) { - const M = grid.length, N = grid[0].length; + const M = grid.length, + N = grid[0].length; const posToVal = (r, c) => r * N + c; const valToPos = (v) => [Math.floor(v / N), v % N]; @@ -496,7 +500,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ -> Where $m$ is the number of rows in the grid and $n$ is the number of columns in the grid. \ No newline at end of file +> Where $m$ is the number of rows in the grid and $n$ is the number of columns in the grid. diff --git a/articles/shifting-letters-ii.md b/articles/shifting-letters-ii.md index 12d3e9499..7c588f014 100644 --- a/articles/shifting-letters-ii.md +++ b/articles/shifting-letters-ii.md @@ -75,7 +75,7 @@ class Solution { * @return {string} */ shiftingLetters(s, shifts) { - let arr = Array.from(s).map(c => c.charCodeAt(0) - 97); + let arr = Array.from(s).map((c) => c.charCodeAt(0) - 97); for (const [l, r, d] of shifts) { for (let i = l; i <= r; i++) { @@ -83,7 +83,7 @@ class Solution { } } - return arr.map(c => String.fromCharCode(c + 97)).join(''); + return arr.map((c) => String.fromCharCode(c + 97)).join(''); } } ``` @@ -92,8 +92,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n)$ > Where $n$ is the length of the string $s$ and $m$ is the size of the array $shifts$. @@ -210,14 +210,18 @@ class Solution { } let diff = 0; - const res = Array.from(s).map(c => c.charCodeAt(0) - 'a'.charCodeAt(0)); + const res = Array.from(s).map( + (c) => c.charCodeAt(0) - 'a'.charCodeAt(0), + ); for (let i = 0; i < n; i++) { diff += prefix_diff[i]; - res[i] = (diff % 26 + res[i] + 26) % 26; + res[i] = ((diff % 26) + res[i] + 26) % 26; } - return res.map(x => String.fromCharCode('a'.charCodeAt(0) + x)).join(''); + return res + .map((x) => String.fromCharCode('a'.charCodeAt(0) + x)) + .join(''); } } ``` @@ -226,8 +230,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(n)$ > Where $n$ is the length of the string $s$ and $m$ is the size of the array $shifts$. @@ -459,7 +463,7 @@ class Solution { bit.rangeUpdate(left, right, delta); } - let res = ""; + let res = ''; for (let i = 0; i < n; i++) { const shift = bit.prefixSum(i) % 26; const code = (s.charCodeAt(i) - 97 + shift + 26) % 26; @@ -475,7 +479,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O((m + n) * \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O((m + n) * \log n)$ +- Space complexity: $O(n)$ -> Where $n$ is the length of the string $s$ and $m$ is the size of the array $shifts$. \ No newline at end of file +> Where $n$ is the length of the string $s$ and $m$ is the size of the array $shifts$. diff --git a/articles/shortest-bridge.md b/articles/shortest-bridge.md index 14f78e190..11ea77be0 100644 --- a/articles/shortest-bridge.md +++ b/articles/shortest-bridge.md @@ -70,7 +70,7 @@ public class Solution { private void dfs(int[][] grid, int r, int c) { if (r < 0 || c < 0 || r >= N || c >= N || grid[r][c] == 0 || visited[r][c]) return; - + visited[r][c] = true; for (int[] d : direct) { @@ -143,7 +143,7 @@ private: void dfs(vector>& grid, int r, int c) { if (r < 0 || c < 0 || r >= N || c >= N || grid[r][c] == 0 || visited[r][c]) return; - + visited[r][c] = true; for (auto& d : direct) { dfs(grid, r + d[0], c + d[1]); @@ -191,12 +191,24 @@ class Solution { */ shortestBridge(grid) { const N = grid.length; - const direct = [[0, 1], [0, -1], [1, 0], [-1, 0]]; + const direct = [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ]; const visited = Array.from({ length: N }, () => Array(N).fill(false)); const q = new Queue(); const dfs = (r, c) => { - if (r < 0 || c < 0 || r >= N || c >= N || grid[r][c] === 0 || visited[r][c]) + if ( + r < 0 || + c < 0 || + r >= N || + c >= N || + grid[r][c] === 0 || + visited[r][c] + ) return; visited[r][c] = true; q.push([r, c]); @@ -212,9 +224,16 @@ class Solution { for (let i = q.size(); i > 0; i--) { const [r, c] = q.pop(); for (const [dr, dc] of direct) { - const curR = r + dr, curC = c + dc; - - if (curR < 0 || curC < 0 || curR >= N || curC >= N || visited[curR][curC]) + const curR = r + dr, + curC = c + dc; + + if ( + curR < 0 || + curC < 0 || + curR >= N || + curC >= N || + visited[curR][curC] + ) continue; if (grid[curR][curC] === 1) return res; @@ -242,8 +261,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -408,7 +427,12 @@ class Solution { */ shortestBridge(grid) { const N = grid.length; - const direct = [[0, 1], [0, -1], [1, 0], [-1, 0]]; + const direct = [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ]; const q = new Queue(); const dfs = (r, c) => { @@ -437,7 +461,8 @@ class Solution { for (let i = q.size(); i > 0; i--) { const [r, c] = q.pop(); for (const [dr, dc] of direct) { - let nr = r + dr, nc = c + dc; + let nr = r + dr, + nc = c + dc; if (nr < 0 || nc < 0 || nr >= N || nc >= N) continue; if (grid[nr][nc] === 1) return res; if (grid[nr][nc] === 0) { @@ -456,8 +481,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -477,7 +502,7 @@ class Solution: for c in range(N): if grid[r][c] == 1: q1 = deque([(r, c)]) - grid[r][c] = 2 + grid[r][c] = 2 while q1: x, y = q1.popleft() q2.append((x, y)) @@ -633,7 +658,12 @@ class Solution { */ shortestBridge(grid) { const N = grid.length; - const direct = [[0, 1], [0, -1], [1, 0], [-1, 0]]; + const direct = [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ]; const q2 = new Queue(); let found = false; @@ -649,8 +679,15 @@ class Solution { q2.push([x, y]); for (let [dx, dy] of direct) { - let nx = x + dx, ny = y + dy; - if (nx >= 0 && ny >= 0 && nx < N && ny < N && grid[nx][ny] === 1) { + let nx = x + dx, + ny = y + dy; + if ( + nx >= 0 && + ny >= 0 && + nx < N && + ny < N && + grid[nx][ny] === 1 + ) { grid[nx][ny] = 2; q1.push([nx, ny]); } @@ -668,7 +705,8 @@ class Solution { const [x, y] = q2.pop(); for (let [dx, dy] of direct) { - let nx = x + dx, ny = y + dy; + let nx = x + dx, + ny = y + dy; if (nx >= 0 && ny >= 0 && nx < N && ny < N) { if (grid[nx][ny] === 1) return res; if (grid[nx][ny] === 0) { @@ -688,8 +726,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -875,7 +913,7 @@ public: } int find(int node) { - if (parent[node] != node) + if (parent[node] != node) parent[node] = find(parent[node]); return parent[node]; } @@ -999,7 +1037,12 @@ class Solution { */ shortestBridge(grid) { const N = grid.length; - const direct = [[0, 1], [0, -1], [1, 0], [-1, 0]]; + const direct = [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ]; const dsu = new DSU(N * N + 1); const q = new Queue(); @@ -1018,14 +1061,19 @@ class Solution { } } - for (let r = 0; r < N; r++) { for (let c = 0; c < N; c++) { if (grid[r][c] === 1 && dsu.find(idx(r, c)) === firstIsland) { for (const [dx, dy] of direct) { let nr = r + dx, nc = c + dy; - if (nr >= 0 && nc >= 0 && nr < N && nc < N && grid[nr][nc] === 0) { + if ( + nr >= 0 && + nc >= 0 && + nr < N && + nc < N && + grid[nr][nc] === 0 + ) { q.push([r, c]); break; } @@ -1042,7 +1090,10 @@ class Solution { let nr = r + dx, nc = c + dy; if (nr >= 0 && nc >= 0 && nr < N && nc < N) { - if (grid[nr][nc] === 1 && dsu.union(idx(r, c), idx(nr, nc))) { + if ( + grid[nr][nc] === 1 && + dsu.union(idx(r, c), idx(nr, nc)) + ) { return res; } if (grid[nr][nc] === 0) { @@ -1064,5 +1115,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ \ No newline at end of file +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ diff --git a/articles/shortest-common-supersequence.md b/articles/shortest-common-supersequence.md index 6390ec39d..3ae4cde8e 100644 --- a/articles/shortest-common-supersequence.md +++ b/articles/shortest-common-supersequence.md @@ -159,9 +159,10 @@ class Solution { * @return {string} */ shortestCommonSupersequence(str1, str2) { - const n = str1.length, m = str2.length; - const cache = Array.from({ length: n + 1 }, () => - Array(m + 1).fill(null) + const n = str1.length, + m = str2.length; + const cache = Array.from({ length: n + 1 }, () => + Array(m + 1).fill(null), ); const dfs = (i, j) => { @@ -206,8 +207,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m * min(n, m))$ -* Space complexity: $O(n * m * min(n, m))$ +- Time complexity: $O(n * m * min(n, m))$ +- Space complexity: $O(n * m * min(n, m))$ > Where $n$ and $m$ are the lengths of the strings $str1$ and $str2$ respectively. @@ -222,7 +223,7 @@ class Solution: def shortestCommonSupersequence(self, str1: str, str2: str) -> str: n, m = len(str1), len(str2) dp = [[-1] * (m + 1) for _ in range(n + 1)] - + def dfs(i, j): if dp[i][j] != -1: return dp[i][j] @@ -395,10 +396,9 @@ class Solution { * @return {string} */ shortestCommonSupersequence(str1, str2) { - const n = str1.length, m = str2.length; - const dp = Array.from({ length: n + 1 }, () => - Array(m + 1).fill(-1) - ); + const n = str1.length, + m = str2.length; + const dp = Array.from({ length: n + 1 }, () => Array(m + 1).fill(-1)); const dfs = (i, j) => { if (dp[i][j] !== -1) return dp[i][j]; @@ -417,7 +417,8 @@ class Solution { const buildSCS = () => { const res = []; - let i = 0, j = 0; + let i = 0, + j = 0; while (i < n || j < m) { if (i === n) { @@ -453,8 +454,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n * m)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n * m)$ > Where $n$ and $m$ are the lengths of the strings $str1$ and $str2$ respectively. @@ -550,10 +551,9 @@ class Solution { * @return {string} */ shortestCommonSupersequence(str1, str2) { - const n = str1.length, m = str2.length; - const dp = Array.from({ length: n + 1 }, () => - Array(m + 1).fill("") - ); + const n = str1.length, + m = str2.length; + const dp = Array.from({ length: n + 1 }, () => Array(m + 1).fill('')); for (let i = 0; i <= n; i++) { for (let j = 0; j <= m; j++) { @@ -564,9 +564,10 @@ class Solution { } else if (str1[i - 1] === str2[j - 1]) { dp[i][j] = dp[i - 1][j - 1] + str1[i - 1]; } else { - dp[i][j] = dp[i - 1][j].length < dp[i][j - 1].length ? - dp[i - 1][j] + str1[i - 1] : - dp[i][j - 1] + str2[j - 1]; + dp[i][j] = + dp[i - 1][j].length < dp[i][j - 1].length + ? dp[i - 1][j] + str1[i - 1] + : dp[i][j - 1] + str2[j - 1]; } } } @@ -580,8 +581,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m * min(n, m))$ -* Space complexity: $O(n * m * min(n, m))$ +- Time complexity: $O(n * m * min(n, m))$ +- Space complexity: $O(n * m * min(n, m))$ > Where $n$ and $m$ are the lengths of the strings $str1$ and $str2$ respectively. @@ -743,10 +744,9 @@ class Solution { * @return {string} */ shortestCommonSupersequence(str1, str2) { - const n = str1.length, m = str2.length; - const dp = Array.from({ length: n + 1 }, () => - Array(m + 1).fill(0) - ); + const n = str1.length, + m = str2.length; + const dp = Array.from({ length: n + 1 }, () => Array(m + 1).fill(0)); for (let i = 0; i <= n; i++) { for (let j = 0; j <= m; j++) { @@ -763,7 +763,8 @@ class Solution { } const res = []; - let i = n, j = m; + let i = n, + j = m; while (i > 0 && j > 0) { if (str1[i - 1] === str2[j - 1]) { res.push(str1[i - 1]); @@ -797,7 +798,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n * m)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n * m)$ -> Where $n$ and $m$ are the lengths of the strings $str1$ and $str2$ respectively. \ No newline at end of file +> Where $n$ and $m$ are the lengths of the strings $str1$ and $str2$ respectively. diff --git a/articles/shortest-path-in-binary-matrix.md b/articles/shortest-path-in-binary-matrix.md index b03bb70fc..879a873cd 100644 --- a/articles/shortest-path-in-binary-matrix.md +++ b/articles/shortest-path-in-binary-matrix.md @@ -9,7 +9,7 @@ class Solution: if grid[0][0] or grid[N - 1][N - 1]: return -1 - q = deque([(0, 0, 1)]) + q = deque([(0, 0, 1)]) visit = set((0, 0)) direct = [(0, 1), (1, 0), (0, -1), (-1, 0), (1, 1), (-1, -1), (1, -1), (-1, 1)] @@ -21,7 +21,7 @@ class Solution: for dr, dc in direct: nr, nc = r + dr, c + dc - if (0 <= nr < N and 0 <= nc < N and grid[nr][nc] == 0 and + if (0 <= nr < N and 0 <= nc < N and grid[nr][nc] == 0 and (nr, nc) not in visit): q.append((nr, nc, length + 1)) visit.add((nr, nc)) @@ -35,7 +35,7 @@ public class Solution { int N = grid.length; if (grid[0][0] == 1 || grid[N - 1][N - 1] == 1) return -1; - int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}, + int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}, {1, 1}, {-1, -1}, {1, -1}, {-1, 1}}; boolean[][] visit = new boolean[N][N]; @@ -51,7 +51,7 @@ public class Solution { for (int[] d : directions) { int nr = r + d[0], nc = c + d[1]; - if (nr >= 0 && nc >= 0 && nr < N && nc < N && + if (nr >= 0 && nc >= 0 && nr < N && nc < N && grid[nr][nc] == 0 && !visit[nr][nc]) { q.offer(new int[]{nr, nc, length + 1}); visit[nr][nc] = true; @@ -70,7 +70,7 @@ public: int N = grid.size(); if (grid[0][0] == 1 || grid[N - 1][N - 1] == 1) return -1; - vector> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}, + vector> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}, {1, 1}, {-1, -1}, {1, -1}, {-1, 1}}; vector> visit(N, vector(N, false)); @@ -86,7 +86,7 @@ public: for (auto [dr, dc] : directions) { int nr = r + dr, nc = c + dc; - if (nr >= 0 && nc >= 0 && nr < N && nc < N && + if (nr >= 0 && nc >= 0 && nr < N && nc < N && grid[nr][nc] == 0 && !visit[nr][nc]) { q.push({nr, nc, length + 1}); visit[nr][nc] = true; @@ -109,12 +109,16 @@ class Solution { if (grid[0][0] === 1 || grid[N - 1][N - 1] === 1) return -1; const directions = [ - [0, 1], [1, 0], [0, -1], [-1, 0], - [1, 1], [-1, -1], [1, -1], [-1, 1] + [0, 1], + [1, 0], + [0, -1], + [-1, 0], + [1, 1], + [-1, -1], + [1, -1], + [-1, 1], ]; - const visit = Array.from({ length: N }, () => - Array(N).fill(false) - ); + const visit = Array.from({ length: N }, () => Array(N).fill(false)); const q = new Queue([[0, 0, 1]]); visit[0][0] = true; @@ -124,9 +128,16 @@ class Solution { if (r === N - 1 && c === N - 1) return length; for (const [dr, dc] of directions) { - const nr = r + dr, nc = c + dc; - if (nr >= 0 && nc >= 0 && nr < N && nc < N && - grid[nr][nc] === 0 && !visit[nr][nc]) { + const nr = r + dr, + nc = c + dc; + if ( + nr >= 0 && + nc >= 0 && + nr < N && + nc < N && + grid[nr][nc] === 0 && + !visit[nr][nc] + ) { q.push([nr, nc, length + 1]); visit[nr][nc] = true; } @@ -161,8 +172,8 @@ public class Solution { foreach (var (dr, dc) in directions) { int nr = r + dr, nc = c + dc; - if (nr >= 0 && nr < n && nc >= 0 && nc < n - && grid[nr][nc] == 0 + if (nr >= 0 && nr < n && nc >= 0 && nc < n + && grid[nr][nc] == 0 && !visit.Contains((nr, nc))) { q.Enqueue((nr, nc, length + 1)); visit.Add((nr, nc)); @@ -179,8 +190,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -196,7 +207,7 @@ class Solution: if grid[0][0] or grid[N - 1][N - 1]: return -1 - + q = deque([(0, 0)]) grid[0][0] = 1 @@ -222,7 +233,7 @@ public class Solution { int N = grid.length; int[] direct = {0, 1, 0, -1, 0, 1, 1, -1, -1, 1}; - if (grid[0][0] == 1 || grid[N - 1][N - 1] == 1) + if (grid[0][0] == 1 || grid[N - 1][N - 1] == 1) return -1; Queue q = new LinkedList<>(); @@ -234,7 +245,7 @@ public class Solution { int r = cell[0], c = cell[1]; int dist = grid[r][c]; - if (r == N - 1 && c == N - 1) + if (r == N - 1 && c == N - 1) return dist; for (int d = 0; d < 9; d++) { @@ -259,7 +270,7 @@ public: int N = grid.size(); int direct[10] = {0, 1, 0, -1, 0, 1, 1, -1, -1, 1}; - if (grid[0][0] || grid[N - 1][N - 1]) + if (grid[0][0] || grid[N - 1][N - 1]) return -1; queue> q; @@ -271,7 +282,7 @@ public: q.pop(); int dist = grid[r][c]; - if (r == N - 1 && c == N - 1) + if (r == N - 1 && c == N - 1) return dist; for (int d = 0; d < 9; d++) { @@ -299,8 +310,7 @@ class Solution { const N = grid.length; const direct = [0, 1, 0, -1, 0, 1, 1, -1, -1, 1]; - if (grid[0][0] || grid[N - 1][N - 1]) - return -1; + if (grid[0][0] || grid[N - 1][N - 1]) return -1; let q = [[0, 0]]; grid[0][0] = 1; @@ -309,13 +319,19 @@ class Solution { let [r, c] = q.shift(); let dist = grid[r][c]; - if (r === N - 1 && c === N - 1) - return dist; + if (r === N - 1 && c === N - 1) return dist; for (let d = 0; d < 9; d++) { - let nr = r + direct[d], nc = c + direct[d + 1]; - - if (nr >= 0 && nc >= 0 && nr < N && nc < N && grid[nr][nc] === 0) { + let nr = r + direct[d], + nc = c + direct[d + 1]; + + if ( + nr >= 0 && + nc >= 0 && + nr < N && + nc < N && + grid[nr][nc] === 0 + ) { grid[nr][nc] = dist + 1; q.push([nr, nc]); } @@ -368,8 +384,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -405,7 +421,7 @@ class Solution: if grid[nr][nc] == 0: grid[nr][nc] = start q1.append((nr, nc)) - + q1, q2 = q2, q1 start, end = end, start res += 1 @@ -517,12 +533,15 @@ class Solution { grid[0][0] = -1; grid[N - 1][N - 1] = -2; - let res = 2, start = -1, end = -2; + let res = 2, + start = -1, + end = -2; while (!q1.isEmpty() && !q2.isEmpty()) { for (let i = q1.size(); i > 0; i--) { const [r, c] = q1.pop(); for (let d = 0; d < 9; d++) { - let nr = r + direct[d], nc = c + direct[d + 1]; + let nr = r + direct[d], + nc = c + direct[d + 1]; if (nr >= 0 && nc >= 0 && nr < N && nc < N) { if (grid[nr][nc] === end) return res; if (grid[nr][nc] === 0) { @@ -600,5 +619,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ \ No newline at end of file +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ diff --git a/articles/shortest-path-with-alternating-colors.md b/articles/shortest-path-with-alternating-colors.md index f5d927069..63a21c484 100644 --- a/articles/shortest-path-with-alternating-colors.md +++ b/articles/shortest-path-with-alternating-colors.md @@ -6,7 +6,7 @@ class Solution: def shortestAlternatingPaths(self, n: int, redEdges: list[list[int]], blueEdges: list[list[int]]) -> list[int]: red, blue = defaultdict(list), defaultdict(list) - + for src, dst in redEdges: red[src].append(dst) @@ -143,25 +143,25 @@ class Solution { const answer = new Array(n).fill(-1); const q = new Queue([[0, 0, null]]); - const visit = new Set(["0,null"]); + const visit = new Set(['0,null']); while (!q.isEmpty()) { const [node, length, edgeColor] = q.pop(); if (answer[node] === -1) answer[node] = length; - if (edgeColor !== "RED") { + if (edgeColor !== 'RED') { for (const nei of red[node]) { if (!visit.has(`${nei},RED`)) { visit.add(`${nei},RED`); - q.push([nei, length + 1, "RED"]); + q.push([nei, length + 1, 'RED']); } } } - if (edgeColor !== "BLUE") { + if (edgeColor !== 'BLUE') { for (const nei of blue[node]) { if (!visit.has(`${nei},BLUE`)) { visit.add(`${nei},BLUE`); - q.push([nei, length + 1, "BLUE"]); + q.push([nei, length + 1, 'BLUE']); } } } @@ -175,8 +175,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ > Where $V$ is the number of vertices and $E$ is the number of edges. @@ -194,7 +194,7 @@ class Solution: for u, v in edges: adj[u].append(v) return adj - + red, blue = buildGraph(redEdges), buildGraph(blueEdges) adj = [red, blue] INF = float("inf") @@ -328,7 +328,10 @@ class Solution { const dist = Array.from({ length: n }, () => [INF, INF]); dist[0][0] = dist[0][1] = 0; - const q = new Queue([[0, 0], [0, 1]]); + const q = new Queue([ + [0, 0], + [0, 1], + ]); while (!q.isEmpty()) { const [node, color] = q.pop(); for (const nei of adj[color][node]) { @@ -364,8 +367,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ > Where $V$ is the number of vertices and $E$ is the number of edges. @@ -458,7 +461,7 @@ class Solution { public: vector shortestAlternatingPaths(int n, vector>& redEdges, vector>& blueEdges) { vector> adj[2] = {buildGraph(n, redEdges), buildGraph(n, blueEdges)}; - + int INF = numeric_limits::max(); vector> dist(n, vector(2, INF)); dist[0][0] = dist[0][1] = 0; @@ -504,8 +507,10 @@ class Solution { */ shortestAlternatingPaths(n, redEdges, blueEdges) { const INF = Number.MAX_SAFE_INTEGER; - const adj = [Array.from({ length: n }, () => []), - Array.from({ length: n }, () => [])]; + const adj = [ + Array.from({ length: n }, () => []), + Array.from({ length: n }, () => []), + ]; redEdges.forEach(([u, v]) => adj[0][u].push(v)); blueEdges.forEach(([u, v]) => adj[1][u].push(v)); @@ -514,7 +519,7 @@ class Solution { dist[0][0] = dist[0][1] = 0; const dfs = (node, color) => { - adj[color][node].forEach(nei => { + adj[color][node].forEach((nei) => { if (dist[nei][color ^ 1] > dist[node][color] + 1) { dist[nei][color ^ 1] = dist[node][color] + 1; dfs(nei, color ^ 1); @@ -537,7 +542,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ -> Where $V$ is the number of vertices and $E$ is the number of edges. \ No newline at end of file +> Where $V$ is the number of vertices and $E$ is the number of edges. diff --git a/articles/shuffle-the-array.md b/articles/shuffle-the-array.md index eded033b7..b20c31311 100644 --- a/articles/shuffle-the-array.md +++ b/articles/shuffle-the-array.md @@ -62,8 +62,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ extra space. --- @@ -80,7 +80,7 @@ class Solution: nums[i] += (nums[i // 2] % M) * M else: nums[i] += (nums[n + i // 2] % M) * M - + for i in range(2 * n): nums[i] //= M @@ -154,8 +154,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -168,7 +168,7 @@ class Solution: def shuffle(self, nums: List[int], n: int) -> List[int]: for i in range(n): nums[i] = (nums[i] << 10) | nums[i + n] # Store x, y in nums[i] - + j = 2 * n - 1 for i in range(n - 1, -1, -1): y = nums[i] & ((1 << 10) - 1) @@ -176,7 +176,7 @@ class Solution: nums[j] = y nums[j - 1] = x j -= 2 - + return nums ``` @@ -253,5 +253,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/sign-of-the-product-of-an-array.md b/articles/sign-of-the-product-of-an-array.md index 76922c8d0..ed9a161f0 100644 --- a/articles/sign-of-the-product-of-an-array.md +++ b/articles/sign-of-the-product-of-an-array.md @@ -73,8 +73,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -154,5 +154,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/simplify-path.md b/articles/simplify-path.md index ae0ecb3ee..ab45b62b7 100644 --- a/articles/simplify-path.md +++ b/articles/simplify-path.md @@ -85,22 +85,22 @@ class Solution { */ simplifyPath(path) { const stack = []; - let cur = ""; + let cur = ''; - for (const c of path + "/") { - if (c === "/") { - if (cur === "..") { + for (const c of path + '/') { + if (c === '/') { + if (cur === '..') { if (stack.length) stack.pop(); - } else if (cur !== "" && cur !== ".") { + } else if (cur !== '' && cur !== '.') { stack.push(cur); } - cur = ""; + cur = ''; } else { cur += c; } } - return "/" + stack.join("/"); + return '/' + stack.join('/'); } } ``` @@ -135,8 +135,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -214,19 +214,19 @@ class Solution { */ simplifyPath(path) { const stack = []; - const paths = path.split("/"); + const paths = path.split('/'); for (const cur of paths) { - if (cur === "..") { + if (cur === '..') { if (stack.length) { stack.pop(); } - } else if (cur !== "" && cur !== ".") { + } else if (cur !== '' && cur !== '.') { stack.push(cur); } } - return "/" + stack.join("/"); + return '/' + stack.join('/'); } } ``` @@ -258,5 +258,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/single-element-in-a-sorted-array.md b/articles/single-element-in-a-sorted-array.md index e2a5a8b0e..8855fac24 100644 --- a/articles/single-element-in-a-sorted-array.md +++ b/articles/single-element-in-a-sorted-array.md @@ -56,8 +56,10 @@ class Solution { singleNonDuplicate(nums) { const n = nums.length; for (let i = 0; i < n; i++) { - if ((i > 0 && nums[i] === nums[i - 1]) || - (i < n - 1 && nums[i] === nums[i + 1])) { + if ( + (i > 0 && nums[i] === nums[i - 1]) || + (i < n - 1 && nums[i] === nums[i + 1]) + ) { continue; } return nums[i]; @@ -71,8 +73,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -134,8 +136,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -150,7 +152,7 @@ class Solution: while l <= r: m = l + ((r - l) // 2) - if ((m - 1 < 0 or nums[m - 1] != nums[m]) and + if ((m - 1 < 0 or nums[m - 1] != nums[m]) and (m + 1 == len(nums) or nums[m] != nums[m + 1])): return nums[m] @@ -168,7 +170,7 @@ public class Solution { while (l <= r) { int m = l + (r - l) / 2; - if ((m - 1 < 0 || nums[m - 1] != nums[m]) && + if ((m - 1 < 0 || nums[m - 1] != nums[m]) && (m + 1 == nums.length || nums[m] != nums[m + 1])) { return nums[m]; } @@ -194,7 +196,7 @@ public: while (l <= r) { int m = l + (r - l) / 2; - if ((m - 1 < 0 || nums[m - 1] != nums[m]) && + if ((m - 1 < 0 || nums[m - 1] != nums[m]) && (m + 1 == nums.size() || nums[m] != nums[m + 1])) { return nums[m]; } @@ -219,16 +221,19 @@ class Solution { * @return {number} */ singleNonDuplicate(nums) { - let l = 0, r = nums.length - 1; + let l = 0, + r = nums.length - 1; while (l <= r) { let m = l + Math.floor((r - l) / 2); - if ((m - 1 < 0 || nums[m - 1] !== nums[m]) && - (m + 1 === nums.length || nums[m] !== nums[m + 1])) { + if ( + (m - 1 < 0 || nums[m - 1] !== nums[m]) && + (m + 1 === nums.length || nums[m] !== nums[m + 1]) + ) { return nums[m]; } - let leftSize = (m - 1 >= 0 && nums[m - 1] === nums[m]) ? m - 1 : m; + let leftSize = m - 1 >= 0 && nums[m - 1] === nums[m] ? m - 1 : m; if (leftSize % 2 === 1) { r = m - 1; } else { @@ -243,8 +248,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ --- @@ -321,7 +326,8 @@ class Solution { * @return {number} */ singleNonDuplicate(nums) { - let l = 0, r = nums.length - 1; + let l = 0, + r = nums.length - 1; while (l < r) { let m = Math.floor(l + (r - l) / 2); @@ -344,8 +350,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ --- @@ -364,7 +370,7 @@ class Solution: r = m else: l = m + 1 - + return nums[l] ``` @@ -414,7 +420,8 @@ class Solution { * @return {number} */ singleNonDuplicate(nums) { - let l = 0, r = nums.length - 1; + let l = 0, + r = nums.length - 1; while (l < r) { let m = (l + r) >> 1; @@ -434,5 +441,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ diff --git a/articles/single-number-iii.md b/articles/single-number-iii.md index 5e714092d..e50165d05 100644 --- a/articles/single-number-iii.md +++ b/articles/single-number-iii.md @@ -13,12 +13,12 @@ class Solution: if i != j and nums[i] == nums[j]: flag = False break - + if flag: res.append(nums[i]) if len(res) == 2: break - + return res ``` @@ -115,8 +115,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ extra space. --- @@ -130,7 +130,7 @@ class Solution: count = {} for num in nums: count[num] = 1 + count.get(num, 0) - + return [k for k in count if count[k] == 1] ``` @@ -203,8 +203,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -290,8 +290,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -310,7 +310,7 @@ class Solution: (i + 1 < n and nums[i] == nums[i + 1])): continue res.append(nums[i]) - + return res ``` @@ -343,7 +343,7 @@ public: int n = nums.size(); for (int i = 0; i < n; i++) { - if ((i > 0 && nums[i] == nums[i - 1]) || + if ((i > 0 && nums[i] == nums[i - 1]) || (i + 1 < n && nums[i] == nums[i + 1])) { continue; } @@ -367,8 +367,10 @@ class Solution { const n = nums.length; for (let i = 0; i < n; i++) { - if ((i > 0 && nums[i] === nums[i - 1]) || - (i + 1 < n && nums[i] === nums[i + 1])) { + if ( + (i > 0 && nums[i] === nums[i - 1]) || + (i + 1 < n && nums[i] === nums[i + 1]) + ) { continue; } res.push(nums[i]); @@ -383,8 +385,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -398,11 +400,11 @@ class Solution: xor = 0 for num in nums: xor ^= num - + diff_bit = 1 while not (xor & diff_bit): diff_bit <<= 1 - + a = b = 0 for num in nums: if diff_bit & num: @@ -482,7 +484,8 @@ class Solution { diff_bit <<= 1; } - let a = 0, b = 0; + let a = 0, + b = 0; for (const num of nums) { if (num & diff_bit) { a ^= num; @@ -499,8 +502,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -514,7 +517,7 @@ class Solution: xor = 0 for num in nums: xor ^= num - + diff_bit = xor & (-xor) a = b = 0 @@ -585,9 +588,10 @@ class Solution { xor ^= num; } - let diff_bit = xor & (-xor); + let diff_bit = xor & -xor; - let a = 0, b = 0; + let a = 0, + b = 0; for (const num of nums) { if (num & diff_bit) { a ^= num; @@ -604,5 +608,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/single-number.md b/articles/single-number.md index 8919e9baa..f9aa4abf2 100644 --- a/articles/single-number.md +++ b/articles/single-number.md @@ -30,7 +30,7 @@ public class Solution { return nums[i]; } } - return -1; + return -1; } } ``` @@ -51,7 +51,7 @@ public: return nums[i]; } } - return -1; + return -1; } }; ``` @@ -160,8 +160,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -246,9 +246,9 @@ public class Solution { } } foreach (int num in seen) { - return num; + return num; } - return -1; + return -1; } } ``` @@ -308,8 +308,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -458,8 +458,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -567,5 +567,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/single-threaded-cpu.md b/articles/single-threaded-cpu.md index 16f487b94..ec2e4fe1f 100644 --- a/articles/single-threaded-cpu.md +++ b/articles/single-threaded-cpu.md @@ -31,7 +31,7 @@ class Solution: ```java public class Solution { public int[] getOrder(int[][] tasks) { - PriorityQueue available = new PriorityQueue<>((a, b) -> + PriorityQueue available = new PriorityQueue<>((a, b) -> a[0] == b[0] ? Integer.compare(a[1], b[1]) : Integer.compare(a[0], b[0]) ); PriorityQueue pending = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])); @@ -109,12 +109,10 @@ class Solution { * @return {number[]} */ getOrder(tasks) { - const available = new PriorityQueue( - (a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0] - ); - const pending = new PriorityQueue( - (a, b) => a[0] - b[0] + const available = new PriorityQueue((a, b) => + a[0] === b[0] ? a[1] - b[1] : a[0] - b[0], ); + const pending = new PriorityQueue((a, b) => a[0] - b[0]); tasks.forEach(([enqueueTime, processTime], i) => { pending.enqueue([enqueueTime, processTime, i]); @@ -183,8 +181,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -225,7 +223,7 @@ public class Solution { Arrays.sort(tasks, Comparator.comparingInt(t -> t[0])); int[] res = new int[n]; - PriorityQueue minHeap = new PriorityQueue<>((a, b) -> + PriorityQueue minHeap = new PriorityQueue<>((a, b) -> a[0] == b[0] ? Integer.compare(a[1], b[1]) : Integer.compare(a[0], b[0]) ); @@ -295,11 +293,12 @@ class Solution { tasks.sort((a, b) => a[0] - b[0]); const res = []; - const minHeap = new PriorityQueue((a, b) => - a[0] === b[0] ? a[1] - b[1] : a[0] - b[0] + const minHeap = new PriorityQueue((a, b) => + a[0] === b[0] ? a[1] - b[1] : a[0] - b[0], ); - let i = 0, time = tasks[0][0]; + let i = 0, + time = tasks[0][0]; while (minHeap.size() || i < n) { while (i < n && time >= tasks[i][0]) { minHeap.enqueue([tasks[i][1], tasks[i][2]]); @@ -360,8 +359,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -375,16 +374,16 @@ class Solution: n = len(tasks) indices = list(range(n)) indices.sort(key=lambda i: (tasks[i][0], i)) - + class Task: def __init__(self, idx): self.idx = idx - + def __lt__(self, other): if tasks[self.idx][1] != tasks[other.idx][1]: return tasks[self.idx][1] < tasks[other.idx][1] return self.idx < other.idx - + minHeap = [] res = [] time = i = 0 @@ -392,14 +391,14 @@ class Solution: while i < n and tasks[indices[i]][0] <= time: heapq.heappush(minHeap, Task(indices[i])) i += 1 - + if not minHeap: time = tasks[indices[i]][0] else: next_task = heapq.heappop(minHeap) time += tasks[next_task.idx][1] res.append(next_task.idx) - + return res ``` @@ -411,15 +410,15 @@ public class Solution { for (int i = 0; i < n; i++) { indices[i] = i; } - - Arrays.sort(indices, (a, b) -> + + Arrays.sort(indices, (a, b) -> tasks[a][0] != tasks[b][0] ? tasks[a][0] - tasks[b][0] : a - b ); - - PriorityQueue minHeap = new PriorityQueue<>((a, b) -> + + PriorityQueue minHeap = new PriorityQueue<>((a, b) -> tasks[a][1] != tasks[b][1] ? tasks[a][1] - tasks[b][1] : a - b ); - + int[] result = new int[n]; long time = 0; int i = 0, resIndex = 0; @@ -428,7 +427,7 @@ public class Solution { minHeap.offer(indices[i]); i++; } - + if (minHeap.isEmpty()) { time = tasks[indices[i]][0]; } else { @@ -437,7 +436,7 @@ public class Solution { result[resIndex++] = nextIndex; } } - + return result; } } @@ -453,26 +452,26 @@ public: iota(indices.begin(), indices.end(), 0); sort(indices.begin(), indices.end(), [&](int a, int b) { - return tasks[a][0] < tasks[b][0] || + return tasks[a][0] < tasks[b][0] || (tasks[a][0] == tasks[b][0] && a < b); }); - + auto comp = [&](int a, int b) { - return tasks[a][1] > tasks[b][1] || + return tasks[a][1] > tasks[b][1] || (tasks[a][1] == tasks[b][1] && a > b); }; priority_queue, decltype(comp)> minHeap(comp); - + vector result; long long time = 0; int i = 0; - + while (!minHeap.empty() || i < n) { while (i < n && tasks[indices[i]][0] <= time) { minHeap.push(indices[i]); i++; } - + if (minHeap.empty()) { time = tasks[indices[i]][0]; } else { @@ -482,7 +481,7 @@ public: result.push_back(nextIndex); } } - + return result; } }; @@ -504,14 +503,12 @@ class Solution { return a - b; }); - const minHeap = new PriorityQueue( - (a, b) => { - if (tasks[a][1] !== tasks[b][1]) { - return tasks[a][1] - tasks[b][1]; - } - return a - b; + const minHeap = new PriorityQueue((a, b) => { + if (tasks[a][1] !== tasks[b][1]) { + return tasks[a][1] - tasks[b][1]; } - ); + return a - b; + }); const res = []; let time = 0; @@ -531,7 +528,7 @@ class Solution { res.push(nextIndex); } } - + return res; } } @@ -583,5 +580,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ diff --git a/articles/sliding-window-maximum.md b/articles/sliding-window-maximum.md index a7af08296..9e2d695b0 100644 --- a/articles/sliding-window-maximum.md +++ b/articles/sliding-window-maximum.md @@ -21,7 +21,7 @@ public class Solution { public int[] maxSlidingWindow(int[] nums, int k) { int n = nums.length; int[] output = new int[n - k + 1]; - + for (int i = 0; i <= n - k; i++) { int maxi = nums[i]; for (int j = i; j < i + k; j++) { @@ -29,7 +29,7 @@ public class Solution { } output[i] = maxi; } - + return output; } } @@ -41,7 +41,7 @@ public: vector maxSlidingWindow(vector& nums, int k) { vector output; int n = nums.size(); - + for (int i = 0; i <= n - k; i++) { int maxi = nums[i]; for (int j = i; j < i + k; j++) { @@ -49,7 +49,7 @@ public: } output.push_back(maxi); } - + return output; } }; @@ -64,7 +64,7 @@ class Solution { */ maxSlidingWindow(nums, k) { let output = []; - + for (let i = 0; i <= nums.length - k; i++) { let maxi = nums[i]; for (let j = i; j < i + k; j++) { @@ -72,7 +72,7 @@ class Solution { } output.push(maxi); } - + return output; } } @@ -155,10 +155,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * k)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n - k + 1)$ space for the output array. +- Time complexity: $O(n * k)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n - k + 1)$ space for the output array. > Where $n$ is the length of the array and $k$ is the size of the window. @@ -308,7 +308,7 @@ public: class SegmentTree { /** * @constructor - * @param {number} N + * @param {number} N * @param {number[]} A */ constructor(N, A) { @@ -320,7 +320,7 @@ class SegmentTree { } /** - * @param {number} N + * @param {number} N * @param {number[]} A * @return {void} */ @@ -330,7 +330,7 @@ class SegmentTree { this.tree[this.n + i] = A[i]; } for (let i = this.n - 1; i > 0; i--) { - this.tree[i] = Math.max(this.tree[i << 1], this.tree[i << 1 | 1]); + this.tree[i] = Math.max(this.tree[i << 1], this.tree[(i << 1) | 1]); } } @@ -437,7 +437,7 @@ func NewSegmentTree(N int, A []int) *SegmentTree { for bits.OnesCount(uint(n)) != 1 { n++ } - + st := &SegmentTree{ n: n, } @@ -449,7 +449,7 @@ func (st *SegmentTree) build(N int, A []int) { st.tree = make([]int, 2*st.n) for i := range st.tree { st.tree[i] = math.MinInt - } + } for i := 0; i < N; i++ { st.tree[st.n+i] = A[i] } @@ -462,7 +462,7 @@ func (st *SegmentTree) Query(l, r int) int { res := math.MinInt l += st.n r += st.n + 1 - + for l < r { if l&1 == 1 { res = max(res, st.tree[l]) @@ -489,11 +489,11 @@ func maxSlidingWindow(nums []int, k int) []int { n := len(nums) segTree := NewSegmentTree(n, nums) output := make([]int, n-k+1) - + for i := 0; i <= n-k; i++ { output[i] = segTree.Query(i, i+k-1) } - + return output } ``` @@ -502,7 +502,7 @@ func maxSlidingWindow(nums []int, k int) []int { class SegmentTree(N: Int, A: IntArray) { private var n: Int = N private var tree: IntArray = IntArray(0) - + init { var size = N while (Integer.bitCount(size) != 1) { @@ -511,10 +511,10 @@ class SegmentTree(N: Int, A: IntArray) { n = size build(N, A) } - + private fun build(N: Int, A: IntArray) { tree = IntArray(2 * n) - tree.fill(Int.MIN_VALUE) + tree.fill(Int.MIN_VALUE) for (i in 0 until N) { tree[n + i] = A[i] } @@ -522,12 +522,12 @@ class SegmentTree(N: Int, A: IntArray) { tree[i] = maxOf(tree[i * 2], tree[i * 2 + 1]) } } - + fun query(l: Int, r: Int): Int { var res = Int.MIN_VALUE var left = l + n var right = r + n + 1 - + while (left < right) { if (left % 2 == 1) { res = maxOf(res, tree[left]) @@ -619,8 +619,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -690,7 +690,7 @@ class Solution { * @return {number[]} */ maxSlidingWindow(nums, k) { - const heap = new MaxPriorityQueue(x => x[0]); + const heap = new MaxPriorityQueue((x) => x[0]); const output = []; const length = nums.length; @@ -716,7 +716,7 @@ public class Solution { PriorityQueue<(int val, int idx), int> pq = new PriorityQueue<(int val, int idx), int>( Comparer.Create((a, b) => b.CompareTo(a)) ); - + int[] output = new int[nums.Length - k + 1]; int idx = 0; @@ -741,7 +741,7 @@ func maxSlidingWindow(nums []int, k int) []int { heap := priorityqueue.NewWith(func(a, b interface{}) int { return b.([2]int)[0] - a.([2]int)[0] }) - + output := []int{} for i := 0; i < len(nums); i++ { heap.Enqueue([2]int{nums[i], i}) @@ -787,7 +787,7 @@ class Solution { for i in 0..= k - 1 { while heap.max!.index <= i - k { heap.removeMax() @@ -813,8 +813,8 @@ struct Item: Comparable { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -947,7 +947,10 @@ class Solution { if ((n - 1 - i) % k === 0) { rightMax[n - 1 - i] = nums[n - 1 - i]; } else { - rightMax[n - 1 - i] = Math.max(rightMax[n - i], nums[n - 1 - i]); + rightMax[n - 1 - i] = Math.max( + rightMax[n - i], + nums[n - 1 - i], + ); } } @@ -1044,29 +1047,29 @@ class Solution { val n = nums.size val leftMax = IntArray(n) val rightMax = IntArray(n) - + leftMax[0] = nums[0] rightMax[n - 1] = nums[n - 1] - + for (i in 1 until n) { if (i % k == 0) { leftMax[i] = nums[i] } else { leftMax[i] = maxOf(leftMax[i - 1], nums[i]) } - + if ((n - 1 - i) % k == 0) { rightMax[n - 1 - i] = nums[n - 1 - i] } else { rightMax[n - 1 - i] = maxOf(rightMax[n - i], nums[n - 1 - i]) } } - + val output = IntArray(n - k + 1) for (i in 0..n - k) { output[i] = maxOf(leftMax[i + k - 1], rightMax[i]) } - + return output } } @@ -1111,8 +1114,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -1215,7 +1218,8 @@ class Solution { const n = nums.length; const output = new Array(n - k + 1); const q = new Deque(); - let l = 0, r = 0; + let l = 0, + r = 0; while (r < n) { while (q.size() && nums[q.back()] < nums[r]) { @@ -1227,7 +1231,7 @@ class Solution { q.popFront(); } - if ((r + 1) >= k) { + if (r + 1 >= k) { output[l] = nums[q.front()]; l++; } @@ -1274,24 +1278,24 @@ func maxSlidingWindow(nums []int, k int) []int { output := []int{} q := []int{} l, r := 0, 0 - + for r < len(nums) { for len(q) > 0 && nums[q[len(q)-1]] < nums[r] { q = q[:len(q)-1] } q = append(q, r) - + if l > q[0] { q = q[1:] } - + if (r + 1) >= k { output = append(output, nums[q[0]]) l += 1 } r += 1 } - + return output } ``` @@ -1303,24 +1307,24 @@ class Solution { val q = ArrayDeque() var l = 0 var r = 0 - + while (r < nums.size) { while (q.isNotEmpty() && nums[q.last()] < nums[r]) { q.removeLast() } q.addLast(r) - + if (l > q.first()) { q.removeFirst() } - + if ((r + 1) >= k) { output.add(nums[q.first()]) l += 1 } r += 1 } - + return output.toIntArray() } } @@ -1359,5 +1363,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/sliding-window-median.md b/articles/sliding-window-median.md index b49ca4071..5c98c3c0d 100644 --- a/articles/sliding-window-median.md +++ b/articles/sliding-window-median.md @@ -68,7 +68,9 @@ class Solution { if (k % 2 === 1) { res.push(tmp[Math.floor(k / 2)]); } else { - res.push((tmp[Math.floor(k / 2)] + tmp[Math.floor((k - 1) / 2)]) / 2); + res.push( + (tmp[Math.floor(k / 2)] + tmp[Math.floor((k - 1) / 2)]) / 2, + ); } } return res; @@ -80,10 +82,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * k\log k)$ -* Space complexity: - * $O(k)$ extra space. - * $O(n - k + 1)$ space for output array. +- Time complexity: $O(n * k\log k)$ +- Space complexity: + - $O(k)$ extra space. + - $O(n - k + 1)$ space for output array. > Where $n$ is the size of the array $nums$ and $k$ is the size of the sliding window. @@ -260,11 +262,14 @@ class Solution { large.enqueue(small.dequeue()); } - const res = [k % 2 === 1 ? small.front() : (large.front() + small.front()) / 2]; + const res = [ + k % 2 === 1 ? small.front() : (large.front() + small.front()) / 2, + ]; for (let i = k; i < nums.length; i++) { const toRemove = nums[i - k]; d.set(toRemove, (d.get(toRemove) || 0) + 1); - let balance = small.size() > 0 && toRemove <= small.front() ? -1 : 1; + let balance = + small.size() > 0 && toRemove <= small.front() ? -1 : 1; if (nums[i] <= small.front()) { small.enqueue(nums[i]); @@ -290,7 +295,11 @@ class Solution { large.dequeue(); } - res.push(k % 2 === 1 ? small.front() : (large.front() + small.front()) / 2); + res.push( + k % 2 === 1 + ? small.front() + : (large.front() + small.front()) / 2, + ); } return res; @@ -302,10 +311,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: - * $O(n)$ extra space. - * $O(n - k + 1)$ space for output array. +- Time complexity: $O(n \log n)$ +- Space complexity: + - $O(n)$ extra space. + - $O(n - k + 1)$ space for output array. > Where $n$ is the size of the array $nums$ and $k$ is the size of the sliding window. @@ -342,10 +351,10 @@ class Solution: ```java public class Solution { public double[] medianSlidingWindow(int[] nums, int k) { - TreeSet small = new TreeSet<>((a, b) -> + TreeSet small = new TreeSet<>((a, b) -> nums[a] != nums[b] ? Integer.compare(nums[a], nums[b]) : Integer.compare(a, b) ); - TreeSet large = new TreeSet<>((a, b) -> + TreeSet large = new TreeSet<>((a, b) -> nums[a] != nums[b] ? Integer.compare(nums[a], nums[b]) : Integer.compare(a, b) ); double[] res = new double[nums.length - k + 1]; @@ -359,7 +368,7 @@ public class Solution { while (small.size() > large.size() + 1) large.add(small.pollLast()); while (large.size() > small.size()) small.add(large.pollFirst()); if (i >= k - 1) { - res[i - k + 1] = k % 2 == 1 ? nums[small.last()] : + res[i - k + 1] = k % 2 == 1 ? nums[small.last()] : (nums[small.last()] + 0L + nums[large.first()]) / 2.0; } } @@ -391,7 +400,7 @@ public: } if (i >= k - 1) { res.push_back( - k % 2 == 1 ? *small.rbegin() : + k % 2 == 1 ? *small.rbegin() : ((*small.rbegin() + 0LL + *large.begin()) / 2.0) ); } @@ -405,10 +414,10 @@ public: ### Time & Space Complexity -* Time complexity: $O(n \log k)$ -* Space complexity: - * $O(k)$ extra space. - * $O(n - k + 1)$ space for output array. +- Time complexity: $O(n \log k)$ +- Space complexity: + - $O(k)$ extra space. + - $O(n - k + 1)$ space for output array. > Where $n$ is the size of the array $nums$ and $k$ is the size of the sliding window. @@ -465,9 +474,9 @@ public: ### Time & Space Complexity -* Time complexity: $O(n \log k)$ -* Space complexity: - * $O(k)$ extra space. - * $O(n - k + 1)$ space for output array. +- Time complexity: $O(n \log k)$ +- Space complexity: + - $O(k)$ extra space. + - $O(n - k + 1)$ space for output array. -> Where $n$ is the size of the array $nums$ and $k$ is the size of the sliding window. \ No newline at end of file +> Where $n$ is the size of the array $nums$ and $k$ is the size of the sliding window. diff --git a/articles/smallest-string-starting-from-leaf.md b/articles/smallest-string-starting-from-leaf.md index d3d241adb..cc389e666 100644 --- a/articles/smallest-string-starting-from-leaf.md +++ b/articles/smallest-string-starting-from-leaf.md @@ -138,7 +138,7 @@ class Solution { const dfs = (node, cur) => { if (!node) return; - + cur = String.fromCharCode(97 + node.val) + cur; if (node.left && node.right) { @@ -149,7 +149,7 @@ class Solution { return cur; }; - return dfs(root, ""); + return dfs(root, ''); } } ``` @@ -158,8 +158,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -291,7 +291,7 @@ class Solution { */ smallestFromLeaf(root) { const q = new Queue(); - q.push([root, ""]); + q.push([root, '']); let res = null; while (!q.isEmpty()) { @@ -315,8 +315,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -342,12 +342,12 @@ class Solution: if not node.left and not node.right: res = min(res, cur) if res else cur - + if node.right: stack.append((node.right, cur)) if node.left: stack.append((node.left, cur)) - + return res ``` @@ -446,7 +446,7 @@ class Solution { * @return {string} */ smallestFromLeaf(root) { - const stack = [[root, ""]]; + const stack = [[root, '']]; let res = null; while (stack.length) { @@ -470,5 +470,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ \ No newline at end of file +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ diff --git a/articles/snakes-and-ladders.md b/articles/snakes-and-ladders.md index afc71ef47..964c7d1fd 100644 --- a/articles/snakes-and-ladders.md +++ b/articles/snakes-and-ladders.md @@ -6,7 +6,7 @@ class Solution: def snakesAndLadders(self, board: List[List[int]]) -> int: n = len(board) - + def intToPos(square): r = (square - 1) // n c = (square - 1) % n @@ -14,26 +14,26 @@ class Solution: c = n - 1 - c r = n - 1 - r return r, c - + q = deque([(1, 0)]) visit = set() - + while q: square, moves = q.popleft() - + for i in range(1, 7): nextSquare = square + i r, c = intToPos(nextSquare) if board[r][c] != -1: nextSquare = board[r][c] - + if nextSquare == n * n: return moves + 1 - + if nextSquare not in visit: visit.add(nextSquare) q.append((nextSquare, moves + 1)) - + return -1 ``` @@ -44,11 +44,11 @@ public class Solution { Queue q = new LinkedList<>(); q.offer(new int[]{1, 0}); Set visit = new HashSet<>(); - + while (!q.isEmpty()) { int[] cur = q.poll(); int square = cur[0], moves = cur[1]; - + for (int i = 1; i <= 6; i++) { int nextSquare = square + i; int[] pos = intToPos(nextSquare, n); @@ -65,7 +65,7 @@ public class Solution { } return -1; } - + private int[] intToPos(int square, int n) { int r = (square - 1) / n; int c = (square - 1) % n; @@ -103,7 +103,7 @@ public: } return -1; } - + private: pair intToPos(int square, int n) { int r = (square - 1) / n; @@ -159,8 +159,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -172,7 +172,7 @@ class Solution { class Solution: def snakesAndLadders(self, board: List[List[int]]) -> int: n = len(board) - + def intToPos(square): r = (square - 1) // n c = (square - 1) % n @@ -180,29 +180,29 @@ class Solution: c = n - 1 - c r = n - 1 - r return r, c - + dist = [-1] * (n * n + 1) q = deque([1]) dist[1] = 0 - + while q: square = q.popleft() - + for i in range(1, 7): nextSquare = square + i if nextSquare > n * n: break - + r, c = intToPos(nextSquare) if board[r][c] != -1: nextSquare = board[r][c] - + if dist[nextSquare] == -1: dist[nextSquare] = dist[square] + 1 if nextSquare == n * n: return dist[nextSquare] q.append(nextSquare) - + return -1 ``` @@ -359,8 +359,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -372,7 +372,7 @@ class Solution { class Solution: def snakesAndLadders(self, board: List[List[int]]) -> int: n = len(board) - + def intToPos(square): r = (square - 1) // n c = (square - 1) % n @@ -380,31 +380,31 @@ class Solution: c = n - 1 - c r = n - 1 - r return r, c - + q = deque([1]) board[n - 1][0] = 0 moves = 0 - + while q: for _ in range(len(q)): square = q.popleft() - + for i in range(1, 7): nextSquare = square + i if nextSquare > n * n: break - + r, c = intToPos(nextSquare) if board[r][c] != -1: nextSquare = board[r][c] - + if board[r][c] != 0: if nextSquare == n * n: return moves + 1 q.append(nextSquare) board[r][c] = 0 moves += 1 - + return -1 ``` @@ -437,7 +437,7 @@ public class Solution { if (nextSquare == n * n) { return moves + 1; } - + board[r][c] = 0; q.add(nextSquare); } @@ -489,7 +489,7 @@ public: if (nextSquare == n * n) { return moves + 1; } - + board[r][c] = 0; q.push(nextSquare); } @@ -550,7 +550,7 @@ class Solution { if (nextSquare === n * n) { return moves + 1; } - + board[r][c] = 0; queue.push(nextSquare); } @@ -568,5 +568,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ \ No newline at end of file +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ diff --git a/articles/solving-questions-with-brainpower.md b/articles/solving-questions-with-brainpower.md index 248ec63b3..d0774539e 100644 --- a/articles/solving-questions-with-brainpower.md +++ b/articles/solving-questions-with-brainpower.md @@ -49,7 +49,10 @@ class Solution { mostPoints(questions) { const dfs = (i) => { if (i >= questions.length) return 0; - return Math.max(dfs(i + 1), questions[i][0] + dfs(i + 1 + questions[i][1])); + return Math.max( + dfs(i + 1), + questions[i][0] + dfs(i + 1 + questions[i][1]), + ); }; return dfs(0); } @@ -60,8 +63,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ --- @@ -134,7 +137,10 @@ class Solution { const dfs = (i) => { if (i >= questions.length) return 0; if (dp[i] !== -1) return dp[i]; - dp[i] = Math.max(dfs(i + 1), questions[i][0] + dfs(i + 1 + questions[i][1])); + dp[i] = Math.max( + dfs(i + 1), + questions[i][0] + dfs(i + 1 + questions[i][1]), + ); return dp[i]; }; @@ -147,8 +153,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -163,7 +169,7 @@ class Solution: for i in range(len(questions) - 1, -1, -1): dp[i] = max( - questions[i][0] + dp.get(i + 1 + questions[i][1], 0), + questions[i][0] + dp.get(i + 1 + questions[i][1], 0), dp.get(i + 1, 0) ) return dp.get(0) @@ -177,7 +183,7 @@ public class Solution { for (int i = n - 1; i >= 0; i--) { dp[i] = Math.max( - questions[i][0] + (i + 1 + questions[i][1] < n ? dp[i + 1 + questions[i][1]] : 0), + questions[i][0] + (i + 1 + questions[i][1] < n ? dp[i + 1 + questions[i][1]] : 0), dp[i + 1] ); } @@ -195,7 +201,7 @@ public: for (int i = n - 1; i >= 0; i--) { dp[i] = max( - (long long)questions[i][0] + (i + 1 + questions[i][1] < n ? dp[i + 1 + questions[i][1]] : 0), + (long long)questions[i][0] + (i + 1 + questions[i][1] < n ? dp[i + 1 + questions[i][1]] : 0), dp[i + 1] ); } @@ -216,8 +222,11 @@ class Solution { for (let i = n - 1; i >= 0; i--) { dp[i] = Math.max( - questions[i][0] + (i + 1 + questions[i][1] < n ? dp[i + 1 + questions[i][1]] : 0), - dp[i + 1] + questions[i][0] + + (i + 1 + questions[i][1] < n + ? dp[i + 1 + questions[i][1]] + : 0), + dp[i + 1], ); } return dp[0]; @@ -229,5 +238,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/sort-an-array.md b/articles/sort-an-array.md index 6b34f49d2..4dbf28c54 100644 --- a/articles/sort-an-array.md +++ b/articles/sort-an-array.md @@ -55,43 +55,43 @@ public class Solution { private int partition(int[] nums, int left, int right) { int mid = (left + right) >> 1; swap(nums, mid, left + 1); - - if (nums[left] > nums[right]) + + if (nums[left] > nums[right]) swap(nums, left, right); - if (nums[left + 1] > nums[right]) + if (nums[left + 1] > nums[right]) swap(nums, left + 1, right); - if (nums[left] > nums[left + 1]) + if (nums[left] > nums[left + 1]) swap(nums, left, left + 1); - + int pivot = nums[left + 1]; int i = left + 1; int j = right; - + while (true) { while (nums[++i] < pivot); while (nums[--j] > pivot); if (i > j) break; swap(nums, i, j); } - + nums[left + 1] = nums[j]; nums[j] = pivot; return j; } - + private void swap(int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } - + private void quickSort(int[] nums, int left, int right) { if (right <= left + 1) { if (right == left + 1 && nums[right] < nums[left]) swap(nums, left, right); return; } - + int j = partition(nums, left, right); quickSort(nums, left, j - 1); quickSort(nums, j + 1, right); @@ -110,30 +110,30 @@ public: int partition(vector& nums, int left, int right) { int mid = (left + right) >> 1; swap(nums[mid], nums[left + 1]); - - if (nums[left] > nums[right]) + + if (nums[left] > nums[right]) swap(nums[left], nums[right]); - if (nums[left + 1] > nums[right]) + if (nums[left + 1] > nums[right]) swap(nums[left + 1], nums[right]); - if (nums[left] > nums[left + 1]) + if (nums[left] > nums[left + 1]) swap(nums[left], nums[left + 1]); - + int pivot = nums[left + 1]; int i = left + 1; int j = right; - + while (true) { while (nums[++i] < pivot); while (nums[--j] > pivot); if (i > j) break; swap(nums[i], nums[j]); } - + nums[left + 1] = nums[j]; nums[j] = pivot; return j; } - + void quickSort(vector& nums, int left, int right) { if (right <= left + 1) { if (right == left + 1 && nums[right] < nums[left]) @@ -163,42 +163,42 @@ class Solution { function partition(left, right) { const mid = (left + right) >> 1; [nums[mid], nums[left + 1]] = [nums[left + 1], nums[mid]]; - + if (nums[left] > nums[right]) [nums[left], nums[right]] = [nums[right], nums[left]]; if (nums[left + 1] > nums[right]) [nums[left + 1], nums[right]] = [nums[right], nums[left + 1]]; if (nums[left] > nums[left + 1]) [nums[left], nums[left + 1]] = [nums[left + 1], nums[left]]; - + const pivot = nums[left + 1]; let i = left + 1; let j = right; - + while (true) { while (nums[++i] < pivot); while (nums[--j] > pivot); if (i > j) break; [nums[i], nums[j]] = [nums[j], nums[i]]; } - + nums[left + 1] = nums[j]; nums[j] = pivot; return j; } - + function quickSort(left, right) { if (right <= left + 1) { if (right == left + 1 && nums[right] < nums[left]) [nums[left], nums[right]] = [nums[right], nums[left]]; return; } - + const j = partition(left, right); quickSort(left, j - 1); quickSort(j + 1, right); } - + quickSort(0, nums.length - 1); return nums; } @@ -261,8 +261,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ in average case, $O(n ^ 2)$ in worst case. -* Space complexity: $O(\log n)$ for recursive stack. +- Time complexity: $O(n \log n)$ in average case, $O(n ^ 2)$ in worst case. +- Space complexity: $O(\log n)$ for recursive stack. --- @@ -293,7 +293,7 @@ class Solution: nums[i] = right[k] k += 1 i += 1 - + def mergeSort(arr, l, r): if l == r: return @@ -303,7 +303,7 @@ class Solution: mergeSort(arr, m + 1, r) merge(arr, l, m, r) return - + mergeSort(nums, 0, len(nums)) return nums ``` @@ -407,11 +407,11 @@ class Solution { } /** - * @param {number[]} arr - * @param {number} l - * @param {number} r - * @return {void} - */ + * @param {number[]} arr + * @param {number} l + * @param {number} r + * @return {void} + */ mergeSort(arr, l, r) { if (l >= r) return; let m = Math.floor((l + r) / 2); @@ -421,15 +421,16 @@ class Solution { } /** - * @param {number[]} arr - * @param {number} l - * @param {number} m - * @param {number} r - * @return {void} - */ + * @param {number[]} arr + * @param {number} l + * @param {number} m + * @param {number} r + * @return {void} + */ merge(arr, l, m, r) { let temp = []; - let i = l, j = m + 1; + let i = l, + j = m + 1; while (i <= m && j <= r) { if (arr[i] <= arr[j]) { @@ -494,8 +495,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -508,27 +509,27 @@ class Solution: def sortArray(self, nums: List[int]) -> List[int]: self.heapSort(nums) return nums - + def heapify(self, arr, n, i): l = (i << 1) + 1 r = (i << 1) + 2 largestNode = i - + if l < n and arr[l] > arr[largestNode]: largestNode = l - + if r < n and arr[r] > arr[largestNode]: largestNode = r - + if largestNode != i: arr[i], arr[largestNode] = arr[largestNode], arr[i] self.heapify(arr, n, largestNode) - + def heapSort(self, arr): n = len(arr) for i in range(n // 2 - 1, -1, -1): self.heapify(arr, n, i) - + for i in range(n - 1, 0, -1): arr[0], arr[i] = arr[i], arr[0] self.heapify(arr, i, 0) @@ -540,20 +541,20 @@ public class Solution { heapSort(nums); return nums; } - + private void heapify(int[] arr, int n, int i) { int l = (i << 1) + 1; int r = (i << 1) + 2; int largestNode = i; - + if (l < n && arr[l] > arr[largestNode]) { largestNode = l; } - + if (r < n && arr[r] > arr[largestNode]) { largestNode = r; } - + if (largestNode != i) { int temp = arr[i]; arr[i] = arr[largestNode]; @@ -561,13 +562,13 @@ public class Solution { heapify(arr, n, largestNode); } } - + private void heapSort(int[] arr) { int n = arr.length; for (int i = n / 2 - 1; i >= 0; i--) { heapify(arr, n, i); } - + for (int i = n - 1; i > 0; i--) { int temp = arr[0]; arr[0] = arr[i]; @@ -590,27 +591,27 @@ private: int l = (i << 1) + 1; int r = (i << 1) + 2; int largestNode = i; - + if (l < n && arr[l] > arr[largestNode]) { largestNode = l; } - + if (r < n && arr[r] > arr[largestNode]) { largestNode = r; } - + if (largestNode != i) { swap(arr[i], arr[largestNode]); heapify(arr, n, largestNode); } } - + void heapSort(vector& arr) { int n = arr.size(); for (int i = n / 2 - 1; i >= 0; i--) { heapify(arr, n, i); } - + for (int i = n - 1; i > 0; i--) { swap(arr[0], arr[i]); heapify(arr, i, 0); @@ -622,49 +623,49 @@ private: ```javascript class Solution { /** - * @param {number[]} nums - * @return {number[]} - */ + * @param {number[]} nums + * @return {number[]} + */ sortArray(nums) { this.heapSort(nums); return nums; } - + /** - * @param {number[]} arr - * @param {number} n - * @param {number} i - * @return {void} - */ + * @param {number[]} arr + * @param {number} n + * @param {number} i + * @return {void} + */ heapify(arr, n, i) { let l = (i << 1) + 1; let r = (i << 1) + 2; let largestNode = i; - + if (l < n && arr[l] > arr[largestNode]) { largestNode = l; } - + if (r < n && arr[r] > arr[largestNode]) { largestNode = r; } - + if (largestNode !== i) { [arr[i], arr[largestNode]] = [arr[largestNode], arr[i]]; this.heapify(arr, n, largestNode); } } - + /** - * @param {number[]} arr - * @return {void} - */ + * @param {number[]} arr + * @return {void} + */ heapSort(arr) { let n = arr.length; for (let i = Math.floor(n / 2) - 1; i >= 0; i--) { this.heapify(arr, n, i); } - + for (let i = n - 1; i > 0; i--) { [arr[0], arr[i]] = [arr[i], arr[0]]; this.heapify(arr, i, 0); @@ -724,8 +725,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(\log n)$ for recursive stack. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(\log n)$ for recursive stack. --- @@ -758,13 +759,13 @@ public class Solution { private void countingSort(int[] arr) { HashMap count = new HashMap<>(); int minVal = arr[0], maxVal = arr[0]; - + for (int i = 0; i < arr.length; i++) { minVal = Math.min(minVal, arr[i]); maxVal = Math.max(maxVal, arr[i]); count.put(arr[i], count.getOrDefault(arr[i], 0) + 1); } - + int index = 0; for (int val = minVal; val <= maxVal; ++val) { while (count.getOrDefault(val, 0) > 0) { @@ -793,7 +794,7 @@ private: for (auto& val : arr) { count[val]++; } - + int index = 0; for (int val = minVal; val <= maxVal; ++val) { while (count[val] > 0) { @@ -815,30 +816,30 @@ public: ```javascript class Solution { /** - * @param {number[]} nums - * @return {number[]} - */ + * @param {number[]} nums + * @return {number[]} + */ sortArray(nums) { this.countingSort(nums); return nums; } - + /** - * @param {number[]} arr - * @return {void} - */ + * @param {number[]} arr + * @return {void} + */ countingSort(arr) { let count = new Map(); - let minVal = Math.min(...nums); - let maxVal = Math.max(...nums); + let minVal = Math.min(...nums); + let maxVal = Math.max(...nums); - nums.forEach(val => { + nums.forEach((val) => { if (!count.has(val)) { count.set(val, 0); } - count.set(val, count.get(val) + 1); + count.set(val, count.get(val) + 1); }); - + let index = 0; for (let val = minVal; val <= maxVal; val += 1) { while (count.get(val) > 0) { @@ -886,8 +887,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n + k)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n + k)$ +- Space complexity: $O(n)$ > Where $n$ is the size of the array $nums$ and $k$ is the range between the minimum and maximum values in the array. @@ -1085,8 +1086,8 @@ class Solution { * @return {number[]} */ sortArray(nums) { - const negatives = nums.filter(num => num < 0).map(num => -num); - const positives = nums.filter(num => num >= 0); + const negatives = nums.filter((num) => num < 0).map((num) => -num); + const positives = nums.filter((num) => num >= 0); if (negatives.length > 0) { this.radixSort(negatives); @@ -1217,8 +1218,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(d * n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(d * n)$ +- Space complexity: $O(n)$ > Where $n$ is the size of the array $nums$ and $d$ is the number of digits in the maximum element of the array. @@ -1242,7 +1243,7 @@ class Solution: j -= gap nums[j + gap] = tmp gap //= 2 - + n = len(nums) if n == 1: return nums @@ -1328,7 +1329,7 @@ class Solution { } gap = Math.floor(gap / 2); } - } + }; shellSort(); return nums; @@ -1368,5 +1369,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ in average case, $O(n ^ 2)$ in worst case. -* Space complexity: $O(1)$ +- Time complexity: $O(n \log n)$ in average case, $O(n ^ 2)$ in worst case. +- Space complexity: $O(1)$ diff --git a/articles/sort-array-by-increasing-frequency.md b/articles/sort-array-by-increasing-frequency.md index 04a4e1c80..b763527da 100644 --- a/articles/sort-array-by-increasing-frequency.md +++ b/articles/sort-array-by-increasing-frequency.md @@ -75,5 +75,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ diff --git a/articles/sort-array-by-parity.md b/articles/sort-array-by-parity.md index b282d0cea..51437ff50 100644 --- a/articles/sort-array-by-parity.md +++ b/articles/sort-array-by-parity.md @@ -23,8 +23,8 @@ public class Solution { class Solution { public: vector sortArrayByParity(vector& nums) { - sort(nums.begin(), nums.end(), [&](int& a, int& b) { - return (a & 1) < (b & 1); + sort(nums.begin(), nums.end(), [&](int& a, int& b) { + return (a & 1) < (b & 1); }); return nums; } @@ -47,8 +47,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -65,7 +65,7 @@ class Solution: odd.append(num) else: even.append(num) - + idx = 0 for e in even: nums[idx] = e @@ -81,7 +81,7 @@ public class Solution { public int[] sortArrayByParity(int[] nums) { List even = new ArrayList<>(); List odd = new ArrayList<>(); - + for (int num : nums) { if ((num & 1) == 1) { odd.add(num); @@ -89,7 +89,7 @@ public class Solution { even.add(num); } } - + int idx = 0; for (int e : even) { nums[idx++] = e; @@ -97,7 +97,7 @@ public class Solution { for (int o : odd) { nums[idx++] = o; } - + return nums; } } @@ -108,7 +108,7 @@ class Solution { public: vector sortArrayByParity(vector& nums) { vector even, odd; - + for (int& num : nums) { if (num & 1) { odd.push_back(num); @@ -116,7 +116,7 @@ public: even.push_back(num); } } - + int idx = 0; for (int& e : even) { nums[idx++] = e; @@ -124,7 +124,7 @@ public: for (int& o : odd) { nums[idx++] = o; } - + return nums; } }; @@ -139,7 +139,7 @@ class Solution { sortArrayByParity(nums) { const even = []; const odd = []; - + for (let num of nums) { if (num % 2) { odd.push(num); @@ -147,7 +147,7 @@ class Solution { even.push(num); } } - + let idx = 0; for (let e of even) { nums[idx++] = e; @@ -155,7 +155,7 @@ class Solution { for (let o of odd) { nums[idx++] = o; } - + return nums; } } @@ -165,8 +165,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -230,7 +230,8 @@ class Solution { * @return {number[]} */ sortArrayByParity(nums) { - let i = 0, j = nums.length - 1; + let i = 0, + j = nums.length - 1; while (i < j) { if ((nums[i] & 1) == 1) { [nums[i], nums[j]] = [nums[j], nums[i]]; @@ -248,8 +249,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -321,5 +322,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/sort-characters-by-frequency.md b/articles/sort-characters-by-frequency.md index 779312faf..943a26c0b 100644 --- a/articles/sort-characters-by-frequency.md +++ b/articles/sort-characters-by-frequency.md @@ -90,8 +90,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -106,7 +106,7 @@ class Solution: for c in s: count[ord(c)] += 1 - freq = [(chr(i), count[i]) for i in range(123) if count[i] > 0] + freq = [(chr(i), count[i]) for i in range(123) if count[i] > 0] freq.sort(key=lambda x: (-x[1], x[0])) return ''.join(char * freq for char, freq in freq) @@ -219,8 +219,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for the output string. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for the output string. --- @@ -242,7 +242,7 @@ class Solution: if i in buckets: for c in buckets[i]: res.append(c * i) - + return "".join(res) ``` @@ -336,5 +336,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/sort-colors.md b/articles/sort-colors.md index 46bc4a86a..16a3ec712 100644 --- a/articles/sort-colors.md +++ b/articles/sort-colors.md @@ -52,8 +52,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -70,7 +70,7 @@ class Solution: count = [0] * 3 for num in nums: count[num] += 1 - + index = 0 for i in range(3): while count[i]: @@ -160,8 +160,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -182,7 +182,7 @@ class Solution: temp = nums[i] nums[i] = nums[j] nums[j] = temp - + while i <= r: if nums[i] == 0: swap(l, i) @@ -246,7 +246,9 @@ class Solution { * @return {void} Do not return anything, modify nums in-place instead. */ sortColors(nums) { - let i = 0, l = 0, r = nums.length - 1; + let i = 0, + l = 0, + r = nums.length - 1; while (i <= r) { if (nums[i] == 0) { [nums[l], nums[i]] = [nums[i], nums[l]]; @@ -292,8 +294,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -374,7 +376,9 @@ class Solution { * @return {void} Do not return anything, modify nums in-place instead. */ sortColors(nums) { - let zero = 0, one = 0, two = 0; + let zero = 0, + one = 0, + two = 0; for (let i = 0; i < nums.length; i++) { if (nums[i] == 0) { nums[two++] = 2; @@ -416,8 +420,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -487,7 +491,8 @@ class Solution { * @return {void} Do not return anything, modify nums in-place instead. */ sortColors(nums) { - let zero = 0, one = 0; + let zero = 0, + one = 0; for (let two = 0; two < nums.length; two++) { let tmp = nums[two]; nums[two] = 2; @@ -526,5 +531,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/sort-items-by-groups-respecting-dependencies.md b/articles/sort-items-by-groups-respecting-dependencies.md index 69ce62c62..9934f1ee8 100644 --- a/articles/sort-items-by-groups-respecting-dependencies.md +++ b/articles/sort-items-by-groups-respecting-dependencies.md @@ -285,8 +285,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ > Where $V$ is the number of items and $E$ is the total number of $beforeItems$ dependencies. @@ -556,7 +556,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ -> Where $V$ is the number of items and $E$ is the total number of $beforeItems$ dependencies. \ No newline at end of file +> Where $V$ is the number of items and $E$ is the total number of $beforeItems$ dependencies. diff --git a/articles/sort-list.md b/articles/sort-list.md index 768ec1c4c..ff17ff660 100644 --- a/articles/sort-list.md +++ b/articles/sort-list.md @@ -139,8 +139,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -362,7 +362,8 @@ class Solution { * @return {ListNode} */ getMid(head) { - let slow = head, fast = head.next; + let slow = head, + fast = head.next; while (fast && fast.next) { slow = slow.next; fast = fast.next.next; @@ -406,8 +407,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(\log n)$ for recursion stack. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(\log n)$ for recursion stack. --- @@ -425,7 +426,7 @@ class Solution: def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: if not head or not head.next: return head - + length = 0 cur = head while cur: @@ -518,7 +519,7 @@ public class Solution { } step *= 2; } - + return dummy.next; } @@ -535,7 +536,7 @@ public class Solution { private ListNode merge(ListNode list1, ListNode list2) { ListNode dummy = new ListNode(0); ListNode tail = dummy; - + while (list1 != null && list2 != null) { if (list1.val < list2.val) { tail.next = list1; @@ -664,7 +665,8 @@ class Solution { let step = 1; while (step < length) { - let prev = dummy, curr = dummy.next; + let prev = dummy, + curr = dummy.next; while (curr) { let left = curr; let right = this.split(left, step); @@ -726,5 +728,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ diff --git a/articles/sort-the-jumbled-numbers.md b/articles/sort-the-jumbled-numbers.md index b8c0cbf47..347cb98d8 100644 --- a/articles/sort-the-jumbled-numbers.md +++ b/articles/sort-the-jumbled-numbers.md @@ -95,7 +95,7 @@ class Solution { pairs.sort((a, b) => a[0] - b[0]); - return pairs.map(p => nums[p[1]]); + return pairs.map((p) => nums[p[1]]); } } ``` @@ -104,8 +104,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -231,7 +231,7 @@ class Solution { pairs.sort((a, b) => a[0] - b[0]); - return pairs.map(p => nums[p[1]]); + return pairs.map((p) => nums[p[1]]); } } ``` @@ -240,5 +240,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ diff --git a/articles/sort-the-people.md b/articles/sort-the-people.md index c5d8ca911..2d239bdf9 100644 --- a/articles/sort-the-people.md +++ b/articles/sort-the-people.md @@ -83,8 +83,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -165,7 +165,7 @@ class Solution { sortPeople(names, heights) { const arr = names.map((name, i) => [heights[i], name]); arr.sort((a, b) => b[0] - a[0]); - return arr.map(pair => pair[1]); + return arr.map((pair) => pair[1]); } } ``` @@ -174,8 +174,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -243,7 +243,7 @@ class Solution { sortPeople(names, heights) { const indices = names.map((_, i) => i); indices.sort((a, b) => heights[b] - heights[a]); - return indices.map(i => names[i]); + return indices.map((i) => names[i]); } } ``` @@ -252,5 +252,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ diff --git a/articles/special-array-i.md b/articles/special-array-i.md index 40ccd36c6..5bc6c1b13 100644 --- a/articles/special-array-i.md +++ b/articles/special-array-i.md @@ -59,8 +59,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -125,5 +125,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/special-array-with-x-elements-greater-than-or-equal-x.md b/articles/special-array-with-x-elements-greater-than-or-equal-x.md index 3ba445d99..c5f2849d8 100644 --- a/articles/special-array-with-x-elements-greater-than-or-equal-x.md +++ b/articles/special-array-with-x-elements-greater-than-or-equal-x.md @@ -83,8 +83,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -167,10 +167,11 @@ class Solution { * @return {number} */ specialArray(nums) { - let l = 1, r = nums.length; + let l = 1, + r = nums.length; while (l <= r) { const mid = Math.floor((l + r) / 2); - const cnt = nums.filter(num => num >= mid).length; + const cnt = nums.filter((num) => num >= mid).length; if (cnt === mid) return mid; @@ -189,8 +190,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ --- @@ -226,7 +227,7 @@ public class Solution { int i = 0, prev = -1, totalRight = nums.length; while (i < nums.length) { - if (nums[i] == totalRight || + if (nums[i] == totalRight || (prev < totalRight && totalRight < nums[i])) { return totalRight; } @@ -253,7 +254,7 @@ public: int i = 0, prev = -1, totalRight = nums.size(); while (i < nums.size()) { - if (nums[i] == totalRight || + if (nums[i] == totalRight || (prev < totalRight && totalRight < nums[i])) { return totalRight; } @@ -280,11 +281,15 @@ class Solution { */ specialArray(nums) { nums.sort((a, b) => a - b); - let i = 0, prev = -1, totalRight = nums.length; + let i = 0, + prev = -1, + totalRight = nums.length; while (i < nums.length) { - if (nums[i] === totalRight || - (prev < totalRight && totalRight < nums[i])) { + if ( + nums[i] === totalRight || + (prev < totalRight && totalRight < nums[i]) + ) { return totalRight; } @@ -306,8 +311,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -385,7 +390,8 @@ class Solution { specialArray(nums) { nums.sort((a, b) => a - b); const n = nums.length; - let i = 0, j = 1; + let i = 0, + j = 1; while (i < n && j <= n) { while (i < n && j > nums[i]) i++; @@ -405,8 +411,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -502,5 +508,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/spiral-matrix-ii.md b/articles/spiral-matrix-ii.md index 1df46f786..2c066c72b 100644 --- a/articles/spiral-matrix-ii.md +++ b/articles/spiral-matrix-ii.md @@ -121,7 +121,11 @@ class Solution { */ generateMatrix(n) { const mat = Array.from({ length: n }, () => Array(n).fill(0)); - let left = 0, right = n - 1, top = 0, bottom = n - 1, val = 1; + let left = 0, + right = n - 1, + top = 0, + bottom = n - 1, + val = 1; while (left <= right) { // Fill every val in top row @@ -158,8 +162,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ for the output matrix. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ for the output matrix. --- @@ -171,11 +175,11 @@ class Solution { class Solution: def generateMatrix(self, n: int) -> List[List[int]]: mat = [[0] * n for _ in range(n)] - + def fill(left, right, top, bottom, val): if left > right or top > bottom: return - + # Fill every val in top row for c in range(left, right + 1): mat[top][c] = val @@ -214,7 +218,7 @@ public class Solution { fill(mat, 0, n - 1, 0, n - 1, 1); return mat; } - + private void fill(int[][] mat, int left, int right, int top, int bottom, int val) { if (left > right || top > bottom) return; @@ -256,7 +260,7 @@ public: fill(mat, 0, n - 1, 0, n - 1, 1); return mat; } - + private: void fill(vector> &mat, int left, int right, int top, int bottom, int val) { if (left > right || top > bottom) return; @@ -299,7 +303,7 @@ class Solution { */ generateMatrix(n) { const mat = Array.from({ length: n }, () => Array(n).fill(0)); - + const fill = (left, right, top, bottom, val) => { if (left > right || top > bottom) return; @@ -341,10 +345,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: - * $O(n)$ space for recursion stack. - * $O(n ^ 2)$ space for the output matrix. +- Time complexity: $O(n ^ 2)$ +- Space complexity: + - $O(n)$ space for recursion stack. + - $O(n ^ 2)$ space for the output matrix. --- @@ -364,7 +368,7 @@ class Solution: if mat[(r + dr) % n][(c + dc) % n] != 0: dr, dc = dc, -dr r, c = r + dr, c + dc - + return mat ``` @@ -427,11 +431,15 @@ class Solution { */ generateMatrix(n) { const mat = Array.from({ length: n }, () => Array(n).fill(0)); - let r = 0, c = 0, dr = 0, dc = 1; + let r = 0, + c = 0, + dr = 0, + dc = 1; for (let val = 0; val < n * n; val++) { mat[r][c] = val + 1; - let nextR = (r + dr) % n, nextC = (c + dc) % n; + let nextR = (r + dr) % n, + nextC = (c + dc) % n; if (nextR < 0) nextR += n; if (nextC < 0) nextC += n; if (mat[nextR][nextC] !== 0) { @@ -450,5 +458,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ for the output matrix. \ No newline at end of file +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ for the output matrix. diff --git a/articles/spiral-matrix.md b/articles/spiral-matrix.md index 2e82fff76..5877c116c 100644 --- a/articles/spiral-matrix.md +++ b/articles/spiral-matrix.md @@ -12,7 +12,7 @@ class Solution: def dfs(row, col, r, c, dr, dc): if row == 0 or col == 0: return - + for i in range(col): r += dr c += dc @@ -20,7 +20,7 @@ class Solution: # sub-problem dfs(col, row - 1, r, c, dc, -dr) - + # start by going to the right dfs(m, n, 0, -1, 0, 1) return res @@ -37,10 +37,10 @@ public class Solution { return res; } - private void dfs(int row, int col, int r, int c, + private void dfs(int row, int col, int r, int c, int dr, int dc, int[][] matrix, List res) { if (row == 0 || col == 0) return; - + for (int i = 0; i < col; i++) { r += dr; c += dc; @@ -65,10 +65,10 @@ public: return res; } - void dfs(int row, int col, int r, int c, int dr, int dc, + void dfs(int row, int col, int r, int c, int dr, int dc, vector>& matrix, vector& res) { if (row == 0 || col == 0) return; - + for (int i = 0; i < col; i++) { r += dr; c += dc; @@ -88,7 +88,8 @@ class Solution { * @return {number[]} */ spiralOrder(matrix) { - const m = matrix.length, n = matrix[0].length; + const m = matrix.length, + n = matrix[0].length; const res = []; // append all the elements in the given direction @@ -123,10 +124,10 @@ public class Solution { return res; } - private void Dfs(int row, int col, int r, int c, int dr, + private void Dfs(int row, int col, int r, int c, int dr, int dc, int[][] matrix, List res) { if (row == 0 || col == 0) return; - + for (int i = 0; i < col; i++) { r += dr; c += dc; @@ -235,10 +236,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: - * $O(min(m, n))$ space for recursion stack. - * $O(m * n)$ space for the output list. +- Time complexity: $O(m * n)$ +- Space complexity: + - $O(min(m, n))$ space for recursion stack. + - $O(m * n)$ space for the output list. > Where $m$ is the number of rows and $n$ is the number of columns. @@ -352,9 +353,9 @@ class Solution { spiralOrder(matrix) { const res = []; let left = 0; - let right = matrix[0].length; + let right = matrix[0].length; let top = 0; - let bottom = matrix.length; + let bottom = matrix.length; while (left < right && top < bottom) { for (let i = left; i < right; i++) { @@ -535,10 +536,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(m * n)$ space for the output list. +- Time complexity: $O(m * n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(m * n)$ space for the output list. > Where $m$ is the number of rows and $n$ is the number of columns. @@ -594,7 +595,7 @@ class Solution { public: vector spiralOrder(vector>& matrix) { vector res; - vector> directions = {{0, 1}, {1, 0}, + vector> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; vector steps = {matrix[0].size(), matrix.size() - 1}; @@ -621,10 +622,17 @@ class Solution { */ spiralOrder(matrix) { const res = []; - const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; + const directions = [ + [0, 1], + [1, 0], + [0, -1], + [-1, 0], + ]; const steps = [matrix[0].length, matrix.length - 1]; - let r = 0, c = -1, d = 0; + let r = 0, + c = -1, + d = 0; while (steps[d % 2]) { for (let i = 0; i < steps[d % 2]; i++) { r += directions[d][0]; @@ -643,7 +651,7 @@ class Solution { public class Solution { public List SpiralOrder(int[][] matrix) { var res = new List(); - var directions = new (int, int)[] { (0, 1), (1, 0), + var directions = new (int, int)[] { (0, 1), (1, 0), (0, -1), (-1, 0) }; var steps = new int[] { matrix[0].Length, matrix.Length - 1 }; @@ -680,8 +688,8 @@ func spiralOrder(matrix [][]int) []int { c += directions[d][1] res = append(res, matrix[r][c]) } - steps[d&1]-- - d = (d + 1) % 4 + steps[d&1]-- + d = (d + 1) % 4 } return res @@ -695,8 +703,8 @@ class Solution { if (matrix.isEmpty() || matrix[0].isEmpty()) return res val directions = arrayOf( - intArrayOf(0, 1), - intArrayOf(1, 0), + intArrayOf(0, 1), + intArrayOf(1, 0), intArrayOf(0, -1), intArrayOf(-1, 0) ) @@ -712,8 +720,8 @@ class Solution { c += directions[d][1] res.add(matrix[r][c]) } - steps[d and 1]-- - d = (d + 1) % 4 + steps[d and 1]-- + d = (d + 1) % 4 } return res @@ -748,9 +756,9 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(m * n)$ space for the output list. +- Time complexity: $O(m * n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(m * n)$ space for the output list. -> Where $m$ is the number of rows and $n$ is the number of columns. \ No newline at end of file +> Where $m$ is the number of rows and $n$ is the number of columns. diff --git a/articles/split-array-largest-sum.md b/articles/split-array-largest-sum.md index 617691f9b..7004771d3 100644 --- a/articles/split-array-largest-sum.md +++ b/articles/split-array-largest-sum.md @@ -147,8 +147,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 2 ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n * 2 ^ n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -175,7 +175,7 @@ class Solution: for j in range(i, n - m + 1): curSum += nums[j] res = min(res, max(curSum, dfs(j + 1, m - 1))) - + dp[i][m] = res return res @@ -281,7 +281,7 @@ class Solution { res = Math.min(res, Math.max(curSum, dfs(j + 1, m - 1))); } - return dp[i][m] = res; + return (dp[i][m] = res); }; return dfs(0, k); @@ -337,8 +337,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(k * n ^ 2)$ -* Space complexity: $O(k * n)$ +- Time complexity: $O(k * n ^ 2)$ +- Space complexity: $O(k * n)$ > Where $n$ is the size of the array $nums$ and $k$ is the number of sub-arrays to form. @@ -422,8 +422,8 @@ class Solution { */ splitArray(nums, k) { const n = nums.length; - const dp = Array.from({ length: n + 1 }, () => - Array(k + 1).fill(Infinity) + const dp = Array.from({ length: n + 1 }, () => + Array(k + 1).fill(Infinity), ); dp[n][0] = 0; @@ -432,7 +432,10 @@ class Solution { let curSum = 0; for (let j = i; j < n - m + 1; j++) { curSum += nums[j]; - dp[i][m] = Math.min(dp[i][m], Math.max(curSum, dp[j + 1][m - 1])); + dp[i][m] = Math.min( + dp[i][m], + Math.max(curSum, dp[j + 1][m - 1]), + ); } } } @@ -477,8 +480,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(k * n ^ 2)$ -* Space complexity: $O(k * n)$ +- Time complexity: $O(k * n ^ 2)$ +- Space complexity: $O(k * n)$ > Where $n$ is the size of the array $nums$ and $k$ is the number of sub-arrays to form. @@ -579,7 +582,10 @@ class Solution { let curSum = 0; for (let j = i; j < n - m + 1; j++) { curSum += nums[j]; - nextDp[i] = Math.min(nextDp[i], Math.max(curSum, dp[j + 1])); + nextDp[i] = Math.min( + nextDp[i], + Math.max(curSum, dp[j + 1]), + ); } } [dp, nextDp] = [nextDp, dp]; @@ -624,8 +630,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(k * n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(k * n ^ 2)$ +- Space complexity: $O(n)$ > Where $n$ is the size of the array $nums$ and $k$ is the number of sub-arrays to form. @@ -744,7 +750,8 @@ class Solution { */ splitArray(nums, k) { const canSplit = (largest) => { - let subarray = 1, curSum = 0; + let subarray = 1, + curSum = 0; for (const num of nums) { curSum += num; if (curSum > largest) { @@ -815,8 +822,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log s)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n \log s)$ +- Space complexity: $O(1)$ > Where $n$ is the size of the array $nums$ and $s$ is the sum of all the elements in the array. @@ -988,9 +995,11 @@ class Solution { } const canSplit = (largest) => { - let subarrays = 0, i = 0; + let subarrays = 0, + i = 0; while (i < n) { - let l = i + 1, r = n; + let l = i + 1, + r = n; while (l <= r) { const mid = Math.floor(l + (r - l) / 2); if (prefix[mid] - prefix[i] <= largest) { @@ -1009,7 +1018,8 @@ class Solution { }; let l = Math.max(...nums); - let r = nums.reduce((a, b) => a + b, 0), res = r; + let r = nums.reduce((a, b) => a + b, 0), + res = r; while (l <= r) { const mid = Math.floor(l + (r - l) / 2); if (canSplit(mid)) { @@ -1082,7 +1092,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n + (k * \log n * \log s))$ -* Space complexity: $O(n)$ +- Time complexity: $O(n + (k * \log n * \log s))$ +- Space complexity: $O(n)$ -> Where $n$ is the size of the array $nums$, $s$ is the sum of all the elements in the array, and $k$ is the number of sub-arrays to form. \ No newline at end of file +> Where $n$ is the size of the array $nums$, $s$ is the sum of all the elements in the array, and $k$ is the number of sub-arrays to form. diff --git a/articles/split-linked-list-in-parts.md b/articles/split-linked-list-in-parts.md index 5df42573a..577ae229f 100644 --- a/articles/split-linked-list-in-parts.md +++ b/articles/split-linked-list-in-parts.md @@ -139,7 +139,8 @@ class Solution { } let N = arr.length; - let base_len = Math.floor(N / k), remainder = N % k; + let base_len = Math.floor(N / k), + remainder = N % k; let res = new Array(k).fill(null); let start = 0; @@ -165,8 +166,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -189,7 +190,7 @@ class Solution: base_len, remainder = length // k, length % k curr, res = head, [] - + for i in range(k): res.append(curr) for j in range(base_len - 1 + (1 if remainder else 0)): @@ -305,13 +306,15 @@ class Solution { * @return {ListNode[]} */ splitListToParts(head, k) { - let length = 0, curr = head; + let length = 0, + curr = head; while (curr) { curr = curr.next; length++; } - let baseLen = Math.floor(length / k), remainder = length % k; + let baseLen = Math.floor(length / k), + remainder = length % k; let res = new Array(k).fill(null); curr = head; @@ -337,7 +340,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n)$ space for the output array. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n)$ space for the output array. diff --git a/articles/splitting-a-string-into-descending-consecutive-values.md b/articles/splitting-a-string-into-descending-consecutive-values.md index b736eda11..cd0529391 100644 --- a/articles/splitting-a-string-into-descending-consecutive-values.md +++ b/articles/splitting-a-string-into-descending-consecutive-values.md @@ -140,8 +140,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ n)$ +- Space complexity: $O(n)$ --- @@ -273,8 +273,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -417,8 +417,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -566,5 +566,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ diff --git a/articles/sqrtx.md b/articles/sqrtx.md index bc2e10fa7..f6b37a7c2 100644 --- a/articles/sqrtx.md +++ b/articles/sqrtx.md @@ -103,8 +103,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(\sqrt {n})$ -* Space complexity: $O(1)$ +- Time complexity: $O(\sqrt {n})$ +- Space complexity: $O(1)$ --- @@ -159,8 +159,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ --- @@ -241,7 +241,8 @@ class Solution { * @return {number} */ mySqrt(x) { - let l = 0, r = x; + let l = 0, + r = x; let res = 0; while (l <= r) { @@ -290,8 +291,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ --- @@ -375,8 +376,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(\log n)$ for recursion stack. +- Time complexity: $O(\log n)$ +- Space complexity: $O(\log n)$ for recursion stack. --- @@ -450,5 +451,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ diff --git a/articles/squares-of-a-sorted-array.md b/articles/squares-of-a-sorted-array.md index 3dd03d8bc..610f4dea6 100644 --- a/articles/squares-of-a-sorted-array.md +++ b/articles/squares-of-a-sorted-array.md @@ -68,8 +68,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -89,7 +89,7 @@ class Solution: else: res.append(nums[r] * nums[r]) r -= 1 - + return res[::-1] ``` @@ -145,7 +145,8 @@ class Solution { * @return {number[]} */ sortedSquares(nums) { - let l = 0, r = nums.length - 1; + let l = 0, + r = nums.length - 1; const res = []; while (l <= r) { @@ -191,8 +192,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for the output array. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for the output array. --- @@ -216,7 +217,7 @@ class Solution: res[res_index] = nums[r] * nums[r] r -= 1 res_index -= 1 - + return res ``` @@ -237,7 +238,7 @@ public class Solution { } resIndex--; } - + return res; } } @@ -261,7 +262,7 @@ public: } resIndex--; } - + return res; } }; @@ -276,7 +277,9 @@ class Solution { sortedSquares(nums) { const n = nums.length; const res = new Array(n); - let l = 0, r = n - 1, resIndex = n - 1; + let l = 0, + r = n - 1, + resIndex = n - 1; while (l <= r) { if (Math.abs(nums[l]) > Math.abs(nums[r])) { @@ -321,5 +324,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for the output array. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for the output array. diff --git a/articles/stickers-to-spell-word.md b/articles/stickers-to-spell-word.md index 2abbe91a7..b803775e0 100644 --- a/articles/stickers-to-spell-word.md +++ b/articles/stickers-to-spell-word.md @@ -41,11 +41,11 @@ class Solution: public class Solution { private List> stickCount; private Map dp; - + public int minStickers(String[] stickers, String target) { stickCount = new ArrayList<>(); dp = new HashMap<>(); - + for (String s : stickers) { Map countMap = new HashMap<>(); for (char c : s.toCharArray()) { @@ -53,18 +53,18 @@ public class Solution { } stickCount.add(countMap); } - + int res = dfs(target, new HashMap<>()); return res == Integer.MAX_VALUE ? -1 : res; } - + private int dfs(String t, Map stick) { if (t.isEmpty()) return 0; if (dp.containsKey(t)) return dp.get(t); - + int res = stick.isEmpty() ? 0 : 1; StringBuilder remainT = new StringBuilder(); - + for (char c : t.toCharArray()) { if (stick.containsKey(c) && stick.get(c) > 0) { stick.put(c, stick.get(c) - 1); @@ -72,7 +72,7 @@ public class Solution { remainT.append(c); } } - + if (remainT.length() > 0) { int used = Integer.MAX_VALUE; for (Map s : stickCount) { @@ -89,7 +89,7 @@ public class Solution { res = Integer.MAX_VALUE; } } - + return res; } } @@ -99,12 +99,12 @@ public class Solution { class Solution { vector> stickCount; unordered_map dp; - + public: int minStickers(vector& stickers, string target) { stickCount.clear(); dp.clear(); - + for (const string& s : stickers) { unordered_map countMap; for (char c : s) { @@ -112,19 +112,19 @@ public: } stickCount.push_back(countMap); } - + int res = dfs(target, unordered_map()); return res == INT_MAX ? -1 : res; } - + private: int dfs(const string& t, unordered_map stick) { if (t.empty()) return 0; if (dp.count(t)) return dp[t]; - + int res = stick.empty() ? 0 : 1; string remainT; - + for (char c : t) { if (stick.count(c) && stick[c] > 0) { stick[c]--; @@ -132,7 +132,7 @@ private: remainT += c; } } - + if (!remainT.empty()) { int used = INT_MAX; for (const auto& s : stickCount) { @@ -149,7 +149,7 @@ private: res = INT_MAX; } } - + return res; } }; @@ -165,7 +165,7 @@ class Solution { minStickers(stickers, target) { const stickCount = []; const dp = new Map(); - + for (const s of stickers) { const countMap = new Map(); for (const c of s) { @@ -177,10 +177,10 @@ class Solution { const dfs = (t, stick) => { if (t === '') return 0; if (dp.has(t)) return dp.get(t); - + let res = stick.size === 0 ? 0 : 1; let remainT = ''; - + for (const c of t) { if (stick.has(c) && stick.get(c) > 0) { stick.set(c, stick.get(c) - 1); @@ -188,7 +188,7 @@ class Solution { remainT += c; } } - + if (remainT.length > 0) { let used = Infinity; for (const s of stickCount) { @@ -204,10 +204,10 @@ class Solution { res = Infinity; } } - + return res; }; - + const res = dfs(target, new Map()); return res === Infinity ? -1 : res; } @@ -218,8 +218,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * k *2 ^ n)$ -* Space complexity: $O(m * k + 2 ^ n)$ +- Time complexity: $O(m * k *2 ^ n)$ +- Space complexity: $O(m * k + 2 ^ n)$ > Where $n$ is the length of the target string, $m$ is the number of stickers and $k$ is the average length of each sticker. @@ -237,14 +237,14 @@ class Solution: stickCount = [] for s in stickers: stickCount.append(Counter(s)) - + dp = {} dp[""] = 0 def dfs(t): if t in dp: return dp[t] - + tarMp = Counter(t) res = float("inf") for s in stickCount: @@ -254,13 +254,13 @@ class Solution: for c in tarMp: if tarMp[c] > s[c]: remainT.extend([c] * (tarMp[c] - s[c])) - + remainT = ''.join(sorted(remainT)) res = min(res, 1 + dfs(remainT)) - + dp[t] = res return res - + ans = dfs(target) return -1 if ans == float("inf") else ans ``` @@ -388,7 +388,7 @@ class Solution { * @return {number} */ minStickers(stickers, target) { - const dp = { "": 0 }; + const dp = { '': 0 }; const stickCount = stickers.map((s) => { const counter = {}; for (const c of s) { @@ -418,7 +418,7 @@ class Solution { } } - remainT = remainT.sort().join(""); + remainT = remainT.sort().join(''); res = Math.min(res, 1 + dfs(remainT)); } @@ -426,7 +426,7 @@ class Solution { return res; }; - const ans = dfs(target.split("").sort().join("")); + const ans = dfs(target.split('').sort().join('')); return ans === Infinity ? -1 : ans; } } @@ -436,8 +436,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * k *2 ^ n)$ -* Space complexity: $O(m * k + 2 ^ n)$ +- Time complexity: $O(m * k *2 ^ n)$ +- Space complexity: $O(m * k + 2 ^ n)$ > Where $n$ is the length of the target string, $m$ is the number of stickers and $k$ is the average length of each sticker. @@ -574,7 +574,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m * k *2 ^ n)$ -* Space complexity: $O(2 ^ n)$ +- Time complexity: $O(n * m * k *2 ^ n)$ +- Space complexity: $O(2 ^ n)$ -> Where $n$ is the length of the target string, $m$ is the number of stickers and $k$ is the average length of each sticker. \ No newline at end of file +> Where $n$ is the length of the target string, $m$ is the number of stickers and $k$ is the average length of each sticker. diff --git a/articles/stone-game-ii.md b/articles/stone-game-ii.md index 4f612e113..daae5b8ef 100644 --- a/articles/stone-game-ii.md +++ b/articles/stone-game-ii.md @@ -114,7 +114,7 @@ class Solution { stoneGameII(piles) { const n = piles.length; this.dp = Array.from({ length: 2 }, () => - Array.from({ length: n }, () => Array(n + 1).fill(-1)) + Array.from({ length: n }, () => Array(n + 1).fill(-1)), ); const dfs = (alice, i, M) => { @@ -188,8 +188,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 3)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 3)$ +- Space complexity: $O(n ^ 2)$ --- @@ -254,7 +254,7 @@ public class Solution { if (i + X > suffixSum.length) break; res = Math.max(res, suffixSum[i] - dfs(i + X, Math.max(M, X))); } - + return dp[i][M] = res; } } @@ -270,7 +270,7 @@ public: int stoneGameII(vector& piles) { int n = piles.size(); dp.resize(n, vector(n + 1, -1)); - + suffixSum.resize(n); suffixSum[n - 1] = piles[n - 1]; for (int i = n - 2; i >= 0; i--) { @@ -322,7 +322,7 @@ class Solution { res = Math.max(res, suffixSum[i] - dfs(i + X, Math.max(M, X))); } - return dp[i][M] = res; + return (dp[i][M] = res); }; return dfs(0, 1); @@ -374,8 +374,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 3)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 3)$ +- Space complexity: $O(n ^ 2)$ --- @@ -399,7 +399,7 @@ class Solution: if i + X > n: break total += piles[i + X - 1] - + dp[1][i][M] = max(dp[1][i][M], total + dp[0][i + X][max(M, X)]) dp[0][i][M] = min(dp[0][i][M], dp[1][i + X][max(M, X)]) @@ -469,7 +469,7 @@ class Solution { stoneGameII(piles) { const n = piles.length; const dp = Array.from({ length: 2 }, () => - Array.from({ length: n + 1 }, () => Array(n + 1).fill(0)) + Array.from({ length: n + 1 }, () => Array(n + 1).fill(0)), ); for (let i = n - 1; i >= 0; i--) { @@ -482,8 +482,14 @@ class Solution { if (i + X > n) break; total += piles[i + X - 1]; - dp[1][i][M] = Math.max(dp[1][i][M], total + dp[0][i + X][Math.max(M, X)]); - dp[0][i][M] = Math.min(dp[0][i][M], dp[1][i + X][Math.max(M, X)]); + dp[1][i][M] = Math.max( + dp[1][i][M], + total + dp[0][i + X][Math.max(M, X)], + ); + dp[0][i][M] = Math.min( + dp[0][i][M], + dp[1][i + X][Math.max(M, X)], + ); } } } @@ -523,8 +529,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 3)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 3)$ +- Space complexity: $O(n ^ 2)$ --- @@ -629,7 +635,10 @@ class Solution { for (let M = 1; M <= n; M++) { for (let X = 1; X <= 2 * M; X++) { if (i + X > n) break; - dp[i][M] = Math.max(dp[i][M], suffixSum[i] - dp[i + X][Math.max(M, X)]); + dp[i][M] = Math.max( + dp[i][M], + suffixSum[i] - dp[i + X][Math.max(M, X)], + ); } } } @@ -670,5 +679,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 3)$ -* Space complexity: $O(n ^ 2)$ \ No newline at end of file +- Time complexity: $O(n ^ 3)$ +- Space complexity: $O(n ^ 2)$ diff --git a/articles/stone-game-iii.md b/articles/stone-game-iii.md index 781024036..01fc6b8bd 100644 --- a/articles/stone-game-iii.md +++ b/articles/stone-game-iii.md @@ -138,8 +138,8 @@ class Solution { }; const result = dfs(0, 1); - if (result === 0) return "Tie"; - return result > 0 ? "Alice" : "Bob"; + if (result === 0) return 'Tie'; + return result > 0 ? 'Alice' : 'Bob'; } } ``` @@ -182,8 +182,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -294,7 +294,8 @@ class Solution { if (i >= n) return 0; if (dp[i] !== undefined) return dp[i]; - let res = -Infinity, total = 0; + let res = -Infinity, + total = 0; for (let j = i; j < Math.min(i + 3, n); j++) { total += stoneValue[j]; res = Math.max(res, total - dfs(j + 1)); @@ -305,8 +306,8 @@ class Solution { }; const result = dfs(0); - if (result === 0) return "Tie"; - return result > 0 ? "Alice" : "Bob"; + if (result === 0) return 'Tie'; + return result > 0 ? 'Alice' : 'Bob'; } } ``` @@ -342,8 +343,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -439,8 +440,8 @@ class Solution { } const result = dp[0]; - if (result === 0) return "Tie"; - return result > 0 ? "Alice" : "Bob"; + if (result === 0) return 'Tie'; + return result > 0 ? 'Alice' : 'Bob'; } } ``` @@ -472,8 +473,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -561,8 +562,8 @@ class Solution { } } - if (dp[0] === 0) return "Tie"; - return dp[0] > 0 ? "Alice" : "Bob"; + if (dp[0] === 0) return 'Tie'; + return dp[0] > 0 ? 'Alice' : 'Bob'; } } ``` @@ -593,5 +594,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/stone-game.md b/articles/stone-game.md index 293ba1458..3b18cdad4 100644 --- a/articles/stone-game.md +++ b/articles/stone-game.md @@ -117,8 +117,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ --- @@ -289,8 +289,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -394,7 +394,10 @@ class Solution { if (l === r) { dp[l][r] = left; } else { - dp[l][r] = Math.max(dp[l + 1][r] + left, dp[l][r - 1] + right); + dp[l][r] = Math.max( + dp[l + 1][r] + left, + dp[l][r - 1] + right, + ); } } } @@ -440,8 +443,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -556,7 +559,7 @@ class Solution { const total = piles.reduce((a, b) => a + b, 0); const aliceScore = dp[n - 1]; - return aliceScore > (total - aliceScore); + return aliceScore > total - aliceScore; } } ``` @@ -596,8 +599,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -614,7 +617,7 @@ class Solution: ```java public class Solution { public boolean stoneGame(int[] piles) { - return true; + return true; } } ``` @@ -652,5 +655,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ diff --git a/articles/string-compression-ii.md b/articles/string-compression-ii.md index d1021b9ea..76a378c8c 100644 --- a/articles/string-compression-ii.md +++ b/articles/string-compression-ii.md @@ -126,7 +126,8 @@ class Solution { let res; if (prev === s.charCodeAt(i) - 97) { - const incr = prevCnt === 1 || prevCnt === 9 || prevCnt === 99 ? 1 : 0; + const incr = + prevCnt === 1 || prevCnt === 9 || prevCnt === 99 ? 1 : 0; res = incr + count(i + 1, k, prev, prevCnt + 1); } else { res = 1 + count(i + 1, k, s.charCodeAt(i) - 97, 1); // don't delete @@ -148,8 +149,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(k * n ^ 2)$ -* Space complexity: $O(k * n ^ 2)$ +- Time complexity: $O(k * n ^ 2)$ +- Space complexity: $O(k * n ^ 2)$ > Where $n$ is the length of the string $s$ and $k$ is the maximum number of characters that can be deleted from the string. @@ -174,7 +175,7 @@ class Solution: res = 150 if k > 0: res = dfs(i + 1, k - 1) - + freq = delCnt = 0 comp_len = 1 for j in range(i, n): @@ -189,7 +190,7 @@ class Solution: res = min(res, comp_len + dfs(j + 1, k - delCnt)) dp[(i, k)] = res return res - + return dfs(0, k) ``` @@ -284,7 +285,9 @@ class Solution { let res = 150; if (k > 0) res = dfs(i + 1, k - 1); - let freq = 0, delCnt = 0, comp_len = 1; + let freq = 0, + delCnt = 0, + comp_len = 1; for (let j = i; j < n; j++) { if (s[i] === s[j]) { if (freq === 1 || freq === 9 || freq === 99) comp_len++; @@ -308,8 +311,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 * k)$ -* Space complexity: $O(n * k)$ +- Time complexity: $O(n ^ 2 * k)$ +- Space complexity: $O(n * k)$ > Where $n$ is the length of the string $s$ and $k$ is the maximum number of characters that can be deleted from the string. @@ -449,7 +452,9 @@ class Solution { dp[i][remK] = dp[i + 1][remK - 1]; } - let freq = 0, delCnt = 0, compLen = 1; + let freq = 0, + delCnt = 0, + compLen = 1; for (let j = i; j < n; j++) { if (s[i] === s[j]) { if (freq === 1 || freq === 9 || freq === 99) { @@ -460,7 +465,10 @@ class Solution { delCnt++; if (delCnt > remK) break; } - dp[i][remK] = Math.min(dp[i][remK], compLen + dp[j + 1][remK - delCnt]); + dp[i][remK] = Math.min( + dp[i][remK], + compLen + dp[j + 1][remK - delCnt], + ); } } } @@ -474,7 +482,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 * k)$ -* Space complexity: $O(n * k)$ +- Time complexity: $O(n ^ 2 * k)$ +- Space complexity: $O(n * k)$ -> Where $n$ is the length of the string $s$ and $k$ is the maximum number of characters that can be deleted from the string. \ No newline at end of file +> Where $n$ is the length of the string $s$ and $k$ is the maximum number of characters that can be deleted from the string. diff --git a/articles/string-encode-and-decode.md b/articles/string-encode-and-decode.md index ca00a45b8..6eabea551 100644 --- a/articles/string-encode-and-decode.md +++ b/articles/string-encode-and-decode.md @@ -38,7 +38,7 @@ class Solution: ```java public class Solution { - + public String encode(List strs) { if (strs.isEmpty()) return ""; StringBuilder res = new StringBuilder(); @@ -133,8 +133,9 @@ class Solution { * @returns {string} */ encode(strs) { - if (strs.length === 0) return ""; - let sizes = [], res = ""; + if (strs.length === 0) return ''; + let sizes = [], + res = ''; for (let s of strs) { sizes.push(s.length); } @@ -154,9 +155,11 @@ class Solution { */ decode(str) { if (str.length === 0) return []; - let sizes = [], res = [], i = 0; + let sizes = [], + res = [], + i = 0; while (str[i] !== '#') { - let cur = ""; + let cur = ''; while (str[i] !== ',') { cur += str[i]; i++; @@ -303,7 +306,7 @@ class Solution { } return res } - + func decode(_ s: String) -> [String] { if s.isEmpty { return [] } let sArr = Array(s) @@ -336,8 +339,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m)$ for each $encode()$ and $decode()$ function calls. -* Space complexity: $O(m + n)$ for each $encode()$ and $decode()$ function calls. +- Time complexity: $O(m)$ for each $encode()$ and $decode()$ function calls. +- Space complexity: $O(m + n)$ for each $encode()$ and $decode()$ function calls. > Where $m$ is the sum of lengths of all the strings and $n$ is the number of strings. @@ -349,7 +352,7 @@ class Solution { ```python class Solution: - + def encode(self, strs: List[str]) -> str: res = "" for s in strs: @@ -359,7 +362,7 @@ class Solution: def decode(self, s: str) -> List[str]: res = [] i = 0 - + while i < len(s): j = i while s[j] != '#': @@ -369,13 +372,13 @@ class Solution: j = i + length res.append(s[i:j]) i = j - + return res ``` ```java public class Solution { - + public String encode(List strs) { StringBuilder res = new StringBuilder(); for (String s : strs) { @@ -440,9 +443,9 @@ class Solution { * @returns {string} */ encode(strs) { - let res = ""; + let res = ''; for (let s of strs) { - res += s.length + "#" + s; + res += s.length + '#' + s; } return res; } @@ -529,7 +532,7 @@ func (s *Solution) Decode(encoded string) []string { ```kotlin class Solution { - + fun encode(strs: List): String { val res = StringBuilder() for (str in strs) { @@ -565,7 +568,7 @@ class Solution { } return res } - + func decode(_ s: String) -> [String] { var res = [String]() let sArr = Array(s) @@ -595,7 +598,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m)$ for each $encode()$ and $decode()$ function calls. -* Space complexity: $O(m + n)$ for each $encode()$ and $decode()$ function calls. +- Time complexity: $O(m)$ for each $encode()$ and $decode()$ function calls. +- Space complexity: $O(m + n)$ for each $encode()$ and $decode()$ function calls. -> Where $m$ is the sum of lengths of all the strings and $n$ is the number of strings. \ No newline at end of file +> Where $m$ is the sum of lengths of all the strings and $n$ is the number of strings. diff --git a/articles/string-matching-in-an-array.md b/articles/string-matching-in-an-array.md index f369be41c..06091fc0a 100644 --- a/articles/string-matching-in-an-array.md +++ b/articles/string-matching-in-an-array.md @@ -97,10 +97,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 * m ^ 2)$ -* Space complexity: - * $O(1)$ extra space. - * $O(n * m)$ space for the output list. +- Time complexity: $O(n ^ 2 * m ^ 2)$ +- Space complexity: + - $O(1)$ extra space. + - $O(n * m)$ space for the output list. > Where $n$ is the number of words, and $m$ is the length of the longest word. @@ -196,10 +196,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 * m ^ 2)$ -* Space complexity: - * $O(1)$ or $O(n)$ depending on the sorting algorithm. - * $O(n * m)$ space for the output list. +- Time complexity: $O(n ^ 2 * m ^ 2)$ +- Space complexity: + - $O(1)$ or $O(n)$ depending on the sorting algorithm. + - $O(n * m)$ space for the output list. > Where $n$ is the number of words, and $m$ is the length of the longest word. @@ -383,7 +383,8 @@ class Solution { stringMatching(words) { const kmp = (word1, word2) => { const lps = Array(word2.length).fill(0); - let prevLPS = 0, i = 1; + let prevLPS = 0, + i = 1; while (i < word2.length) { if (word2[i] === word2[prevLPS]) { @@ -438,11 +439,11 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 * m)$ -* Space complexity: - * $O(m)$ extra space. - * $O(1)$ or $O(n)$ space depending on the sorting algorithm. - * $O(n * m)$ space for the output list. +- Time complexity: $O(n ^ 2 * m)$ +- Space complexity: + - $O(m)$ extra space. + - $O(1)$ or $O(n)$ space depending on the sorting algorithm. + - $O(n * m)$ space for the output list. > Where $n$ is the number of words, and $m$ is the length of the longest word. @@ -627,18 +628,24 @@ class Solution { */ stringMatching(words) { const rabinKarp = (word1, word2) => { - const base1 = 31, mod1 = 768258391; - const base2 = 37, mod2 = 685683731; - const n = word1.length, m = word2.length; - - let power1 = 1, power2 = 1; + const base1 = 31, + mod1 = 768258391; + const base2 = 37, + mod2 = 685683731; + const n = word1.length, + m = word2.length; + + let power1 = 1, + power2 = 1; for (let k = 0; k < m; k++) { power1 = (power1 * base1) % mod1; power2 = (power2 * base2) % mod2; } - let hash1 = 0, hash2 = 0; - let cur1 = 0, cur2 = 0; + let hash1 = 0, + hash2 = 0; + let cur1 = 0, + cur2 = 0; for (let i = 0; i < m; i++) { hash1 = (hash1 * base1 + word2.charCodeAt(i)) % mod1; @@ -653,8 +660,16 @@ class Solution { } if (i + m < n) { - cur1 = (cur1 * base1 - word1.charCodeAt(i) * power1 + word1.charCodeAt(i + m)) % mod1; - cur2 = (cur2 * base2 - word1.charCodeAt(i) * power2 + word1.charCodeAt(i + m)) % mod2; + cur1 = + (cur1 * base1 - + word1.charCodeAt(i) * power1 + + word1.charCodeAt(i + m)) % + mod1; + cur2 = + (cur2 * base2 - + word1.charCodeAt(i) * power2 + + word1.charCodeAt(i + m)) % + mod2; cur1 = (cur1 + mod1) % mod1; cur2 = (cur2 + mod2) % mod2; @@ -685,10 +700,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 * m)$ -* Space complexity: - * $O(1)$ or $O(n)$ space depending on the sorting algorithm. - * $O(n * m)$ space for the output list. +- Time complexity: $O(n ^ 2 * m)$ +- Space complexity: + - $O(1)$ or $O(n)$ space depending on the sorting algorithm. + - $O(n * m)$ space for the output list. > Where $n$ is the number of words, and $m$ is the length of the longest word. @@ -841,10 +856,11 @@ class Solution { */ stringMatching(words) { const zAlgorithm = (word1, word2) => { - const s = word2 + "$" + word1; + const s = word2 + '$' + word1; const n = s.length; const z = Array(n).fill(0); - let l = 0, r = 0; + let l = 0, + r = 0; for (let i = 1; i < n; i++) { if (i <= r) { @@ -889,11 +905,11 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 * m)$ -* Space complexity: - * $O(m)$ extra space. - * $O(1)$ or $O(n)$ space depending on the sorting algorithm. - * $O(n * m)$ space for the output list. +- Time complexity: $O(n ^ 2 * m)$ +- Space complexity: + - $O(m)$ extra space. + - $O(1)$ or $O(n)$ space depending on the sorting algorithm. + - $O(n * m)$ space for the output list. > Where $n$ is the number of words, and $m$ is the length of the longest word. @@ -1149,9 +1165,9 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m ^ 2)$ -* Space complexity: - * $O(n * m ^ 2)$ extra space. - * $O(n * m)$ space for the output list. +- Time complexity: $O(n * m ^ 2)$ +- Space complexity: + - $O(n * m ^ 2)$ extra space. + - $O(n * m)$ space for the output list. -> Where $n$ is the number of words, and $m$ is the length of the longest word. \ No newline at end of file +> Where $n$ is the number of words, and $m$ is the length of the longest word. diff --git a/articles/student-attendance-record-ii.md b/articles/student-attendance-record-ii.md index b941f3076..3db9174d1 100644 --- a/articles/student-attendance-record-ii.md +++ b/articles/student-attendance-record-ii.md @@ -110,7 +110,7 @@ class Solution { checkRecord(n) { const MOD = 1000000007; let cache = Array.from({ length: n + 1 }, () => - Array.from({ length: 2 }, () => new Array(3).fill(-1)) + Array.from({ length: 2 }, () => new Array(3).fill(-1)), ); const dfs = (i, cntA, cntL) => { @@ -139,8 +139,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -303,10 +303,10 @@ class Solution { const MOD = 1000000007; const baseCase = [ [1, 1, 0], // (A = 0, L = 0, 1, 2) - [1, 0, 0] // (A = 1, L = 0, 1, 2) + [1, 0, 0], // (A = 1, L = 0, 1, 2) ]; let cache = Array.from({ length: n + 1 }, () => - Array.from({ length: 2 }, () => new Array(3).fill(-1)) + Array.from({ length: 2 }, () => new Array(3).fill(-1)), ); const count = (n) => { @@ -317,8 +317,8 @@ class Solution { const res = cache[n]; // Choose P - res[0][0] = ((prev[0][0] + prev[0][1]) % MOD + prev[0][2]) % MOD; - res[1][0] = ((prev[1][0] + prev[1][1]) % MOD + prev[1][2]) % MOD; + res[0][0] = (((prev[0][0] + prev[0][1]) % MOD) + prev[0][2]) % MOD; + res[1][0] = (((prev[1][0] + prev[1][1]) % MOD) + prev[1][2]) % MOD; // Choose L res[0][1] = prev[0][0]; @@ -327,7 +327,10 @@ class Solution { res[1][2] = prev[1][1]; // Choose A - res[1][0] = (res[1][0] + ((prev[0][0] + prev[0][1]) % MOD + prev[0][2]) % MOD) % MOD; + res[1][0] = + (res[1][0] + + ((((prev[0][0] + prev[0][1]) % MOD) + prev[0][2]) % MOD)) % + MOD; return res; }; @@ -348,8 +351,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -362,7 +365,7 @@ class Solution: def checkRecord(self, n: int) -> int: MOD = 1000000007 dp = [[[0 for _ in range(3)] for _ in range(2)] for _ in range(n + 1)] - + dp[0][0][0] = 1 # Base case for i in range(1, n + 1): @@ -470,7 +473,7 @@ class Solution { checkRecord(n) { const MOD = 1000000007; const dp = Array.from({ length: n + 1 }, () => - Array.from({ length: 2 }, () => new Array(3).fill(0)) + Array.from({ length: 2 }, () => new Array(3).fill(0)), ); dp[0][0][0] = 1; @@ -479,16 +482,20 @@ class Solution { for (let cntA = 0; cntA < 2; cntA++) { for (let cntL = 0; cntL < 3; cntL++) { // Choose P - dp[i][cntA][0] = (dp[i][cntA][0] + dp[i - 1][cntA][cntL]) % MOD; + dp[i][cntA][0] = + (dp[i][cntA][0] + dp[i - 1][cntA][cntL]) % MOD; // Choose A if (cntA > 0) { - dp[i][cntA][0] = (dp[i][cntA][0] + dp[i - 1][cntA - 1][cntL]) % MOD; + dp[i][cntA][0] = + (dp[i][cntA][0] + dp[i - 1][cntA - 1][cntL]) % MOD; } // Choose L if (cntL > 0) { - dp[i][cntA][cntL] = (dp[i][cntA][cntL] + dp[i - 1][cntA][cntL - 1]) % MOD; + dp[i][cntA][cntL] = + (dp[i][cntA][cntL] + dp[i - 1][cntA][cntL - 1]) % + MOD; } } } @@ -510,8 +517,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -639,14 +646,17 @@ class Solution { if (n === 1) return 3; const MOD = 1000000007; - let dp = [[1, 1, 0], [1, 0, 0]]; + let dp = [ + [1, 1, 0], + [1, 0, 0], + ]; for (let i = 0; i < n - 1; i++) { let ndp = Array.from({ length: 2 }, () => new Array(3).fill(0)); // Choose P - ndp[0][0] = ((dp[0][0] + dp[0][1]) % MOD + dp[0][2]) % MOD; - ndp[1][0] = ((dp[1][0] + dp[1][1]) % MOD + dp[1][2]) % MOD; + ndp[0][0] = (((dp[0][0] + dp[0][1]) % MOD) + dp[0][2]) % MOD; + ndp[1][0] = (((dp[1][0] + dp[1][1]) % MOD) + dp[1][2]) % MOD; // Choose L ndp[0][1] = dp[0][0]; @@ -655,7 +665,10 @@ class Solution { ndp[1][2] = dp[1][1]; // Choose A - ndp[1][0] = (ndp[1][0] + ((dp[0][0] + dp[0][1]) % MOD + dp[0][2]) % MOD) % MOD; + ndp[1][0] = + (ndp[1][0] + + ((((dp[0][0] + dp[0][1]) % MOD) + dp[0][2]) % MOD)) % + MOD; [dp, ndp] = [ndp, dp]; } @@ -675,8 +688,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -689,7 +702,7 @@ class Solution: def checkRecord(self, n: int) -> int: MOD = 1000000007 dp = [[0] * 3 for _ in range(2)] - + dp[0][0] = 1 # Base case for i in range(1, n + 1): @@ -821,12 +834,14 @@ class Solution { // Choose A if (cntA > 0) { - nextDp[cntA][0] = (nextDp[cntA][0] + dp[cntA - 1][cntL]) % MOD; + nextDp[cntA][0] = + (nextDp[cntA][0] + dp[cntA - 1][cntL]) % MOD; } // Choose L if (cntL > 0) { - nextDp[cntA][cntL] = (nextDp[cntA][cntL] + dp[cntA][cntL - 1]) % MOD; + nextDp[cntA][cntL] = + (nextDp[cntA][cntL] + dp[cntA][cntL - 1]) % MOD; } } } @@ -850,5 +865,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/subarray-product-less-than-k.md b/articles/subarray-product-less-than-k.md index dd7807c14..b1d660234 100644 --- a/articles/subarray-product-less-than-k.md +++ b/articles/subarray-product-less-than-k.md @@ -14,7 +14,7 @@ class Solution: if curProd >= k: break res += 1 - + return res ``` @@ -65,7 +65,8 @@ class Solution { * @return {number} */ numSubarrayProductLessThanK(nums, k) { - let n = nums.length, res = 0; + let n = nums.length, + res = 0; for (let i = 0; i < n; i++) { let curProd = 1; @@ -85,8 +86,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -115,7 +116,7 @@ class Solution: l = mid + 1 else: r = mid - + res += l - (i + 1) return res @@ -204,7 +205,8 @@ class Solution { } for (let i = 0; i < n; i++) { - let l = i + 1, r = n + 1; + let l = i + 1, + r = n + 1; while (l < r) { const mid = Math.floor((l + r) / 2); if (logs[mid] < logs[i] + logK) { @@ -225,8 +227,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -292,13 +294,15 @@ class Solution { * @return {number} */ numSubarrayProductLessThanK(nums, k) { - let res = 0, l = 0, product = 1; + let res = 0, + l = 0, + product = 1; for (let r = 0; r < nums.length; r++) { product *= nums[r]; while (l <= r && product >= k) { product = Math.floor(product / nums[l++]); } - res += (r - l + 1); + res += r - l + 1; } return res; } @@ -309,5 +313,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/subarray-sum-equals-k.md b/articles/subarray-sum-equals-k.md index fa979f529..e513192d1 100644 --- a/articles/subarray-sum-equals-k.md +++ b/articles/subarray-sum-equals-k.md @@ -91,8 +91,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -112,7 +112,7 @@ class Solution: res += prefixSums.get(diff, 0) prefixSums[curSum] = 1 + prefixSums.get(curSum, 0) - + return res ``` @@ -163,7 +163,8 @@ class Solution { * @return {number} */ subarraySum(nums, k) { - let res = 0, curSum = 0; + let res = 0, + curSum = 0; const prefixSums = new Map(); prefixSums.set(0, 1); @@ -209,5 +210,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/subarray-sums-divisible-by-k.md b/articles/subarray-sums-divisible-by-k.md index f1faeaf61..30cc5ace9 100644 --- a/articles/subarray-sums-divisible-by-k.md +++ b/articles/subarray-sums-divisible-by-k.md @@ -88,8 +88,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -166,7 +166,8 @@ class Solution { * @return {number} */ subarraysDivByK(nums, k) { - let prefixSum = 0, res = 0; + let prefixSum = 0, + res = 0; const prefixCnt = new Map(); prefixCnt.set(0, 1); @@ -188,8 +189,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(k)$ +- Time complexity: $O(n)$ +- Space complexity: $O(k)$ --- @@ -259,10 +260,11 @@ class Solution { subarraysDivByK(nums, k) { const count = Array(k).fill(0); count[0] = 1; - let prefix = 0, res = 0; + let prefix = 0, + res = 0; for (let num of nums) { - prefix = (prefix + num % k + k) % k; + prefix = (prefix + (num % k) + k) % k; res += count[prefix]; count[prefix]++; } @@ -276,5 +278,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + k)$ -* Space complexity: $O(k)$ \ No newline at end of file +- Time complexity: $O(n + k)$ +- Space complexity: $O(k)$ diff --git a/articles/subarrays-with-k-different-integers.md b/articles/subarrays-with-k-different-integers.md index a2e24a470..a61fba032 100644 --- a/articles/subarrays-with-k-different-integers.md +++ b/articles/subarrays-with-k-different-integers.md @@ -6,17 +6,17 @@ class Solution: def subarraysWithKDistinct(self, nums: List[int], k: int) -> int: n, res = len(nums), 0 - + for i in range(n): seen = set() for j in range(i, n): seen.add(nums[j]) if len(seen) > k: break - + if len(seen) == k: res += 1 - + return res ``` @@ -75,7 +75,8 @@ class Solution { * @return {number} */ subarraysWithKDistinct(nums, k) { - let n = nums.length, res = 0; + let n = nums.length, + res = 0; for (let i = 0; i < n; i++) { let seen = new Set(); @@ -99,8 +100,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -111,7 +112,7 @@ class Solution { ```python class Solution: def subarraysWithKDistinct(self, nums: List[int], k: int) -> int: - + def atMostK(k): count = defaultdict(int) res = l = 0 @@ -120,17 +121,17 @@ class Solution: count[nums[r]] += 1 if count[nums[r]] == 1: k -= 1 - + while k < 0: count[nums[l]] -= 1 if count[nums[l]] == 0: k += 1 l += 1 - + res += (r - l + 1) - + return res - + return atMostK(k) - atMostK(k - 1) ``` @@ -139,17 +140,17 @@ public class Solution { public int subarraysWithKDistinct(int[] nums, int k) { return atMostK(nums, k) - atMostK(nums, k - 1); } - + private int atMostK(int[] nums, int k) { HashMap count = new HashMap<>(); int res = 0, l = 0; - + for (int r = 0; r < nums.length; r++) { count.put(nums[r], count.getOrDefault(nums[r], 0) + 1); if (count.get(nums[r]) == 1) { k--; } - + while (k < 0) { count.put(nums[l], count.get(nums[l]) - 1); if (count.get(nums[l]) == 0) { @@ -157,10 +158,10 @@ public class Solution { } l++; } - + res += (r - l + 1); } - + return res; } } @@ -210,7 +211,8 @@ class Solution { subarraysWithKDistinct(nums, k) { const atMostK = (k) => { const count = new Map(); - let res = 0, l = 0; + let res = 0, + l = 0; for (let r = 0; r < nums.length; r++) { count.set(nums[r], (count.get(nums[r]) || 0) + 1); @@ -226,7 +228,7 @@ class Solution { l++; } - res += (r - l + 1); + res += r - l + 1; } return res; @@ -241,8 +243,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -354,7 +356,9 @@ class Solution { */ subarraysWithKDistinct(nums, k) { const count = new Map(); - let res = 0, l_far = 0, l_near = 0; + let res = 0, + l_far = 0, + l_near = 0; for (let r = 0; r < nums.length; r++) { count.set(nums[r], (count.get(nums[r]) || 0) + 1); @@ -386,8 +390,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -507,7 +511,9 @@ class Solution { subarraysWithKDistinct(nums, k) { const n = nums.length; const count = new Array(n + 1).fill(0); - let res = 0, l = 0, cnt = 0; + let res = 0, + l = 0, + cnt = 0; for (let r = 0; r < n; r++) { count[nums[r]]++; @@ -529,7 +535,7 @@ class Solution { cnt++; } - res += (cnt + 1); + res += cnt + 1; } } @@ -542,5 +548,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/subsets-ii.md b/articles/subsets-ii.md index fef683226..d1aeb5b99 100644 --- a/articles/subsets-ii.md +++ b/articles/subsets-ii.md @@ -83,7 +83,7 @@ class Solution { subsetsWithDup(nums) { nums.sort((a, b) => a - b); this.backtrack(nums, 0, []); - return Array.from(this.res).map(subset => JSON.parse(subset)); + return Array.from(this.res).map((subset) => JSON.parse(subset)); } /** @@ -160,7 +160,7 @@ func subsetsWithDup(nums []int) [][]int { } backtrack(0, []int{}) - + var result [][]int for _, v := range res { result = append(result, v) @@ -222,8 +222,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 2 ^n)$ -* Space complexity: $O(2 ^ n)$ +- Time complexity: $O(n * 2 ^n)$ +- Space complexity: $O(2 ^ n)$ --- @@ -436,24 +436,24 @@ class Solution { var res = [[Int]]() var subset = [Int]() let nums = nums.sorted() - + func backtrack(_ i: Int) { if i == nums.count { res.append(subset) return } - + subset.append(nums[i]) backtrack(i + 1) subset.removeLast() - + var j = i while j + 1 < nums.count && nums[j] == nums[j + 1] { j += 1 } backtrack(j + 1) } - + backtrack(0) return res } @@ -464,10 +464,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 2 ^ n)$ -* Space complexity: - * $O(n)$ extra space. - * $O(2 ^ n)$ space for the output list. +- Time complexity: $O(n * 2 ^ n)$ +- Space complexity: + - $O(n)$ extra space. + - $O(2 ^ n)$ space for the output list. --- @@ -658,10 +658,10 @@ class Solution { var res = [[Int]]() var subset = [Int]() let nums = nums.sorted() - + func backtrack(_ i: Int) { res.append(subset) - + for j in i.. i && nums[j] == nums[j - 1] { continue @@ -671,7 +671,7 @@ class Solution { subset.removeLast() } } - + backtrack(0) return res } @@ -682,10 +682,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 2 ^ n)$ -* Space complexity: - * $O(n)$ extra space. - * $O(2 ^ n)$ space for the output list. +- Time complexity: $O(n * 2 ^ n)$ +- Space complexity: + - $O(n)$ extra space. + - $O(2 ^ n)$ space for the output list. --- @@ -716,7 +716,7 @@ public class Solution { public List> subsetsWithDup(int[] nums) { Arrays.sort(nums); List> res = new ArrayList<>(); - res.add(new ArrayList<>()); + res.add(new ArrayList<>()); int prevIdx = 0; int idx = 0; @@ -772,7 +772,7 @@ class Solution { let idx = 0; for (let i = 0; i < nums.length; i++) { - idx = (i >= 1 && nums[i] === nums[i - 1]) ? prevIdx : 0; + idx = i >= 1 && nums[i] === nums[i - 1] ? prevIdx : 0; prevIdx = res.length; for (let j = idx; j < prevIdx; j++) { const tmp = [...res[j]]; @@ -884,7 +884,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 2 ^ n)$ -* Space complexity: - * $O(1)$ extra space. - * $O(2 ^ n)$ space for the output list. \ No newline at end of file +- Time complexity: $O(n * 2 ^ n)$ +- Space complexity: + - $O(1)$ extra space. + - $O(2 ^ n)$ space for the output list. diff --git a/articles/subsets.md b/articles/subsets.md index 733609e9f..86be6b23d 100644 --- a/articles/subsets.md +++ b/articles/subsets.md @@ -23,7 +23,7 @@ class Solution: ```java public class Solution { - + public List> subsets(int[] nums) { List> res = new ArrayList<>(); List subset = new ArrayList<>(); @@ -103,7 +103,7 @@ class Solution { ```csharp public class Solution { - + public List> Subsets(int[] nums) { var res = new List>(); var subset = new List(); @@ -187,7 +187,7 @@ class Solution { subset.removeLast() dfs(i + 1) } - + dfs(0) return res } @@ -198,10 +198,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 2 ^ n)$ -* Space complexity: - * $O(n)$ extra space. - * $O(2 ^ n)$ for the output list. +- Time complexity: $O(n * 2 ^ n)$ +- Space complexity: + - $O(n)$ extra space. + - $O(2 ^ n)$ for the output list. --- @@ -213,10 +213,10 @@ class Solution { class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: res = [[]] - + for num in nums: res += [subset + [num] for subset in res] - + return res ``` @@ -245,7 +245,7 @@ class Solution { public: vector> subsets(vector& nums) { vector> res = {{}}; - + for (int num : nums) { int size = res.size(); for (int i = 0; i < size; i++) { @@ -272,7 +272,7 @@ class Solution { for (let num of nums) { let size = res.length; for (let i = 0; i < size; i++) { - let subset = res[i].slice(); + let subset = res[i].slice(); subset.push(num); res.push(subset); } @@ -288,7 +288,7 @@ public class Solution { public List> Subsets(int[] nums) { List> res = new List>(); res.Add(new List()); - + foreach (int num in nums) { int size = res.Count; for (int i = 0; i < size; i++) { @@ -358,10 +358,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 2 ^ n)$ -* Space complexity: - * $O(n)$ extra space. - * $O(2 ^ n)$ for the output list. +- Time complexity: $O(n * 2 ^ n)$ +- Space complexity: + - $O(n)$ extra space. + - $O(2 ^ n)$ for the output list. --- @@ -428,7 +428,7 @@ class Solution { subsets(nums) { let res = []; let n = nums.length; - for (let i = 0; i < (1 << n); i++) { + for (let i = 0; i < 1 << n; i++) { let subset = []; for (let j = 0; j < n; j++) { if (i & (1 << j)) { @@ -526,7 +526,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 2 ^ n)$ -* Space complexity: - * $O(n)$ extra space. - * $O(2 ^ n)$ for the output list. \ No newline at end of file +- Time complexity: $O(n * 2 ^ n)$ +- Space complexity: + - $O(n)$ extra space. + - $O(2 ^ n)$ for the output list. diff --git a/articles/subtree-of-a-binary-tree.md b/articles/subtree-of-a-binary-tree.md index f4e7e57f2..db358f599 100644 --- a/articles/subtree-of-a-binary-tree.md +++ b/articles/subtree-of-a-binary-tree.md @@ -11,7 +11,7 @@ # self.right = right class Solution: - + def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool: if not subRoot: return True @@ -20,14 +20,14 @@ class Solution: if self.sameTree(root, subRoot): return True - return (self.isSubtree(root.left, subRoot) or + return (self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)) def sameTree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool: if not root and not subRoot: return True if root and subRoot and root.val == subRoot.val: - return (self.sameTree(root.left, subRoot.left) and + return (self.sameTree(root.left, subRoot.left) and self.sameTree(root.right, subRoot.right)) return False ``` @@ -50,7 +50,7 @@ class Solution: */ class Solution { - + public boolean isSubtree(TreeNode root, TreeNode subRoot) { if (subRoot == null) { return true; @@ -62,7 +62,7 @@ class Solution { if (sameTree(root, subRoot)) { return true; } - return isSubtree(root.left, subRoot) || + return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot); } @@ -71,7 +71,7 @@ class Solution { return true; } if (root != null && subRoot != null && root.val == subRoot.val) { - return sameTree(root.left, subRoot.left) && + return sameTree(root.left, subRoot.left) && sameTree(root.right, subRoot.right); } return false; @@ -105,7 +105,7 @@ public: if (sameTree(root, subRoot)) { return true; } - return isSubtree(root->left, subRoot) || + return isSubtree(root->left, subRoot) || isSubtree(root->right, subRoot); } @@ -193,7 +193,7 @@ class Solution { */ public class Solution { - + public bool IsSubtree(TreeNode root, TreeNode subRoot) { if (subRoot == null) { return true; @@ -205,7 +205,7 @@ public class Solution { if (SameTree(root, subRoot)) { return true; } - return IsSubtree(root.left, subRoot) || + return IsSubtree(root.left, subRoot) || IsSubtree(root.right, subRoot); } @@ -214,7 +214,7 @@ public class Solution { return true; } if (root != null && subRoot != null && root.val == subRoot.val) { - return SameTree(root.left, subRoot.left) && + return SameTree(root.left, subRoot.left) && SameTree(root.right, subRoot.right); } return false; @@ -340,8 +340,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m + n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m + n)$ > Where $m$ is the number of nodes in $subRoot$ and $n$ is the number of nodes in $root$. @@ -359,12 +359,12 @@ class Solution { # self.left = left # self.right = right -class Solution: +class Solution: def serialize(self, root: Optional[TreeNode]) -> str: if root == None: return "$#" - return ("$" + str(root.val) + self.serialize(root.left) + self.serialize(root.right)) + return ("$" + str(root.val) + self.serialize(root.left) + self.serialize(root.right)) def z_function(self, s: str) -> list: z = [0] * len(s) @@ -439,10 +439,10 @@ public class Solution { String serialized_root = serialize(root); String serialized_subRoot = serialize(subRoot); String combined = serialized_subRoot + "|" + serialized_root; - + int[] z_values = z_function(combined); int sub_len = serialized_subRoot.length(); - + for (int i = sub_len + 1; i < combined.length(); i++) { if (z_values[i] == sub_len) { return true; @@ -472,7 +472,7 @@ public: if (root == nullptr) { return "$#"; } - return "$" + to_string(root->val) + + return "$" + to_string(root->val) + serialize(root->left) + serialize(root->right); } @@ -498,10 +498,10 @@ public: string serialized_root = serialize(root); string serialized_subRoot = serialize(subRoot); string combined = serialized_subRoot + "|" + serialized_root; - + vector z_values = z_function(combined); int sub_len = serialized_subRoot.length(); - + for (int i = sub_len + 1; i < combined.length(); i++) { if (z_values[i] == sub_len) { return true; @@ -531,9 +531,14 @@ class Solution { */ serialize(root) { if (root === null) { - return "$#"; + return '$#'; } - return "$" + root.val + this.serialize(root.left) + this.serialize(root.right); + return ( + '$' + + root.val + + this.serialize(root.left) + + this.serialize(root.right) + ); } /** @@ -542,7 +547,9 @@ class Solution { */ z_function(s) { const z = new Array(s.length).fill(0); - let l = 0, r = 0, n = s.length; + let l = 0, + r = 0, + n = s.length; for (let i = 1; i < n; i++) { if (i <= r) { z[i] = Math.min(r - i + 1, z[i - l]); @@ -566,11 +573,11 @@ class Solution { isSubtree(root, subRoot) { const serialized_root = this.serialize(root); const serialized_subRoot = this.serialize(subRoot); - const combined = serialized_subRoot + "|" + serialized_root; - + const combined = serialized_subRoot + '|' + serialized_root; + const z_values = this.z_function(combined); const sub_len = serialized_subRoot.length; - + for (let i = sub_len + 1; i < combined.length; i++) { if (z_values[i] === sub_len) { return true; @@ -601,7 +608,7 @@ public class Solution { if (root == null) { return "$#"; } - return "$" + root.val + + return "$" + root.val + Serialize(root.left) + Serialize(root.right); } @@ -627,10 +634,10 @@ public class Solution { string serialized_root = Serialize(root); string serialized_subRoot = Serialize(subRoot); string combined = serialized_subRoot + "|" + serialized_root; - + int[] z_values = ZFunction(combined); int sub_len = serialized_subRoot.Length; - + for (int i = sub_len + 1; i < combined.Length; i++) { if (z_values[i] == sub_len) { return true; @@ -661,7 +668,7 @@ func zFunction(s string) []int { n := len(s) z := make([]int, n) l, r := 0, 0 - + for i := 1; i < n; i++ { if i <= r { z[i] = min(r-i+1, z[i-l]) @@ -688,10 +695,10 @@ func isSubtree(root *TreeNode, subRoot *TreeNode) bool { serializedRoot := serialize(root) serializedSubRoot := serialize(subRoot) combined := serializedSubRoot + "|" + serializedRoot - + zValues := zFunction(combined) subLen := len(serializedSubRoot) - + for i := subLen + 1; i < len(combined); i++ { if zValues[i] == subLen { return true @@ -719,13 +726,13 @@ class Solution { else -> "$${root.`val`}${serialize(root.left)}${serialize(root.right)}" } } - + private fun zFunction(s: String): IntArray { val n = s.length val z = IntArray(n) var l = 0 var r = 0 - + for (i in 1 until n) { if (i <= r) { z[i] = minOf(r - i + 1, z[i - l]) @@ -740,15 +747,15 @@ class Solution { } return z } - + fun isSubtree(root: TreeNode?, subRoot: TreeNode?): Boolean { val serializedRoot = serialize(root) val serializedSubRoot = serialize(subRoot) val combined = serializedSubRoot + "|" + serializedRoot - + val zValues = zFunction(combined) val subLen = serializedSubRoot.length - + return (subLen + 1 until combined.length).any { i -> zValues[i] == subLen } } } @@ -821,7 +828,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n)$ -* Space complexity: $O(m + n)$ +- Time complexity: $O(m + n)$ +- Space complexity: $O(m + n)$ -> Where $m$ is the number of nodes in $subRoot$ and $n$ is the number of nodes in $root$. \ No newline at end of file +> Where $m$ is the number of nodes in $subRoot$ and $n$ is the number of nodes in $root$. diff --git a/articles/successful-pairs-of-spells-and-potions.md b/articles/successful-pairs-of-spells-and-potions.md index 87faf3177..532ed79dd 100644 --- a/articles/successful-pairs-of-spells-and-potions.md +++ b/articles/successful-pairs-of-spells-and-potions.md @@ -6,14 +6,14 @@ class Solution: def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]: res = [] - + for s in spells: cnt = 0 for p in potions: if s * p >= success: cnt += 1 res.append(cnt) - + return res ``` @@ -88,8 +88,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(1)$ > Where $n$ and $m$ are the sizes of the arrays $spells$ and $potions$ respectively. @@ -104,7 +104,7 @@ class Solution: def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]: potions.sort() res = [] - + for s in spells: l, r = 0, len(potions) - 1 idx = len(potions) @@ -116,9 +116,9 @@ class Solution: idx = m else: l = m + 1 - + res.append(len(potions) - idx) - + return res ``` @@ -190,7 +190,9 @@ class Solution { let res = []; for (let s of spells) { - let l = 0, r = potions.length - 1, idx = potions.length; + let l = 0, + r = potions.length - 1, + idx = potions.length; while (l <= r) { let m = Math.floor((l + r) / 2); @@ -214,10 +216,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O((m + n) * \log m)$ -* Space complexity: - * $O(1)$ or $O(m)$ extra space depending on the sorting algorithm. - * $O(n)$ space for the output array. +- Time complexity: $O((m + n) * \log m)$ +- Space complexity: + - $O(1)$ or $O(m)$ extra space depending on the sorting algorithm. + - $O(n)$ space for the output array. > Where $n$ and $m$ are the sizes of the arrays $spells$ and $potions$ respectively. @@ -235,17 +237,17 @@ class Solution: count = defaultdict(int) spells.sort() potions.sort() - + j = m - 1 for i in range(n): while j >= 0 and spells[i] * potions[j] >= success: j -= 1 count[spells[i]] = m - j - 1 - + res = [0] * n for i in range(n): res[i] = count[S[i]] - + return res ``` @@ -257,7 +259,7 @@ public class Solution { Map count = new HashMap<>(); Arrays.sort(spells); Arrays.sort(potions); - + int j = m - 1; for (int i = 0; i < n; i++) { while (j >= 0 && (long) spells[i] * potions[j] >= success) { @@ -265,12 +267,12 @@ public class Solution { } count.put(spells[i], m - j - 1); } - + int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = count.get(S[i]); } - + return res; } } @@ -285,7 +287,7 @@ public: unordered_map count; sort(spells.begin(), spells.end()); sort(potions.begin(), potions.end()); - + int j = m - 1; for (int i = 0; i < n; i++) { while (j >= 0 && (long long) spells[i] * potions[j] >= success) { @@ -293,12 +295,12 @@ public: } count[spells[i]] = m - j - 1; } - + vector res(n); for (int i = 0; i < n; i++) { res[i] = count[S[i]]; } - + return res; } }; @@ -313,12 +315,13 @@ class Solution { * @return {number[]} */ successfulPairs(spells, potions, success) { - const n = spells.length, m = potions.length; + const n = spells.length, + m = potions.length; const S = [...spells]; const count = new Map(); spells.sort((a, b) => a - b); potions.sort((a, b) => a - b); - + let j = m - 1; for (let i = 0; i < n; i++) { while (j >= 0 && spells[i] * potions[j] >= success) { @@ -326,8 +329,8 @@ class Solution { } count.set(spells[i], m - j - 1); } - - return S.map(s => count.get(s)); + + return S.map((s) => count.get(s)); } } ``` @@ -336,10 +339,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n + m\log m)$ -* Space complexity: - * $O(1)$ or $O(m + n)$ extra space depending on the sorting algorithm. - * $O(n)$ space for the output array. +- Time complexity: $O(n \log n + m\log m)$ +- Space complexity: + - $O(1)$ or $O(m + n)$ extra space depending on the sorting algorithm. + - $O(n)$ space for the output array. > Where $n$ and $m$ are the sizes of the arrays $spells$ and $potions$ respectively. @@ -373,10 +376,10 @@ public class Solution { int n = spells.length, m = potions.length; Integer[] sIdx = new Integer[n]; for (int i = 0; i < n; i++) sIdx[i] = i; - + Arrays.sort(sIdx, Comparator.comparingInt(i -> spells[i])); Arrays.sort(potions); - + int j = m - 1; int[] res = new int[n]; for (int i = 0; i < n; i++) { @@ -404,7 +407,7 @@ public: }); sort(potions.begin(), potions.end()); - + int j = m - 1; vector res(n); for (int i = 0; i < n; i++) { @@ -428,15 +431,16 @@ class Solution { * @return {number[]} */ successfulPairs(spells, potions, success) { - const n = spells.length, m = potions.length; + const n = spells.length, + m = potions.length; const sIdx = Array.from({ length: n }, (_, i) => i); - + sIdx.sort((a, b) => spells[a] - spells[b]); potions.sort((a, b) => a - b); - + let j = m - 1; const res = new Array(n).fill(0); - + for (let i = 0; i < n; i++) { while (j >= 0 && spells[sIdx[i]] * potions[j] >= success) { j--; @@ -453,9 +457,9 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n + m\log m)$ -* Space complexity: - * $O(1)$ or $O(m + n)$ extra space depending on the sorting algorithm. - * $O(n)$ space for the output array. +- Time complexity: $O(n \log n + m\log m)$ +- Space complexity: + - $O(1)$ or $O(m + n)$ extra space depending on the sorting algorithm. + - $O(n)$ space for the output array. -> Where $n$ and $m$ are the sizes of the arrays $spells$ and $potions$ respectively. \ No newline at end of file +> Where $n$ and $m$ are the sizes of the arrays $spells$ and $potions$ respectively. diff --git a/articles/sum-of-absolute-differences-in-a-sorted-array.md b/articles/sum-of-absolute-differences-in-a-sorted-array.md index f705f47d7..a8b0fa5fa 100644 --- a/articles/sum-of-absolute-differences-in-a-sorted-array.md +++ b/articles/sum-of-absolute-differences-in-a-sorted-array.md @@ -12,7 +12,7 @@ class Solution: for j in nums: sum += abs(i - j) res.append(sum) - + return res ``` @@ -29,7 +29,7 @@ public class Solution { } res[i] = sum; } - + return res; } } @@ -49,7 +49,7 @@ public: } res.push_back(sum); } - + return res; } }; @@ -72,7 +72,7 @@ class Solution { } res.push(sum); } - + return res; } } @@ -82,8 +82,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ for the output array. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ for the output array. --- @@ -98,20 +98,20 @@ class Solution: prefix_sum = [0] * n suffix_sum = [0] * n res = [0] * n - + prefix_sum[0] = nums[0] for i in range(1, n): prefix_sum[i] = prefix_sum[i - 1] + nums[i] - + suffix_sum[n - 1] = nums[n - 1] for i in range(n - 2, -1, -1): suffix_sum[i] = suffix_sum[i + 1] + nums[i] - + for i in range(n): left_sum = (i * nums[i]) - (prefix_sum[i - 1] if i > 0 else 0) right_sum = (suffix_sum[i + 1] if i < n - 1 else 0) - ((n - i - 1) * nums[i]) res[i] = left_sum + right_sum - + return res ``` @@ -195,8 +195,9 @@ class Solution { } for (let i = 0; i < n; i++) { - const leftSum = i > 0 ? (i * nums[i] - prefixSum[i - 1]) : 0; - const rightSum = i < n - 1 ? (suffixSum[i + 1] - (n - i - 1) * nums[i]) : 0; + const leftSum = i > 0 ? i * nums[i] - prefixSum[i - 1] : 0; + const rightSum = + i < n - 1 ? suffixSum[i + 1] - (n - i - 1) * nums[i] : 0; res[i] = leftSum + rightSum; } @@ -209,8 +210,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -223,18 +224,18 @@ class Solution: def getSumAbsoluteDifferences(self, nums: List[int]) -> List[int]: n = len(nums) res = [0] * n - + res[n - 1] = nums[n - 1] for i in range(n - 2, -1, -1): res[i] = res[i + 1] + nums[i] - + prefix_sum = 0 for i in range(n): left_sum = (i * nums[i]) - prefix_sum right_sum = (res[i + 1] if i < n - 1 else 0) - ((n - i - 1) * nums[i]) res[i] = left_sum + right_sum prefix_sum += nums[i] - + return res ``` @@ -305,7 +306,7 @@ class Solution { let prefixSum = 0; for (let i = 0; i < n; i++) { const leftSum = i * nums[i] - prefixSum; - const rightSum = i < n - 1 ? (res[i + 1] - (n - i - 1) * nums[i]) : 0; + const rightSum = i < n - 1 ? res[i + 1] - (n - i - 1) * nums[i] : 0; res[i] = leftSum + rightSum; prefixSum += nums[i]; } @@ -319,8 +320,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for the output array. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for the output array. --- @@ -333,7 +334,7 @@ class Solution: def getSumAbsoluteDifferences(self, nums: List[int]) -> List[int]: n = len(nums) res = [0] * n - + total_sum = sum(nums) prefix_sum = 0 @@ -343,7 +344,7 @@ class Solution: right_sum = total_sum - (n - i - 1) * nums[i] res[i] = left_sum + right_sum prefix_sum += nums[i] - + return res ``` @@ -352,7 +353,7 @@ public class Solution { public int[] getSumAbsoluteDifferences(int[] nums) { int n = nums.length; int[] res = new int[n]; - + int totalSum = 0, prefixSum = 0; for (int num : nums) { totalSum += num; @@ -365,7 +366,7 @@ public class Solution { res[i] = leftSum + rightSum; prefixSum += nums[i]; } - + return res; } } @@ -377,7 +378,7 @@ public: vector getSumAbsoluteDifferences(vector& nums) { int n = nums.size(); vector res(n, 0); - + int totalSum = 0, prefixSum = 0; for (int& num : nums) { totalSum += num; @@ -390,7 +391,7 @@ public: res[i] = leftSum + rightSum; prefixSum += nums[i]; } - + return res; } }; @@ -405,7 +406,7 @@ class Solution { getSumAbsoluteDifferences(nums) { const n = nums.length; const res = Array(n).fill(0); - + let totalSum = nums.reduce((sum, num) => sum + num, 0); let prefixSum = 0; @@ -416,7 +417,7 @@ class Solution { res[i] = leftSum + rightSum; prefixSum += nums[i]; } - + return res; } } @@ -426,5 +427,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for the output array. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for the output array. diff --git a/articles/sum-of-all-subset-xor-totals.md b/articles/sum-of-all-subset-xor-totals.md index b35c24e37..a89444a0f 100644 --- a/articles/sum-of-all-subset-xor-totals.md +++ b/articles/sum-of-all-subset-xor-totals.md @@ -18,7 +18,7 @@ class Solution: subset.append(nums[j]) backtrack(j + 1, subset) subset.pop() - + backtrack(0, []) return res ``` @@ -127,8 +127,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 2 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * 2 ^ n)$ +- Space complexity: $O(n)$ --- @@ -217,8 +217,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -238,7 +238,7 @@ class Solution: if mask & (1 << i): xorr ^= nums[i] res += xorr - + return res ``` @@ -257,7 +257,7 @@ public class Solution { } res += xorr; } - + return res; } } @@ -279,7 +279,7 @@ public: } res += xorr; } - + return res; } }; @@ -295,16 +295,16 @@ class Solution { const n = nums.length; let res = 0; - for (let mask = 0; mask < (1 << n); mask++) { + for (let mask = 0; mask < 1 << n; mask++) { let xorr = 0; for (let i = 0; i < n; i++) { - if ((mask & ( 1 << i)) !== 0) { + if ((mask & (1 << i)) !== 0) { xorr ^= nums[i]; } } res += xorr; } - + return res; } } @@ -335,8 +335,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * 2 ^ n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n * 2 ^ n)$ +- Space complexity: $O(1)$ extra space. --- @@ -410,5 +410,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/sum-of-subarray-minimums.md b/articles/sum-of-subarray-minimums.md index f1103db9b..cbe2dcd37 100644 --- a/articles/sum-of-subarray-minimums.md +++ b/articles/sum-of-subarray-minimums.md @@ -84,8 +84,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -98,7 +98,7 @@ class Solution: def sumSubarrayMins(self, arr: List[int]) -> int: MOD = 10**9 + 7 n = len(arr) - + # Compute previous smaller prev_smaller = [-1] * n stack = [] @@ -107,7 +107,7 @@ class Solution: stack.pop() prev_smaller[i] = stack[-1] if stack else -1 stack.append(i) - + # Compute next smaller next_smaller = [n] * n stack = [] @@ -116,13 +116,13 @@ class Solution: stack.pop() next_smaller[i] = stack[-1] if stack else n stack.append(i) - + res = 0 for i in range(n): left = i - prev_smaller[i] right = next_smaller[i] - i res = (res + arr[i] * left * right) % MOD - + return res ``` @@ -131,7 +131,7 @@ public class Solution { public int sumSubarrayMins(int[] arr) { int MOD = 1000000007; int n = arr.length; - + // Compute previous smaller int[] prevSmaller = new int[n]; Stack stack = new Stack<>(); @@ -142,7 +142,7 @@ public class Solution { prevSmaller[i] = stack.isEmpty() ? -1 : stack.peek(); stack.push(i); } - + // Compute next smaller int[] nextSmaller = new int[n]; stack = new Stack<>(); @@ -153,7 +153,7 @@ public class Solution { nextSmaller[i] = stack.isEmpty() ? n : stack.peek(); stack.push(i); } - + // Calculate result long res = 0; for (int i = 0; i < n; i++) { @@ -161,7 +161,7 @@ public class Solution { long right = nextSmaller[i] - i; res = (res + arr[i] * left * right) % MOD; } - + return (int) res; } } @@ -173,7 +173,7 @@ public: int sumSubarrayMins(vector& arr) { const int MOD = 1e9 + 7; int n = arr.size(); - + // Compute previous smaller vector prevSmaller(n, -1); stack stack; @@ -184,7 +184,7 @@ public: prevSmaller[i] = stack.empty() ? -1 : stack.top(); stack.push(i); } - + // Compute next smaller vector nextSmaller(n, n); stack = {}; @@ -195,7 +195,7 @@ public: nextSmaller[i] = stack.empty() ? n : stack.top(); stack.push(i); } - + // Calculate result long long res = 0; for (int i = 0; i < n; i++) { @@ -203,7 +203,7 @@ public: long long right = nextSmaller[i] - i; res = (res + arr[i] * left * right) % MOD; } - + return res; } }; @@ -218,7 +218,7 @@ class Solution { sumSubarrayMins(arr) { const MOD = 1e9 + 7; const n = arr.length; - + // Compute previous smaller const prevSmaller = new Array(n).fill(-1); const stack = []; @@ -229,7 +229,7 @@ class Solution { prevSmaller[i] = stack.length > 0 ? stack[stack.length - 1] : -1; stack.push(i); } - + // Compute next smaller const nextSmaller = new Array(n).fill(n); stack.length = 0; @@ -240,7 +240,7 @@ class Solution { nextSmaller[i] = stack.length > 0 ? stack[stack.length - 1] : n; stack.push(i); } - + // Calculate result let res = 0; for (let i = 0; i < n; i++) { @@ -248,7 +248,7 @@ class Solution { const right = nextSmaller[i] - i; res = (res + arr[i] * left * right) % MOD; } - + return res; } } @@ -258,8 +258,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -351,12 +351,13 @@ class Solution { const MOD = 1e9 + 7; let res = 0; arr = [-Infinity, ...arr, -Infinity]; - let stack = []; + let stack = []; for (let i = 0; i < arr.length; i++) { while (stack.length > 0 && arr[i] < stack[stack.length - 1][1]) { let [j, m] = stack.pop(); - let left = stack.length > 0 ? j - stack[stack.length - 1][0] : j + 1; + let left = + stack.length > 0 ? j - stack[stack.length - 1][0] : j + 1; let right = i - j; res = (res + m * left * right) % MOD; } @@ -372,8 +373,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -460,9 +461,13 @@ class Solution { let res = 0; for (let i = 0; i <= n; i++) { - while (stack.length > 0 && (i === n || arr[i] < arr[stack[stack.length - 1]])) { + while ( + stack.length > 0 && + (i === n || arr[i] < arr[stack[stack.length - 1]]) + ) { const j = stack.pop(); - const left = j - (stack.length > 0 ? stack[stack.length - 1] : -1); + const left = + j - (stack.length > 0 ? stack[stack.length - 1] : -1); const right = i - j; res = (res + arr[j] * left * right) % MOD; } @@ -478,8 +483,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -498,7 +503,7 @@ class Solution: for i in range(n): while stack and arr[stack[-1]] > arr[i]: stack.pop() - + j = stack[-1] if stack else -1 dp[i] = (dp[j] if j != -1 else 0) + arr[i] * (i - j) dp[i] %= MOD @@ -592,5 +597,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/sum-of-two-integers.md b/articles/sum-of-two-integers.md index 6d43c0a14..a22bdc3fc 100644 --- a/articles/sum-of-two-integers.md +++ b/articles/sum-of-two-integers.md @@ -11,7 +11,7 @@ class Solution: ```java public class Solution { public int getSum(int a, int b) { - return a + b; + return a + b; } } ``` @@ -72,8 +72,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ --- @@ -98,7 +98,7 @@ class Solution: if res > 0x7FFFFFFF: res = ~(res ^ mask) - + return res ``` @@ -120,7 +120,7 @@ public class Solution { if (res > 0x7FFFFFFF) { res = ~(res ^ mask); } - + return res; } } @@ -145,7 +145,7 @@ public: if (res > 0x7FFFFFFF) { res = ~(res ^ mask); } - + return res; } }; @@ -159,22 +159,24 @@ class Solution { * @return {number} */ getSum(a, b) { - let carry = 0, res = 0, mask = 0xFFFFFFFF; + let carry = 0, + res = 0, + mask = 0xffffffff; for (let i = 0; i < 32; i++) { let a_bit = (a >> i) & 1; let b_bit = (b >> i) & 1; let cur_bit = a_bit ^ b_bit ^ carry; - carry = (a_bit + b_bit + carry) >= 2 ? 1 : 0; + carry = a_bit + b_bit + carry >= 2 ? 1 : 0; if (cur_bit) { - res |= (1 << i); + res |= 1 << i; } } - if (res > 0x7FFFFFFF) { + if (res > 0x7fffffff) { res = ~(res ^ mask); } - + return res; } } @@ -198,7 +200,7 @@ public class Solution { if (res > Int32.MaxValue) { res = ~(res ^ mask); } - + return res; } } @@ -288,8 +290,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ --- @@ -436,5 +438,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ diff --git a/articles/sum-root-to-leaf-numbers.md b/articles/sum-root-to-leaf-numbers.md index 02bfd196e..445fc6317 100644 --- a/articles/sum-root-to-leaf-numbers.md +++ b/articles/sum-root-to-leaf-numbers.md @@ -120,8 +120,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(h)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(h)$ for recursion stack. > Where $n$ is the number of nodes and $h$ is the height of the given tree. @@ -271,8 +271,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -334,7 +334,7 @@ public class Solution { num = num * 10 + cur.val; if (cur.left == null && cur.right == null) res += num; - + stack.push(new Pair<>(cur.right, num)); cur = cur.left; } else { @@ -371,9 +371,9 @@ public: while (cur || !st.empty()) { if (cur) { num = num * 10 + cur->val; - if (!cur->left && !cur->right) + if (!cur->left && !cur->right) res += num; - + st.push({cur->right, num}); cur = cur->left; } else { @@ -404,16 +404,16 @@ class Solution { * @return {number} */ sumNumbers(root) { - let res = 0, num = 0; + let res = 0, + num = 0; let stack = []; let cur = root; while (cur || stack.length) { if (cur) { num = num * 10 + cur.val; - if (!cur.left && !cur.right) - res += num; - + if (!cur.left && !cur.right) res += num; + stack.push([cur.right, num]); cur = cur.left; } else { @@ -429,8 +429,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(h)$ +- Time complexity: $O(n)$ +- Space complexity: $O(h)$ > Where $n$ is the number of nodes and $h$ is the height of the given tree. @@ -608,7 +608,8 @@ class Solution { * @return {number} */ sumNumbers(root) { - let res = 0, num = 0; + let res = 0, + num = 0; let power = Array(10).fill(1); for (let i = 1; i < 10; i++) { power[i] = power[i - 1] * 10; @@ -621,7 +622,8 @@ class Solution { if (!cur.right) res += num; cur = cur.right; } else { - let prev = cur.left, steps = 1; + let prev = cur.left, + steps = 1; while (prev.right && prev.right !== cur) { prev = prev.right; steps++; @@ -648,5 +650,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/surrounded-regions.md b/articles/surrounded-regions.md index 1c0c5445c..915c3563f 100644 --- a/articles/surrounded-regions.md +++ b/articles/surrounded-regions.md @@ -8,7 +8,7 @@ class Solution: ROWS, COLS = len(board), len(board[0]) def capture(r, c): - if (r < 0 or c < 0 or r == ROWS or + if (r < 0 or c < 0 or r == ROWS or c == COLS or board[r][c] != "O" ): return @@ -23,7 +23,7 @@ class Solution: capture(r, 0) if board[r][COLS - 1] == "O": capture(r, COLS - 1) - + for c in range(COLS): if board[0][c] == "O": capture(0, c) @@ -76,7 +76,7 @@ public class Solution { } private void capture(char[][] board, int r, int c) { - if (r < 0 || c < 0 || r >= ROWS || + if (r < 0 || c < 0 || r >= ROWS || c >= COLS || board[r][c] != 'O') { return; } @@ -129,7 +129,7 @@ public: private: void capture(vector>& board, int r, int c) { - if (r < 0 || c < 0 || r >= ROWS || + if (r < 0 || c < 0 || r >= ROWS || c >= COLS || board[r][c] != 'O') { return; } @@ -149,11 +149,17 @@ class Solution { * @return {void} Do not return anything, modify board in-place instead. */ solve(board) { - let ROWS = board.length, COLS = board[0].length; + let ROWS = board.length, + COLS = board[0].length; const capture = (r, c) => { - if (r < 0 || c < 0 || r == ROWS || - c == COLS || board[r][c] !== 'O') { + if ( + r < 0 || + c < 0 || + r == ROWS || + c == COLS || + board[r][c] !== 'O' + ) { return; } board[r][c] = 'T'; @@ -161,7 +167,7 @@ class Solution { capture(r - 1, c); capture(r, c + 1); capture(r, c - 1); - } + }; for (let r = 0; r < ROWS; r++) { if (board[r][0] === 'O') capture(r, 0); @@ -221,7 +227,7 @@ public class Solution { } private void Capture(char[][] board, int r, int c) { - if (r < 0 || c < 0 || r == ROWS || + if (r < 0 || c < 0 || r == ROWS || c == COLS || board[r][c] != 'O') { return; } @@ -240,7 +246,7 @@ func solve(board [][]byte) { var capture func(r, c int) capture = func(r, c int) { - if r < 0 || c < 0 || r == rows || + if r < 0 || c < 0 || r == rows || c == cols || board[r][c] != 'O' { return } @@ -288,7 +294,7 @@ class Solution { val cols = board[0].size fun capture(r: Int, c: Int) { - if (r < 0 || c < 0 || r == rows || + if (r < 0 || c < 0 || r == rows || c == cols || board[r][c] != 'O') { return } @@ -382,8 +388,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns of the $board$. @@ -403,8 +409,8 @@ class Solution: q = deque() for r in range(ROWS): for c in range(COLS): - if (r == 0 or r == ROWS - 1 or - c == 0 or c == COLS - 1 and + if (r == 0 or r == ROWS - 1 or + c == 0 or c == COLS - 1 and board[r][c] == "O" ): q.append((r, c)) @@ -416,7 +422,7 @@ class Solution: nr, nc = r + dr, c + dc if 0 <= nr < ROWS and 0 <= nc < COLS: q.append((nr, nc)) - + capture() for r in range(ROWS): for c in range(COLS): @@ -454,8 +460,8 @@ public class Solution { Queue q = new LinkedList<>(); for (int r = 0; r < ROWS; r++) { for (int c = 0; c < COLS; c++) { - if (r == 0 || r == ROWS - 1 || - c == 0 || c == COLS - 1 && + if (r == 0 || r == ROWS - 1 || + c == 0 || c == COLS - 1 && board[r][c] == 'O') { q.offer(new int[]{r, c}); } @@ -481,7 +487,7 @@ public class Solution { ```cpp class Solution { int ROWS, COLS; - vector> directions = {{1, 0}, {-1, 0}, + vector> directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; public: @@ -507,8 +513,8 @@ private: queue> q; for (int r = 0; r < ROWS; r++) { for (int c = 0; c < COLS; c++) { - if (r == 0 || r == ROWS - 1 || - c == 0 || c == COLS - 1 && + if (r == 0 || r == ROWS - 1 || + c == 0 || c == COLS - 1 && board[r][c] == 'O') { q.push({r, c}); } @@ -520,9 +526,9 @@ private: if (board[r][c] == 'O') { board[r][c] = 'T'; for (auto& direction : directions) { - int nr = r + direction.first; + int nr = r + direction.first; int nc = c + direction.second; - if (nr >= 0 && nr < ROWS && + if (nr >= 0 && nr < ROWS && nc >= 0 && nc < COLS) { q.push({nr, nc}); } @@ -540,16 +546,25 @@ class Solution { * @return {void} Do not return anything, modify board in-place instead. */ solve(board) { - let ROWS = board.length, COLS = board[0].length; - let directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; - + let ROWS = board.length, + COLS = board[0].length; + let directions = [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + ]; + const capture = () => { let q = new Queue(); for (let r = 0; r < ROWS; r++) { for (let c = 0; c < COLS; c++) { - if (r === 0 || r === ROWS - 1 || - c === 0 || c === COLS - 1 && - board[r][c] === 'O') { + if ( + r === 0 || + r === ROWS - 1 || + c === 0 || + (c === COLS - 1 && board[r][c] === 'O') + ) { q.push([r, c]); } } @@ -559,15 +574,15 @@ class Solution { if (board[r][c] === 'O') { board[r][c] = 'T'; for (let [dr, dc] of directions) { - let nr = r + dr, nc = c + dc; - if (nr >= 0 && nr < ROWS && - nc >= 0 && nc < COLS) { + let nr = r + dr, + nc = c + dc; + if (nr >= 0 && nr < ROWS && nc >= 0 && nc < COLS) { q.push([nr, nc]); } } } } - } + }; capture(); for (let r = 0; r < ROWS; r++) { @@ -583,9 +598,9 @@ class Solution { ```csharp public class Solution { private int ROWS, COLS; - private int[][] directions = new int[][] { - new int[] { 1, 0 }, new int[] { -1, 0 }, - new int[] { 0, 1 }, new int[] { 0, -1 } + private int[][] directions = new int[][] { + new int[] { 1, 0 }, new int[] { -1, 0 }, + new int[] { 0, 1 }, new int[] { 0, -1 } }; public void Solve(char[][] board) { @@ -609,8 +624,8 @@ public class Solution { Queue q = new Queue(); for (int r = 0; r < ROWS; r++) { for (int c = 0; c < COLS; c++) { - if (r == 0 || r == ROWS - 1 || - c == 0 || c == COLS - 1 && + if (r == 0 || r == ROWS - 1 || + c == 0 || c == COLS - 1 && board[r][c] == 'O') { q.Enqueue(new int[] { r, c }); } @@ -624,7 +639,7 @@ public class Solution { foreach (var direction in directions) { int nr = r + direction[0]; int nc = c + direction[1]; - if (nr >= 0 && nr < ROWS && + if (nr >= 0 && nr < ROWS && nc >= 0 && nc < COLS) { q.Enqueue(new int[] { nr, nc }); } @@ -686,9 +701,9 @@ class Solution { fun solve(board: Array) { val rows = board.size val cols = board[0].size - val directions = arrayOf(intArrayOf(1, 0), - intArrayOf(-1, 0), - intArrayOf(0, 1), + val directions = arrayOf(intArrayOf(1, 0), + intArrayOf(-1, 0), + intArrayOf(0, 1), intArrayOf(0, -1)) fun capture() { @@ -783,8 +798,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns of the $board$. @@ -817,7 +832,7 @@ class DSU: self.Size[pv] += self.Size[pu] self.Parent[pu] = pv return True - + def connected(self, u, v): return self.find(u) == self.find(v) @@ -831,7 +846,7 @@ class Solution: for c in range(COLS): if board[r][c] != "O": continue - if (r == 0 or c == 0 or + if (r == 0 or c == 0 or r == (ROWS - 1) or c == (COLS - 1) ): dsu.union(ROWS * COLS, r * COLS + c) @@ -894,7 +909,7 @@ public class Solution { for (int r = 0; r < ROWS; r++) { for (int c = 0; c < COLS; c++) { if (board[r][c] != 'O') continue; - if (r == 0 || c == 0 || + if (r == 0 || c == 0 || r == ROWS - 1 || c == COLS - 1) { dsu.union(ROWS * COLS, r * COLS + c); } else { @@ -963,13 +978,13 @@ public: void solve(vector>& board) { int ROWS = board.size(), COLS = board[0].size(); DSU dsu(ROWS * COLS + 1); - vector> directions = {{1, 0}, {-1, 0}, + vector> directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; for (int r = 0; r < ROWS; r++) { for (int c = 0; c < COLS; c++) { if (board[r][c] != 'O') continue; - if (r == 0 || c == 0 || + if (r == 0 || c == 0 || r == ROWS - 1 || c == COLS - 1) { dsu.unionNodes(ROWS * COLS, r * COLS + c); } else { @@ -1047,19 +1062,25 @@ class Solution { * @return {void} Do not return anything, modify board in-place instead. */ solve(board) { - const ROWS = board.length, COLS = board[0].length; + const ROWS = board.length, + COLS = board[0].length; const dsu = new DSU(ROWS * COLS + 1); - const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; + const directions = [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + ]; for (let r = 0; r < ROWS; r++) { for (let c = 0; c < COLS; c++) { if (board[r][c] !== 'O') continue; - if (r === 0 || c === 0 || - r === ROWS - 1 || c === COLS - 1) { + if (r === 0 || c === 0 || r === ROWS - 1 || c === COLS - 1) { dsu.union(ROWS * COLS, r * COLS + c); } else { for (let [dx, dy] of directions) { - const nr = r + dx, nc = c + dy; + const nr = r + dx, + nc = c + dy; if (board[nr][nc] === 'O') { dsu.union(r * COLS + c, nr * COLS + nc); } @@ -1121,15 +1142,15 @@ public class Solution { public void Solve(char[][] board) { int ROWS = board.Length, COLS = board[0].Length; DSU dsu = new DSU(ROWS * COLS + 1); - int[][] directions = new int[][] { - new int[] { 1, 0 }, new int[] { -1, 0 }, - new int[] { 0, 1 }, new int[] { 0, -1 } + int[][] directions = new int[][] { + new int[] { 1, 0 }, new int[] { -1, 0 }, + new int[] { 0, 1 }, new int[] { 0, -1 } }; for (int r = 0; r < ROWS; r++) { for (int c = 0; c < COLS; c++) { if (board[r][c] != 'O') continue; - if (r == 0 || c == 0 || + if (r == 0 || c == 0 || r == ROWS - 1 || c == COLS - 1) { dsu.Union(ROWS * COLS, r * COLS + c); } else { @@ -1214,7 +1235,7 @@ func solve(board [][]byte) { } else { for _, dir := range directions { nr, nc := r+dir[0], c+dir[1] - if nr >= 0 && nr < rows && nc >= 0 && + if nr >= 0 && nr < rows && nc >= 0 && nc < cols && board[nr][nc] == 'O' { dsu.Union(r*cols+c, nr*cols+nc) } @@ -1268,9 +1289,9 @@ class Solution { fun solve(board: Array) { val rows = board.size val cols = board[0].size - val directions = arrayOf(intArrayOf(1, 0), - intArrayOf(-1, 0), - intArrayOf(0, 1), + val directions = arrayOf(intArrayOf(1, 0), + intArrayOf(-1, 0), + intArrayOf(0, 1), intArrayOf(0, -1)) val dsu = DSU(rows * cols) @@ -1283,7 +1304,7 @@ class Solution { for (dir in directions) { val nr = r + dir[0] val nc = c + dir[1] - if (nr in 0 until rows && + if (nr in 0 until rows && nc in 0 until cols && board[nr][nc] == 'O') { dsu.union(r * cols + c, nr * cols + nc) } @@ -1380,7 +1401,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ -> Where $m$ is the number of rows and $n$ is the number of columns of the $board$. \ No newline at end of file +> Where $m$ is the number of rows and $n$ is the number of columns of the $board$. diff --git a/articles/swap-nodes-in-pairs.md b/articles/swap-nodes-in-pairs.md index 89edd0eee..384141389 100644 --- a/articles/swap-nodes-in-pairs.md +++ b/articles/swap-nodes-in-pairs.md @@ -43,7 +43,7 @@ class Solution: public class Solution { public ListNode swapPairs(ListNode head) { if (head == null) return null; - + List arr = new ArrayList<>(); ListNode cur = head; @@ -83,7 +83,7 @@ class Solution { public: ListNode* swapPairs(ListNode* head) { if (!head) return nullptr; - + vector arr; ListNode* cur = head; @@ -150,8 +150,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -266,8 +266,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -390,7 +390,8 @@ class Solution { */ swapPairs(head) { let dummy = new ListNode(0, head); - let prev = dummy, curr = head; + let prev = dummy, + curr = head; while (curr && curr.next) { let nxtPair = curr.next.next; @@ -415,5 +416,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/swapping-nodes-in-a-linked-list.md b/articles/swapping-nodes-in-a-linked-list.md index 8a0267213..6e80c42f1 100644 --- a/articles/swapping-nodes-in-a-linked-list.md +++ b/articles/swapping-nodes-in-a-linked-list.md @@ -18,7 +18,7 @@ class Solution: n = len(arr) arr[k - 1], arr[n - k] = arr[n - k], arr[k - 1] - + cur, i = head, 0 while cur: cur.val = arr[i] @@ -150,8 +150,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -173,15 +173,15 @@ class Solution: nonlocal left, right, startIdx if not node: return 0 - + startIdx += 1 if startIdx == k: left = node - + endIdx = dfs(node.next) + 1 if endIdx == k: right = node - + return endIdx dfs(head) @@ -209,7 +209,7 @@ public class Solution { int[] startIdx = {0}; dfs(head, k, startIdx, left, right); - + if (left[0] != null && right[0] != null) { int temp = left[0].val; left[0].val = right[0].val; @@ -304,7 +304,9 @@ class Solution { * @return {ListNode} */ swapNodes(head, k) { - let left = null, right = null, startIdx = 0; + let left = null, + right = null, + startIdx = 0; const dfs = (node) => { if (!node) return 0; @@ -332,8 +334,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -403,7 +405,7 @@ public class Solution { int temp = left.val; left.val = right.val; right.val = temp; - + return head; } } @@ -473,13 +475,14 @@ class Solution { cur = cur.next; } - let left = null, right = null; + let left = null, + right = null; cur = head; for (let i = 1; i <= n; i++) { if (i === k) { left = cur; } - if (i === (n - k + 1)) { + if (i === n - k + 1) { right = cur; } cur = cur.next; @@ -495,8 +498,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -635,8 +638,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -698,7 +701,7 @@ public class Solution { int temp = left.val; left.val = right.val; right.val = temp; - + return head; } } @@ -757,7 +760,9 @@ class Solution { * @return {ListNode} */ swapNodes(head, k) { - let left = null, right = null, cur = head; + let left = null, + right = null, + cur = head; while (cur) { if (right) { @@ -781,5 +786,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/swim-in-rising-water.md b/articles/swim-in-rising-water.md index b87262dcb..0e2e3ea66 100644 --- a/articles/swim-in-rising-water.md +++ b/articles/swim-in-rising-water.md @@ -22,7 +22,7 @@ class Solution: dfs((r, c - 1), t)) visit[r][c] = False return res - + return dfs((0, 0), 0) ``` @@ -35,7 +35,7 @@ public class Solution { return dfs(grid, visit, 0, 0, 0); } - private int dfs(int[][] grid, boolean[][] visit, + private int dfs(int[][] grid, boolean[][] visit, int r, int c, int t) { int n = grid.length; if (r < 0 || c < 0 || r >= n || c >= n || visit[r][c]) { @@ -66,7 +66,7 @@ public: } private: - int dfs(vector>& grid, vector>& visit, + int dfs(vector>& grid, vector>& visit, int r, int c, int t) { int n = grid.size(); if (r < 0 || c < 0 || r >= n || c >= n || visit[r][c]) { @@ -95,12 +95,10 @@ class Solution { */ swimInWater(grid) { const n = grid.length; - const visit = Array.from({ length: n }, () => - Array(n).fill(false)); - + const visit = Array.from({ length: n }, () => Array(n).fill(false)); + const dfs = (r, c, t) => { - if (r < 0 || c < 0 || r >= n || - c >= n || visit[r][c]) { + if (r < 0 || c < 0 || r >= n || c >= n || visit[r][c]) { return 1000000; } if (r === n - 1 && c === n - 1) { @@ -109,14 +107,12 @@ class Solution { visit[r][c] = true; t = Math.max(t, grid[r][c]); const res = Math.min( - Math.min(dfs(r + 1, c, t), - dfs(r - 1, c, t)), - Math.min(dfs(r, c + 1, t), - dfs(r, c - 1, t)) + Math.min(dfs(r + 1, c, t), dfs(r - 1, c, t)), + Math.min(dfs(r, c + 1, t), dfs(r, c - 1, t)), ); visit[r][c] = false; return res; - } + }; return dfs(0, 0, 0); } @@ -134,10 +130,10 @@ public class Solution { return Dfs(grid, visit, 0, 0, 0); } - private int Dfs(int[][] grid, bool[][] visit, + private int Dfs(int[][] grid, bool[][] visit, int r, int c, int t) { int n = grid.Length; - if (r < 0 || c < 0 || r >= n || + if (r < 0 || c < 0 || r >= n || c >= n || visit[r][c]) { return 1000000; } @@ -174,16 +170,16 @@ func swimInWater(grid [][]int) int { } visit[r][c] = true t = max(t, grid[r][c]) - + res := min( min(dfs(r+1, c, t), dfs(r-1, c, t)), min(dfs(r, c+1, t), dfs(r, c-1, t)), ) - + visit[r][c] = false return res } - + return dfs(0, 0, 0) } @@ -265,8 +261,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(4 ^ {n ^ 2})$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(4 ^ {n ^ 2})$ +- Space complexity: $O(n ^ 2)$ --- @@ -286,7 +282,7 @@ class Solution: def dfs(node, t): r, c = node - if (min(r, c) < 0 or max(r, c) >= n or + if (min(r, c) < 0 or max(r, c) >= n or visit[r][c] or grid[r][c] > t): return False if r == (n - 1) and c == (n - 1): @@ -296,14 +292,14 @@ class Solution: dfs((r - 1, c), t) or dfs((r, c + 1), t) or dfs((r, c - 1), t)) - + for t in range(minH, maxH): if dfs((0, 0), t): return t for r in range(n): for c in range(n): visit[r][c] = False - + return maxH ``` @@ -332,7 +328,7 @@ public class Solution { } private boolean dfs(int[][] grid, boolean[][] visit, int r, int c, int t) { - if (r < 0 || c < 0 || r >= grid.length || + if (r < 0 || c < 0 || r >= grid.length || c >= grid.length || visit[r][c] || grid[r][c] > t) { return false; } @@ -340,9 +336,9 @@ public class Solution { return true; } visit[r][c] = true; - return dfs(grid, visit, r + 1, c, t) || - dfs(grid, visit, r - 1, c, t) || - dfs(grid, visit, r, c + 1, t) || + return dfs(grid, visit, r + 1, c, t) || + dfs(grid, visit, r - 1, c, t) || + dfs(grid, visit, r, c + 1, t) || dfs(grid, visit, r, c - 1, t); } } @@ -374,9 +370,9 @@ public: } private: - bool dfs(vector>& grid, vector>& visit, + bool dfs(vector>& grid, vector>& visit, int r, int c, int t) { - if (r < 0 || c < 0 || r >= grid.size() || + if (r < 0 || c < 0 || r >= grid.size() || c >= grid.size() || visit[r][c] || grid[r][c] > t) { return false; } @@ -384,9 +380,9 @@ private: return true; } visit[r][c] = true; - return dfs(grid, visit, r + 1, c, t) || - dfs(grid, visit, r - 1, c, t) || - dfs(grid, visit, r, c + 1, t) || + return dfs(grid, visit, r + 1, c, t) || + dfs(grid, visit, r - 1, c, t) || + dfs(grid, visit, r, c + 1, t) || dfs(grid, visit, r, c - 1, t); } }; @@ -400,9 +396,9 @@ class Solution { */ swimInWater(grid) { const n = grid.length; - const visit = Array.from({ length: n }, () => - Array(n).fill(false)); - let minH = grid[0][0], maxH = grid[0][0]; + const visit = Array.from({ length: n }, () => Array(n).fill(false)); + let minH = grid[0][0], + maxH = grid[0][0]; for (let row = 0; row < n; row++) { for (let col = 0; col < n; col++) { maxH = Math.max(maxH, grid[row][col]); @@ -412,18 +408,24 @@ class Solution { const dfs = (node, t) => { const [r, c] = node; - if (Math.min(r, c) < 0 || Math.max(r, c) >= n || - visit[r][c] || grid[r][c] > t) { + if ( + Math.min(r, c) < 0 || + Math.max(r, c) >= n || + visit[r][c] || + grid[r][c] > t + ) { return false; } if (r === n - 1 && c === n - 1) { return true; } visit[r][c] = true; - return dfs([r + 1, c], t) || - dfs([r - 1, c], t) || - dfs([r, c + 1], t) || - dfs([r, c - 1], t); + return ( + dfs([r + 1, c], t) || + dfs([r - 1, c], t) || + dfs([r, c + 1], t) || + dfs([r, c - 1], t) + ); }; for (let t = minH; t < maxH; t++) { @@ -469,7 +471,7 @@ public class Solution { } private bool dfs(int[][] grid, bool[][] visit, int r, int c, int t) { - if (r < 0 || c < 0 || r >= grid.Length || + if (r < 0 || c < 0 || r >= grid.Length || c >= grid.Length || visit[r][c] || grid[r][c] > t) { return false; } @@ -477,9 +479,9 @@ public class Solution { return true; } visit[r][c] = true; - return dfs(grid, visit, r + 1, c, t) || - dfs(grid, visit, r - 1, c, t) || - dfs(grid, visit, r, c + 1, t) || + return dfs(grid, visit, r + 1, c, t) || + dfs(grid, visit, r - 1, c, t) || + dfs(grid, visit, r, c + 1, t) || dfs(grid, visit, r, c - 1, t); } } @@ -507,7 +509,7 @@ func swimInWater(grid [][]int) int { var dfs func(r, c, t int) bool dfs = func(r, c, t int) bool { - if r < 0 || c < 0 || r >= n || c >= n || + if r < 0 || c < 0 || r >= n || c >= n || visit[r][c] || grid[r][c] > t { return false } @@ -515,7 +517,7 @@ func swimInWater(grid [][]int) int { return true } visit[r][c] = true - found := dfs(r+1, c, t) || dfs(r-1, c, t) || + found := dfs(r+1, c, t) || dfs(r-1, c, t) || dfs(r, c+1, t) || dfs(r, c-1, t) return found } @@ -549,7 +551,7 @@ class Solution { val visit = Array(n) { BooleanArray(n) } fun dfs(r: Int, c: Int, t: Int): Boolean { - if (r < 0 || c < 0 || r >= n || c >= n || + if (r < 0 || c < 0 || r >= n || c >= n || visit[r][c] || grid[r][c] > t) { return false } @@ -557,7 +559,7 @@ class Solution { return true } visit[r][c] = true - return dfs(r + 1, c, t) || dfs(r - 1, c, t) || + return dfs(r + 1, c, t) || dfs(r - 1, c, t) || dfs(r, c + 1, t) || dfs(r, c - 1, t) } @@ -622,8 +624,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 4)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 4)$ +- Space complexity: $O(n ^ 2)$ --- @@ -643,7 +645,7 @@ class Solution: def dfs(node, t): r, c = node - if (min(r, c) < 0 or max(r, c) >= n or + if (min(r, c) < 0 or max(r, c) >= n or visit[r][c] or grid[r][c] > t): return False if r == (n - 1) and c == (n - 1): @@ -653,7 +655,7 @@ class Solution: dfs((r - 1, c), t) or dfs((r, c + 1), t) or dfs((r, c - 1), t)) - + l, r = minH, maxH while l < r: m = (l + r) >> 1 @@ -664,7 +666,7 @@ class Solution: for row in range(n): for col in range(n): visit[row][col] = False - + return r ``` @@ -697,7 +699,7 @@ public class Solution { } private boolean dfs(int[][] grid, boolean[][] visit, int r, int c, int t) { - if (r < 0 || c < 0 || r >= grid.length || + if (r < 0 || c < 0 || r >= grid.length || c >= grid.length || visit[r][c] || grid[r][c] > t) { return false; } @@ -705,9 +707,9 @@ public class Solution { return true; } visit[r][c] = true; - return dfs(grid, visit, r + 1, c, t) || - dfs(grid, visit, r - 1, c, t) || - dfs(grid, visit, r, c + 1, t) || + return dfs(grid, visit, r + 1, c, t) || + dfs(grid, visit, r - 1, c, t) || + dfs(grid, visit, r, c + 1, t) || dfs(grid, visit, r, c - 1, t); } } @@ -743,9 +745,9 @@ public: } private: - bool dfs(vector>& grid, vector>& visit, + bool dfs(vector>& grid, vector>& visit, int r, int c, int t) { - if (r < 0 || c < 0 || r >= grid.size() || + if (r < 0 || c < 0 || r >= grid.size() || c >= grid.size() || visit[r][c] || grid[r][c] > t) { return false; } @@ -753,9 +755,9 @@ private: return true; } visit[r][c] = true; - return dfs(grid, visit, r + 1, c, t) || - dfs(grid, visit, r - 1, c, t) || - dfs(grid, visit, r, c + 1, t) || + return dfs(grid, visit, r + 1, c, t) || + dfs(grid, visit, r - 1, c, t) || + dfs(grid, visit, r, c + 1, t) || dfs(grid, visit, r, c - 1, t); } }; @@ -769,9 +771,9 @@ class Solution { */ swimInWater(grid) { const n = grid.length; - const visit = Array.from({ length: n }, () => - Array(n).fill(false)); - let minH = grid[0][0], maxH = grid[0][0]; + const visit = Array.from({ length: n }, () => Array(n).fill(false)); + let minH = grid[0][0], + maxH = grid[0][0]; for (let row = 0; row < n; row++) { for (let col = 0; col < n; col++) { maxH = Math.max(maxH, grid[row][col]); @@ -781,21 +783,28 @@ class Solution { const dfs = (node, t) => { const [r, c] = node; - if (Math.min(r, c) < 0 || Math.max(r, c) >= n || - visit[r][c] || grid[r][c] > t) { + if ( + Math.min(r, c) < 0 || + Math.max(r, c) >= n || + visit[r][c] || + grid[r][c] > t + ) { return false; } if (r === n - 1 && c === n - 1) { return true; } visit[r][c] = true; - return dfs([r + 1, c], t) || - dfs([r - 1, c], t) || - dfs([r, c + 1], t) || - dfs([r, c - 1], t); + return ( + dfs([r + 1, c], t) || + dfs([r - 1, c], t) || + dfs([r, c + 1], t) || + dfs([r, c - 1], t) + ); }; - let l = minH, r = maxH; + let l = minH, + r = maxH; while (l < r) { let m = (l + r) >> 1; if (dfs([0, 0], m)) { @@ -846,7 +855,7 @@ public class Solution { } private bool dfs(int[][] grid, bool[][] visit, int r, int c, int t) { - if (r < 0 || c < 0 || r >= grid.Length || + if (r < 0 || c < 0 || r >= grid.Length || c >= grid.Length || visit[r][c] || grid[r][c] > t) { return false; } @@ -854,9 +863,9 @@ public class Solution { return true; } visit[r][c] = true; - return dfs(grid, visit, r + 1, c, t) || - dfs(grid, visit, r - 1, c, t) || - dfs(grid, visit, r, c + 1, t) || + return dfs(grid, visit, r + 1, c, t) || + dfs(grid, visit, r - 1, c, t) || + dfs(grid, visit, r, c + 1, t) || dfs(grid, visit, r, c - 1, t); } } @@ -884,7 +893,7 @@ func swimInWater(grid [][]int) int { var dfs func(r, c, t int) bool dfs = func(r, c, t int) bool { - if r < 0 || c < 0 || r >= n || c >= n || + if r < 0 || c < 0 || r >= n || c >= n || visit[r][c] || grid[r][c] > t { return false } @@ -892,7 +901,7 @@ func swimInWater(grid [][]int) int { return true } visit[r][c] = true - found := dfs(r+1, c, t) || dfs(r-1, c, t) || + found := dfs(r+1, c, t) || dfs(r-1, c, t) || dfs(r, c+1, t) || dfs(r, c-1, t) return found } @@ -930,7 +939,7 @@ class Solution { val visit = Array(n) { BooleanArray(n) } fun dfs(r: Int, c: Int, t: Int): Boolean { - if (r < 0 || c < 0 || r >= n || c >= n || + if (r < 0 || c < 0 || r >= n || c >= n || visit[r][c] || grid[r][c] > t) { return false } @@ -938,7 +947,7 @@ class Solution { return true } visit[r][c] = true - return dfs(r + 1, c, t) || dfs(r - 1, c, t) || + return dfs(r + 1, c, t) || dfs(r - 1, c, t) || dfs(r, c + 1, t) || dfs(r, c - 1, t) } @@ -1014,8 +1023,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 \log n)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2 \log n)$ +- Space complexity: $O(n ^ 2)$ --- @@ -1038,7 +1047,7 @@ class Solution: return t for dr, dc in directions: neiR, neiC = r + dr, c + dc - if (neiR < 0 or neiC < 0 or + if (neiR < 0 or neiC < 0 or neiR == N or neiC == N or (neiR, neiC) in visit ): @@ -1051,7 +1060,7 @@ class Solution: public class Solution { public int swimInWater(int[][] grid) { int N = grid.length; - boolean[][] visit = new boolean[N][N]; + boolean[][] visit = new boolean[N][N]; PriorityQueue minHeap = new PriorityQueue<>( Comparator.comparingInt(a -> a[0]) ); @@ -1060,27 +1069,27 @@ public class Solution { }; minHeap.offer(new int[]{grid[0][0], 0, 0}); - visit[0][0] = true; + visit[0][0] = true; while (!minHeap.isEmpty()) { int[] curr = minHeap.poll(); int t = curr[0], r = curr[1], c = curr[2]; if (r == N - 1 && c == N - 1) { - return t; + return t; } for (int[] dir : directions) { int neiR = r + dir[0], neiC = c + dir[1]; - if (neiR >= 0 && neiC >= 0 && neiR < N && + if (neiR >= 0 && neiC >= 0 && neiR < N && neiC < N && !visit[neiR][neiC]) { - visit[neiR][neiC] = true; + visit[neiR][neiC] = true; minHeap.offer(new int[]{ - Math.max(t, grid[neiR][neiC]), + Math.max(t, grid[neiR][neiC]), neiR, neiC }); } } } - return N * N; + return N * N; } } ``` @@ -1091,7 +1100,7 @@ public: int swimInWater(vector>& grid) { int N = grid.size(); set> visit; - priority_queue, + priority_queue, vector>, greater<>> minHeap; vector> directions = { {0, 1}, {0, -1}, {1, 0}, {-1, 0} @@ -1109,7 +1118,7 @@ public: } for (const auto& dir : directions) { int neiR = r + dir[0], neiC = c + dir[1]; - if (neiR < 0 || neiC < 0 || neiR == N || + if (neiR < 0 || neiC < 0 || neiR == N || neiC == N || visit.count({neiR, neiC})) { continue; } @@ -1138,7 +1147,7 @@ class Solution { swimInWater(grid) { const N = grid.length; const visit = new Set(); - const minPQ = new MinPriorityQueue(entry => entry[0]); + const minPQ = new MinPriorityQueue((entry) => entry[0]); const directions = [ [0, 1], [0, -1], @@ -1167,9 +1176,7 @@ class Solution { continue; } visit.add(`${neiR},${neiC}`); - minPQ.push([ - Math.max(t, grid[neiR][neiC]), neiR, neiC - ]); + minPQ.push([Math.max(t, grid[neiR][neiC]), neiR, neiC]); } } } @@ -1182,9 +1189,9 @@ public class Solution { int N = grid.Length; var visit = new HashSet<(int, int)>(); var minHeap = new PriorityQueue<(int t, int r, int c), int>(); - int[][] directions = { - new int[]{0, 1}, new int[]{0, -1}, - new int[]{1, 0}, new int[]{-1, 0} + int[][] directions = { + new int[]{0, 1}, new int[]{0, -1}, + new int[]{1, 0}, new int[]{-1, 0} }; minHeap.Enqueue((grid[0][0], 0, 0), grid[0][0]); @@ -1198,18 +1205,18 @@ public class Solution { } foreach (var dir in directions) { int neiR = r + dir[0], neiC = c + dir[1]; - if (neiR < 0 || neiC < 0 || neiR >= N || + if (neiR < 0 || neiC < 0 || neiR >= N || neiC >= N || visit.Contains((neiR, neiC))) { continue; } visit.Add((neiR, neiC)); minHeap.Enqueue( - (Math.Max(t, grid[neiR][neiC]), neiR, neiC), + (Math.Max(t, grid[neiR][neiC]), neiR, neiC), Math.Max(t, grid[neiR][neiC])); } } - return N * N; + return N * N; } } ``` @@ -1242,7 +1249,7 @@ func swimInWater(grid [][]int) int { for _, dir := range directions { neiR, neiC := r+dir[0], c+dir[1] - if neiR < 0 || neiC < 0 || neiR >= N || neiC >= N || + if neiR < 0 || neiC < 0 || neiR >= N || neiC >= N || visited[[2]int{neiR, neiC}] { continue } @@ -1268,10 +1275,10 @@ class Solution { fun swimInWater(grid: Array): Int { val N = grid.size val directions = listOf(Pair(0, 1), Pair(0, -1), Pair(1, 0), Pair(-1, 0)) - + val minHeap = PriorityQueue(compareBy>> { it.first }) minHeap.offer(Pair(grid[0][0], Pair(0, 0))) - + val visited = HashSet>() visited.add(Pair(0, 0)) @@ -1347,8 +1354,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 \log n)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2 \log n)$ +- Space complexity: $O(n ^ 2)$ --- @@ -1377,7 +1384,7 @@ class DSU: self.Size[pu] += self.Size[pv] self.Parent[pv] = pu return True - + def connected(self, u, v): return self.find(u) == self.find(v) @@ -1387,7 +1394,7 @@ class Solution: dsu = DSU(N * N) positions = sorted((grid[r][c], r, c) for r in range(N) for c in range(N)) directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] - + for t, r, c in positions: for dr, dc in directions: nr, nc = r + dr, c + dc @@ -1450,7 +1457,7 @@ public class Solution { int t = pos[0], r = pos[1], c = pos[2]; for (int[] dir : directions) { int nr = r + dir[0], nc = c + dir[1]; - if (nr >= 0 && nr < N && nc >= 0 && + if (nr >= 0 && nr < N && nc >= 0 && nc < N && grid[nr][nc] <= t) { dsu.union(r * N + c, nr * N + nc); } @@ -1508,7 +1515,7 @@ public: for (auto& [t, r, c] : positions) { for (auto& [dr, dc] : directions) { int nr = r + dr, nc = c + dc; - if (nr >= 0 && nr < N && nc >= 0 && + if (nr >= 0 && nr < N && nc >= 0 && nc < N && grid[nr][nc] <= t) { dsu.unionSets(r * N + c, nr * N + nc); } @@ -1544,7 +1551,8 @@ class DSU { * @return {boolean} */ union(u, v) { - let pu = this.find(u), pv = this.find(v); + let pu = this.find(u), + pv = this.find(v); if (pu === pv) return false; if (this.Size[pu] < this.Size[pv]) [pu, pv] = [pv, pu]; this.Size[pu] += this.Size[pv]; @@ -1578,14 +1586,23 @@ class Solution { } positions.sort((a, b) => a[0] - b[0]); const directions = [ - [0, 1], [1, 0], [0, -1], [-1, 0] + [0, 1], + [1, 0], + [0, -1], + [-1, 0], ]; for (const [t, r, c] of positions) { for (const [dr, dc] of directions) { - const nr = r + dr, nc = c + dc; - if (nr >= 0 && nr < N && nc >= 0 && - nc < N && grid[nr][nc] <= t) { + const nr = r + dr, + nc = c + dc; + if ( + nr >= 0 && + nr < N && + nc >= 0 && + nc < N && + grid[nr][nc] <= t + ) { dsu.union(r * N + c, nr * N + nc); } } @@ -1640,16 +1657,16 @@ public class Solution { for (int c = 0; c < N; c++) positions.Add(new int[] {grid[r][c], r, c}); positions.Sort((a, b) => a[0] - b[0]); - int[][] directions = new int[][] { - new int[] {0, 1}, new int[] {1, 0}, - new int[] {0, -1}, new int[] {-1, 0} + int[][] directions = new int[][] { + new int[] {0, 1}, new int[] {1, 0}, + new int[] {0, -1}, new int[] {-1, 0} }; foreach (var pos in positions) { int t = pos[0], r = pos[1], c = pos[2]; foreach (var dir in directions) { int nr = r + dir[0], nc = c + dir[1]; - if (nr >= 0 && nr < N && nc >= 0 && + if (nr >= 0 && nr < N && nc >= 0 && nc < N && grid[nr][nc] <= t) { dsu.Union(r * N + c, nr * N + nc); } @@ -1711,8 +1728,8 @@ func swimInWater(grid [][]int) int { positions = append(positions, [3]int{grid[r][c], r, c}) } } - sort.Slice(positions, func(i, j int) bool { - return positions[i][0] < positions[j][0] + sort.Slice(positions, func(i, j int) bool { + return positions[i][0] < positions[j][0] }) directions := [][2]int{{0, 1}, {1, 0}, {0, -1}, {-1, 0}} @@ -1866,5 +1883,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2 \log n)$ -* Space complexity: $O(n ^ 2)$ \ No newline at end of file +- Time complexity: $O(n ^ 2 \log n)$ +- Space complexity: $O(n ^ 2)$ diff --git a/articles/symmetric-tree.md b/articles/symmetric-tree.md index 615d4dd34..dc721b31a 100644 --- a/articles/symmetric-tree.md +++ b/articles/symmetric-tree.md @@ -52,8 +52,8 @@ public class Solution { if (left == null || right == null) { return false; } - return left.val == right.val && - dfs(left.left, right.right) && + return left.val == right.val && + dfs(left.left, right.right) && dfs(left.right, right.left); } } @@ -85,8 +85,8 @@ private: if (!left || !right) { return false; } - return (left->val == right->val) && - dfs(left->left, right->right) && + return (left->val == right->val) && + dfs(left->left, right->right) && dfs(left->right, right->left); } }; @@ -131,8 +131,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -284,8 +284,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -315,7 +315,7 @@ class Solution: return False queue.append((left.left, right.right)) queue.append((left.right, right.left)) - + return True ``` @@ -382,7 +382,7 @@ public: queue.push({root->left, root->right}); while (!queue.empty()) { - for (int i = queue.size(); i > 0; i--) { + for (int i = queue.size(); i > 0; i--) { auto [left, right] = queue.front(); queue.pop(); @@ -443,5 +443,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/target-sum.md b/articles/target-sum.md index 71c10c0c2..1f21f5185 100644 --- a/articles/target-sum.md +++ b/articles/target-sum.md @@ -5,14 +5,14 @@ ```python class Solution: def findTargetSumWays(self, nums: List[int], target: int) -> int: - + def backtrack(i, total): if i ==len(nums): return total == target - - return (backtrack(i + 1, total + nums[i]) + + + return (backtrack(i + 1, total + nums[i]) + backtrack(i + 1, total - nums[i])) - + return backtrack(0, 0) ``` @@ -26,7 +26,7 @@ public class Solution { if (i == nums.length) { return total == target ? 1 : 0; } - return backtrack(i + 1, total + nums[i], nums, target) + + return backtrack(i + 1, total + nums[i], nums, target) + backtrack(i + 1, total - nums[i], nums, target); } } @@ -38,12 +38,12 @@ public: int findTargetSumWays(vector& nums, int target) { return backtrack(0, 0, nums, target); } - + int backtrack(int i, int total, vector& nums, int target) { if (i == nums.size()) { return total == target; } - return backtrack(i + 1, total + nums[i], nums, target) + + return backtrack(i + 1, total + nums[i], nums, target) + backtrack(i + 1, total - nums[i], nums, target); } }; @@ -57,14 +57,15 @@ class Solution { * @return {number} */ findTargetSumWays(nums, target) { - const backtrack = (i, total) => { if (i === nums.length) { return total === target ? 1 : 0; } - return backtrack(i + 1, total + nums[i]) + - backtrack(i + 1, total - nums[i]); - } + return ( + backtrack(i + 1, total + nums[i]) + + backtrack(i + 1, total - nums[i]) + ); + }; return backtrack(0, 0); } @@ -81,7 +82,7 @@ public class Solution { if (i == nums.Length) { return total == target ? 1 : 0; } - return Backtrack(i + 1, total + nums[i], nums, target) + + return Backtrack(i + 1, total + nums[i], nums, target) + Backtrack(i + 1, total - nums[i], nums, target); } } @@ -99,7 +100,7 @@ func findTargetSumWays(nums []int, target int) int { } return backtrack(i+1, total+nums[i]) + backtrack(i+1, total-nums[i]) } - + return backtrack(0, 0) } ``` @@ -111,10 +112,10 @@ class Solution { if (i == nums.size) { return if (total == target) 1 else 0 } - return backtrack(i + 1, total + nums[i]) + + return backtrack(i + 1, total + nums[i]) + backtrack(i + 1, total - nums[i]) } - + return backtrack(0, 0) } } @@ -138,8 +139,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ --- @@ -158,7 +159,7 @@ class Solution: if (i, total) in dp: return dp[(i, total)] - dp[(i, total)] = (backtrack(i + 1, total + nums[i]) + + dp[(i, total)] = (backtrack(i + 1, total + nums[i]) + backtrack(i + 1, total - nums[i])) return dp[(i, total)] @@ -189,7 +190,7 @@ public class Solution { if (dp[i][total + totalSum] != Integer.MIN_VALUE) { return dp[i][total + totalSum]; } - dp[i][total + totalSum] = backtrack(i + 1, total + nums[i], nums, target) + + dp[i][total + totalSum] = backtrack(i + 1, total + nums[i], nums, target) + backtrack(i + 1, total - nums[i], nums, target); return dp[i][total + totalSum]; } @@ -207,7 +208,7 @@ public: dp = vector>(nums.size(), vector(2 * totalSum + 1, INT_MIN)); return backtrack(0, 0, nums, target); } - + int backtrack(int i, int total, vector& nums, int target) { if (i == nums.size()) { return total == target; @@ -215,7 +216,7 @@ public: if (dp[i][total + totalSum] != INT_MIN) { return dp[i][total + totalSum]; } - dp[i][total + totalSum] = backtrack(i + 1, total + nums[i], nums, target) + + dp[i][total + totalSum] = backtrack(i + 1, total + nums[i], nums, target) + backtrack(i + 1, total - nums[i], nums, target); return dp[i][total + totalSum]; } @@ -232,8 +233,9 @@ class Solution { findTargetSumWays(nums, target) { const NEG_INF = Number.MIN_SAFE_INTEGER; const totalSum = nums.reduce((a, b) => a + b, 0); - const dp = Array.from({ length: nums.length }, () => - Array(2 * totalSum + 1).fill(NEG_INF)); + const dp = Array.from({ length: nums.length }, () => + Array(2 * totalSum + 1).fill(NEG_INF), + ); const backtrack = (i, total) => { if (i === nums.length) { @@ -242,10 +244,11 @@ class Solution { if (dp[i][total + totalSum] !== NEG_INF) { return dp[i][total + totalSum]; } - dp[i][total + totalSum] = backtrack(i + 1, total + nums[i]) + - backtrack(i + 1, total - nums[i]); + dp[i][total + totalSum] = + backtrack(i + 1, total + nums[i]) + + backtrack(i + 1, total - nums[i]); return dp[i][total + totalSum]; - } + }; return backtrack(0, 0); } @@ -263,7 +266,7 @@ public class Solution { dp = new int[nums.Length, 2 * totalSum + 1]; for (int i = 0; i < nums.Length; i++) { for (int j = 0; j < 2 * totalSum + 1; j++) { - dp[i, j] = int.MinValue; + dp[i, j] = int.MinValue; } } return Backtrack(0, 0, nums, target); @@ -275,11 +278,11 @@ public class Solution { } if (dp[i, total + totalSum] != int.MinValue) { - return dp[i, total + totalSum]; + return dp[i, total + totalSum]; } - dp[i, total + totalSum] = Backtrack(i + 1, total + nums[i], nums, target) + - Backtrack(i + 1, total - nums[i], nums, target); + dp[i, total + totalSum] = Backtrack(i + 1, total + nums[i], nums, target) + + Backtrack(i + 1, total - nums[i], nums, target); return dp[i, total + totalSum]; } } @@ -313,7 +316,7 @@ func findTargetSumWays(nums []int, target int) int { return dp[i][total+totalSum] } - dp[i][total+totalSum] = (backtrack(i+1, total+nums[i]) + + dp[i][total+totalSum] = (backtrack(i+1, total+nums[i]) + backtrack(i+1, total-nums[i])) return dp[i][total+totalSum] } @@ -335,11 +338,11 @@ class Solution { if (dp[i][total + totalSum] != Int.MIN_VALUE) { return dp[i][total + totalSum] } - dp[i][total + totalSum] = backtrack(i + 1, total + nums[i]) + + dp[i][total + totalSum] = backtrack(i + 1, total + nums[i]) + backtrack(i + 1, total - nums[i]) return dp[i][total + totalSum] } - + return backtrack(0, 0) } } @@ -358,7 +361,7 @@ class Solution { if dp[i][total + totalSum] != Int.min { return dp[i][total + totalSum] } - dp[i][total + totalSum] = backtrack(i + 1, total + nums[i]) + + dp[i][total + totalSum] = backtrack(i + 1, total + nums[i]) + backtrack(i + 1, total - nums[i]) return dp[i][total + totalSum] } @@ -372,8 +375,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n * m)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n * m)$ > Where $n$ is the length of the array $nums$ and $m$ is the sum of all the elements in the array. @@ -412,9 +415,9 @@ public class Solution { for (Map.Entry entry : dp[i].entrySet()) { int total = entry.getKey(); int count = entry.getValue(); - dp[i + 1].put(total + nums[i], + dp[i + 1].put(total + nums[i], dp[i + 1].getOrDefault(total + nums[i], 0) + count); - dp[i + 1].put(total - nums[i], + dp[i + 1].put(total - nums[i], dp[i + 1].getOrDefault(total - nums[i], 0) + count); } } @@ -458,8 +461,10 @@ class Solution { for (let total in dp[i]) { total = Number(total); let count = dp[i][total]; - dp[i + 1][total + nums[i]] = (dp[i + 1][total + nums[i]] || 0) + count; - dp[i + 1][total - nums[i]] = (dp[i + 1][total - nums[i]] || 0) + count; + dp[i + 1][total + nums[i]] = + (dp[i + 1][total + nums[i]] || 0) + count; + dp[i + 1][total - nums[i]] = + (dp[i + 1][total - nums[i]] || 0) + count; } } return dp[n][target] || 0; @@ -506,7 +511,7 @@ func findTargetSumWays(nums []int, target int) int { dp[i] = make(map[int]int) } - dp[0][0] = 1 + dp[0][0] = 1 for i := 0; i < n; i++ { for total, count := range dp[i] { @@ -525,7 +530,7 @@ class Solution { val n = nums.size val dp = Array(n + 1) { mutableMapOf() } - dp[0][0] = 1 + dp[0][0] = 1 for (i in 0 until n) { for ((total, count) in dp[i]) { @@ -561,8 +566,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n * m)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n * m)$ > Where $n$ is the length of the array $nums$ and $m$ is the sum of all the elements in the array. @@ -584,7 +589,7 @@ class Solution: next_dp[total + num] += count next_dp[total - num] += count dp = next_dp - + return dp[target] ``` @@ -599,9 +604,9 @@ public class Solution { for (Map.Entry entry : dp.entrySet()) { int total = entry.getKey(); int count = entry.getValue(); - nextDp.put(total + num, + nextDp.put(total + num, nextDp.getOrDefault(total + num, 0) + count); - nextDp.put(total - num, + nextDp.put(total - num, nextDp.getOrDefault(total - num, 0) + count); } dp = nextDp; @@ -647,10 +652,8 @@ class Solution { for (let num of nums) { let nextDp = new Map(); for (let [total, count] of dp) { - nextDp.set((total + num), - (nextDp.get((total + num)) || 0) + count); - nextDp.set((total - num), - (nextDp.get((total - num)) || 0) + count); + nextDp.set(total + num, (nextDp.get(total + num) || 0) + count); + nextDp.set(total - num, (nextDp.get(total - num) || 0) + count); } dp = nextDp; } @@ -691,7 +694,7 @@ public class Solution { ```go func findTargetSumWays(nums []int, target int) int { dp := make(map[int]int) - dp[0] = 1 + dp[0] = 1 for _, num := range nums { nextDp := make(map[int]int) @@ -709,7 +712,7 @@ func findTargetSumWays(nums []int, target int) int { ```kotlin class Solution { fun findTargetSumWays(nums: IntArray, target: Int): Int { - val dp = mutableMapOf(0 to 1) + val dp = mutableMapOf(0 to 1) for (num in nums) { val nextDp = mutableMapOf() @@ -748,7 +751,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(m)$ -> Where $n$ is the length of the array $nums$ and $m$ is the sum of all the elements in the array. \ No newline at end of file +> Where $n$ is the length of the array $nums$ and $m$ is the sum of all the elements in the array. diff --git a/articles/task-scheduling.md b/articles/task-scheduling.md index 03e752212..6f4292428 100644 --- a/articles/task-scheduling.md +++ b/articles/task-scheduling.md @@ -8,7 +8,7 @@ class Solution: count = [0] * 26 for task in tasks: count[ord(task) - ord('A')] += 1 - + arr = [] for i in range(26): if count[i] > 0: @@ -22,7 +22,7 @@ class Solution: if all(processed[j] != arr[i][1] for j in range(max(0, time - n), time)): if maxi == -1 or arr[maxi][0] < arr[i][0]: maxi = i - + time += 1 cur = -1 if maxi != -1: @@ -41,7 +41,7 @@ public class Solution { for (char task : tasks) { count[task - 'A']++; } - + List arr = new ArrayList<>(); for (int i = 0; i < 26; i++) { if (count[i] > 0) { @@ -66,7 +66,7 @@ public class Solution { maxi = i; } } - + time++; int cur = -1; if (maxi != -1) { @@ -91,7 +91,7 @@ public: for (char task : tasks) { count[task - 'A']++; } - + vector> arr; for (int i = 0; i < 26; i++) { if (count[i] > 0) { @@ -116,7 +116,7 @@ public: maxi = i; } } - + time++; int cur = -1; if (maxi != -1) { @@ -145,7 +145,7 @@ class Solution { for (const task of tasks) { count[task.charCodeAt(0) - 'A'.charCodeAt(0)]++; } - + const arr = []; for (let i = 0; i < 26; i++) { if (count[i] > 0) { @@ -170,7 +170,7 @@ class Solution { maxi = i; } } - + time++; let cur = -1; if (maxi !== -1) { @@ -194,7 +194,7 @@ public class Solution { foreach (char task in tasks) { count[task - 'A']++; } - + List arr = new List(); for (int i = 0; i < 26; i++) { if (count[i] > 0) { @@ -219,7 +219,7 @@ public class Solution { maxi = i; } } - + time++; int cur = -1; if (maxi != -1) { @@ -378,8 +378,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(t * n)$ -* Space complexity: $O(t)$ +- Time complexity: $O(t * n)$ +- Space complexity: $O(t)$ > Where $t$ is the time to process given tasks and $n$ is the cooldown time. @@ -431,7 +431,7 @@ public class Solution { Queue q = new LinkedList<>(); while (!maxHeap.isEmpty() || !q.isEmpty()) { time++; - + if (maxHeap.isEmpty()) { time = q.peek()[1]; } else { @@ -445,7 +445,7 @@ public class Solution { maxHeap.add(q.poll()[0]); } } - + return time; } } @@ -459,19 +459,19 @@ public: for (char task : tasks) { count[task - 'A']++; } - + priority_queue maxHeap; for (int cnt : count) { if (cnt > 0) { maxHeap.push(cnt); } } - + int time = 0; queue> q; while (!maxHeap.empty() || !q.empty()) { time++; - + if (maxHeap.empty()) { time = q.front().second; } else { @@ -481,13 +481,13 @@ public: q.push({cnt, time + n}); } } - + if (!q.empty() && q.front().second == time) { maxHeap.push(q.front().first); q.pop(); } } - + return time; } }; @@ -512,15 +512,15 @@ class Solution { } let time = 0; - let q = new Queue(); + let q = new Queue(); while (maxHeap.size() > 0 || q.size() > 0) { time++; if (maxHeap.size() > 0) { - let cnt = maxHeap.pop() - 1; + let cnt = maxHeap.pop() - 1; if (cnt !== 0) { - q.push([cnt, time + n]); + q.push([cnt, time + n]); } } @@ -550,7 +550,7 @@ public class Solution { } int time = 0; - Queue queue = new Queue(); + Queue queue = new Queue(); while (maxHeap.Count > 0 || queue.Count > 0) { if (queue.Count > 0 && time >= queue.Peek()[1]) { int[] temp = queue.Dequeue(); @@ -575,20 +575,20 @@ func leastInterval(tasks []byte, n int) int { for _, task := range tasks { count[task]++ } - + maxHeap := priorityqueue.NewWith(func(a, b interface{}) int { return b.(int) - a.(int) }) for _, cnt := range count { maxHeap.Enqueue(cnt) } - + time := 0 q := make([][2]int, 0) - + for maxHeap.Size() > 0 || len(q) > 0 { time++ - + if maxHeap.Size() == 0 { time = q[0][1] } else { @@ -598,13 +598,13 @@ func leastInterval(tasks []byte, n int) int { q = append(q, [2]int{cnt.(int), time + n}) } } - + if len(q) > 0 && q[0][1] == time { maxHeap.Enqueue(q[0][0]) q = q[1:] } } - + return time } ``` @@ -685,8 +685,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m)$ -* Space complexity: $O(1)$ since we have at most $26$ different characters. +- Time complexity: $O(m)$ +- Space complexity: $O(1)$ since we have at most $26$ different characters. > Where $m$ is the number of tasks. @@ -702,7 +702,7 @@ class Solution: count = [0] * 26 for task in tasks: count[ord(task) - ord('A')] += 1 - + count.sort() maxf = count[25] idle = (maxf - 1) * n @@ -867,7 +867,7 @@ class Solution { for i in stride(from: 24, through: 0, by: -1) { idle -= min(maxf - 1, count[i]) } - + return max(0, idle) + tasks.count } } @@ -877,8 +877,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m)$ -* Space complexity: $O(1)$ since we have at most $26$ different characters. +- Time complexity: $O(m)$ +- Space complexity: $O(1)$ since we have at most $26$ different characters. > Where $m$ is the number of tasks. @@ -894,7 +894,7 @@ class Solution: count = [0] * 26 for task in tasks: count[ord(task) - ord('A')] += 1 - + maxf = max(count) maxCount = 0 for i in count: @@ -911,7 +911,7 @@ public class Solution { for (char task : tasks) { count[task - 'A']++; } - + int maxf = Arrays.stream(count).max().getAsInt(); int maxCount = 0; for (int i : count) { @@ -1075,7 +1075,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m)$ -* Space complexity: $O(1)$ since we have at most $26$ different characters. +- Time complexity: $O(m)$ +- Space complexity: $O(1)$ since we have at most $26$ different characters. -> Where $m$ is the number of tasks. \ No newline at end of file +> Where $m$ is the number of tasks. diff --git a/articles/text-justification.md b/articles/text-justification.md index fb48dcabe..6b20d676a 100644 --- a/articles/text-justification.md +++ b/articles/text-justification.md @@ -112,8 +112,8 @@ public: } // Handling last line - string last_line = accumulate(line.begin(), line.end(), string(), - [](string a, string b) { + string last_line = accumulate(line.begin(), line.end(), string(), + [](string a, string b) { return a.empty() ? b : a + " " + b; }); int trail_space = maxWidth - last_line.size(); @@ -134,7 +134,9 @@ class Solution { */ fullJustify(words, maxWidth) { let res = []; - let line = [], length = 0, i = 0; + let line = [], + length = 0, + i = 0; while (i < words.length) { if (length + words[i].length + line.length <= maxWidth) { @@ -145,26 +147,28 @@ class Solution { // Line complete let extra_space = maxWidth - length; let remainder = extra_space % Math.max(1, line.length - 1); - let space = Math.floor(extra_space / Math.max(1, line.length - 1)); + let space = Math.floor( + extra_space / Math.max(1, line.length - 1), + ); for (let j = 0; j < Math.max(1, line.length - 1); j++) { - line[j] += " ".repeat(space); + line[j] += ' '.repeat(space); if (remainder > 0) { - line[j] += " "; + line[j] += ' '; remainder--; } } - res.push(line.join("")); + res.push(line.join('')); line = []; length = 0; } } // Handling last line - let last_line = line.join(" "); + let last_line = line.join(' '); let trail_space = maxWidth - last_line.length; - res.push(last_line + " ".repeat(trail_space)); + res.push(last_line + ' '.repeat(trail_space)); return res; } @@ -175,7 +179,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n * m)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n * m)$ -> Where $n$ is the number of words and $m$ is the average length of the words. \ No newline at end of file +> Where $n$ is the number of words and $m$ is the average length of the words. diff --git a/articles/the-number-of-beautiful-subsets.md b/articles/the-number-of-beautiful-subsets.md index 1ed55b435..f23f58f89 100644 --- a/articles/the-number-of-beautiful-subsets.md +++ b/articles/the-number-of-beautiful-subsets.md @@ -109,8 +109,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ --- @@ -130,7 +130,7 @@ class Solution: return 1 if n in cache: return cache[n] - + skip = helper(n + k, g) include = (2**g[n] - 1) * helper(n + 2 * k, g) cache[n] = skip + include @@ -335,8 +335,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -420,7 +420,7 @@ class Solution { if (prev == null || prev + k != num) { dp.put(num, dp.getOrDefault(prev, 1) * (1 + (int) Math.pow(2, count) - 1)); } else { - dp.put(num, dp.get(prev) + + dp.put(num, dp.get(prev) + ((int) Math.pow(2, count) - 1) * dp.getOrDefault(prev - k, 1)); } prev = num; @@ -477,10 +477,10 @@ public: for (int num : keys) { int count = g[num]; if (prev == -1 || prev + k != num) { - dp[num] = dp.count(prev) ? dp[prev] * (1 + (1 << count) - 1) : + dp[num] = dp.count(prev) ? dp[prev] * (1 + (1 << count) - 1) : (1 + (1 << count) - 1); } else { - dp[num] = dp[prev] + ((1 << count) - 1) * + dp[num] = dp[prev] + ((1 << count) - 1) * (dp.count(prev - k) ? dp[prev - k] : 1); } prev = num; @@ -537,7 +537,11 @@ class Solution { if (prev === null || prev + k !== num) { dp.set(num, (dp.get(prev) || 1) * (1 + (2 ** count - 1))); } else { - dp.set(num, dp.get(prev) + (2 ** count - 1) * (dp.get(prev - k) || 1)); + dp.set( + num, + dp.get(prev) + + (2 ** count - 1) * (dp.get(prev - k) || 1), + ); } prev = num; } @@ -554,8 +558,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -705,7 +709,9 @@ class Solution { let res = 1; for (const g of groups.values()) { - let prev = 0, dp = 0, ndp = 1; + let prev = 0, + dp = 0, + ndp = 1; let sortedKeys = Array.from(g.keys()).sort((a, b) => a - b); for (const num of sortedKeys) { @@ -723,7 +729,7 @@ class Solution { prev = num; } - res *= (dp + ndp); + res *= dp + ndp; } return res - 1; @@ -735,5 +741,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ diff --git a/articles/three-integer-sum.md b/articles/three-integer-sum.md index 18b4b76b7..c3d13aa3e 100644 --- a/articles/three-integer-sum.md +++ b/articles/three-integer-sum.md @@ -74,7 +74,7 @@ class Solution { } } } - return Array.from(res).map(item => JSON.parse(item)); + return Array.from(res).map((item) => JSON.parse(item)); } } ``` @@ -150,7 +150,7 @@ class Solution { func threeSum(_ nums: [Int]) -> [[Int]] { var res = Set<[Int]>() let nums = nums.sorted() - + for i in 0.. Where $m$ is the number of triplets and $n$ is the length of the given array. @@ -194,7 +194,7 @@ class Solution: count[nums[i]] -= 1 if i and nums[i] == nums[i - 1]: continue - + for j in range(i + 1, len(nums)): count[nums[j]] -= 1 if j - 1 > i and nums[j] == nums[j - 1]: @@ -434,7 +434,7 @@ class Solution { if i > 0 && nums[i] == nums[i - 1] { continue } - + for j in (i + 1).. i + 1 && nums[j] == nums[j - 1] { @@ -459,8 +459,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -494,7 +494,7 @@ class Solution: r -= 1 while nums[l] == nums[l - 1] and l < r: l += 1 - + return res ``` @@ -744,9 +744,9 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: - * $O(1)$ or $O(n)$ extra space depending on the sorting algorithm. - * $O(m)$ space for the output list. +- Time complexity: $O(n ^ 2)$ +- Space complexity: + - $O(1)$ or $O(n)$ extra space depending on the sorting algorithm. + - $O(m)$ space for the output list. -> Where $m$ is the number of triplets and $n$ is the length of the given array. \ No newline at end of file +> Where $m$ is the number of triplets and $n$ is the length of the given array. diff --git a/articles/time-based-key-value-store.md b/articles/time-based-key-value-store.md index 8fc87e0e5..50f1951c7 100644 --- a/articles/time-based-key-value-store.md +++ b/articles/time-based-key-value-store.md @@ -116,7 +116,7 @@ class TimeMap { */ get(key, timestamp) { if (!this.keyStore.has(key)) { - return ""; + return ''; } let seen = 0; @@ -125,7 +125,7 @@ class TimeMap { seen = Math.max(seen, time); } } - return seen === 0 ? "" : this.keyStore.get(key).get(seen).at(-1); + return seen === 0 ? '' : this.keyStore.get(key).get(seen).at(-1); } } ``` @@ -187,14 +187,14 @@ func (this *TimeMap) Get(key string, timestamp int) string { if _, exists := this.keyStore[key]; !exists { return "" } - + seen := 0 for time := range this.keyStore[key] { if time <= timestamp { seen = max(seen, time) } } - + if seen == 0 { return "" } @@ -213,7 +213,7 @@ func max(a, b int) int { ```kotlin class TimeMap() { private val keyStore = HashMap>>() - + fun set(key: String, value: String, timestamp: Int) { if (!keyStore.containsKey(key)) { keyStore[key] = HashMap() @@ -223,19 +223,19 @@ class TimeMap() { } keyStore[key]!![timestamp]!!.add(value) } - + fun get(key: String, timestamp: Int): String { if (!keyStore.containsKey(key)) { return "" } - + var seen = 0 for (time in keyStore[key]!!.keys) { if (time <= timestamp) { seen = maxOf(seen, time) } } - + if (seen == 0) { return "" } @@ -282,8 +282,8 @@ class TimeMap { ### Time & Space Complexity -* Time complexity: $O(1)$ for $set()$ and $O(n)$ for $get()$. -* Space complexity: $O(m * n)$ +- Time complexity: $O(1)$ for $set()$ and $O(n)$ for $get()$. +- Space complexity: $O(m * n)$ > Where $n$ is the total number of unique timestamps associated with a key and $m$ is the total number of keys. @@ -306,10 +306,10 @@ class TimeMap: def get(self, key: str, timestamp: int) -> str: if key not in self.m: return "" - + timestamps = self.m[key] idx = timestamps.bisect_right(timestamp) - 1 - + if idx >= 0: closest_time = timestamps.iloc[idx] return timestamps[closest_time] @@ -420,7 +420,7 @@ public class TimeMap { var timestamps = m[key]; int left = 0; int right = timestamps.Count - 1; - + while (left <= right) { int mid = left + (right - left) / 2; if (timestamps.Keys[mid] == timestamp) { @@ -431,7 +431,7 @@ public class TimeMap { right = mid - 1; } } - + if (right >= 0) { return timestamps.Values[right]; } @@ -464,12 +464,12 @@ func (this *TimeMap) Get(key string, timestamp int) string { if _, exists := this.m[key]; !exists { return "" } - + pairs := this.m[key] idx := sort.Search(len(pairs), func(i int) bool { return pairs[i].timestamp > timestamp }) - + if idx == 0 { return "" } @@ -480,11 +480,11 @@ func (this *TimeMap) Get(key string, timestamp int) string { ```kotlin class TimeMap() { private val m = HashMap>() - + fun set(key: String, value: String, timestamp: Int) { m.computeIfAbsent(key) { TreeMap() }[timestamp] = value } - + fun get(key: String, timestamp: Int): String { if (!m.containsKey(key)) return "" return m[key]!!.floorEntry(timestamp)?.value ?: "" @@ -511,7 +511,7 @@ class TimeMap { guard let timestamps = m[key] else { return "" } - + var l = 0, r = timestamps.count - 1 var res = "" @@ -524,7 +524,7 @@ class TimeMap { r = mid - 1 } } - + return res } } @@ -534,8 +534,8 @@ class TimeMap { ### Time & Space Complexity -* Time complexity: $O(1)$ for $set()$ and $O(\log n)$ for $get()$. -* Space complexity: $O(m * n)$ +- Time complexity: $O(1)$ for $set()$ and $O(\log n)$ for $get()$. +- Space complexity: $O(m * n)$ > Where $n$ is the total number of values associated with a key and $m$ is the total number of keys. @@ -571,7 +571,7 @@ class TimeMap: ```java public class TimeMap { - + private Map>> keyStore; public TimeMap() { @@ -699,7 +699,7 @@ class TimeMap { ```csharp public class TimeMap { - + private Dictionary>> keyStore; public TimeMap() { @@ -761,10 +761,10 @@ func (this *TimeMap) Get(key string, timestamp int) string { if _, exists := this.m[key]; !exists { return "" } - + pairs := this.m[key] l, r := 0, len(pairs)-1 - + for l <= r { mid := (l + r) / 2 if pairs[mid].timestamp <= timestamp { @@ -783,20 +783,20 @@ func (this *TimeMap) Get(key string, timestamp int) string { ```kotlin class TimeMap() { private val keyStore = HashMap>>() - + fun set(key: String, value: String, timestamp: Int) { if (!keyStore.containsKey(key)) { keyStore[key] = mutableListOf() } keyStore[key]!!.add(Pair(value, timestamp)) } - + fun get(key: String, timestamp: Int): String { var res = "" val values = keyStore[key] ?: return res var l = 0 var r = values.size - 1 - + while (l <= r) { val m = (l + r) / 2 if (values[m].second <= timestamp) { @@ -830,7 +830,7 @@ class TimeMap { guard let values = keyStore[key] else { return "" } - + var res = "" var l = 0, r = values.count - 1 @@ -853,7 +853,7 @@ class TimeMap { ### Time & Space Complexity -* Time complexity: $O(1)$ for $set()$ and $O(\log n)$ for $get()$. -* Space complexity: $O(m * n)$ +- Time complexity: $O(1)$ for $set()$ and $O(\log n)$ for $get()$. +- Space complexity: $O(m * n)$ -> Where $n$ is the total number of values associated with a key and $m$ is the total number of keys. \ No newline at end of file +> Where $n$ is the total number of values associated with a key and $m$ is the total number of keys. diff --git a/articles/time-needed-to-buy-tickets.md b/articles/time-needed-to-buy-tickets.md index b7422f54c..3a46b0ed9 100644 --- a/articles/time-needed-to-buy-tickets.md +++ b/articles/time-needed-to-buy-tickets.md @@ -119,8 +119,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n)$ > Where $n$ is the size of the input array and $m$ is the maximum value in the input array. @@ -146,7 +146,7 @@ class Solution: idx = (idx + 1) % n while tickets[idx] == 0: idx = (idx + 1) % n - + return time ``` @@ -195,7 +195,7 @@ public: idx = (idx + 1) % n; } } - + return time; } }; @@ -236,8 +236,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(1)$ > Where $n$ is the size of the input array and $m$ is the maximum value in the input array. @@ -257,7 +257,7 @@ class Solution: res += min(tickets[i], tickets[k]) else: res += min(tickets[i], tickets[k] - 1) - + return res ``` @@ -325,5 +325,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/time-needed-to-inform-all-employees.md b/articles/time-needed-to-inform-all-employees.md index 7a80a7c02..b51e1ca7d 100644 --- a/articles/time-needed-to-inform-all-employees.md +++ b/articles/time-needed-to-inform-all-employees.md @@ -103,8 +103,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -118,16 +118,16 @@ class Solution: adj = defaultdict(list) for i in range(n): adj[manager[i]].append(i) - + q = deque([(headID, 0)]) # (id, time) res = 0 - + while q: node, time = q.popleft() res = max(res, time) for emp in adj[node]: q.append((emp, time + informTime[node])) - + return res ``` @@ -138,11 +138,11 @@ public class Solution { for (int i = 0; i < n; i++) { adj.computeIfAbsent(manager[i], k -> new ArrayList<>()).add(i); } - + Queue queue = new LinkedList<>(); queue.add(new int[]{headID, 0}); int res = 0; - + while (!queue.isEmpty()) { int[] curr = queue.poll(); int id = curr[0], time = curr[1]; @@ -151,7 +151,7 @@ public class Solution { queue.add(new int[]{emp, time + informTime[id]}); } } - + return res; } } @@ -222,8 +222,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -379,8 +379,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -396,7 +396,7 @@ class Solution: informTime[node] += dfs(manager[node]) manager[node] = -1 return informTime[node] - + res = 0 for node in range(n): res = max(res, dfs(node)) @@ -412,7 +412,7 @@ public class Solution { } return res; } - + private int dfs(int node, int[] manager, int[] informTime) { if (manager[node] != -1) { informTime[node] += dfs(manager[node], manager, informTime); @@ -434,7 +434,7 @@ public: } return informTime[node]; }; - + int res = 0; for (int node = 0; node < n; ++node) { res = max(res, dfs(node)); @@ -475,5 +475,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. diff --git a/articles/top-k-elements-in-list.md b/articles/top-k-elements-in-list.md index 7bca2df74..c41763d75 100644 --- a/articles/top-k-elements-in-list.md +++ b/articles/top-k-elements-in-list.md @@ -80,10 +80,13 @@ class Solution { count[num] = (count[num] || 0) + 1; } - const arr = Object.entries(count).map(([num, freq]) => [freq, parseInt(num)]); + const arr = Object.entries(count).map(([num, freq]) => [ + freq, + parseInt(num), + ]); arr.sort((a, b) => b[0] - a[0]); - return arr.slice(0, k).map(pair => pair[1]); + return arr.slice(0, k).map((pair) => pair[1]); } } ``` @@ -184,8 +187,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -277,18 +280,18 @@ class Solution { count[num] = (count[num] || 0) + 1; } - const heap = new MinPriorityQueue(x => x[1]); - for(const [num, cnt] of Object.entries(count)){ + const heap = new MinPriorityQueue((x) => x[1]); + for (const [num, cnt] of Object.entries(count)) { heap.enqueue([num, cnt]); if (heap.size() > k) heap.dequeue(); } const res = []; - for(let i = 0; i < k; i++) { + for (let i = 0; i < k; i++) { const [num, cnt] = heap.dequeue(); - res.push(num) + res.push(num); } - return res; + return res; } } ``` @@ -312,7 +315,7 @@ public class Solution { heap.Dequeue(); } } - + var res = new int[k]; for (int i = 0; i < k; i++) { res[i] = heap.Dequeue(); @@ -332,7 +335,7 @@ func topKFrequent(nums []int, k int) []int { heap := priorityqueue.NewWith(func(a, b interface{}) int { freqA := a.([2]int)[0] freqB := b.([2]int)[0] - return utils.IntComparator(freqA, freqB) + return utils.IntComparator(freqA, freqB) }) for num, freq := range count { @@ -344,7 +347,7 @@ func topKFrequent(nums []int, k int) []int { res := make([]int, k) for i := k - 1; i >= 0; i-- { - value, _ := heap.Dequeue() + value, _ := heap.Dequeue() res[i] = value.([2]int)[1] } return res @@ -393,7 +396,7 @@ class Solution { count[num, default: 0] += 1 } - var heap: Heap = [] + var heap: Heap = [] for (num, freq) in count { heap.insert(NumFreq(num: num, freq: freq)) if heap.count > k { @@ -415,8 +418,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log k)$ -* Space complexity: $O(n + k)$ +- Time complexity: $O(n \log k)$ +- Space complexity: $O(n + k)$ > Where $n$ is the length of the array and $k$ is the number of top frequent elements. @@ -436,7 +439,7 @@ class Solution: count[num] = 1 + count.get(num, 0) for num, cnt in count.items(): freq[cnt].append(num) - + res = [] for i in range(len(freq) - 1, 0, -1): for num in freq[i]: @@ -628,15 +631,15 @@ class Solution { func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] { var count = [Int: Int]() var freq = [[Int]](repeating: [], count: nums.count + 1) - + for num in nums { count[num, default: 0] += 1 } - + for (num, cnt) in count { freq[cnt].append(num) } - + var res = [Int]() for i in stride(from: freq.count - 1, through: 1, by: -1) { for num in freq[i] { @@ -646,7 +649,7 @@ class Solution { } } } - + return res } } @@ -656,5 +659,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/transpose-matrix.md b/articles/transpose-matrix.md index e7efd17d4..ded06389b 100644 --- a/articles/transpose-matrix.md +++ b/articles/transpose-matrix.md @@ -57,7 +57,8 @@ class Solution { * @return {number[][]} */ transpose(matrix) { - const ROWS = matrix.length, COLS = matrix[0].length; + const ROWS = matrix.length, + COLS = matrix[0].length; const res = Array.from({ length: COLS }, () => Array(ROWS).fill(0)); for (let r = 0; r < ROWS; r++) { @@ -97,8 +98,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n * m)$ for the output array. +- Time complexity: $O(n * m)$ +- Space complexity: $O(n * m)$ for the output array. > Where $n$ is the number of rows and $m$ is the number of columns in the matrix. @@ -117,7 +118,7 @@ class Solution: for r in range(ROWS): for c in range(r): matrix[r][c], matrix[c][r] = matrix[c][r], matrix[r][c] - + return matrix res = [[0] * ROWS for _ in range(COLS)] @@ -133,7 +134,7 @@ class Solution: public class Solution { public int[][] transpose(int[][] matrix) { int ROWS = matrix.length, COLS = matrix[0].length; - + if (ROWS == COLS) { for (int r = 0; r < ROWS; r++) { for (int c = 0; c < r; c++) { @@ -164,14 +165,14 @@ class Solution { public: vector> transpose(vector>& matrix) { int ROWS = matrix.size(), COLS = matrix[0].size(); - + if (ROWS == COLS) { for (int r = 0; r < ROWS; r++) { for (int c = 0; c < r; c++) { swap(matrix[r][c], matrix[c][r]); } } - + return matrix; } @@ -195,18 +196,19 @@ class Solution { * @return {number[][]} */ transpose(matrix) { - const ROWS = matrix.length, COLS = matrix[0].length; + const ROWS = matrix.length, + COLS = matrix[0].length; if (ROWS === COLS) { - for (let r = 0; r < ROWS; r++) { - for (let c = 0; c < r; c++) { - [matrix[r][c], matrix[c][r]] = [matrix[c][r], matrix[r][c]]; - } + for (let r = 0; r < ROWS; r++) { + for (let c = 0; c < r; c++) { + [matrix[r][c], matrix[c][r]] = [matrix[c][r], matrix[r][c]]; } - - return matrix; } + return matrix; + } + const res = Array.from({ length: COLS }, () => Array(ROWS).fill(0)); for (let r = 0; r < ROWS; r++) { @@ -257,7 +259,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n * m)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n * m)$ -> Where $n$ is the number of rows and $m$ is the number of columns in the matrix. \ No newline at end of file +> Where $n$ is the number of rows and $m$ is the number of columns in the matrix. diff --git a/articles/trapping-rain-water.md b/articles/trapping-rain-water.md index 4e8f600b8..175aa3dbb 100644 --- a/articles/trapping-rain-water.md +++ b/articles/trapping-rain-water.md @@ -17,7 +17,7 @@ class Solution: leftMax = max(leftMax, height[j]) for j in range(i + 1, n): rightMax = max(rightMax, height[j]) - + res += min(leftMax, rightMax) - height[i] return res ``` @@ -228,8 +228,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -243,22 +243,22 @@ class Solution: n = len(height) if n == 0: return 0 - + leftMax = [0] * n rightMax = [0] * n - + leftMax[0] = height[0] for i in range(1, n): leftMax[i] = max(leftMax[i - 1], height[i]) - + rightMax[n - 1] = height[n - 1] for i in range(n - 2, -1, -1): rightMax[i] = max(rightMax[i + 1], height[i]) - + res = 0 for i in range(n): res += min(leftMax[i], rightMax[i]) - height[i] - return res + return res ``` ```java @@ -490,8 +490,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -526,7 +526,7 @@ public class Solution { if (height.length == 0) { return 0; } - + Stack stack = new Stack<>(); int res = 0; @@ -594,7 +594,10 @@ class Solution { let res = 0; for (let i = 0; i < height.length; i++) { - while (stack.length > 0 && height[i] >= height[stack[stack.length - 1]]) { + while ( + stack.length > 0 && + height[i] >= height[stack[stack.length - 1]] + ) { const mid = height[stack.pop()]; if (stack.length > 0) { const right = height[i]; @@ -650,12 +653,12 @@ func trap(height []int) int { for i := 0; i < len(height); i++ { for !stack.Empty() { - topIndex, _ := stack.Peek() + topIndex, _ := stack.Peek() if height[i] >= height[topIndex.(int)] { - midIndex, _ := stack.Pop() - mid := height[midIndex.(int)] + midIndex, _ := stack.Pop() + mid := height[midIndex.(int)] if !stack.Empty() { - topIndex, _ := stack.Peek() + topIndex, _ := stack.Peek() right := height[i] left := height[topIndex.(int)] h := min(right, left) - mid @@ -663,7 +666,7 @@ func trap(height []int) int { res += h * w } } else { - break + break } } stack.Push(i) @@ -736,8 +739,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -763,7 +766,7 @@ class Solution: r -= 1 rightMax = max(rightMax, height[r]) res += rightMax - height[r] - return res + return res ``` ```java @@ -967,5 +970,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/triangle.md b/articles/triangle.md index 53b994a33..19505370f 100644 --- a/articles/triangle.md +++ b/articles/triangle.md @@ -9,7 +9,7 @@ class Solution: if row >= len(triangle): return 0 return triangle[row][col] + min(dfs(row + 1, col), dfs(row + 1, col + 1)) - + return dfs(0, 0) ``` @@ -56,9 +56,12 @@ class Solution { if (row >= triangle.length) { return 0; } - return triangle[row][col] + Math.min(dfs(row + 1, col), dfs(row + 1, col + 1)); + return ( + triangle[row][col] + + Math.min(dfs(row + 1, col), dfs(row + 1, col + 1)) + ); }; - + return dfs(0, 0); } } @@ -68,8 +71,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -94,7 +97,7 @@ class Solution: memo[row][col] = triangle[row][col] + min(dfs(row + 1, col), dfs(row + 1, col + 1)) return memo[row][col] - + return dfs(0, 0) ``` @@ -160,7 +163,9 @@ class Solution { * @return {number} */ minimumTotal(triangle) { - const memo = Array.from({ length: triangle.length }, (_, r) => Array(triangle[r].length).fill(Infinity)); + const memo = Array.from({ length: triangle.length }, (_, r) => + Array(triangle[r].length).fill(Infinity), + ); const dfs = (row, col) => { if (row >= triangle.length) { @@ -170,7 +175,9 @@ class Solution { return memo[row][col]; } - memo[row][col] = triangle[row][col] + Math.min(dfs(row + 1, col), dfs(row + 1, col + 1)); + memo[row][col] = + triangle[row][col] + + Math.min(dfs(row + 1, col), dfs(row + 1, col + 1)); return memo[row][col]; }; @@ -183,8 +190,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -198,7 +205,7 @@ class Solution: n = len(triangle) dp = [[0] * len(triangle[row]) for row in range(n)] dp[-1] = triangle[-1][:] - + for row in range(n - 2, -1, -1): for col in range(len(triangle[row])): dp[row][col] = triangle[row][col] + min(dp[row + 1][col], dp[row + 1][col + 1]) @@ -255,14 +262,18 @@ class Solution { */ minimumTotal(triangle) { const n = triangle.length; - const dp = Array.from({ length: n }, (_, i) => Array(triangle[i].length).fill(0)); + const dp = Array.from({ length: n }, (_, i) => + Array(triangle[i].length).fill(0), + ); for (let col = 0; col < triangle[n - 1].length; col++) { dp[n - 1][col] = triangle[n - 1][col]; } for (let row = n - 2; row >= 0; row--) { for (let col = 0; col < triangle[row].length; col++) { - dp[row][col] = triangle[row][col] + Math.min(dp[row + 1][col], dp[row + 1][col + 1]); + dp[row][col] = + triangle[row][col] + + Math.min(dp[row + 1][col], dp[row + 1][col + 1]); } } @@ -275,8 +286,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -363,7 +374,8 @@ class Solution { let nxtDp = new Array(row + 1).fill(0); nxtDp[0] = dp[0] + triangle[row][0]; for (let col = 1; col < row; col++) { - nxtDp[col] = triangle[row][col] + Math.min(dp[col], dp[col - 1]); + nxtDp[col] = + triangle[row][col] + Math.min(dp[col], dp[col - 1]); } nxtDp[row] = dp[row - 1] + triangle[row][row]; dp = nxtDp; @@ -378,8 +390,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ extra space. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ extra space. --- @@ -396,7 +408,7 @@ class Solution: for row in range(n - 2, -1, -1): for col in range(len(triangle[row])): dp[col] = triangle[row][col] + min(dp[col], dp[col + 1]) - + return dp[0] ``` @@ -408,13 +420,13 @@ public class Solution { for (int i = 0; i < n; i++) { dp[i] = triangle.get(n - 1).get(i); } - + for (int row = n - 2; row >= 0; row--) { for (int col = 0; col < triangle.get(row).size(); col++) { dp[col] = triangle.get(row).get(col) + Math.min(dp[col], dp[col + 1]); } } - + return dp[0]; } } @@ -432,7 +444,7 @@ public: dp[col] = triangle[row][col] + min(dp[col], dp[col + 1]); } } - + return dp[0]; } }; @@ -463,8 +475,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ extra space. +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ extra space. --- @@ -478,7 +490,7 @@ class Solution: for row in range(len(triangle) - 2, -1, -1): for col in range(len(triangle[row])): triangle[row][col] += min(triangle[row + 1][col], triangle[row + 1][col + 1]) - + return triangle[0][0] ``` @@ -487,7 +499,7 @@ public class Solution { public int minimumTotal(List> triangle) { for (int row = triangle.size() - 2; row >= 0; row--) { for (int col = 0; col < triangle.get(row).size(); col++) { - triangle.get(row).set(col, triangle.get(row).get(col) + + triangle.get(row).set(col, triangle.get(row).get(col) + Math.min(triangle.get(row + 1).get(col), triangle.get(row + 1).get(col + 1))); } } @@ -519,7 +531,10 @@ class Solution { minimumTotal(triangle) { for (let row = triangle.length - 2; row >= 0; row--) { for (let col = 0; col < triangle[row].length; col++) { - triangle[row][col] += Math.min(triangle[row + 1][col], triangle[row + 1][col + 1]); + triangle[row][col] += Math.min( + triangle[row + 1][col], + triangle[row + 1][col + 1], + ); } } return triangle[0][0]; @@ -531,5 +546,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/trim-a-binary-search-tree.md b/articles/trim-a-binary-search-tree.md index 6a7eb3f21..9edd9850d 100644 --- a/articles/trim-a-binary-search-tree.md +++ b/articles/trim-a-binary-search-tree.md @@ -126,8 +126,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -195,14 +195,14 @@ public class Solution { Stack stack = new Stack<>(); stack.push(root); - + while (!stack.isEmpty()) { TreeNode node = stack.pop(); if (node == null) continue; - + boolean leftOut = (node.left != null && node.left.val < low); boolean rightOut = (node.right != null && node.right.val > high); - + if (leftOut) node.left = node.left.right; if (rightOut) node.right = node.right.left; @@ -213,7 +213,7 @@ public class Solution { if (node.right != null) stack.push(node.right); } } - + return root; } } @@ -285,7 +285,7 @@ class Solution { */ trimBST(root, low, high) { while (root && (root.val < low || root.val > high)) { - root = (root.val < low) ? root.right : root.left; + root = root.val < low ? root.right : root.left; } const stack = [root]; @@ -317,8 +317,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -456,7 +456,7 @@ class Solution { */ trimBST(root, low, high) { while (root && (root.val < low || root.val > high)) { - root = (root.val < low) ? root.right : root.left; + root = root.val < low ? root.right : root.left; } let tmpRoot = root; @@ -484,5 +484,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/two-city-scheduling.md b/articles/two-city-scheduling.md index 61f80767c..dc8a3e6e9 100644 --- a/articles/two-city-scheduling.md +++ b/articles/two-city-scheduling.md @@ -96,7 +96,10 @@ class Solution { } if (bCount > 0) { - res = Math.min(res, costs[i][1] + dfs(i + 1, aCount, bCount - 1)); + res = Math.min( + res, + costs[i][1] + dfs(i + 1, aCount, bCount - 1), + ); } return res; @@ -111,8 +114,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ N)$ -* Space complexity: $O(N)$ for recursion stack. +- Time complexity: $O(2 ^ N)$ +- Space complexity: $O(N)$ for recursion stack. > Where $N$ is the size of the array $costs$. @@ -238,7 +241,10 @@ class Solution { res = costs[i][0] + dfs(i + 1, aCount - 1, bCount); } if (bCount > 0) { - res = Math.min(res, costs[i][1] + dfs(i + 1, aCount, bCount - 1)); + res = Math.min( + res, + costs[i][1] + dfs(i + 1, aCount, bCount - 1), + ); } dp[aCount][bCount] = res; @@ -254,8 +260,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ > Where $n$ is the half of the size of the array $costs$. @@ -356,10 +362,16 @@ class Solution { dp[aCount][bCount] = Infinity; if (aCount > 0) { - dp[aCount][bCount] = Math.min(dp[aCount][bCount], dp[aCount - 1][bCount] + costs[i - 1][0]); + dp[aCount][bCount] = Math.min( + dp[aCount][bCount], + dp[aCount - 1][bCount] + costs[i - 1][0], + ); } if (bCount > 0) { - dp[aCount][bCount] = Math.min(dp[aCount][bCount], dp[aCount][bCount - 1] + costs[i - 1][1]); + dp[aCount][bCount] = Math.min( + dp[aCount][bCount], + dp[aCount][bCount - 1] + costs[i - 1][1], + ); } } } @@ -373,8 +385,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ > Where $n$ is the half of the size of the array $costs$. @@ -482,7 +494,10 @@ class Solution { dp[bCount] = Math.min(dp[bCount], tmp + costs[i - 1][0]); } if (bCount > 0) { - dp[bCount] = Math.min(dp[bCount], dp[bCount - 1] + costs[i - 1][1]); + dp[bCount] = Math.min( + dp[bCount], + dp[bCount - 1] + costs[i - 1][1], + ); } } } @@ -496,8 +511,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ > Where $n$ is the half of the size of the array $costs$. @@ -606,8 +621,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -664,8 +679,9 @@ class Solution { * @return {number} */ twoCitySchedCost(costs) { - costs.sort((a, b) => (a[1] - a[0]) - (b[1] - b[0])); - let n = costs.length / 2, res = 0; + costs.sort((a, b) => a[1] - a[0] - (b[1] - b[0])); + let n = costs.length / 2, + res = 0; for (let i = 0; i < n; i++) { res += costs[i][1] + costs[i + n][0]; @@ -679,5 +695,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. diff --git a/articles/two-integer-sum-ii.md b/articles/two-integer-sum-ii.md index f63e71a60..95727fe90 100644 --- a/articles/two-integer-sum-ii.md +++ b/articles/two-integer-sum-ii.md @@ -125,8 +125,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -205,7 +205,8 @@ class Solution { */ twoSum(numbers, target) { for (let i = 0; i < numbers.length; i++) { - let l = i + 1, r = numbers.length - 1; + let l = i + 1, + r = numbers.length - 1; let tmp = target - numbers[i]; while (l <= r) { let mid = l + Math.floor((r - l) / 2); @@ -313,8 +314,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ --- @@ -456,8 +457,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -533,7 +534,8 @@ class Solution { * @return {number[]} */ twoSum(numbers, target) { - let l = 0, r = numbers.length - 1; + let l = 0, + r = numbers.length - 1; while (l < r) { const curSum = numbers[l] + numbers[r]; @@ -634,5 +636,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/two-integer-sum.md b/articles/two-integer-sum.md index 9fba0afdc..e02ab8d68 100644 --- a/articles/two-integer-sum.md +++ b/articles/two-integer-sum.md @@ -54,7 +54,7 @@ class Solution { for (let i = 0; i < nums.length; i++) { for (let j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] === target) { - return [i, j]; + return [i, j]; } } } @@ -69,11 +69,11 @@ public class Solution { for (int i = 0; i < nums.Length; i++) { for (int j = i + 1; j < nums.Length; j++) { if (nums[i] + nums[j] == target) { - return new int[]{i, j}; + return new int[]{i, j}; } } } - return new int[0]; + return new int[0]; } } ``` @@ -125,8 +125,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(1)$ --- @@ -140,13 +140,13 @@ class Solution: A = [] for i, num in enumerate(nums): A.append([num, i]) - + A.sort() i, j = 0, len(nums) - 1 while i < j: cur = A[i][0] + A[j][0] if cur == target: - return [min(A[i][1], A[j][1]), + return [min(A[i][1], A[j][1]), max(A[i][1], A[j][1])] elif cur < target: i += 1 @@ -170,7 +170,7 @@ public class Solution { while (i < j) { int cur = A[i][0] + A[j][0]; if (cur == target) { - return new int[]{Math.min(A[i][1], A[j][1]), + return new int[]{Math.min(A[i][1], A[j][1]), Math.max(A[i][1], A[j][1])}; } else if (cur < target) { i++; @@ -198,7 +198,7 @@ public: while (i < j) { int cur = A[i].first + A[j].first; if (cur == target) { - return {min(A[i].second, A[j].second), + return {min(A[i].second, A[j].second), max(A[i].second, A[j].second)}; } else if (cur < target) { i++; @@ -226,12 +226,12 @@ class Solution { A.sort((a, b) => a[0] - b[0]); - let i = 0, j = nums.length - 1; + let i = 0, + j = nums.length - 1; while (i < j) { let cur = A[i][0] + A[j][0]; if (cur === target) { - return [Math.min(A[i][1], A[j][1]), - Math.max(A[i][1], A[j][1])]; + return [Math.min(A[i][1], A[j][1]), Math.max(A[i][1], A[j][1])]; } else if (cur < target) { i++; } else { @@ -258,7 +258,7 @@ public class Solution { int cur = A[i][0] + A[j][0]; if (cur == target) { return new int[]{ - Math.Min(A[i][1], A[j][1]), + Math.Min(A[i][1], A[j][1]), Math.Max(A[i][1], A[j][1]) }; } else if (cur < target) { @@ -278,11 +278,11 @@ func twoSum(nums []int, target int) []int { for i, num := range nums { A[i] = [2]int{num, i} } - + sort.Slice(A, func(i, j int) bool { return A[i][0] < A[j][0] }) - + i, j := 0, len(nums)-1 for i < j { cur := A[i][0] + A[j][0] @@ -343,7 +343,7 @@ class Solution { while i < j { let cur = A[i].0 + A[j].0 if cur == target { - return [min(A[i].1, A[j].1), + return [min(A[i].1, A[j].1), max(A[i].1, A[j].1)] } else if cur < target { i += 1 @@ -360,8 +360,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -434,7 +434,7 @@ class Solution { * @return {number[]} */ twoSum(nums, target) { - const indices = {}; // val -> index + const indices = {}; // val -> index for (let i = 0; i < nums.length; i++) { indices[nums[i]] = i; @@ -456,7 +456,7 @@ class Solution { public class Solution { public int[] TwoSum(int[] nums, int target) { // val -> index - Dictionary indices = new Dictionary(); + Dictionary indices = new Dictionary(); for (int i = 0; i < nums.Length; i++) { indices[nums[i]] = i; @@ -537,8 +537,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -584,7 +584,7 @@ class Solution { public: vector twoSum(vector& nums, int target) { int n = nums.size(); - unordered_map prevMap; + unordered_map prevMap; for (int i = 0; i < n; i++) { int diff = target - nums[i]; @@ -693,5 +693,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/ugly-number.md b/articles/ugly-number.md index f2a68a2e5..f389b697d 100644 --- a/articles/ugly-number.md +++ b/articles/ugly-number.md @@ -7,11 +7,11 @@ class Solution: def isUgly(self, n: int) -> bool: if n <= 0: return False - + for p in [2, 3, 5]: while n % p == 0: n //= p - + return n == 1 ``` @@ -72,5 +72,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ diff --git a/articles/uncommon-words-from-two-sentences.md b/articles/uncommon-words-from-two-sentences.md index 67be56a4b..aedc12901 100644 --- a/articles/uncommon-words-from-two-sentences.md +++ b/articles/uncommon-words-from-two-sentences.md @@ -69,7 +69,7 @@ class Solution { * @return {string[]} */ uncommonFromSentences(s1, s2) { - const words = (s1 + " " + s2).split(" "); + const words = (s1 + ' ' + s2).split(' '); const count = new Map(); for (const w of words) { @@ -92,8 +92,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n + m)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(n + m)$ > Where $n$ and $m$ are the lengths of the strings $s1$ and $s2$, respectively. @@ -159,16 +159,14 @@ class Solution { * @return {string[]} */ uncommonFromSentences(s1, s2) { - const words = (s1 + " " + s2).split(" "); + const words = (s1 + ' ' + s2).split(' '); const count = new Map(); for (const w of words) { count.set(w, (count.get(w) || 0) + 1); } - return [...count.entries()] - .filter(([_, c]) => c === 1) - .map(([w]) => w); + return [...count.entries()].filter(([_, c]) => c === 1).map(([w]) => w); } } ``` @@ -177,7 +175,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(n + m)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(n + m)$ -> Where $n$ and $m$ are the lengths of the strings $s1$ and $s2$, respectively. \ No newline at end of file +> Where $n$ and $m$ are the lengths of the strings $s1$ and $s2$, respectively. diff --git a/articles/uncrossed-lines.md b/articles/uncrossed-lines.md index a08442f64..2410057a1 100644 --- a/articles/uncrossed-lines.md +++ b/articles/uncrossed-lines.md @@ -8,11 +8,11 @@ class Solution: def dfs(i, j): if i == len(nums1) or j == len(nums2): return 0 - + if nums1[i] == nums2[j]: return 1 + dfs(i + 1, j + 1) return max(dfs(i, j + 1), dfs(i + 1, j)) - + return dfs(0, 0) ``` @@ -40,13 +40,13 @@ class Solution { public: int dfs(vector& nums1, vector& nums2, int i, int j) { if (i == nums1.size() || j == nums2.size()) return 0; - + if (nums1[i] == nums2[j]) { return 1 + dfs(nums1, nums2, i + 1, j + 1); } return max(dfs(nums1, nums2, i, j + 1), dfs(nums1, nums2, i + 1, j)); } - + int maxUncrossedLines(vector& nums1, vector& nums2) { return dfs(nums1, nums2, 0, 0); } @@ -80,8 +80,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ {n + m})$ -* Space complexity: $O(n + m)$ for recursion stack. +- Time complexity: $O(2 ^ {n + m})$ +- Space complexity: $O(n + m)$ for recursion stack. > Where $n$ and $m$ are the sizes of the arrays $nums1$ and $nums2$ respectively. @@ -107,9 +107,9 @@ class Solution: dp[(i, j)] = 1 + dfs(i + 1, j + 1) else: dp[(i, j)] = max(dfs(i, j + 1), dfs(i + 1, j)) - + return dp[(i, j)] - + return dfs(0, 0) ``` @@ -185,7 +185,8 @@ class Solution { * @return {number} */ maxUncrossedLines(nums1, nums2) { - const n = nums1.length, m = nums2.length; + const n = nums1.length, + m = nums2.length; const dp = Array.from({ length: n }, () => Array(m).fill(-1)); const dfs = (i, j) => { @@ -215,8 +216,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n * m)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n * m)$ > Where $n$ and $m$ are the sizes of the arrays $nums1$ and $nums2$ respectively. @@ -238,7 +239,7 @@ class Solution: dp[i + 1][j + 1] = 1 + dp[i][j] else: dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j]) - + return dp[n][m] ``` @@ -293,7 +294,8 @@ class Solution { * @return {number} */ maxUncrossedLines(nums1, nums2) { - const n = nums1.length, m = nums2.length; + const n = nums1.length, + m = nums2.length; const dp = Array.from({ length: n + 1 }, () => Array(m + 1).fill(0)); for (let i = 0; i < n; i++) { @@ -315,8 +317,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n * m)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n * m)$ > Where $n$ and $m$ are the sizes of the arrays $nums1$ and $nums2$ respectively. @@ -419,8 +421,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(m)$ > Where $n$ and $m$ are the sizes of the arrays $nums1$ and $nums2$ respectively. @@ -524,7 +526,8 @@ class Solution { * @return {number} */ maxUncrossedLines(nums1, nums2) { - let n = nums1.length, m = nums2.length; + let n = nums1.length, + m = nums2.length; if (m > n) { [nums1, nums2] = [nums2, nums1]; [n, m] = [m, n]; @@ -554,7 +557,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(min(n, m))$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(min(n, m))$ -> Where $n$ and $m$ are the sizes of the arrays $nums1$ and $nums2$ respectively. \ No newline at end of file +> Where $n$ and $m$ are the sizes of the arrays $nums1$ and $nums2$ respectively. diff --git a/articles/unique-binary-search-trees-ii.md b/articles/unique-binary-search-trees-ii.md index 3c3a4ccee..2f73b472c 100644 --- a/articles/unique-binary-search-trees-ii.md +++ b/articles/unique-binary-search-trees-ii.md @@ -150,10 +150,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\frac {4 ^ n}{\sqrt {n}})$ -* Space complexity: - * $O(n)$ space for recursion stack. - * $O(\frac {4 ^ n}{\sqrt {n}})$ space for the output. +- Time complexity: $O(\frac {4 ^ n}{\sqrt {n}})$ +- Space complexity: + - $O(n)$ space for recursion stack. + - $O(\frac {4 ^ n}{\sqrt {n}})$ space for the output. --- @@ -314,11 +314,11 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\frac {4 ^ n}{\sqrt {n}})$ -* Space complexity: - * $O(n)$ space for recursion stack. - * $O(n ^ 2)$ extra space. - * $O(\frac {4 ^ n}{\sqrt {n}})$ space for the output. +- Time complexity: $O(\frac {4 ^ n}{\sqrt {n}})$ +- Space complexity: + - $O(n)$ space for recursion stack. + - $O(n ^ 2)$ extra space. + - $O(\frac {4 ^ n}{\sqrt {n}})$ space for the output. --- @@ -463,7 +463,9 @@ class Solution { for (let val = left; val <= right; val++) { for (let leftTree of dp[left][val - 1]) { for (let rightTree of dp[val + 1][right]) { - dp[left][right].push(new TreeNode(val, leftTree, rightTree)); + dp[left][right].push( + new TreeNode(val, leftTree, rightTree), + ); } } } @@ -478,10 +480,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\frac {4 ^ n}{\sqrt {n}})$ -* Space complexity: - * $O(n ^ 2)$ extra space. - * $O(\frac {4 ^ n}{\sqrt {n}})$ space for the output. +- Time complexity: $O(\frac {4 ^ n}{\sqrt {n}})$ +- Space complexity: + - $O(n ^ 2)$ extra space. + - $O(\frac {4 ^ n}{\sqrt {n}})$ space for the output. --- @@ -663,8 +665,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\frac {4 ^ n}{\sqrt {n}})$ -* Space complexity: - * $O(n)$ for the recursion stack. - * $O(n)$ extra space. - * $O(\frac {4 ^ n}{\sqrt {n}})$ space for the output. \ No newline at end of file +- Time complexity: $O(\frac {4 ^ n}{\sqrt {n}})$ +- Space complexity: + - $O(n)$ for the recursion stack. + - $O(n)$ extra space. + - $O(\frac {4 ^ n}{\sqrt {n}})$ space for the output. diff --git a/articles/unique-binary-search-trees.md b/articles/unique-binary-search-trees.md index 499868203..af8d05ed0 100644 --- a/articles/unique-binary-search-trees.md +++ b/articles/unique-binary-search-trees.md @@ -71,8 +71,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(3 ^ n)$ -* Space complexity: $O(n)$ for recursion stack. +- Time complexity: $O(3 ^ n)$ +- Space complexity: $O(n)$ for recursion stack. --- @@ -181,8 +181,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -277,8 +277,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -344,8 +344,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. --- @@ -407,5 +407,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/unique-email-addresses.md b/articles/unique-email-addresses.md index 41aead4ae..5a445cafb 100644 --- a/articles/unique-email-addresses.md +++ b/articles/unique-email-addresses.md @@ -19,12 +19,12 @@ class Solution: public class Solution { public int numUniqueEmails(String[] emails) { Set unique = new HashSet<>(); - + for (String e : emails) { String[] parts = e.split("@"); String local = parts[0]; String domain = parts[1]; - + local = local.split("\\+")[0]; local = local.replace(".", ""); unique.add(local + "@" + domain); @@ -39,13 +39,13 @@ class Solution { public: int numUniqueEmails(vector& emails) { unordered_set unique; - + for (string e : emails) { string local = e.substr(0, e.find('@')); local = local.substr(0, local.find('+')); erase(local, '.'); unique.insert(local + e.substr(e.find('@'))); - } + } return unique.size(); } }; @@ -59,7 +59,7 @@ class Solution { */ numUniqueEmails(emails) { const unique = new Set(); - + for (let e of emails) { let [local, domain] = e.split('@'); local = local.split('+')[0]; @@ -75,8 +75,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n)$ > Where $n$ is the number of strings in the array, and $m$ is the average length of these strings. @@ -97,7 +97,7 @@ class Solution: if e[i] != ".": local += e[i] i += 1 - + while e[i] != "@": i += 1 domain = e[i + 1:] @@ -109,7 +109,7 @@ class Solution: public class Solution { public int numUniqueEmails(String[] emails) { Set unique = new HashSet<>(); - + for (String e : emails) { int i = 0; StringBuilder local = new StringBuilder(); @@ -119,10 +119,10 @@ public class Solution { } i++; } - + while (i < e.length() && e.charAt(i) != '@') { i++; - } + } String domain = e.substring(i + 1); unique.add(local.toString() + "@" + domain); } @@ -136,7 +136,7 @@ class Solution { public: int numUniqueEmails(vector& emails) { unordered_set unique; - + for (string e : emails) { int i = 0; string local = ""; @@ -146,7 +146,7 @@ public: } i++; } - + while (i < e.length() && e[i] != '@') { i++; } @@ -166,16 +166,17 @@ class Solution { */ numUniqueEmails(emails) { const unique = new Set(); - + for (let e of emails) { - let i = 0, local = ""; + let i = 0, + local = ''; while (i < e.length && e[i] !== '@' && e[i] !== '+') { if (e[i] !== '.') { local += e[i]; } i++; } - + while (i < e.length && e[i] !== '@') { i++; } @@ -191,7 +192,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(n)$ -> Where $n$ is the number of strings in the array, and $m$ is the average length of these strings. \ No newline at end of file +> Where $n$ is the number of strings in the array, and $m$ is the average length of these strings. diff --git a/articles/unique-length-3-palindromic-subsequences.md b/articles/unique-length-3-palindromic-subsequences.md index 642af0a41..86dee8403 100644 --- a/articles/unique-length-3-palindromic-subsequences.md +++ b/articles/unique-length-3-palindromic-subsequences.md @@ -94,7 +94,7 @@ class Solution { rec(i + 1, cur + s[i]); }; - rec(0, ""); + rec(0, ''); return res.size; } } @@ -104,10 +104,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(2 ^ n)$ -* Space complexity: $O(n + m)$ +- Time complexity: $O(2 ^ n)$ +- Space complexity: $O(n + m)$ -> Where $n$ is the length of the string $s$ and $m$ is the number of unique three length pallindromic subsequences (26 * 26 = 676). +> Where $n$ is the length of the string $s$ and $m$ is the number of unique three length pallindromic subsequences (26 \* 26 = 676). --- @@ -198,10 +198,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 3)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n ^ 3)$ +- Space complexity: $O(m)$ -> Where $n$ is the length of the string $s$ and $m$ is the number of unique three length pallindromic subsequences (26 * 26 = 676). +> Where $n$ is the length of the string $s$ and $m$ is the number of unique three length pallindromic subsequences (26 \* 26 = 676). --- @@ -288,10 +288,12 @@ class Solution { let res = 0; for (let ends = 'a'.charCodeAt(0); ends <= 'z'.charCodeAt(0); ends++) { for (let mid = 'a'.charCodeAt(0); mid <= 'z'.charCodeAt(0); mid++) { - const seq = String.fromCharCode(ends) + - String.fromCharCode(mid) + - String.fromCharCode(ends); - let idx = 0, found = 0; + const seq = + String.fromCharCode(ends) + + String.fromCharCode(mid) + + String.fromCharCode(ends); + let idx = 0, + found = 0; for (const c of s) { if (seq[idx] === c) { idx++; @@ -313,10 +315,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n * m)$ +- Space complexity: $O(1)$ -> Where $n$ is the length of the string $s$ and $m$ is the number of unique three length pallindromic subsequences (26 * 26 = 676). +> Where $n$ is the length of the string $s$ and $m$ is the number of unique three length pallindromic subsequences (26 \* 26 = 676). --- @@ -330,18 +332,18 @@ class Solution: res = set() left = set() right = collections.Counter(s) - + for i in range(len(s)): right[s[i]] -= 1 if right[s[i]] == 0: right.pop(s[i]) - + for j in range(26): c = chr(ord('a') + j) if c in left and c in right: res.add((s[i], c)) left.add(s[i]) - + return len(res) ``` @@ -447,10 +449,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(26 * n)$ -* Space complexity: $O(m)$ +- Time complexity: $O(26 * n)$ +- Space complexity: $O(m)$ -> Where $n$ is the length of the string $s$ and $m$ is the number of unique three length pallindromic subsequences (26 * 26 = 676). +> Where $n$ is the length of the string $s$ and $m$ is the number of unique three length pallindromic subsequences (26 \* 26 = 676). --- @@ -586,10 +588,14 @@ class Solution { let res = 0; for (let ends = 0; ends < 26; ends++) { - if (firstIndex[ends] === -1 || firstIndex[ends] === lastIndex[ends]) { + if ( + firstIndex[ends] === -1 || + firstIndex[ends] === lastIndex[ends] + ) { continue; } - const l = firstIndex[ends], r = lastIndex[ends]; + const l = firstIndex[ends], + r = lastIndex[ends]; for (let mid = 0; mid < 26; mid++) { if (prefix[r][mid] - prefix[l + 1][mid] > 0) { res++; @@ -605,8 +611,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(26 * n)$ -* Space complexity: $O(26 * n)$ +- Time complexity: $O(26 * n)$ +- Space complexity: $O(26 * n)$ --- @@ -624,12 +630,12 @@ class Solution: l, r = s.find(c), s.rfind(c) if l == -1 or l == r: continue - + mids = set() for j in range(l + 1, r): mids.add(s[j]) res += len(mids) - + return res ``` @@ -648,7 +654,7 @@ public class Solution { } res += mids.size(); } - + return res; } } @@ -670,7 +676,7 @@ public: } res += mids.size(); } - + return res; } }; @@ -687,7 +693,8 @@ class Solution { for (let i = 0; i < 26; i++) { const c = String.fromCharCode('a'.charCodeAt(0) + i); - const l = s.indexOf(c), r = s.lastIndexOf(c); + const l = s.indexOf(c), + r = s.lastIndexOf(c); if (l === -1 || l === r) continue; const mids = new Set(); @@ -706,8 +713,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(26 * n)$ -* Space complexity: $O(1)$ since we have at most $26$ different characters. +- Time complexity: $O(26 * n)$ +- Space complexity: $O(1)$ since we have at most $26$ different characters. --- @@ -836,17 +843,21 @@ class Solution { let res = 0; for (let ends = 0; ends < 26; ends++) { - if (firstIndex[ends] === -1 || firstIndex[ends] === lastIndex[ends]) { + if ( + firstIndex[ends] === -1 || + firstIndex[ends] === lastIndex[ends] + ) { continue; } - const l = firstIndex[ends], r = lastIndex[ends]; + const l = firstIndex[ends], + r = lastIndex[ends]; let mask = 0; for (let i = l + 1; i < r; i++) { const c = s.charCodeAt(i) - 'a'.charCodeAt(0); if (mask & (1 << c)) { continue; } - mask |= (1 << c); + mask |= 1 << c; res++; } } @@ -859,5 +870,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(26 * n)$ -* Space complexity: $O(1)$ since we have at most $26$ different characters. \ No newline at end of file +- Time complexity: $O(26 * n)$ +- Space complexity: $O(1)$ since we have at most $26$ different characters. diff --git a/articles/unique-paths-ii.md b/articles/unique-paths-ii.md index a1e64ca4a..e4eee8a98 100644 --- a/articles/unique-paths-ii.md +++ b/articles/unique-paths-ii.md @@ -86,7 +86,8 @@ class Solution { * @return {number} */ uniquePathsWithObstacles(grid) { - const M = grid.length, N = grid[0].length; + const M = grid.length, + N = grid[0].length; const dp = Array.from({ length: M }, () => Array(N).fill(-1)); const dfs = (r, c) => { @@ -143,8 +144,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns. @@ -238,7 +239,8 @@ class Solution { * @return {number} */ uniquePathsWithObstacles(grid) { - const M = grid.length, N = grid[0].length; + const M = grid.length, + N = grid[0].length; if (grid[0][0] === 1 || grid[M - 1][N - 1] === 1) { return 0; } @@ -293,8 +295,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(m * n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(m * n)$ > Where $m$ is the number of rows and $n$ is the number of columns. @@ -317,7 +319,7 @@ class Solution: dp[c] = 0 else: dp[c] += dp[c + 1] - + return dp[0] ``` @@ -373,7 +375,8 @@ class Solution { * @return {number} */ uniquePathsWithObstacles(grid) { - const M = grid.length, N = grid[0].length; + const M = grid.length, + N = grid[0].length; const dp = new Array(N + 1).fill(0); dp[N - 1] = 1; @@ -418,8 +421,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(m * n)$ +- Space complexity: $O(n)$ > Where $m$ is the number of rows and $n$ is the number of columns. @@ -435,9 +438,9 @@ class Solution: M, N = len(grid), len(grid[0]) if grid[0][0] == 1 or grid[M - 1][N - 1] == 1: return 0 - + grid[M - 1][N - 1] = 1 - + for r in range(M - 1, -1, -1): for c in range(N - 1, -1, -1): if r == M - 1 and c == N - 1: @@ -449,7 +452,7 @@ class Solution: down = grid[r + 1][c] if r + 1 < M else 0 right = grid[r][c + 1] if c + 1 < N else 0 grid[r][c] = down + right - + return grid[0][0] ``` @@ -523,7 +526,8 @@ class Solution { * @return {number} */ uniquePathsWithObstacles(grid) { - const M = grid.length, N = grid[0].length; + const M = grid.length, + N = grid[0].length; if (grid[0][0] === 1 || grid[M - 1][N - 1] === 1) { return 0; } @@ -539,8 +543,8 @@ class Solution { if (grid[r][c] === 1) { grid[r][c] = 0; } else { - const down = (r + 1 < M) ? grid[r + 1][c] : 0; - const right = (c + 1 < N) ? grid[r][c + 1] : 0; + const down = r + 1 < M ? grid[r + 1][c] : 0; + const right = c + 1 < N ? grid[r][c + 1] : 0; grid[r][c] = down + right; } } @@ -586,7 +590,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m * n)$ -* Space complexity: $O(1)$ extra space. +- Time complexity: $O(m * n)$ +- Space complexity: $O(1)$ extra space. -> Where $m$ is the number of rows and $n$ is the number of columns. \ No newline at end of file +> Where $m$ is the number of rows and $n$ is the number of columns. diff --git a/articles/valid-binary-search-tree.md b/articles/valid-binary-search-tree.md index 3b076e3c7..8405b5be4 100644 --- a/articles/valid-binary-search-tree.md +++ b/articles/valid-binary-search-tree.md @@ -11,17 +11,17 @@ # self.right = right class Solution: - left_check = staticmethod(lambda val, limit: val < limit) - right_check = staticmethod(lambda val, limit: val > limit) + left_check = staticmethod(lambda val, limit: val < limit) + right_check = staticmethod(lambda val, limit: val > limit) def isValidBST(self, root: Optional[TreeNode]) -> bool: if not root: return True - + if (not self.isValid(root.left, root.val, self.left_check) or not self.isValid(root.right, root.val, self.right_check)): return False - + return self.isValidBST(root.left) and self.isValidBST(root.right) def isValid(self, root: Optional[TreeNode], limit: int, check) -> bool: @@ -52,11 +52,11 @@ class Solution: public class Solution { static boolean left_check(int val, int limit) { - return val < limit; + return val < limit; } static boolean right_check(int val, int limit) { - return val > limit; + return val > limit; } public boolean isValidBST(TreeNode root) { @@ -64,7 +64,7 @@ public class Solution { return true; } - if (!isValid(root.left, root.val, Solution::left_check) || + if (!isValid(root.left, root.val, Solution::left_check) || !isValid(root.right, root.val, Solution::right_check)) { return false; } @@ -79,10 +79,10 @@ public class Solution { if (!check.apply(root.val, limit)) { return false; } - return isValid(root.left, limit, check) && + return isValid(root.left, limit, check) && isValid(root.right, limit, check); } - + interface CheckFunction { boolean apply(int val, int limit); } @@ -117,7 +117,7 @@ public: return true; } - if (!isValid(root->left, root->val, left_check) || + if (!isValid(root->left, root->val, left_check) || !isValid(root->right, root->val, right_check)) { return false; } @@ -132,7 +132,7 @@ public: if (!check(root->val, limit)) { return false; } - return isValid(root->left, limit, check) && + return isValid(root->left, limit, check) && isValid(root->right, limit, check); } }; @@ -178,8 +178,10 @@ class Solution { return true; } - if (!this.isValid(root.left, root.val, this.left_check) || - !this.isValid(root.right, root.val, this.right_check)) { + if ( + !this.isValid(root.left, root.val, this.left_check) || + !this.isValid(root.right, root.val, this.right_check) + ) { return false; } @@ -199,8 +201,10 @@ class Solution { if (!check.call(this, root.val, limit)) { return false; } - return this.isValid(root.left, limit, check) && - this.isValid(root.right, limit, check); + return ( + this.isValid(root.left, limit, check) && + this.isValid(root.right, limit, check) + ); } } ``` @@ -222,11 +226,11 @@ class Solution { public class Solution { static bool LeftCheck(int val, int limit) { - return val < limit; + return val < limit; } static bool RightCheck(int val, int limit) { - return val > limit; + return val > limit; } public bool IsValidBST(TreeNode root) { @@ -234,7 +238,7 @@ public class Solution { return true; } - if (!IsValid(root.left, root.val, LeftCheck) || + if (!IsValid(root.left, root.val, LeftCheck) || !IsValid(root.right, root.val, RightCheck)) { return false; } @@ -249,7 +253,7 @@ public class Solution { if (!check(root.val, limit)) { return false; } - return IsValid(root.left, limit, check) && + return IsValid(root.left, limit, check) && IsValid(root.right, limit, check); } } @@ -335,7 +339,7 @@ class Solution { class Solution { func isValidBST(_ root: TreeNode?) -> Bool { guard let root = root else { return true } - if !isValid(root.left, root.val, { $0 < $1 }) || + if !isValid(root.left, root.val, { $0 < $1 }) || !isValid(root.right, root.val, { $0 > $1 }) { return false } @@ -358,8 +362,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -419,7 +423,7 @@ public class Solution { if (!(left < node.val && node.val < right)) { return false; } - return valid(node.left, left, node.val) && + return valid(node.left, left, node.val) && valid(node.right, node.val, right); } } @@ -490,8 +494,10 @@ class Solution { if (!(left < node.val && node.val < right)) { return false; } - return this.valid(node.left, left, node.val) && - this.valid(node.right, node.val, right); + return ( + this.valid(node.left, left, node.val) && + this.valid(node.right, node.val, right) + ); } } ``` @@ -546,12 +552,12 @@ func valid(node *TreeNode, left, right int64) bool { if node == nil { return true } - + val := int64(node.Val) if val <= left || val >= right { return false } - + return valid(node.Left, left, val) && valid(node.Right, val, right) } ``` @@ -571,18 +577,18 @@ class Solution { fun isValidBST(root: TreeNode?): Boolean { return valid(root, Long.MIN_VALUE, Long.MAX_VALUE) } - + private fun valid(node: TreeNode?, left: Long, right: Long): Boolean { if (node == null) { return true } - + val value = node.`val`.toLong() if (value <= left || value >= right) { return false } - - return valid(node.left, left, value) && + + return valid(node.left, left, value) && valid(node.right, value, right) } } @@ -623,8 +629,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -777,7 +783,7 @@ class Solution { while (queue.size() > 0) { const [node, left, right] = queue.pop(); - + if (!(left < node.val && node.val < right)) { return false; } @@ -856,18 +862,18 @@ func isValidBST(root *TreeNode) bool { if root == nil { return true } - + queue := []QueueItem{{root, math.MinInt64, math.MaxInt64}} - + for len(queue) > 0 { item := queue[0] queue = queue[1:] - + val := int64(item.node.Val) if val <= item.left || val >= item.right { return false } - + if item.node.Left != nil { queue = append(queue, QueueItem{item.node.Left, item.left, val}) } @@ -875,7 +881,7 @@ func isValidBST(root *TreeNode) bool { queue = append(queue, QueueItem{item.node.Right, val, item.right}) } } - + return true } ``` @@ -897,31 +903,31 @@ class Solution { val left: Long, val right: Long ) - + fun isValidBST(root: TreeNode?): Boolean { if (root == null) { return true } - + val queue = ArrayDeque() queue.addLast(QueueItem(root, Long.MIN_VALUE, Long.MAX_VALUE)) - + while (queue.isNotEmpty()) { val (node, left, right) = queue.removeFirst() - + val value = node.`val`.toLong() if (value <= left || value >= right) { return false } - - node.left?.let { + + node.left?.let { queue.addLast(QueueItem(it, left, value)) } node.right?.let { queue.addLast(QueueItem(it, value, right)) } } - + return true } } @@ -973,5 +979,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/valid-palindrome-ii.md b/articles/valid-palindrome-ii.md index 6b1fbf303..0fdce66b1 100644 --- a/articles/valid-palindrome-ii.md +++ b/articles/valid-palindrome-ii.md @@ -7,12 +7,12 @@ class Solution: def validPalindrome(self, s: str) -> bool: if s == s[::-1]: return True - + for i in range(len(s)): newS = s[:i] + s[i + 1:] if newS == newS[::-1]: return True - + return False ``` @@ -106,7 +106,8 @@ class Solution { * @return {boolean} */ isPalindrome(s) { - let left = 0, right = s.length - 1; + let left = 0, + right = s.length - 1; while (left < right) { if (s[left] !== s[right]) { return false; @@ -148,8 +149,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -179,7 +180,7 @@ public class Solution { while (l < r) { if (s.charAt(l) != s.charAt(r)) { - return isPalindrome(s.substring(0, l) + s.substring(l + 1)) || + return isPalindrome(s.substring(0, l) + s.substring(l + 1)) || isPalindrome(s.substring(0, r) + s.substring(r + 1)); } l++; @@ -211,7 +212,7 @@ public: while (l < r) { if (s[l] != s[r]) { - return isPalindrome(s.substr(0, l) + s.substr(l + 1)) || + return isPalindrome(s.substr(0, l) + s.substr(l + 1)) || isPalindrome(s.substr(0, r) + s.substr(r + 1)); } l++; @@ -243,12 +244,15 @@ class Solution { * @return {boolean} */ validPalindrome(s) { - let l = 0, r = s.length - 1; + let l = 0, + r = s.length - 1; while (l < r) { if (s[l] !== s[r]) { - return this.isPalindrome(s.slice(0, l) + s.slice(l + 1)) || - this.isPalindrome(s.slice(0, r) + s.slice(r + 1)); + return ( + this.isPalindrome(s.slice(0, l) + s.slice(l + 1)) || + this.isPalindrome(s.slice(0, r) + s.slice(r + 1)) + ); } l++; r--; @@ -262,7 +266,8 @@ class Solution { * @return {boolean} */ isPalindrome(s) { - let left = 0, right = s.length - 1; + let left = 0, + right = s.length - 1; while (left < right) { if (s[left] !== s[right]) { return false; @@ -309,8 +314,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -332,7 +337,7 @@ class Solution: l, r = 0, len(s) - 1 while l < r: if s[l] != s[r]: - return (is_palindrome(l + 1, r) or + return (is_palindrome(l + 1, r) or is_palindrome(l, r - 1)) l += 1 r -= 1 @@ -347,7 +352,7 @@ public class Solution { while (l < r) { if (s.charAt(l) != s.charAt(r)) { - return isPalindrome(s, l + 1, r) || + return isPalindrome(s, l + 1, r) || isPalindrome(s, l, r - 1); } l++; @@ -378,7 +383,7 @@ public: while (l < r) { if (s[l] != s[r]) { - return isPalindrome(s, l + 1, r) || + return isPalindrome(s, l + 1, r) || isPalindrome(s, l, r - 1); } l++; @@ -409,12 +414,15 @@ class Solution { * @return {boolean} */ validPalindrome(s) { - let l = 0, r = s.length - 1; + let l = 0, + r = s.length - 1; while (l < r) { if (s[l] !== s[r]) { - return this.isPalindrome(s, l + 1, r) || - this.isPalindrome(s, l, r - 1); + return ( + this.isPalindrome(s, l + 1, r) || + this.isPalindrome(s, l, r - 1) + ); } l++; r--; @@ -472,5 +480,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/valid-parenthesis-string.md b/articles/valid-parenthesis-string.md index c412ad605..dceb4b217 100644 --- a/articles/valid-parenthesis-string.md +++ b/articles/valid-parenthesis-string.md @@ -5,13 +5,13 @@ ```python class Solution: def checkValidString(self, s: str) -> bool: - + def dfs(i, open): if open < 0: return False if i == len(s): return open == 0 - + if s[i] == '(': return dfs(i + 1, open + 1) elif s[i] == ')': @@ -26,7 +26,7 @@ class Solution: ```java public class Solution { public boolean checkValidString(String s) { - + return dfs(0, 0, s); } @@ -88,9 +88,11 @@ class Solution { } else if (s[i] === ')') { return dfs(i + 1, open - 1); } else { - return dfs(i + 1, open) || - dfs(i + 1, open + 1) || - dfs(i + 1, open - 1); + return ( + dfs(i + 1, open) || + dfs(i + 1, open + 1) || + dfs(i + 1, open - 1) + ); } } @@ -138,8 +140,8 @@ func checkValidString(s string) bool { } else if s[i] == ')' { return dfs(i+1, open-1) } else { - return (dfs(i+1, open) || - dfs(i+1, open+1) || + return (dfs(i+1, open) || + dfs(i+1, open+1) || dfs(i+1, open-1)) } } @@ -158,7 +160,7 @@ class Solution { if (i == s.length) { return open == 0 } - + return when (s[i]) { '(' -> dfs(i + 1, open + 1) ')' -> dfs(i + 1, open - 1) @@ -200,8 +202,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(3 ^ n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(3 ^ n)$ +- Space complexity: $O(n)$ --- @@ -222,16 +224,16 @@ class Solution: return open == 0 if memo[i][open] is not None: return memo[i][open] - + if s[i] == '(': result = dfs(i + 1, open + 1) elif s[i] == ')': result = dfs(i + 1, open - 1) else: - result = (dfs(i + 1, open) or - dfs(i + 1, open + 1) or + result = (dfs(i + 1, open) or + dfs(i + 1, open + 1) or dfs(i + 1, open - 1)) - + memo[i][open] = result return result @@ -258,11 +260,11 @@ public class Solution { } else if (s.charAt(i) == ')') { result = dfs(i + 1, open - 1, s, memo); } else { - result = (dfs(i + 1, open, s, memo) || - dfs(i + 1, open + 1, s, memo) || + result = (dfs(i + 1, open, s, memo) || + dfs(i + 1, open + 1, s, memo) || dfs(i + 1, open - 1, s, memo)); } - + memo[i][open] = result; return result; } @@ -293,11 +295,11 @@ private: } else if (s[i] == ')') { result = dfs(i + 1, open - 1, s); } else { - result = (dfs(i + 1, open, s) || - dfs(i + 1, open + 1, s) || + result = (dfs(i + 1, open, s) || + dfs(i + 1, open + 1, s) || dfs(i + 1, open - 1, s)); } - + memo[i][open] = result ? 1 : 0; return result; } @@ -312,8 +314,9 @@ class Solution { */ checkValidString(s) { const n = s.length; - const memo = Array.from({ length: n + 1 }, () => - Array(n + 1).fill(null)); + const memo = Array.from({ length: n + 1 }, () => + Array(n + 1).fill(null), + ); function dfs(i, open) { if (open < 0) return false; @@ -327,11 +330,12 @@ class Solution { } else if (s[i] === ')') { result = dfs(i + 1, open - 1); } else { - result = dfs(i + 1, open) || - dfs(i + 1, open + 1) || - dfs(i + 1, open - 1); + result = + dfs(i + 1, open) || + dfs(i + 1, open + 1) || + dfs(i + 1, open - 1); } - + memo[i][open] = result; return result; } @@ -361,8 +365,8 @@ public class Solution { } else if (s[i] == ')') { result = Dfs(i + 1, open - 1, s, memo); } else { - result = Dfs(i + 1, open, s, memo) || - Dfs(i + 1, open + 1, s, memo) || + result = Dfs(i + 1, open, s, memo) || + Dfs(i + 1, open + 1, s, memo) || Dfs(i + 1, open - 1, s, memo); } @@ -400,8 +404,8 @@ func checkValidString(s string) bool { } else if s[i] == ')' { result = dfs(i+1, open-1) } else { - result = (dfs(i+1, open) || - dfs(i+1, open+1) || + result = (dfs(i+1, open) || + dfs(i+1, open+1) || dfs(i+1, open-1)) } @@ -428,8 +432,8 @@ class Solution { val result = when (s[i]) { '(' -> dfs(i + 1, open + 1) ')' -> dfs(i + 1, open - 1) - else -> (dfs(i + 1, open) || - dfs(i + 1, open + 1) || + else -> (dfs(i + 1, open) || + dfs(i + 1, open + 1) || dfs(i + 1, open - 1)) } @@ -487,8 +491,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -588,8 +592,9 @@ class Solution { */ checkValidString(s) { const n = s.length; - const dp = Array.from({ length: n + 1 }, () => - Array(n + 1).fill(false)); + const dp = Array.from({ length: n + 1 }, () => + Array(n + 1).fill(false), + ); dp[n][0] = true; for (let i = n - 1; i >= 0; i--) { @@ -744,8 +749,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -764,8 +769,8 @@ class Solution: new_dp = [False] * (n + 1) for open in range(n): if s[i] == '*': - new_dp[open] = (dp[open + 1] or - (open > 0 and dp[open - 1]) or + new_dp[open] = (dp[open + 1] or + (open > 0 and dp[open - 1]) or dp[open]) elif s[i] == '(': new_dp[open] = dp[open + 1] @@ -787,7 +792,7 @@ public class Solution { boolean[] newDp = new boolean[n + 1]; for (int open = 0; open < n; open++) { if (s.charAt(i) == '*') { - newDp[open] = dp[open + 1] || + newDp[open] = dp[open + 1] || (open > 0 && dp[open - 1]) || dp[open]; } else if (s.charAt(i) == '(') { newDp[open] = dp[open + 1]; @@ -814,7 +819,7 @@ public: vector newDp(n + 1, false); for (int open = 0; open < n; ++open) { if (s[i] == '*') { - newDp[open] = dp[open + 1] || + newDp[open] = dp[open + 1] || (open > 0 && dp[open - 1]) || dp[open]; } else if (s[i] == '(') { newDp[open] = dp[open + 1]; @@ -844,8 +849,8 @@ class Solution { const newDp = Array(n + 1).fill(false); for (let open = 0; open < n; open++) { if (s[i] === '*') { - newDp[open] = dp[open + 1] || - (open > 0 && dp[open - 1]) || dp[open]; + newDp[open] = + dp[open + 1] || (open > 0 && dp[open - 1]) || dp[open]; } else if (s[i] === '(') { newDp[open] = dp[open + 1]; } else if (open > 0) { @@ -870,7 +875,7 @@ public class Solution { bool[] newDp = new bool[n + 1]; for (int open = 0; open < n; open++) { if (s[i] == '*') { - newDp[open] = dp[open + 1] || + newDp[open] = dp[open + 1] || (open > 0 && dp[open - 1]) || dp[open]; } else if (s[i] == '(') { newDp[open] = dp[open + 1]; @@ -895,8 +900,8 @@ func checkValidString(s string) bool { newDp := make([]bool, n+1) for open := 0; open < n; open++ { if s[i] == '*' { - newDp[open] = (dp[open+1] || - (open > 0 && dp[open-1]) || + newDp[open] = (dp[open+1] || + (open > 0 && dp[open-1]) || dp[open]) } else if s[i] == '(' { newDp[open] = dp[open+1] @@ -921,8 +926,8 @@ class Solution { val newDp = BooleanArray(n + 1) for (open in 0 until n) { newDp[open] = when (s[i]) { - '*' -> (dp[open + 1] || - (open > 0 && dp[open - 1]) || + '*' -> (dp[open + 1] || + (open > 0 && dp[open - 1]) || dp[open]) '(' -> dp[open + 1] else -> open > 0 && dp[open - 1] @@ -967,8 +972,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -993,7 +998,7 @@ class Solution: left.pop() else: star.pop() - + while left and star: if left.pop() > star.pop(): return False @@ -1017,11 +1022,11 @@ public class Solution { left.pop(); } else{ star.pop(); - } + } } } while (!left.isEmpty() && !star.isEmpty()) { - if (left.pop() > star.pop()) + if (left.pop() > star.pop()) return false; } return left.isEmpty(); @@ -1048,7 +1053,7 @@ public: } } } - + while (!left.empty() && !star.empty()) { if (left.top() > star.top()) return false; left.pop(); @@ -1085,7 +1090,7 @@ class Solution { } } } - + while (left.length > 0 && star.length > 0) { if (left.pop() > star.pop()) return false; } @@ -1114,7 +1119,7 @@ public class Solution { } } } - + while (left.Count > 0 && star.Count > 0) { if (left.Pop() > star.Pop()) return false; } @@ -1224,8 +1229,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -1455,5 +1460,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/valid-perfect-square.md b/articles/valid-perfect-square.md index c5682c5d4..0304292a6 100644 --- a/articles/valid-perfect-square.md +++ b/articles/valid-perfect-square.md @@ -73,8 +73,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\sqrt {n})$ -* Space complexity: $O(1)$ +- Time complexity: $O(\sqrt {n})$ +- Space complexity: $O(1)$ --- @@ -125,8 +125,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ -* Space complexity: $O(1)$ +- Time complexity: $O(1)$ +- Space complexity: $O(1)$ --- @@ -204,7 +204,8 @@ class Solution { * @return {boolean} */ isPerfectSquare(num) { - let l = 1, r = num; + let l = 1, + r = num; while (l <= r) { let m = Math.floor(l + (r - l) / 2); @@ -227,8 +228,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ --- @@ -294,8 +295,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\sqrt {n})$ -* Space complexity: $O(1)$ +- Time complexity: $O(\sqrt {n})$ +- Space complexity: $O(1)$ --- @@ -357,8 +358,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(\log n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(\log n)$ +- Space complexity: $O(1)$ --- @@ -376,7 +377,7 @@ class Solution: if r > (num // r): r ^= mask mask >>= 1 - + return r * r == num ``` @@ -392,7 +393,7 @@ public class Solution { } mask >>= 1; } - + return r * r == num; } } @@ -411,7 +412,7 @@ public: } mask >>= 1; } - + return r * r == num; } }; @@ -424,7 +425,8 @@ class Solution { * @return {boolean} */ isPerfectSquare(num) { - let r = 0, mask = 1 << 15; + let r = 0, + mask = 1 << 15; while (mask > 0) { r |= mask; @@ -433,7 +435,7 @@ class Solution { } mask >>= 1; } - + return r * r === num; } } @@ -443,5 +445,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(1)$ since we iterate at most $15$ times. -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(1)$ since we iterate at most $15$ times. +- Space complexity: $O(1)$ diff --git a/articles/valid-sudoku.md b/articles/valid-sudoku.md index 74fb5deda..5a0a5b4e0 100644 --- a/articles/valid-sudoku.md +++ b/articles/valid-sudoku.md @@ -8,12 +8,12 @@ class Solution: for row in range(9): seen = set() for i in range(9): - if board[row][i] == ".": + if board[row][i] == ".": continue if board[row][i] in seen: return False seen.add(board[row][i]) - + for col in range(9): seen = set() for i in range(9): @@ -22,7 +22,7 @@ class Solution: if board[i][col] in seen: return False seen.add(board[i][col]) - + for square in range(9): seen = set() for i in range(3): @@ -48,7 +48,7 @@ public class Solution { seen.add(board[row][i]); } } - + for (int col = 0; col < 9; col++) { Set seen = new HashSet<>(); for (int i = 0; i < 9; i++) { @@ -57,7 +57,7 @@ public class Solution { seen.add(board[i][col]); } } - + for (int square = 0; square < 9; square++) { Set seen = new HashSet<>(); for (int i = 0; i < 3; i++) { @@ -70,7 +70,7 @@ public class Solution { } } } - + return true; } } @@ -88,7 +88,7 @@ public: seen.insert(board[row][i]); } } - + for (int col = 0; col < 9; col++) { unordered_set seen; for (int i = 0; i < 9; i++) { @@ -97,7 +97,7 @@ public: seen.insert(board[i][col]); } } - + for (int square = 0; square < 9; square++) { unordered_set seen; for (int i = 0; i < 3; i++) { @@ -110,7 +110,7 @@ public: } } } - + return true; } }; @@ -131,7 +131,7 @@ class Solution { seen.add(board[row][i]); } } - + for (let col = 0; col < 9; col++) { let seen = new Set(); for (let i = 0; i < 9; i++) { @@ -140,7 +140,7 @@ class Solution { seen.add(board[i][col]); } } - + for (let square = 0; square < 9; square++) { let seen = new Set(); for (let i = 0; i < 3; i++) { @@ -153,7 +153,7 @@ class Solution { } } } - + return true; } } @@ -170,7 +170,7 @@ public class Solution { seen.Add(board[row][i]); } } - + for (int col = 0; col < 9; col++) { HashSet seen = new HashSet(); for (int i = 0; i < 9; i++) { @@ -179,7 +179,7 @@ public class Solution { seen.Add(board[i][col]); } } - + for (int square = 0; square < 9; square++) { HashSet seen = new HashSet(); for (int i = 0; i < 3; i++) { @@ -192,7 +192,7 @@ public class Solution { } } } - + return true; } } @@ -317,7 +317,7 @@ class Solution { } } } - + return true } } @@ -327,8 +327,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -341,7 +341,7 @@ class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: cols = defaultdict(set) rows = defaultdict(set) - squares = defaultdict(set) + squares = defaultdict(set) for r in range(9): for c in range(9): @@ -398,7 +398,7 @@ public: for (int r = 0; r < 9; r++) { for (int c = 0; c < 9; c++) { if (board[r][c] == '.') continue; - + pair squareKey = {r / 3, c / 3}; if (rows[r].count(board[r][c]) || cols[c].count(board[r][c]) || squares[squareKey].count(board[r][c])) { @@ -432,9 +432,12 @@ class Solution { const squareKey = `${Math.floor(r / 3)},${Math.floor(c / 3)}`; - if ((rows.get(r) && rows.get(r).has(board[r][c])) || + if ( + (rows.get(r) && rows.get(r).has(board[r][c])) || (cols.get(c) && cols.get(c).has(board[r][c])) || - (squares.get(squareKey) && squares.get(squareKey).has(board[r][c]))) { + (squares.get(squareKey) && + squares.get(squareKey).has(board[r][c])) + ) { return false; } @@ -505,7 +508,7 @@ func isValidSudoku(board [][]byte) bool { val := board[r][c] squareIdx := (r/3)*3 + c/3 - if rows[r][val] || cols[c][val] || + if rows[r][val] || cols[c][val] || squares[squareIdx][val] { return false } @@ -533,7 +536,7 @@ class Solution { if (value == '.') continue val squareIdx = (r / 3) * 3 + (c / 3) - if (value in rows[r] || value in cols[c] || + if (value in rows[r] || value in cols[c] || value in squares[squareIdx]) { return false } @@ -573,7 +576,7 @@ class Solution { squares[squareKey, default: []].insert(board[r][c]) } } - + return true } } @@ -583,8 +586,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n ^ 2)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n ^ 2)$ --- @@ -603,7 +606,7 @@ class Solution: for c in range(9): if board[r][c] == ".": continue - + val = int(board[r][c]) - 1 if (1 << val) & rows[r]: return False @@ -611,7 +614,7 @@ class Solution: return False if (1 << val) & squares[(r // 3) * 3 + (c // 3)]: return False - + rows[r] |= (1 << val) cols[c] |= (1 << val) squares[(r // 3) * 3 + (c // 3)] |= (1 << val) @@ -632,7 +635,7 @@ public class Solution { int val = board[r][c] - '1'; - if ((rows[r] & (1 << val)) > 0 || (cols[c] & (1 << val)) > 0 || + if ((rows[r] & (1 << val)) > 0 || (cols[c] & (1 << val)) > 0 || (squares[(r / 3) * 3 + (c / 3)] & (1 << val)) > 0) { return false; } @@ -689,14 +692,18 @@ class Solution { let val = board[r][c] - '1'; - if ((rows[r] & (1 << val)) || (cols[c] & (1 << val)) || - (squares[Math.floor(r / 3) * 3 + Math.floor(c / 3)] & (1 << val))) { + if ( + rows[r] & (1 << val) || + cols[c] & (1 << val) || + squares[Math.floor(r / 3) * 3 + Math.floor(c / 3)] & + (1 << val) + ) { return false; } - rows[r] |= (1 << val); - cols[c] |= (1 << val); - squares[Math.floor(r / 3) * 3 + Math.floor(c / 3)] |= (1 << val); + rows[r] |= 1 << val; + cols[c] |= 1 << val; + squares[Math.floor(r / 3) * 3 + Math.floor(c / 3)] |= 1 << val; } } return true; @@ -717,7 +724,7 @@ public class Solution { int val = board[r][c] - '1'; - if ((rows[r] & (1 << val)) > 0 || (cols[c] & (1 << val)) > 0 || + if ((rows[r] & (1 << val)) > 0 || (cols[c] & (1 << val)) > 0 || (squares[(r / 3) * 3 + (c / 3)] & (1 << val)) > 0) { return false; } @@ -743,16 +750,16 @@ func isValidSudoku(board [][]byte) bool { if board[r][c] == '.' { continue } - + val := board[r][c] - '1' bit := 1 << val squareIdx := (r/3)*3 + c/3 - if rows[r]&bit != 0 || cols[c]&bit != 0 || + if rows[r]&bit != 0 || cols[c]&bit != 0 || squares[squareIdx]&bit != 0 { return false } - + rows[r] |= bit cols[c] |= bit squares[squareIdx] |= bit @@ -773,12 +780,12 @@ class Solution { for (r in 0 until 9) { for (c in 0 until 9) { if (board[r][c] == '.') continue - + val value = board[r][c] - '1' val bit = 1 shl value val squareIdx = (r / 3) * 3 + (c / 3) - if ((rows[r] and bit) != 0 || (cols[c] and bit) != 0 || + if ((rows[r] and bit) != 0 || (cols[c] and bit) != 0 || (squares[squareIdx] and bit) != 0) { return false } @@ -804,7 +811,7 @@ class Solution { for r in 0..<9 { for c in 0..<9 { if board[r][c] == "." { continue } - + let val = Int(board[r][c].asciiValue! - Character("0").asciiValue!) let bitmask = 1 << (val - 1) @@ -827,5 +834,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ diff --git a/articles/valid-tree.md b/articles/valid-tree.md index 7266d9836..198762e4d 100644 --- a/articles/valid-tree.md +++ b/articles/valid-tree.md @@ -7,17 +7,17 @@ class Solution: def validTree(self, n: int, edges: List[List[int]]) -> bool: if len(edges) > (n - 1): return False - + adj = [[] for _ in range(n)] for u, v in edges: adj[u].append(v) adj[v].append(u) - + visit = set() def dfs(node, par): if node in visit: return False - + visit.add(node) for nei in adj[node]: if nei == par: @@ -25,7 +25,7 @@ class Solution: if not dfs(nei, node): return False return True - + return dfs(0, -1) and len(visit) == n ``` @@ -50,16 +50,16 @@ public class Solution { if (!dfs(0, -1, visit, adj)) { return false; } - + return visit.size() == n; } - private boolean dfs(int node, int parent, Set visit, + private boolean dfs(int node, int parent, Set visit, List> adj) { if (visit.contains(node)) { return false; } - + visit.add(node); for (int nei : adj.get(node)) { if (nei == parent) { @@ -97,7 +97,7 @@ public: } private: - bool dfs(int node, int parent, unordered_set& visit, + bool dfs(int node, int parent, unordered_set& visit, vector>& adj) { if (visit.count(node)) { return false; @@ -183,7 +183,7 @@ public class Solution { return visit.Count == n; } - private bool Dfs(int node, int parent, HashSet visit, + private bool Dfs(int node, int parent, HashSet visit, List> adj) { if (visit.Contains(node)) { return false; @@ -208,7 +208,7 @@ func validTree(n int, edges [][]int) bool { if len(edges) > n-1 { return false } - + adj := make([][]int, n) for _, edge := range edges { u, v := edge[0], edge[1] @@ -242,15 +242,15 @@ func validTree(n int, edges [][]int) bool { class Solution { fun validTree(n: Int, edges: Array): Boolean { if (edges.size > n - 1) return false - + val adj = Array(n) { mutableListOf() } for ((u, v) in edges) { adj[u].add(v) adj[v].add(u) } - + val visit = HashSet() - + fun dfs(node: Int, parent: Int): Boolean { if (node in visit) return false visit.add(node) @@ -260,7 +260,7 @@ class Solution { } return true } - + return dfs(0, -1) && visit.size == n } } @@ -272,7 +272,7 @@ class Solution { if edges.count > (n - 1) { return false } - + var adj = Array(repeating: [Int](), count: n) for edge in edges { let u = edge[0] @@ -280,9 +280,9 @@ class Solution { adj[u].append(v) adj[v].append(u) } - + var visited = Set() - + func dfs(_ node: Int, _ parent: Int) -> Bool { if visited.contains(node) { return false @@ -298,7 +298,7 @@ class Solution { } return true } - + return dfs(0, -1) && visited.count == n } } @@ -308,8 +308,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ > Where $V$ is the number vertices and $E$ is the number of edges in the graph. @@ -324,16 +324,16 @@ class Solution: def validTree(self, n: int, edges: List[List[int]]) -> bool: if len(edges) > n - 1: return False - + adj = [[] for _ in range(n)] for u, v in edges: adj[u].append(v) adj[v].append(u) - + visit = set() q = deque([(0, -1)]) # (current node, parent node) visit.add(0) - + while q: node, parent = q.popleft() for nei in adj[node]: @@ -343,7 +343,7 @@ class Solution: return False visit.add(nei) q.append((nei, node)) - + return len(visit) == n ``` @@ -447,7 +447,7 @@ class Solution { } const visit = new Set(); - const q = new Queue([[0, -1]]); // [current node, parent node] + const q = new Queue([[0, -1]]); // [current node, parent node] visit.add(0); while (!q.isEmpty()) { @@ -581,7 +581,7 @@ class Solution { if edges.count > n - 1 { return false } - + var adj = [[Int]](repeating: [], count: n) for edge in edges { let u = edge[0] @@ -589,12 +589,12 @@ class Solution { adj[u].append(v) adj[v].append(u) } - + var visit = Set() var q = Deque<(Int, Int)>() // (current node, parent node) q.append((0, -1)) visit.insert(0) - + while !q.isEmpty { let (node, parent) = q.removeFirst() for nei in adj[node] { @@ -608,7 +608,7 @@ class Solution { q.append((nei, node)) } } - + return visit.count == n } } @@ -618,8 +618,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + E)$ -* Space complexity: $O(V + E)$ +- Time complexity: $O(V + E)$ +- Space complexity: $O(V + E)$ > Where $V$ is the number vertices and $E$ is the number of edges in the graph. @@ -653,7 +653,7 @@ class DSU: self.Size[pu] += self.Size[pv] self.Parent[pv] = pu return True - + def components(self): return self.comps @@ -661,7 +661,7 @@ class Solution: def validTree(self, n: int, edges: List[List[int]]) -> bool: if len(edges) > n - 1: return False - + dsu = DSU(n) for u, v in edges: if not dsu.union(u, v): @@ -1014,20 +1014,20 @@ class DSU { var comps: Int var parent: [Int] var size: [Int] - + init(_ n: Int) { comps = n parent = Array(0.. Int { if parent[node] != node { parent[node] = find(parent[node]) } return parent[node] } - + func union(_ u: Int, _ v: Int) -> Bool { let pu = find(u) let pv = find(v) @@ -1044,7 +1044,7 @@ class DSU { } return true } - + func components() -> Int { return comps } @@ -1055,7 +1055,7 @@ class Solution { if edges.count > n - 1 { return false } - + let dsu = DSU(n) for edge in edges { let u = edge[0], v = edge[1] @@ -1072,7 +1072,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(V + (E * α(V)))$ -* Space complexity: $O(V)$ +- Time complexity: $O(V + (E * α(V)))$ +- Space complexity: $O(V)$ -> Where $V$ is the number of vertices and $E$ is the number of edges in the graph. $α()$ is used for amortized complexity. \ No newline at end of file +> Where $V$ is the number of vertices and $E$ is the number of edges in the graph. $α()$ is used for amortized complexity. diff --git a/articles/valid-word-abbreviation.md b/articles/valid-word-abbreviation.md index 79c44a2e7..3b417b460 100644 --- a/articles/valid-word-abbreviation.md +++ b/articles/valid-word-abbreviation.md @@ -96,15 +96,18 @@ class Solution { * @return {boolean} */ validWordAbbreviation(word, abbr) { - let n = word.length, m = abbr.length; - let i = 0, j = 0; + let n = word.length, + m = abbr.length; + let i = 0, + j = 0; while (i < n && j < m) { if (abbr[j] === '0') return false; if (isNaN(abbr[j])) { if (word[i] === abbr[j]) { - i++; j++; + i++; + j++; } else { return false; } @@ -157,7 +160,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(1)$ -> Where $n$ and $m$ are the lengths of the strings $word$ and $abbr$, respectively. \ No newline at end of file +> Where $n$ and $m$ are the lengths of the strings $word$ and $abbr$, respectively. diff --git a/articles/validate-binary-tree-nodes.md b/articles/validate-binary-tree-nodes.md index fe797fbd4..52d6939e2 100644 --- a/articles/validate-binary-tree-nodes.md +++ b/articles/validate-binary-tree-nodes.md @@ -53,7 +53,7 @@ public class Solution { if (i == -1) return true; if (visit.contains(i)) return false; visit.add(i); - return dfs(leftChild[i], leftChild, rightChild) && + return dfs(leftChild[i], leftChild, rightChild) && dfs(rightChild[i], leftChild, rightChild); } } @@ -85,7 +85,7 @@ private: if (i == -1) return true; if (visit.count(i)) return false; visit.insert(i); - return dfs(leftChild[i], leftChild, rightChild) && + return dfs(leftChild[i], leftChild, rightChild) && dfs(rightChild[i], leftChild, rightChild); } }; @@ -100,7 +100,9 @@ class Solution { * @return {boolean} */ validateBinaryTreeNodes(n, leftChild, rightChild) { - let hasParent = new Set([...leftChild, ...rightChild].filter(c => c !== -1)); + let hasParent = new Set( + [...leftChild, ...rightChild].filter((c) => c !== -1), + ); if (hasParent.size === n) return false; let root = 0; @@ -128,8 +130,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -297,8 +299,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -456,8 +458,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -664,5 +666,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/validate-parentheses.md b/articles/validate-parentheses.md index a7e649a78..b900e101b 100644 --- a/articles/validate-parentheses.md +++ b/articles/validate-parentheses.md @@ -57,12 +57,12 @@ class Solution { * @return {boolean} */ isValid(s) { - while (s.includes("()") || s.includes("{}") || s.includes("[]")) { - s = s.replace("()", ""); - s = s.replace("{}", ""); - s = s.replace("[]", ""); + while (s.includes('()') || s.includes('{}') || s.includes('[]')) { + s = s.replace('()', ''); + s = s.replace('{}', ''); + s = s.replace('[]', ''); } - return s === ""; + return s === ''; } } ``` @@ -123,8 +123,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 2)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n ^ 2)$ +- Space complexity: $O(n)$ --- @@ -146,7 +146,7 @@ class Solution: return False else: stack.append(c) - + return True if not stack else False ``` @@ -213,12 +213,15 @@ class Solution { const closeToOpen = { ')': '(', ']': '[', - '}': '{' + '}': '{', }; for (let c of s) { if (closeToOpen[c]) { - if (stack.length > 0 && stack[stack.length - 1] === closeToOpen[c]) { + if ( + stack.length > 0 && + stack[stack.length - 1] === closeToOpen[c] + ) { stack.pop(); } else { return false; @@ -322,7 +325,7 @@ class Solution { stack.append(c) } } - + return stack.isEmpty } } @@ -332,5 +335,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ diff --git a/articles/validate-stack-sequences.md b/articles/validate-stack-sequences.md index 00867b541..911c0204a 100644 --- a/articles/validate-stack-sequences.md +++ b/articles/validate-stack-sequences.md @@ -62,7 +62,11 @@ class Solution { let i = 0; for (const n of pushed) { stack.push(n); - while (i < popped.length && stack.length > 0 && popped[i] === stack[stack.length - 1]) { + while ( + i < popped.length && + stack.length > 0 && + popped[i] === stack[stack.length - 1] + ) { stack.pop(); i++; } @@ -76,8 +80,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ --- @@ -139,7 +143,8 @@ class Solution { * @return {boolean} */ validateStackSequences(pushed, popped) { - let l = 0, r = 0; + let l = 0, + r = 0; for (const num of pushed) { pushed[l++] = num; while (l > 0 && pushed[l - 1] === popped[r]) { @@ -156,5 +161,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ extra space. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ extra space. diff --git a/articles/verifying-an-alien-dictionary.md b/articles/verifying-an-alien-dictionary.md index 86694cf0a..cd9e67deb 100644 --- a/articles/verifying-an-alien-dictionary.md +++ b/articles/verifying-an-alien-dictionary.md @@ -6,10 +6,10 @@ class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: order_index = {c: i for i, c in enumerate(order)} - + def compare(word): return [order_index[c] for c in word] - + return words == sorted(words, key=compare) ``` @@ -19,7 +19,7 @@ public class Solution { int[] orderIndex = new int[26]; for (int i = 0; i < order.length(); i++) orderIndex[order.charAt(i) - 'a'] = i; - + Comparator compare = (w1, w2) -> { for (int i = 0; i < Math.min(w1.length(), w2.length()); i++) { if (w1.charAt(i) != w2.charAt(i)) @@ -42,7 +42,7 @@ public: int orderIndex[26]; for (int i = 0; i < order.size(); ++i) orderIndex[order[i] - 'a'] = i; - + auto compare = [&](const string &a, const string &b) { for (int i = 0; i < min(a.size(), b.size()); ++i) { if (a[i] != b[i]) @@ -72,7 +72,10 @@ class Solution { const compare = (w1, w2) => { for (let i = 0; i < Math.min(w1.length, w2.length); i++) { if (w1[i] !== w2[i]) { - return orderIndex[w1.charCodeAt(i) - 97] - orderIndex[w2.charCodeAt(i) - 97]; + return ( + orderIndex[w1.charCodeAt(i) - 97] - + orderIndex[w2.charCodeAt(i) - 97] + ); } } return w1.length - w2.length; @@ -117,8 +120,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m\log n)$ -* Space complexity: $O(n * m)$ +- Time complexity: $O(n * m\log n)$ +- Space complexity: $O(n * m)$ > Where $n$ is the number of words and $m$ is the average length of a word. @@ -132,14 +135,14 @@ public class Solution { class Solution: def isAlienSorted(self, words: List[str], order: str) -> bool: order_index = {c: i for i, c in enumerate(order)} - + for i in range(len(words) - 1): w1, w2 = words[i], words[i + 1] - + for j in range(len(w1)): if j == len(w2): return False - + if w1[j] != w2[j]: if order_index[w1[j]] > order_index[w2[j]]: return False @@ -153,11 +156,11 @@ public class Solution { int[] orderIndex = new int[26]; for (int i = 0; i < order.length(); i++) orderIndex[order.charAt(i) - 'a'] = i; - + for (int i = 0; i < words.length - 1; i++) { String w1 = words[i], w2 = words[i + 1]; int j = 0; - + for (; j < w1.length(); j++) { if (j == w2.length()) return false; if (w1.charAt(j) != w2.charAt(j)) { @@ -180,11 +183,11 @@ public: int orderIndex[26] = {0}; for (int i = 0; i < order.size(); ++i) orderIndex[order[i] - 'a'] = i; - + for (int i = 0; i < words.size() - 1; ++i) { string w1 = words[i], w2 = words[i + 1]; int j = 0; - + for (; j < w1.size(); ++j) { if (j == w2.size()) return false; if (w1[j] != w2[j]) { @@ -211,15 +214,19 @@ class Solution { for (let i = 0; i < order.length; i++) { orderIndex[order.charCodeAt(i) - 97] = i; } - + for (let i = 0; i < words.length - 1; i++) { - let w1 = words[i], w2 = words[i + 1]; - + let w1 = words[i], + w2 = words[i + 1]; + for (let j = 0; j < w1.length; j++) { if (j === w2.length) return false; - + if (w1[j] !== w2[j]) { - if (orderIndex[w1.charCodeAt(j) - 97] > orderIndex[w2.charCodeAt(j) - 97]) + if ( + orderIndex[w1.charCodeAt(j) - 97] > + orderIndex[w2.charCodeAt(j) - 97] + ) return false; break; } @@ -265,7 +272,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m)$ -* Space complexity: $O(1)$ since we have $26$ different characters. +- Time complexity: $O(n * m)$ +- Space complexity: $O(1)$ since we have $26$ different characters. -> Where $n$ is the number of words and $m$ is the average length of a word. \ No newline at end of file +> Where $n$ is the number of words and $m$ is the average length of a word. diff --git a/articles/widest-vertical-area-between-two-points-containing-no-points.md b/articles/widest-vertical-area-between-two-points-containing-no-points.md index b41a574f7..9b08fdf4e 100644 --- a/articles/widest-vertical-area-between-two-points-containing-no-points.md +++ b/articles/widest-vertical-area-between-two-points-containing-no-points.md @@ -41,7 +41,7 @@ public class Solution { for (int k = 0; k < n; k++) { if (k == i || k == j) continue; - + int x3 = points[k][0]; if (x3 > Math.min(x1, x2) && x3 < Math.max(x1, x2)) { hasPoints = true; @@ -100,7 +100,8 @@ class Solution { * @return {number} */ maxWidthOfVerticalArea(points) { - let n = points.length, res = 0; + let n = points.length, + res = 0; for (let i = 1; i < n; i++) { let x1 = points[i][0]; @@ -133,8 +134,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n ^ 3)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n ^ 3)$ +- Space complexity: $O(1)$ --- @@ -208,5 +209,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. \ No newline at end of file +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. diff --git a/articles/wiggle-sort.md b/articles/wiggle-sort.md index d18f99598..250815c41 100644 --- a/articles/wiggle-sort.md +++ b/articles/wiggle-sort.md @@ -67,7 +67,7 @@ class Solution { */ wiggleSort(nums) { const maxHeap = new PriorityQueue((a, b) => b - a); - nums.forEach(num => maxHeap.enqueue(num)); + nums.forEach((num) => maxHeap.enqueue(num)); for (let i = 1; i < nums.length; i += 2) { nums[i] = maxHeap.dequeue(); @@ -83,8 +83,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n \log n)$ +- Space complexity: $O(n)$ --- @@ -148,8 +148,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n \log n)$ -* Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. +- Time complexity: $O(n \log n)$ +- Space complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm. --- @@ -163,7 +163,7 @@ class Solution: """ Do not return anything, modify nums in-place instead. """ - + for i in range(1, len(nums)): if ((i % 2 == 1 and nums[i] < nums[i - 1]) or (i % 2 == 0 and nums[i] > nums[i - 1]) @@ -208,8 +208,10 @@ class Solution { */ wiggleSort(nums) { for (let i = 1; i < nums.length; i++) { - if ((i % 2 == 1 && nums[i] < nums[i - 1]) || - (i % 2 == 0 && nums[i] > nums[i - 1])) { + if ( + (i % 2 == 1 && nums[i] < nums[i - 1]) || + (i % 2 == 0 && nums[i] > nums[i - 1]) + ) { [nums[i], nums[i - 1]] = [nums[i - 1], nums[i]]; } } @@ -221,8 +223,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ --- @@ -236,7 +238,7 @@ class Solution: """ Do not return anything, modify nums in-place instead. """ - + for i in range(1, len(nums)): if (i % 2) ^ (nums[i] > nums[i - 1]): nums[i], nums[i - 1] = nums[i - 1], nums[i] @@ -276,8 +278,8 @@ class Solution { * @return {void} Do not return anything, modify nums in-place instead. */ wiggleSort(nums) { - for(var i = 1; i < nums.length; i++) { - if ((i % 2) ^ (nums[i] > nums[i - 1])) { + for (var i = 1; i < nums.length; i++) { + if (i % 2 ^ (nums[i] > nums[i - 1])) { [nums[i], nums[i - 1]] = [nums[i - 1], nums[i]]; } } @@ -289,5 +291,5 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(1)$ \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(1)$ diff --git a/articles/word-break-ii.md b/articles/word-break-ii.md index 45660e5f9..01c43f537 100644 --- a/articles/word-break-ii.md +++ b/articles/word-break-ii.md @@ -111,7 +111,7 @@ class Solution { const backtrack = (i) => { if (i === s.length) { - res.push(cur.join(" ")); + res.push(cur.join(' ')); return; } @@ -164,8 +164,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n * 2 ^ n)$ -* Space complexity: $O(m + 2 ^ n)$ +- Time complexity: $O(m + n * 2 ^ n)$ +- Space complexity: $O(m + 2 ^ n)$ > Where $n$ is the length of the string $s$ and $m$ is the sum of the lengths of the strings in the $wordDict$. @@ -184,7 +184,7 @@ class TrieNode: class Trie: def __init__(self): self.root = TrieNode() - + def addWord(self, word): curr = self.root for c in word: @@ -198,27 +198,27 @@ class Solution: trie = Trie() for word in wordDict: trie.addWord(word) - + def backtrack(i, path): if i == len(s): res.append(" ".join(path)) return - + node = trie.root word = [] for i in range(i, len(s)): char = s[i] if char not in node.children: break - + word.append(char) node = node.children[char] - + if node.isWord: path.append("".join(word)) backtrack(i + 1, path) path.pop() - + res = [] backtrack(0, []) return res @@ -401,12 +401,12 @@ class Solution { const res = []; const backtrack = (index, path) => { if (index === s.length) { - res.push(path.join(" ")); + res.push(path.join(' ')); return; } let node = trie.root; - let word = ""; + let word = ''; for (let i = index; i < s.length; i++) { const char = s[i]; if (!node.children.has(char)) { @@ -494,8 +494,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n * 2 ^ n)$ -* Space complexity: $O(m + 2 ^ n)$ +- Time complexity: $O(m + n * 2 ^ n)$ +- Space complexity: $O(m + 2 ^ n)$ > Where $n$ is the length of the string $s$ and $m$ is the sum of the lengths of the strings in the $wordDict$. @@ -621,7 +621,7 @@ class Solution { const backtrack = (i) => { if (i === s.length) { - return [""]; + return ['']; } if (cache.has(i)) { return cache.get(i); @@ -636,7 +636,7 @@ class Solution { for (const substr of strings) { let sentence = w; if (substr) { - sentence += " " + substr; + sentence += ' ' + substr; } res.push(sentence); } @@ -688,8 +688,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n * 2 ^ n)$ -* Space complexity: $O(m + n * 2 ^ n)$ +- Time complexity: $O(m + n * 2 ^ n)$ +- Space complexity: $O(m + n * 2 ^ n)$ > Where $n$ is the length of the string $s$ and $m$ is the sum of the lengths of the strings in the $wordDict$. @@ -750,7 +750,7 @@ public: int n = s.size(); vector> dp(n + 1); dp[0] = {""}; - + for (int i = 1; i <= n; ++i) { for (int j = 0; j < i; ++j) { string word = s.substr(j, i - j); @@ -765,7 +765,7 @@ public: } } } - + return dp[n]; } }; @@ -782,13 +782,13 @@ class Solution { const wordSet = new Set(wordDict); const n = s.length; const dp = Array.from({ length: n + 1 }, () => []); - dp[0].push(""); + dp[0].push(''); for (let i = 1; i <= n; i++) { for (let j = 0; j < i; j++) { if (wordSet.has(s.substring(j, i))) { for (const sentence of dp[j]) { - dp[i].push((sentence + " " + s.substring(j, i)).trim()); + dp[i].push((sentence + ' ' + s.substring(j, i)).trim()); } } } @@ -831,8 +831,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n * 2 ^ n)$ -* Space complexity: $O(m + n * 2 ^ n)$ +- Time complexity: $O(m + n * 2 ^ n)$ +- Space complexity: $O(m + n * 2 ^ n)$ > Where $n$ is the length of the string $s$ and $m$ is the sum of the lengths of the strings in the $wordDict$. @@ -851,7 +851,7 @@ class TrieNode: class Trie: def __init__(self): self.root = TrieNode() - + def addWord(self, word): curr = self.root for c in word: @@ -865,15 +865,15 @@ class Solution: trie = Trie() for word in wordDict: trie.addWord(word) - + cache = {} - + def backtrack(index): if index == len(s): return [""] if index in cache: return cache[index] - + res = [] curr = trie.root for i in range(index, len(s)): @@ -887,10 +887,10 @@ class Solution: res.append(s[index:i + 1] + " " + suffix) else: res.append(s[index:i + 1]) - + cache[index] = res return res - + return backtrack(0) ``` @@ -1081,7 +1081,7 @@ class Solution { const backtrack = (index) => { if (index === s.length) { - return [""]; + return ['']; } if (cache.has(index)) { return cache.get(index); @@ -1099,7 +1099,7 @@ class Solution { if (curr.isWord) { for (const suffix of backtrack(i + 1)) { if (suffix) { - res.push(s.slice(index, i + 1) + " " + suffix); + res.push(s.slice(index, i + 1) + ' ' + suffix); } else { res.push(s.slice(index, i + 1)); } @@ -1182,7 +1182,7 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(m + n * 2 ^ n)$ -* Space complexity: $O(m + n * 2 ^ n)$ +- Time complexity: $O(m + n * 2 ^ n)$ +- Space complexity: $O(m + n * 2 ^ n)$ -> Where $n$ is the length of the string $s$ and $m$ is the sum of the lengths of the strings in the $wordDict$. \ No newline at end of file +> Where $n$ is the length of the string $s$ and $m$ is the sum of the lengths of the strings in the $wordDict$. diff --git a/articles/word-break.md b/articles/word-break.md index acc8366d3..4b03965f5 100644 --- a/articles/word-break.md +++ b/articles/word-break.md @@ -9,15 +9,15 @@ class Solution: def dfs(i): if i == len(s): return True - + for w in wordDict: - if ((i + len(w)) <= len(s) and + if ((i + len(w)) <= len(s) and s[i : i + len(w)] == w ): if dfs(i + len(w)): return True return False - + return dfs(0) ``` @@ -26,14 +26,14 @@ public class Solution { public boolean wordBreak(String s, List wordDict) { return dfs(s, wordDict, 0); } - + private boolean dfs(String s, List wordDict, int i) { if (i == s.length()) { return true; } for (String w : wordDict) { - if (i + w.length() <= s.length() && + if (i + w.length() <= s.length() && s.substring(i, i + w.length()).equals(w)) { if (dfs(s, wordDict, i + w.length())) { return true; @@ -59,7 +59,7 @@ private: } for (const string& w : wordDict) { - if (i + w.length() <= s.length() && + if (i + w.length() <= s.length() && s.substr(i, w.length()) == w) { if (dfs(s, wordDict, i + w.length())) { return true; @@ -94,8 +94,10 @@ class Solution { } for (let w of wordDict) { - if (i + w.length <= s.length && - s.substring(i, i + w.length) === w) { + if ( + i + w.length <= s.length && + s.substring(i, i + w.length) === w + ) { if (this.dfs(s, wordDict, i + w.length)) { return true; } @@ -118,7 +120,7 @@ public class Solution { } foreach (string w in wordDict) { - if (i + w.Length <= s.Length && + if (i + w.Length <= s.Length && s.Substring(i, w.Length) == w) { if (Dfs(s, wordDict, i + w.Length)) { return true; @@ -185,9 +187,9 @@ class Solution { if i == chars.count { return true } - + for w in wordDict { - if i + w.count <= chars.count, + if i + w.count <= chars.count, String(chars[i.. Where $n$ is the length of the string $s$, $m$ is the number of words in $wordDict$ and $t$ is the maximum length of any word in $wordDict$. @@ -225,13 +227,13 @@ class Solution: def dfs(i): if i == len(s): return True - + for j in range(i, len(s)): if s[i : j + 1] in wordSet: if dfs(j + 1): return True return False - + return dfs(0) ``` @@ -307,7 +309,7 @@ class Solution { } } return false; - } + }; return dfs(0); } @@ -419,10 +421,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O( (n * 2 ^ n) + m)$ -* Space complexity: $O(n + (m * t))$ +- Time complexity: $O( (n * 2 ^ n) + m)$ +- Space complexity: $O(n + (m * t))$ ->Where $n$ is the length of the string $s$ and $m$ is the number of words in $wordDict$. +> Where $n$ is the length of the string $s$ and $m$ is the number of words in $wordDict$. --- @@ -437,9 +439,9 @@ class Solution: def dfs(i): if i in memo: return memo[i] - + for w in wordDict: - if ((i + len(w)) <= len(s) and + if ((i + len(w)) <= len(s) and s[i : i + len(w)] == w ): if dfs(i + len(w)): @@ -447,7 +449,7 @@ class Solution: return True memo[i] = False return False - + return dfs(0) ``` @@ -467,7 +469,7 @@ public class Solution { } for (String w : wordDict) { - if (i + w.length() <= s.length() && + if (i + w.length() <= s.length() && s.substring(i, i + w.length()).equals(w)) { if (dfs(s, wordDict, i + w.length())) { memo.put(i, true); @@ -497,7 +499,7 @@ public: } for (const string& w : wordDict) { - if (i + w.length() <= s.length() && + if (i + w.length() <= s.length() && s.substr(i, w.length()) == w) { if (dfs(s, wordDict, i + w.length())) { memo[i] = true; @@ -539,8 +541,10 @@ class Solution { } for (let w of wordDict) { - if (i + w.length <= s.length && - s.substring(i, i + w.length) === w) { + if ( + i + w.length <= s.length && + s.substring(i, i + w.length) === w + ) { if (this.dfs(s, wordDict, i + w.length)) { this.memo[i] = true; return true; @@ -568,7 +572,7 @@ public class Solution { } foreach (var w in wordDict) { - if (i + w.Length <= s.Length && + if (i + w.Length <= s.Length && s.Substring(i, w.Length) == w) { if (Dfs(s, wordDict, i + w.Length)) { memo[i] = true; @@ -619,7 +623,7 @@ class Solution { memo[i]?.let { return it } for (w in wordDict) { - if (i + w.length <= s.length && + if (i + w.length <= s.length && s.substring(i, i + w.length) == w) { if (dfs(i + w.length)) { memo[i] = true @@ -650,7 +654,7 @@ class Solution { } for w in wordDict { - if i + w.count <= chars.count, + if i + w.count <= chars.count, String(chars[i.. Where $n$ is the length of the string $s$, $m$ is the number of words in $wordDict$ and $t$ is the maximum length of any word in $wordDict$. @@ -703,7 +707,7 @@ class Solution: return True memo[i] = False return False - + return dfs(0) ``` @@ -973,8 +977,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O((t ^ 2 * n) + m)$ -* Space complexity: $O(n + (m * t))$ +- Time complexity: $O((t ^ 2 * n) + m)$ +- Space complexity: $O(n + (m * t))$ > Where $n$ is the length of the string $s$, $m$ is the number of words in $wordDict$ and $t$ is the maximum length of any word in $wordDict$. @@ -1008,7 +1012,7 @@ public class Solution { for (int i = s.length() - 1; i >= 0; i--) { for (String w : wordDict) { - if ((i + w.length()) <= s.length() && + if ((i + w.length()) <= s.length() && s.substring(i, i + w.length()).equals(w)) { dp[i] = dp[i + w.length()]; } @@ -1032,7 +1036,7 @@ public: for (int i = s.size() - 1; i >= 0; i--) { for (const auto& w : wordDict) { - if ((i + w.size()) <= s.size() && + if ((i + w.size()) <= s.size() && s.substr(i, w.size()) == w) { dp[i] = dp[i + w.size()]; } @@ -1060,8 +1064,10 @@ class Solution { for (let i = s.length - 1; i >= 0; i--) { for (const w of wordDict) { - if ( i + w.length <= s.length && - s.slice(i, i + w.length) === w) { + if ( + i + w.length <= s.length && + s.slice(i, i + w.length) === w + ) { dp[i] = dp[i + w.length]; } if (dp[i]) { @@ -1083,7 +1089,7 @@ public class Solution { for (int i = s.Length - 1; i >= 0; i--) { foreach (string w in wordDict) { - if ((i + w.Length) <= s.Length && + if ((i + w.Length) <= s.Length && s.Substring(i, w.Length) == w) { dp[i] = dp[i + w.Length]; } @@ -1126,7 +1132,7 @@ class Solution { for (i in s.length - 1 downTo 0) { for (w in wordDict) { - if (i + w.length <= s.length && + if (i + w.length <= s.length && s.substring(i, i + w.length) == w) { dp[i] = dp[i + w.length] } @@ -1166,8 +1172,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n * m * t)$ -* Space complexity: $O(n)$ +- Time complexity: $O(n * m * t)$ +- Space complexity: $O(n)$ > Where $n$ is the length of the string $s$, $m$ is the number of words in $wordDict$ and $t$ is the maximum length of any word in $wordDict$. @@ -1215,7 +1221,7 @@ class Solution: t = 0 for w in wordDict: t = max(t, len(w)) - + for i in range(len(s), -1, -1): for j in range(i, min(len(s), i + t)): if trie.search(s, i, j): @@ -1706,7 +1712,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O((n * t ^ 2) + m)$ -* Space complexity: $O(n + (m * t))$ +- Time complexity: $O((n * t ^ 2) + m)$ +- Space complexity: $O(n + (m * t))$ -> Where $n$ is the length of the string $s$, $m$ is the number of words in $wordDict$ and $t$ is the maximum length of any word in $wordDict$. \ No newline at end of file +> Where $n$ is the length of the string $s$, $m$ is the number of words in $wordDict$ and $t$ is the maximum length of any word in $wordDict$. diff --git a/articles/word-ladder.md b/articles/word-ladder.md index ea29ccf35..a6a564c8a 100644 --- a/articles/word-ladder.md +++ b/articles/word-ladder.md @@ -7,7 +7,7 @@ class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: if (endWord not in wordList) or (beginWord == endWord): return 0 - + n, m = len(wordList), len(wordList[0]) adj = [[] for _ in range(n)] mp = {} @@ -23,7 +23,7 @@ class Solution: if cnt == 1: adj[i].append(j) adj[j].append(i) - + q, res = deque(), 1 visit = set() for i in range(m): @@ -34,7 +34,7 @@ class Solution: if word in mp and mp[word] not in visit: q.append(mp[word]) visit.add(mp[word]) - + while q: res += 1 for i in range(len(q)): @@ -45,7 +45,7 @@ class Solution: if nei not in visit: visit.add(nei) q.append(nei) - + return 0 ``` @@ -55,14 +55,14 @@ public class Solution { if (!wordList.contains(endWord) || beginWord.equals(endWord)) { return 0; } - + int n = wordList.size(); int m = wordList.get(0).length(); List> adj = new ArrayList<>(n); for (int i = 0; i < n; i++) { adj.add(new ArrayList<>()); } - + Map mp = new HashMap<>(); for (int i = 0; i < n; i++) { mp.put(wordList.get(i), i); @@ -86,7 +86,7 @@ public class Solution { Queue q = new LinkedList<>(); int res = 1; Set visit = new HashSet<>(); - + for (int i = 0; i < m; i++) { for (char c = 'a'; c <= 'z'; c++) { if (c == beginWord.charAt(i)) { @@ -116,7 +116,7 @@ public class Solution { } } } - + return 0; } } @@ -126,11 +126,11 @@ public class Solution { class Solution { public: int ladderLength(string beginWord, string endWord, vector& wordList) { - if (find(wordList.begin(), wordList.end(), endWord) == wordList.end() || + if (find(wordList.begin(), wordList.end(), endWord) == wordList.end() || beginWord == endWord) { return 0; } - + int n = wordList.size(); int m = wordList[0].size(); vector> adj(n); @@ -157,7 +157,7 @@ public: queue q; int res = 1; unordered_set visit; - + for (int i = 0; i < m; i++) { for (char c = 'a'; c <= 'z'; c++) { if (c == beginWord[i]) { @@ -188,7 +188,7 @@ public: } } } - + return 0; } }; @@ -203,8 +203,7 @@ class Solution { * @return {number} */ ladderLength(beginWord, endWord, wordList) { - if (!wordList.includes(endWord) || - beginWord === endWord) { + if (!wordList.includes(endWord) || beginWord === endWord) { return 0; } @@ -212,7 +211,7 @@ class Solution { const m = wordList[0].length; const adj = Array.from({ length: n }, () => []); const mp = new Map(); - + for (let i = 0; i < n; i++) { mp.set(wordList[i], i); } @@ -241,8 +240,10 @@ class Solution { if (String.fromCharCode(c) === beginWord[i]) { continue; } - const word = beginWord.slice(0, i) + - String.fromCharCode(c) + beginWord.slice(i + 1); + const word = + beginWord.slice(0, i) + + String.fromCharCode(c) + + beginWord.slice(i + 1); if (mp.has(word) && !visit.has(mp.get(word))) { q.push(mp.get(word)); visit.add(mp.get(word)); @@ -266,7 +267,7 @@ class Solution { } } } - + return 0; } } @@ -278,14 +279,14 @@ public class Solution { if (!wordList.Contains(endWord) || beginWord == endWord) { return 0; } - + int n = wordList.Count; int m = wordList[0].Length; List> adj = new List>(n); for (int i = 0; i < n; i++) { adj.Add(new List()); } - + Dictionary mp = new Dictionary(); for (int i = 0; i < n; i++) { mp[wordList[i]] = i; @@ -309,13 +310,13 @@ public class Solution { Queue q = new Queue(); int res = 1; HashSet visit = new HashSet(); - + for (int i = 0; i < m; i++) { for (char c = 'a'; c <= 'z'; c++) { if (c == beginWord[i]) { continue; } - string word = beginWord.Substring(0, i) + c + + string word = beginWord.Substring(0, i) + c + beginWord.Substring(i + 1); if (mp.ContainsKey(word) && !visit.Contains(mp[word])) { q.Enqueue(mp[word]); @@ -340,7 +341,7 @@ public class Solution { } } } - + return 0; } } @@ -498,18 +499,18 @@ class Solution { if !wordList.contains(endWord) || beginWord == endWord { return 0 } - + let n = wordList.count let m = wordList[0].count var adj = [[Int]](repeating: [], count: n) var mp = [String: Int]() - + for i in 0..() var res = 1 var visit = Set() let beginChars = Array(beginWord) - + for i in 0.. Where $n$ is the number of words and $m$ is the length of the word. @@ -617,7 +618,7 @@ public class Solution { int res = 0; Queue q = new LinkedList<>(); q.offer(beginWord); - + while (!q.isEmpty()) { res++; for (int i = q.size(); i > 0; i--) { @@ -649,7 +650,7 @@ public: int res = 0; queue q; q.push(beginWord); - + while (!q.empty()) { res++; int len = q.size(); @@ -691,7 +692,7 @@ class Solution { } let res = 0; const q = new Queue([beginWord]); - + while (!q.isEmpty()) { res++; let len = q.size(); @@ -703,9 +704,10 @@ class Solution { if (String.fromCharCode(c) === node[j]) { continue; } - const nei = node.slice(0, j) + - String.fromCharCode(c) + - node.slice(j + 1); + const nei = + node.slice(0, j) + + String.fromCharCode(c) + + node.slice(j + 1); if (words.has(nei)) { q.push(nei); words.delete(nei); @@ -727,7 +729,7 @@ public class Solution { int res = 0; var q = new Queue(); q.Enqueue(beginWord); - + while (q.Count > 0) { res++; int len = q.Count; @@ -775,7 +777,7 @@ func ladderLength(beginWord string, endWord string, wordList []string) int { for i := 0; i < size; i++ { node := q[0] q = q[1:] - + if node == endWord { return res } @@ -822,7 +824,7 @@ class Solution { res++ repeat(q.size) { val node = q.removeFirst() - + if (node == endWord) { return res } @@ -892,8 +894,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m ^ 2 * n)$ -* Space complexity: $O(m ^ 2 * n)$ +- Time complexity: $O(m ^ 2 * n)$ +- Space complexity: $O(m ^ 2 * n)$ > Where $n$ is the number of words and $m$ is the length of the word. @@ -1041,8 +1043,8 @@ class Solution { wordList.push(beginWord); for (const word of wordList) { for (let j = 0; j < word.length; ++j) { - const pattern = word.substring(0, j) + - '*' + word.substring(j + 1); + const pattern = + word.substring(0, j) + '*' + word.substring(j + 1); if (!nei[pattern]) { nei[pattern] = []; } @@ -1051,7 +1053,7 @@ class Solution { } const visit = new Set([beginWord]); - const q =new Queue([beginWord]); + const q = new Queue([beginWord]); let res = 1; while (!q.isEmpty()) { const size = q.size(); @@ -1061,8 +1063,8 @@ class Solution { return res; } for (let j = 0; j < word.length; ++j) { - const pattern = word.substring(0, j) + - '*' + word.substring(j + 1); + const pattern = + word.substring(0, j) + '*' + word.substring(j + 1); for (const neiWord of nei[pattern]) { if (!visit.has(neiWord)) { visit.add(neiWord); @@ -1089,7 +1091,7 @@ public class Solution { wordList.Add(beginWord); foreach (string word in wordList) { for (int j = 0; j < word.Length; j++) { - string pattern = word.Substring(0, j) + + string pattern = word.Substring(0, j) + "*" + word.Substring(j + 1); if (!nei.ContainsKey(pattern)) { nei[pattern] = new List(); @@ -1110,7 +1112,7 @@ public class Solution { return res; } for (int j = 0; j < word.Length; j++) { - string pattern = word.Substring(0, j) + + string pattern = word.Substring(0, j) + "*" + word.Substring(j + 1); if (nei.ContainsKey(pattern)) { foreach (string neiWord in nei[pattern]) { @@ -1154,7 +1156,7 @@ func ladderLength(beginWord string, endWord string, wordList []string) int { for i := len(q); i > 0; i-- { word := q[0] q = q[1:] - + if word == endWord { return res } @@ -1208,7 +1210,7 @@ class Solution { while (q.isNotEmpty()) { repeat(q.size) { val word = q.removeFirst() - + if (word == endWord) { return res } @@ -1288,8 +1290,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m ^ 2 * n)$ -* Space complexity: $O(m ^ 2 * n)$ +- Time complexity: $O(m ^ 2 * n)$ +- Space complexity: $O(m ^ 2 * n)$ > Where $n$ is the number of words and $m$ is the length of the word. @@ -1308,7 +1310,7 @@ class Solution: wordSet = set(wordList) qb, qe = deque([beginWord]), deque([endWord]) fromBegin, fromEnd = {beginWord: 1}, {endWord: 1} - + while qb and qe: if len(qb) > len(qe): qb, qe = qe, qb @@ -1345,7 +1347,7 @@ public class Solution { qe.add(endWord); fromBegin.put(beginWord, 1); fromEnd.put(endWord, 1); - + while (!qb.isEmpty() && !qe.isEmpty()) { if (qb.size() > qe.size()) { Queue tempQ = qb; @@ -1363,7 +1365,7 @@ public class Solution { for (char c = 'a'; c <= 'z'; c++) { if (c == word.charAt(i)) continue; - String nei = word.substring(0, i) + + String nei = word.substring(0, i) + c + word.substring(i + 1); if (!wordSet.contains(nei)) continue; @@ -1386,7 +1388,7 @@ public class Solution { class Solution { public: int ladderLength(string beginWord, string endWord, vector& wordList) { - if (find(wordList.begin(), wordList.end(), endWord) == wordList.end() || + if (find(wordList.begin(), wordList.end(), endWord) == wordList.end() || beginWord == endWord) return 0; int m = wordList[0].size(); @@ -1397,7 +1399,7 @@ public: qe.push(endWord); fromBegin[beginWord] = 1; fromEnd[endWord] = 1; - + while (!qb.empty() && !qe.empty()) { if (qb.size() > qe.size()) { swap(qb, qe); @@ -1412,7 +1414,7 @@ public: for (char c = 'a'; c <= 'z'; c++) { if (c == word[i]) continue; - string nei = word.substr(0, i) + + string nei = word.substr(0, i) + c + word.substr(i + 1); if (!wordSet.count(nei)) continue; @@ -1440,8 +1442,7 @@ class Solution { * @return {number} */ ladderLength(beginWord, endWord, wordList) { - if (!wordList.includes(endWord) || - beginWord === endWord) { + if (!wordList.includes(endWord) || beginWord === endWord) { return 0; } const m = wordList[0].length; @@ -1462,13 +1463,12 @@ class Solution { const steps = fromBegin[word]; for (let i = 0; i < m; i++) { for (let c = 97; c <= 122; c++) { - if (String.fromCharCode(c) === word[i]) - continue; - const nei = word.slice(0, i) + - String.fromCharCode(c) + - word.slice(i + 1); - if (!wordSet.has(nei)) - continue; + if (String.fromCharCode(c) === word[i]) continue; + const nei = + word.slice(0, i) + + String.fromCharCode(c) + + word.slice(i + 1); + if (!wordSet.has(nei)) continue; if (fromEnd[nei] !== undefined) return steps + fromEnd[nei]; if (fromBegin[nei] === undefined) { @@ -1492,13 +1492,13 @@ public class Solution { int m = wordList[0].Length; HashSet wordSet = new HashSet(wordList); Queue qb = new Queue(), qe = new Queue(); - Dictionary fromBegin = new Dictionary(), + Dictionary fromBegin = new Dictionary(), fromEnd = new Dictionary(); qb.Enqueue(beginWord); qe.Enqueue(endWord); fromBegin[beginWord] = 1; fromEnd[endWord] = 1; - + while (qb.Count > 0 && qe.Count > 0) { if (qb.Count > qe.Count) { var tempQ = qb; @@ -1516,7 +1516,7 @@ public class Solution { for (char c = 'a'; c <= 'z'; c++) { if (c == word[i]) continue; - string nei = word.Substring(0, i) + + string nei = word.Substring(0, i) + c + word.Substring(i + 1); if (!wordSet.Contains(nei)) continue; @@ -1540,34 +1540,34 @@ func ladderLength(beginWord string, endWord string, wordList []string) int { if len(wordList) == 0 || len(beginWord) != len(wordList[0]) { return 0 } - + wordSet := make(map[string]bool) for _, word := range wordList { wordSet[word] = true } - + if !wordSet[endWord] || beginWord == endWord { return 0 } - + m := len(beginWord) qb := []string{beginWord} qe := []string{endWord} fromBegin := map[string]int{beginWord: 1} fromEnd := map[string]int{endWord: 1} - + for len(qb) > 0 && len(qe) > 0 { if len(qb) > len(qe) { qb, qe = qe, qb fromBegin, fromEnd = fromEnd, fromBegin } - + size := len(qb) for i := 0; i < size; i++ { word := qb[0] qb = qb[1:] steps := fromBegin[word] - + wordBytes := []byte(word) for j := 0; j < m; j++ { orig := wordBytes[j] @@ -1577,7 +1577,7 @@ func ladderLength(beginWord string, endWord string, wordList []string) int { } wordBytes[j] = c nei := string(wordBytes) - + if !wordSet[nei] { continue } @@ -1603,29 +1603,29 @@ class Solution { if (!wordList.contains(endWord) || beginWord == endWord) { return 0 } - + val m = wordList[0].length val wordSet = wordList.toSet() val qb = ArrayDeque().apply { add(beginWord) } val qe = ArrayDeque().apply { add(endWord) } val fromBegin = hashMapOf(beginWord to 1) val fromEnd = hashMapOf(endWord to 1) - + while (qb.isNotEmpty() && qe.isNotEmpty()) { if (qb.size > qe.size) { qb.swap(qe) fromBegin.swap(fromEnd) } - + repeat(qb.size) { val word = qb.removeFirst() val steps = fromBegin[word]!! - + for (i in 0 until m) { for (c in 'a'..'z') { if (c == word[i]) continue val nei = word.substring(0, i) + c + word.substring(i + 1) - + if (!wordSet.contains(nei)) continue fromEnd[nei]?.let { return steps + it } if (nei !in fromBegin) { @@ -1638,7 +1638,7 @@ class Solution { } return 0 } - + private fun ArrayDeque.swap(other: ArrayDeque) { val temp = ArrayDeque(this) this.clear() @@ -1646,7 +1646,7 @@ class Solution { other.clear() other.addAll(temp) } - + private fun HashMap.swap(other: HashMap) { val temp = HashMap() temp.putAll(this) @@ -1717,7 +1717,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(m ^ 2 * n)$ -* Space complexity: $O(m ^ 2 * n)$ +- Time complexity: $O(m ^ 2 * n)$ +- Space complexity: $O(m ^ 2 * n)$ -> Where $n$ is the number of words and $m$ is the length of the word. \ No newline at end of file +> Where $n$ is the number of words and $m$ is the length of the word. diff --git a/articles/word-pattern.md b/articles/word-pattern.md index c09b50aa1..9aed8cbe2 100644 --- a/articles/word-pattern.md +++ b/articles/word-pattern.md @@ -97,7 +97,7 @@ class Solution { * @return {boolean} */ wordPattern(pattern, s) { - const words = s.split(" "); + const words = s.split(' '); if (pattern.length !== words.length) { return false; } @@ -128,8 +128,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(m)$ > Where $n$ is the length of the string $pattern$ and $m$ is the length of the string $s$. @@ -164,24 +164,24 @@ public class Solution { Map charToWord = new HashMap<>(); Map wordToChar = new HashMap<>(); String[] words = s.split(" "); - + if (words.length != pattern.length()) return false; - + for (int i = 0; i < pattern.length(); i++) { - if (charToWord.containsKey(pattern.charAt(i)) && + if (charToWord.containsKey(pattern.charAt(i)) && !words[charToWord.get(pattern.charAt(i))].equals(words[i])) { return false; } - - if (wordToChar.containsKey(words[i]) && + + if (wordToChar.containsKey(words[i]) && pattern.charAt(wordToChar.get(words[i])) != pattern.charAt(i)) { return false; } - + charToWord.put(pattern.charAt(i), i); wordToChar.put(words[i], i); } - + return true; } } @@ -216,20 +216,20 @@ class Solution { wordPattern(pattern, s) { const charToWord = new Map(); const wordToChar = new Map(); - const words = s.split(" "); - + const words = s.split(' '); + if (pattern.length !== words.length) { return false; } - + for (let i = 0; i < words.length; i++) { const c = pattern[i]; const word = words[i]; - + if ((charToWord.get(c) || 0) !== (wordToChar.get(word) || 0)) { return false; } - + charToWord.set(c, i + 1); wordToChar.set(word, i + 1); } @@ -243,8 +243,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(m)$ > Where $n$ is the length of the string $pattern$ and $m$ is the length of the string $s$. @@ -260,10 +260,10 @@ class Solution: words = s.split() if len(pattern) != len(words): return False - + charToWord = {} store = set() - + for i, (c, w) in enumerate(zip(pattern, words)): if c in charToWord: if words[charToWord[c]] != w: @@ -274,7 +274,7 @@ class Solution: charToWord[c] = i store.add(w) - return True + return True ``` ```java @@ -282,13 +282,13 @@ public class Solution { public boolean wordPattern(String pattern, String s) { String[] words = s.split(" "); if (pattern.length() != words.length) return false; - + Map charToWord = new HashMap<>(); Set store = new HashSet<>(); - + for (int i = 0; i < pattern.length(); i++) { char c = pattern.charAt(i); - + if (charToWord.containsKey(c)) { if (!words[charToWord.get(c)].equals(words[i])) { return false; @@ -301,7 +301,7 @@ public class Solution { store.add(words[i]); } } - + return true; } } @@ -314,19 +314,19 @@ public: stringstream ss(s); string word; vector words; - + while (ss >> word) { words.push_back(word); } - + if (pattern.length() != words.size()) return false; - + unordered_map charToWord; set store; - + for (int i = 0; i < pattern.length(); i++) { char c = pattern[i]; - + if (charToWord.count(c)) { if (words[charToWord[c]] != words[i]) { return false; @@ -339,7 +339,7 @@ public: store.insert(words[i]); } } - + return true; } }; @@ -355,20 +355,20 @@ class Solution { wordPattern(pattern, s) { const charToWord = new Map(); const wordToChar = new Map(); - const words = s.split(" "); - + const words = s.split(' '); + if (pattern.length !== words.length) { return false; } - + for (let i = 0; i < words.length; i++) { const c = pattern[i]; const word = words[i]; - + if ((charToWord.get(c) || 0) !== (wordToChar.get(word) || 0)) { return false; } - + charToWord.set(c, i + 1); wordToChar.set(word, i + 1); } @@ -382,8 +382,8 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(m)$ > Where $n$ is the length of the string $pattern$ and $m$ is the length of the string $s$. @@ -399,9 +399,9 @@ class Solution: words = s.split() if len(pattern) != len(words): return False - + charToWord = {} - + for i, (c, w) in enumerate(zip(pattern, words)): if c in charToWord: if words[charToWord[c]] != w: @@ -413,7 +413,7 @@ class Solution: return False charToWord[c] = i - return True + return True ``` ```java @@ -457,7 +457,7 @@ public: while (ss >> word) { words.push_back(word); } - + if (pattern.size() != words.size()) { return false; } @@ -494,7 +494,7 @@ class Solution { * @return {boolean} */ wordPattern(pattern, s) { - const words = s.split(" "); + const words = s.split(' '); if (pattern.length !== words.length) { return false; } @@ -517,7 +517,7 @@ class Solution { charToWord.set(c, i); } } - + return true; } } @@ -527,7 +527,7 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(n + m)$ -* Space complexity: $O(m)$ +- Time complexity: $O(n + m)$ +- Space complexity: $O(m)$ -> Where $n$ is the length of the string $pattern$ and $m$ is the length of the string $s$. \ No newline at end of file +> Where $n$ is the length of the string $pattern$ and $m$ is the length of the string $s$. diff --git a/articles/word-subsets.md b/articles/word-subsets.md index d96eab686..cb9fdcbb6 100644 --- a/articles/word-subsets.md +++ b/articles/word-subsets.md @@ -12,7 +12,7 @@ class Solution: for w2 in words2: count2 = Counter(w2) - for c in count2: + for c in count2: if count2[c] > count1[c]: is_subset = False break @@ -131,10 +131,10 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(N * n + N * M * m)$ -* Space complexity: - * $O(1)$ extra space, since we have at most $26$ different characters. - * $O(N * n)$ space for the output list. +- Time complexity: $O(N * n + N * M * m)$ +- Space complexity: + - $O(1)$ extra space, since we have at most $26$ different characters. + - $O(N * n)$ space for the output list. > Where $N$ is the size of the array $words1$, $n$ is the length of the longest word in $words1$, $M$ is the size of the array $words2$, and $m$ is the length of the longest word in $words2$. @@ -285,9 +285,9 @@ class Solution { ### Time & Space Complexity -* Time complexity: $O(N * n + M * m)$ -* Space complexity: - * $O(1)$ extra space, since we have at most $26$ different characters. - * $O(N * n)$ space for the output list. +- Time complexity: $O(N * n + M * m)$ +- Space complexity: + - $O(1)$ extra space, since we have at most $26$ different characters. + - $O(N * n)$ space for the output list. -> Where $N$ is the size of the array $words1$, $n$ is the length of the longest word in $words1$, $M$ is the size of the array $words2$, and $m$ is the length of the longest word in $words2$. \ No newline at end of file +> Where $N$ is the size of the array $words1$, $n$ is the length of the longest word in $words1$, $M$ is the size of the array $words2$, and $m$ is the length of the longest word in $words2$. diff --git a/articles/zigzag-conversion.md b/articles/zigzag-conversion.md index c027503be..e0a388017 100644 --- a/articles/zigzag-conversion.md +++ b/articles/zigzag-conversion.md @@ -15,7 +15,7 @@ class Solution: res.append(s[i]) if r > 0 and r < numRows - 1 and i + increment - 2 * r < len(s): res.append(s[i + increment - 2 * r]) - + return ''.join(res) ``` @@ -128,8 +128,8 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for the ouput string. +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for the ouput string. --- @@ -142,7 +142,7 @@ class Solution: def convert(self, s: str, numRows: int) -> str: if numRows == 1 or numRows >= len(s): return s - + res = [[] for _ in range(numRows)] row, dir = 0, 1 for c in s: @@ -150,7 +150,7 @@ class Solution: row += dir if row == 0 or row == (numRows - 1): dir *= -1 - + return ''.join([''.join(row) for row in res]) ``` @@ -227,7 +227,8 @@ class Solution { } const res = Array.from({ length: numRows }, () => []); - let row = 0, dir = 1; + let row = 0, + dir = 1; for (const c of s) { res[row].push(c); @@ -237,7 +238,7 @@ class Solution { } } - return res.map(row => row.join("")).join(""); + return res.map((row) => row.join('')).join(''); } } ``` @@ -248,12 +249,12 @@ public class Solution { if (numRows == 1 || numRows >= s.Length) { return s; } - + var res = new List(numRows); for (int i = 0; i < numRows; i++) { res.Add(new StringBuilder()); } - + int row = 0, dir = 1; foreach (char c in s) { res[row].Append(c); @@ -262,7 +263,7 @@ public class Solution { dir = -dir; } } - + var result = new StringBuilder(); foreach (var sb in res) { result.Append(sb); @@ -276,5 +277,5 @@ public class Solution { ### Time & Space Complexity -* Time complexity: $O(n)$ -* Space complexity: $O(n)$ for the output string. \ No newline at end of file +- Time complexity: $O(n)$ +- Space complexity: $O(n)$ for the output string. diff --git a/hints/add-two-numbers.md b/hints/add-two-numbers.md index 2cdafc4fa..5813a0333 100644 --- a/hints/add-two-numbers.md +++ b/hints/add-two-numbers.md @@ -20,4 +20,4 @@

We track the extra value, carry, here as well. We iterate through the lists l1 and l2 until both lists reach null. We add the values of both nodes as well as the carry. If either of the nodes is null, we add 0 in its place and continue the process while tracking the carry simultaneously. Once we complete the process, if we are left with any carry, we add an extra node with that carry value and return the head of the result list.

- \ No newline at end of file + diff --git a/hints/anagram-groups.md b/hints/anagram-groups.md index b77b383f8..34708db8c 100644 --- a/hints/anagram-groups.md +++ b/hints/anagram-groups.md @@ -28,4 +28,4 @@

We can simply use an array of size O(26), since the character set is a through z (26 continuous characters), to count the frequency of each character in a string. Then, we can use this array as the key in the hash map to group the strings.

- \ No newline at end of file + diff --git a/hints/balanced-binary-tree.md b/hints/balanced-binary-tree.md index 51473ca01..aa4796f99 100644 --- a/hints/balanced-binary-tree.md +++ b/hints/balanced-binary-tree.md @@ -20,4 +20,4 @@

We can use the Depth First Search (DFS) algorithm to compute the heights at each node. While calculating the heights of the left and right subtrees, we also check if the tree rooted at the current node is balanced. If leftHeight - rightHeight > 1, we update a global variable, such as isBalanced = False. After traversing all the nodes, the value of isBalanced indicates whether the entire tree is balanced or not.

- \ No newline at end of file + diff --git a/hints/binary-search.md b/hints/binary-search.md index a1a01c8e2..f46678074 100644 --- a/hints/binary-search.md +++ b/hints/binary-search.md @@ -36,4 +36,4 @@

Because the array is sorted, all elements to the left of mid (including 3) are guaranteed to be smaller than the target. Therefore, we can safely eliminate that half of the array from consideration, narrowing the search to the right half and repeat this search until we find the target.

- \ No newline at end of file + diff --git a/hints/binary-tree-diameter.md b/hints/binary-tree-diameter.md index d8c6b6ec3..654308abe 100644 --- a/hints/binary-tree-diameter.md +++ b/hints/binary-tree-diameter.md @@ -36,4 +36,4 @@

We can use the Depth First Search (DFS) algorithm to calculate the height of the tree. At each node, the subtrees return their respective heights (leftHeight and rightHeight). Then we calculate the diameter at that node as d = leftHeight + rightHeight. We use a global variable to update the maximum diameter as needed during the traversal.

- \ No newline at end of file + diff --git a/hints/binary-tree-from-preorder-and-inorder-traversal.md b/hints/binary-tree-from-preorder-and-inorder-traversal.md index d46b6141c..0b5f198ab 100644 --- a/hints/binary-tree-from-preorder-and-inorder-traversal.md +++ b/hints/binary-tree-from-preorder-and-inorder-traversal.md @@ -44,4 +44,4 @@

We use Depth First Search (DFS) to construct the tree. A global variable tracks the current index in the pre-order array. Indices l and r represent the segment in the in-order array for the current subtree. For each node in the pre-order array, we create a node, find its index in the in-order array using the hash map, and recursively build the left and right subtrees by splitting the range [l, r] into two parts for the left and right subtrees.

- \ No newline at end of file + diff --git a/hints/binary-tree-maximum-path-sum.md b/hints/binary-tree-maximum-path-sum.md index 318e1a388..c6db48d91 100644 --- a/hints/binary-tree-maximum-path-sum.md +++ b/hints/binary-tree-maximum-path-sum.md @@ -36,4 +36,4 @@

We return the maximum path sum from the current node to its parent, considering only one of the subtrees (either left or right) to extend the path. While calculating the left and right subtree path sums, we also ensure that we take the maximum with 0 to avoid negative sums, indicating that we should not include the subtree path in the calculation of the maximum path at the current node.

- \ No newline at end of file + diff --git a/hints/binary-tree-right-side-view.md b/hints/binary-tree-right-side-view.md index a02d2c585..c1ad99fe3 100644 --- a/hints/binary-tree-right-side-view.md +++ b/hints/binary-tree-right-side-view.md @@ -28,4 +28,4 @@

We can use the Breadth First Search (BFS) algorithm to traverse the tree level by level. Once we completely visit a level, we take the last node of that level and add it to the result array. After processing all levels, we return the result.

- \ No newline at end of file + diff --git a/hints/burst-balloons.md b/hints/burst-balloons.md index c553a4f8e..10e8011cb 100644 --- a/hints/burst-balloons.md +++ b/hints/burst-balloons.md @@ -36,4 +36,4 @@

We can use memoization to cache the results of recursive calls and avoid redundant calculations. A hash map or a 2D array can be used to store results since the recursive function parameters l and r are within the range of the input array size.

- \ No newline at end of file + diff --git a/hints/buy-and-sell-crypto-with-cooldown.md b/hints/buy-and-sell-crypto-with-cooldown.md index 84988bd54..b62688da9 100644 --- a/hints/buy-and-sell-crypto-with-cooldown.md +++ b/hints/buy-and-sell-crypto-with-cooldown.md @@ -36,4 +36,4 @@

We can use memoization to cache the results of recursive calls and avoid recalculations. A hash map or a 2D array can be used to store these results.

- \ No newline at end of file + diff --git a/hints/buy-and-sell-crypto.md b/hints/buy-and-sell-crypto.md index 0597ae13a..19f125d59 100644 --- a/hints/buy-and-sell-crypto.md +++ b/hints/buy-and-sell-crypto.md @@ -36,4 +36,4 @@

We are trying to maximize profit = sell - buy. If the current i is the sell value, we want to choose the minimum buy value to the left of i to maximize the profit. The result will be the maximum profit among all. However, if all profits are negative, we can return 0 since we are allowed to skip doing transaction.

- \ No newline at end of file + diff --git a/hints/car-fleet.md b/hints/car-fleet.md index 23c63e134..350b5ee6a 100644 --- a/hints/car-fleet.md +++ b/hints/car-fleet.md @@ -36,4 +36,4 @@

We can use a stack to maintain the times of the fleets. As we iterate through the array (sorted in descending order of positions), we compute the time for each car to reach the target and check if it can form a fleet with the car ahead. If the current car's time is less than or equal to the top of the stack, it joins the same fleet. Otherwise, it forms a new fleet, and we push its time onto the stack. The length of the stack at the end represents the total number of fleets formed.

- \ No newline at end of file + diff --git a/hints/cheapest-flight-path.md b/hints/cheapest-flight-path.md index b42275442..865960823 100644 --- a/hints/cheapest-flight-path.md +++ b/hints/cheapest-flight-path.md @@ -28,4 +28,4 @@

At each level of iteration, we go through the given flights and use them to update the price array with the minimum costs compared to the previous level. We use a temporary prices array at each level to store the updated costs. After completing all levels, we return the result stored in prices[dst]. If that value is Infinity, we return -1 instead.

- \ No newline at end of file + diff --git a/hints/climbing-stairs.md b/hints/climbing-stairs.md index 78e5ce36b..72d35d8a4 100644 --- a/hints/climbing-stairs.md +++ b/hints/climbing-stairs.md @@ -36,4 +36,4 @@

At each recursion, we perform two recursive calls: one for climbing one step and another for climbing two steps. The minimum return value between the two is the result for the current recursion. The base condition is to return 0 if i == n. This is a one-dimensional dynamic programming problem, which can be further optimized using more advanced techniques.

- \ No newline at end of file + diff --git a/hints/clone-graph.md b/hints/clone-graph.md index 1e332bf4a..337204291 100644 --- a/hints/clone-graph.md +++ b/hints/clone-graph.md @@ -28,4 +28,4 @@

We stop this recursive path when we encounter a node that has already been cloned or visited. This DFS approach creates an exact clone of the given graph, and we return the clone of the given node.

- \ No newline at end of file + diff --git a/hints/coin-change-ii.md b/hints/coin-change-ii.md index 3f18a6318..dadc9b273 100644 --- a/hints/coin-change-ii.md +++ b/hints/coin-change-ii.md @@ -36,4 +36,4 @@

We can use memoization to cache the results of recursive calls and avoid redundant computations. A hash map or a 2D array can be used to store these results.

- \ No newline at end of file + diff --git a/hints/coin-change.md b/hints/coin-change.md index c8522e7cb..15bc86ed2 100644 --- a/hints/coin-change.md +++ b/hints/coin-change.md @@ -28,4 +28,4 @@

We can use memoization to avoid the repeated work of calculating the result for each recursive call. A hash map or an array of size t can be used to cache the computed values for a specific amount. At each recursion step, we iterate over every coin and extend only the valid paths. If a result has already been computed, we return it from the cache instead of recalculating it.

- \ No newline at end of file + diff --git a/hints/combination-target-sum-ii.md b/hints/combination-target-sum-ii.md index ef8aabd56..4d2115d9c 100644 --- a/hints/combination-target-sum-ii.md +++ b/hints/combination-target-sum-ii.md @@ -28,4 +28,4 @@

We recursively traverse the given array starting at index i, with a variable sum representing the sum of the picked elements. We explore elements from i to the end of the array and extend the recursive path if adding the current element results in sum <= target. When we processed an element, we backtrack and proceed to the next distinct element, skipping any similar elements in the middle to avoid duplicate combinations.

- \ No newline at end of file + diff --git a/hints/combination-target-sum.md b/hints/combination-target-sum.md index 1eca71f3f..c4cd75c35 100644 --- a/hints/combination-target-sum.md +++ b/hints/combination-target-sum.md @@ -28,4 +28,4 @@

We recursively traverse the array starting from index i. At each step, we select an element from i to the end of the array. We extend the recursive path with elements where sum <= target after including that element. This creates multiple recursive paths, and we append the current list to the result whenever the base condition is met.

- \ No newline at end of file + diff --git a/hints/combinations-of-a-phone-number.md b/hints/combinations-of-a-phone-number.md index 7154a859d..f500d84c5 100644 --- a/hints/combinations-of-a-phone-number.md +++ b/hints/combinations-of-a-phone-number.md @@ -28,4 +28,4 @@

We initialize an empty string that represents the choices of the characters throughout the current recursive path. When the index i reaches the end of the string, we add the current string to the result list and return.

- \ No newline at end of file + diff --git a/hints/copy-linked-list-with-random-pointer.md b/hints/copy-linked-list-with-random-pointer.md index 73a1417ae..05dc7eec3 100644 --- a/hints/copy-linked-list-with-random-pointer.md +++ b/hints/copy-linked-list-with-random-pointer.md @@ -28,4 +28,4 @@

We can use a hash data structure, such as a hash map, which takes O(1) time to retrieve data. This can help by mapping the original nodes to their corresponding copies. This way, we can easily retrieve the copy of any node and assign the random pointers in a subsequent pass after creating copies of all nodes in the first pass.

- \ No newline at end of file + diff --git a/hints/count-connected-components.md b/hints/count-connected-components.md index 4998f22ad..50dc73666 100644 --- a/hints/count-connected-components.md +++ b/hints/count-connected-components.md @@ -28,4 +28,4 @@

We create an object of the DSU and initialize the result variable res = n, which indicates that there are n components initially. We then iterate through the given edges. For each edge, we attempt to connect the nodes using the union function of the DSU. If the union is successful, we decrement res; otherwise, we continue. Finally, we return res as the number of components.

- \ No newline at end of file + diff --git a/hints/count-good-nodes-in-binary-tree.md b/hints/count-good-nodes-in-binary-tree.md index 39e8783d5..f9296abf7 100644 --- a/hints/count-good-nodes-in-binary-tree.md +++ b/hints/count-good-nodes-in-binary-tree.md @@ -28,4 +28,4 @@

While traversing the tree, we should track the maximum value along the current path. This allows us to determine whether the nodes we encounter are good. We can use a global variable to count the number of good nodes.

- \ No newline at end of file + diff --git a/hints/count-number-of-islands.md b/hints/count-number-of-islands.md index a8cb92e6f..a7c1d8537 100644 --- a/hints/count-number-of-islands.md +++ b/hints/count-number-of-islands.md @@ -20,4 +20,4 @@

We can use the Depth First Search (DFS) algorithm to traverse each group independently. We iterate through each cell of the grid. When we encounter a 1, we perform a DFS starting at that cell and recursively visit every other 1 that is reachable. During this process, we mark the visited 1's as 0 to ensure we don't revisit them, as they belong to the same group. The number of groups corresponds to the number of islands.

- \ No newline at end of file + diff --git a/hints/count-paths.md b/hints/count-paths.md index 299793547..5f8bd1d96 100644 --- a/hints/count-paths.md +++ b/hints/count-paths.md @@ -36,4 +36,4 @@

We can use memoization to cache the results of recursive calls and avoid recalculations. A hash map or a 2D array can be used to store these results.

- \ No newline at end of file + diff --git a/hints/count-squares.md b/hints/count-squares.md index 69b289bdb..9e632b81f 100644 --- a/hints/count-squares.md +++ b/hints/count-squares.md @@ -36,4 +36,4 @@

The other two points are point1 (x, qy) and point2 (qx, y). For counting, we simply add count of point1 * count of point2 to the result res.

- \ No newline at end of file + diff --git a/hints/count-subsequences.md b/hints/count-subsequences.md index 53a37dcee..39e022cdd 100644 --- a/hints/count-subsequences.md +++ b/hints/count-subsequences.md @@ -36,4 +36,4 @@

We can use memoization to cache the results of recursive calls and avoid redundant computations. A hash map or a 2D array can be used to store these results.

- \ No newline at end of file + diff --git a/hints/counting-bits.md b/hints/counting-bits.md index 45188a165..90f0fb120 100644 --- a/hints/counting-bits.md +++ b/hints/counting-bits.md @@ -28,4 +28,4 @@

We find an offset for the current number based on the number before offset positions. The dynamic programming relation is dp[i] = 1 + dp[i - offset], where dp[i] represents the number of set bits in i. The offset starts at 1 and updates when encountering a power of 2. To simplify the power of 2 check, if offset * 2 equals the current number, we update offset to the current number.

- \ No newline at end of file + diff --git a/hints/course-schedule-ii.md b/hints/course-schedule-ii.md index e187980f9..e551ae0b8 100644 --- a/hints/course-schedule-ii.md +++ b/hints/course-schedule-ii.md @@ -28,4 +28,4 @@

We compute the indegrees of all the nodes. Then, we perform a BFS starting from the nodes that have no parents (indegree[node] == 0). At each level, we traverse these nodes, decrement the indegree of their child nodes, and append those child nodes to the queue if their indegree becomes 0. We only append nodes whose indegree is 0 or becomes 0 during the BFS to our result array. If the length of the result array is not equal to the number of courses, we return an empty array.

- \ No newline at end of file + diff --git a/hints/course-schedule.md b/hints/course-schedule.md index 1392ac134..ac08d3837 100644 --- a/hints/course-schedule.md +++ b/hints/course-schedule.md @@ -28,4 +28,4 @@

We run a DFS starting from each course by initializing a hash set, path, to track the nodes in the current DFS call. At each step of the DFS, we return false if the current node is already in the path, indicating a cycle. We recursively traverse the neighbors of the current node, and if any of the neighbor DFS calls detect a cycle, we immediately return false. Additionally, we clear the neighbors list of a node when no cycle is found from that node to avoid revisiting those paths again.

- \ No newline at end of file + diff --git a/hints/daily-temperatures.md b/hints/daily-temperatures.md index 64c1a171e..bd589fb24 100644 --- a/hints/daily-temperatures.md +++ b/hints/daily-temperatures.md @@ -36,4 +36,4 @@

In the array [2, 1, 1, 3], we don't perform any pop operations while processing [2, 1, 1] because these elements are already in decreasing order. However, when we reach 3, we pop elements from the stack until the top element of the stack is no longer less than the current element. For each popped element, we compute the difference between the indices and store it in the position corresponding to the popped element.

- \ No newline at end of file + diff --git a/hints/decode-ways.md b/hints/decode-ways.md index 56c40d46a..411886000 100644 --- a/hints/decode-ways.md +++ b/hints/decode-ways.md @@ -36,4 +36,4 @@

The base condition is to return 1 if i goes out of bounds. If the current digit is '0', return 0, as no character maps to '0', making the string invalid. Use memoization to avoid repeated work by caching recursion results in an array or hash map and returning the stored value when the result is already calculated.

- \ No newline at end of file + diff --git a/hints/depth-of-binary-tree.md b/hints/depth-of-binary-tree.md index 51538e4c8..8aafe8820 100644 --- a/hints/depth-of-binary-tree.md +++ b/hints/depth-of-binary-tree.md @@ -28,4 +28,4 @@

The +1 accounts for the current node, as it contributes to the current depth in the recursion call. We pass the maximum depth from the current node's left and right subtrees to its parent because the current maximum depth determines the longest path from the parent to a leaf node through this subtree.

- \ No newline at end of file + diff --git a/hints/design-twitter-feed.md b/hints/design-twitter-feed.md index 8fc7ab4f8..e108c6ffb 100644 --- a/hints/design-twitter-feed.md +++ b/hints/design-twitter-feed.md @@ -36,4 +36,4 @@

We can use a Max-Heap to efficiently retrieve the top 10 most recent tweets. For each followee and the userId, we insert their most recent tweet from the tweetMap into the heap, along with the tweet's count and its index in the tweet list. This index is necessary because after processing a tweet, we can insert the next most recent tweet from the same user's list. By always pushing and popping tweets from the heap, we ensure that the 10 most recent tweets are retrieved without sorting all tweets.

- \ No newline at end of file + diff --git a/hints/design-word-search-data-structure.md b/hints/design-word-search-data-structure.md index db99718c2..d647440ce 100644 --- a/hints/design-word-search-data-structure.md +++ b/hints/design-word-search-data-structure.md @@ -28,4 +28,4 @@

We traverse the word with index i, starting at the root of the Trie. For normal characters, we search as usual. When encountering a dot ('.'), we try all possible characters by recursively extending the search in each direction. If any path leads to a valid word, we return true; otherwise, we return false. Although we try all paths for a dot, the time complexity is still O(n) because there are at most two dots ('.') in the word, making the complexity O((26^2) * n).

- \ No newline at end of file + diff --git a/hints/eating-bananas.md b/hints/eating-bananas.md index 41bb76a40..69410d87f 100644 --- a/hints/eating-bananas.md +++ b/hints/eating-bananas.md @@ -44,4 +44,4 @@

Rather than linearly scanning, we can use binary search. The upper bound of k is max(piles) and since we are only dealing with positive values, the lower bound is 1. The search space of our binary search is 1 through max(piles). This allows us to find the smallest possible k using binary search.

- \ No newline at end of file + diff --git a/hints/edit-distance.md b/hints/edit-distance.md index 277fa3cbe..7f7a88d8a 100644 --- a/hints/edit-distance.md +++ b/hints/edit-distance.md @@ -36,4 +36,4 @@

We can use memoization to cache the results and avoid redundant calculations. A hash map or a 2D array can be used to store these results.

- \ No newline at end of file + diff --git a/hints/evaluate-reverse-polish-notation.md b/hints/evaluate-reverse-polish-notation.md index 8e63e0dfd..c58d671b3 100644 --- a/hints/evaluate-reverse-polish-notation.md +++ b/hints/evaluate-reverse-polish-notation.md @@ -28,4 +28,4 @@

As the array has postfix expression, stack helps us to maintain the correct order of operations by ensuring that we always use the most recent operands (those closest to the operator) when performing the operation. After the iteration, the final result is left in the stack.

- \ No newline at end of file + diff --git a/hints/find-duplicate-integer.md b/hints/find-duplicate-integer.md index e399acf89..284a71781 100644 --- a/hints/find-duplicate-integer.md +++ b/hints/find-duplicate-integer.md @@ -36,4 +36,4 @@

For example, in the array [2, 1, 2, 3], where 2 is repeated, we mark the index corresponding to each element as negative. If we encounter a number whose corresponding position is already negative, it means the number is a duplicate, and we return it.

- \ No newline at end of file + diff --git a/hints/find-median-in-a-data-stream.md b/hints/find-median-in-a-data-stream.md index ea07e7519..fd0b89e02 100644 --- a/hints/find-median-in-a-data-stream.md +++ b/hints/find-median-in-a-data-stream.md @@ -36,4 +36,4 @@

We initialize a Max-Heap and a Min-Heap. When adding an element, if the element is greater than the minimum element of the Min-Heap, we push it into the Min-Heap; otherwise, we push it into the Max-Heap. If the size difference between the two heaps becomes greater than one, we rebalance them by popping an element from the larger heap and pushing it into the smaller heap. This process ensures that the elements are evenly distributed between the two heaps, allowing us to retrieve the middle element or elements in O(1) time.

- \ No newline at end of file + diff --git a/hints/find-minimum-in-rotated-sorted-array.md b/hints/find-minimum-in-rotated-sorted-array.md index e6153047e..b0f9559ae 100644 --- a/hints/find-minimum-in-rotated-sorted-array.md +++ b/hints/find-minimum-in-rotated-sorted-array.md @@ -37,4 +37,4 @@ There will be two conditions where l and mid will be in left sorted segment or mid and r will be in right sorted segement. If l and mid in sorted segement, then nums[l] < nums[mid] and the minimum element will be in the right part. If mid and r in sorted segment, then nums[mid] < nums[r] and the minimum element will be in the left part. After the binary search we end up finding the minimum element.

- \ No newline at end of file + diff --git a/hints/find-target-in-rotated-sorted-array.md b/hints/find-target-in-rotated-sorted-array.md index 7133b3821..504264627 100644 --- a/hints/find-target-in-rotated-sorted-array.md +++ b/hints/find-target-in-rotated-sorted-array.md @@ -37,4 +37,4 @@ There are two cases: l and mid belong to the left sorted segment, or mid and r belong to the right sorted segment. If l and mid are in the same segment, nums[l] < nums[mid], so the pivot index must lie in the right part. If mid and r are in the same segment, nums[mid] < nums[r], so the pivot index must lie in the left part. After the binary search, we eventually find the pivot index. Once the pivot is found, it's straightforward to select the segment where the target lies and perform a binary search on that segement to find its position. If we don't find the target, we return -1.

- \ No newline at end of file + diff --git a/hints/foreign-dictionary.md b/hints/foreign-dictionary.md index 9837818a0..e7c30969c 100644 --- a/hints/foreign-dictionary.md +++ b/hints/foreign-dictionary.md @@ -36,4 +36,4 @@

When we visit a node and its children and don't find a cycle, we mark the node as False in the map and append it to the result, treating this as a post-order traversal. If we find a cycle, we return an empty string; otherwise, we return the result list.

- \ No newline at end of file + diff --git a/hints/gas-station.md b/hints/gas-station.md index 52464072d..7c961b748 100644 --- a/hints/gas-station.md +++ b/hints/gas-station.md @@ -28,4 +28,4 @@

We start with a variable total to track the gas balance and initialize the result index to 0. As we iterate through the array with index i, we accumulate the difference (gas[i] - cost[i]). If total becomes negative at any index, we reset it to 0 and update the result index to (i + 1).

- \ No newline at end of file + diff --git a/hints/generate-parentheses.md b/hints/generate-parentheses.md index 454a10e81..61ab3d1bf 100644 --- a/hints/generate-parentheses.md +++ b/hints/generate-parentheses.md @@ -28,4 +28,4 @@

When the count of closing brackets exceeds the count of opening brackets, the string becomes invalid. Therefore, we can maintain two variables, open and close, to track the number of opening and closing brackets. We avoid exploring paths where close > open. Once the string length reaches 2n, we add it to the result.

- \ No newline at end of file + diff --git a/hints/hand-of-straights.md b/hints/hand-of-straights.md index 1a35e0287..25ebfe9c8 100644 --- a/hints/hand-of-straights.md +++ b/hints/hand-of-straights.md @@ -28,4 +28,4 @@

Sorting ensures we start with the smallest available value, while the hash map helps track element availability using frequency counts. At each step, we pick the smallest available value x and attempt to form a group from x to x + groupSize - 1. If all elements are present based on their frequency counts, we decrement their counts as we iterate. If we successfully form all groups, we return true; otherwise, we return false.

- \ No newline at end of file + diff --git a/hints/house-robber-ii.md b/hints/house-robber-ii.md index 1cc52b34d..4d17802c8 100644 --- a/hints/house-robber-ii.md +++ b/hints/house-robber-ii.md @@ -36,4 +36,4 @@

We can create two arrays from the given array. The first will include houses from the first house to the second-to-last house, and the second will include houses from the second house to the last house. We can run the recursive function on both arrays independently and return the maximum result between the two. Advanced techniques such as bottom-up dynamic programming can further optimize the solution.

- \ No newline at end of file + diff --git a/hints/house-robber.md b/hints/house-robber.md index 2a1e5d7c8..13b851233 100644 --- a/hints/house-robber.md +++ b/hints/house-robber.md @@ -36,4 +36,4 @@

We can use Memoization to avoid recalculating the result multiple times for a recursive call. By storing the result of each recursive call in a hash map or an array using i as the parameter, we can immediately return the stored result if the recursion is called with the same i value again. Further optimization can be achieved using advanced techniques like Bottom-Up dynamic programming.

- \ No newline at end of file + diff --git a/hints/implement-prefix-tree.md b/hints/implement-prefix-tree.md index f2908be7f..f118b254f 100644 --- a/hints/implement-prefix-tree.md +++ b/hints/implement-prefix-tree.md @@ -28,4 +28,4 @@

Searching for a word is similar to inserting, but instead of creating new nodes, we return false if we don't find a character in the path while iterating or if the end-of-word marker is not set to true when we reach the end of the word.

- \ No newline at end of file + diff --git a/hints/insert-new-interval.md b/hints/insert-new-interval.md index a807b4c61..b287929f7 100644 --- a/hints/insert-new-interval.md +++ b/hints/insert-new-interval.md @@ -28,4 +28,4 @@

We iterate through the remaining intervals, updating the new interval if its end value is greater than or equal to the current interval's start value. We adjust the start and end of the new interval to the minimum and maximum values, respectively. After this, any remaining intervals are appended to the output list, and we return the result.

- \ No newline at end of file + diff --git a/hints/interleaving-string.md b/hints/interleaving-string.md index 16a8c100a..b4811f4e2 100644 --- a/hints/interleaving-string.md +++ b/hints/interleaving-string.md @@ -36,4 +36,4 @@

We can use memoization to cache the results of recursive calls and avoid redundant computations. Treating i and j as states, we can use a hash map or a 2D array to store the results.

- \ No newline at end of file + diff --git a/hints/invert-a-binary-tree.md b/hints/invert-a-binary-tree.md index eacb6582d..596ab0506 100644 --- a/hints/invert-a-binary-tree.md +++ b/hints/invert-a-binary-tree.md @@ -20,4 +20,4 @@

We can use the Depth First Search (DFS) algorithm. At each node, we swap its left and right children by swapping their pointers. This inverts the current node, but every node in the tree also needs to be inverted. To achieve this, we recursively visit the left and right children and perform the same operation. If the current node is null, we simply return.

- \ No newline at end of file + diff --git a/hints/is-anagram.md b/hints/is-anagram.md index 8454011d2..e775554df 100644 --- a/hints/is-anagram.md +++ b/hints/is-anagram.md @@ -28,4 +28,4 @@

We can just consider maintaining the frequency of each character. We can do this by having two separate hash tables for the two strings. Then, we can check whether the frequency of each character in string s is equal to that in string t and vice versa.

- \ No newline at end of file + diff --git a/hints/is-palindrome.md b/hints/is-palindrome.md index 697108060..e7eaef8e9 100644 --- a/hints/is-palindrome.md +++ b/hints/is-palindrome.md @@ -28,4 +28,4 @@

A palindrome string is a string that is read the same from the start as well as from the end. This means the character at the start should match the character at the end at the same index. We can use the two pointer algorithm to do this efficiently.

- \ No newline at end of file + diff --git a/hints/islands-and-treasure.md b/hints/islands-and-treasure.md index b7ef502de..2234fc59f 100644 --- a/hints/islands-and-treasure.md +++ b/hints/islands-and-treasure.md @@ -28,4 +28,4 @@

We insert all the cells (row, col) that represent the treasure chests into the queue. Then, we process the cells level by level, handling all the current cells in the queue at once. For each cell, we mark it as visited and store the current level value as the distance at that cell. We then try to add the neighboring cells (adjacent cells) to the queue, but only if they have not been visited and are land cells.

- \ No newline at end of file + diff --git a/hints/jump-game-ii.md b/hints/jump-game-ii.md index 4c7c41e30..54d12dd0b 100644 --- a/hints/jump-game-ii.md +++ b/hints/jump-game-ii.md @@ -36,4 +36,4 @@

The number of steps taken represents the minimum steps required to reach the last index, as it is guaranteed that we can reach it.

- \ No newline at end of file + diff --git a/hints/jump-game.md b/hints/jump-game.md index 91e7092c9..990af601a 100644 --- a/hints/jump-game.md +++ b/hints/jump-game.md @@ -36,4 +36,4 @@

To determine if we can reach the last index, the goal should be 0 after the iteration. Otherwise, reaching the last index is not possible.

- \ No newline at end of file + diff --git a/hints/k-closest-points-to-origin.md b/hints/k-closest-points-to-origin.md index 277e19160..d0676f0de 100644 --- a/hints/k-closest-points-to-origin.md +++ b/hints/k-closest-points-to-origin.md @@ -28,4 +28,4 @@

We initialize a Max-Heap that orders points based on their distances from the origin. Starting with an empty heap, we iterate through the array of points, inserting each point into the heap. If the size of the heap exceeds k, we remove the farthest point (the maximum element in the heap). After completing the iteration, the heap will contain the k closest points to the origin. Finally, we convert the heap into an array and return it.

- \ No newline at end of file + diff --git a/hints/kth-largest-element-in-an-array.md b/hints/kth-largest-element-in-an-array.md index 8d68feba3..1a3a12263 100644 --- a/hints/kth-largest-element-in-an-array.md +++ b/hints/kth-largest-element-in-an-array.md @@ -36,4 +36,4 @@

We initialize an empty Min-Heap. We iterate through the array and add elements to the heap. When the size of the heap exceeds k, we pop from the heap and continue. After the iteration, the top element of the heap is the k-th largest element.

- \ No newline at end of file + diff --git a/hints/kth-largest-integer-in-a-stream.md b/hints/kth-largest-integer-in-a-stream.md index 2d7d952e8..232b94f16 100644 --- a/hints/kth-largest-integer-in-a-stream.md +++ b/hints/kth-largest-integer-in-a-stream.md @@ -36,4 +36,4 @@

We initialize a Min-Heap with the elements of the input array. When the add() function is called, we insert the new element into the heap. If the heap size exceeds k, we remove the smallest element (the root of the heap). Finally, the top element of the heap represents the k-th largest element and is returned.

- \ No newline at end of file + diff --git a/hints/kth-smallest-integer-in-bst.md b/hints/kth-smallest-integer-in-bst.md index 2af2e63de..8943884a3 100644 --- a/hints/kth-smallest-integer-in-bst.md +++ b/hints/kth-smallest-integer-in-bst.md @@ -28,4 +28,4 @@

We keep a counter variable cnt to track the position of the current node in the ascending order of values. When cnt == k, we store the current node's value in a global variable and return. This allows us to identify and return the k-th smallest element during the in-order traversal.

- \ No newline at end of file + diff --git a/hints/largest-rectangle-in-histogram.md b/hints/largest-rectangle-in-histogram.md index 35976b385..c4841aa48 100644 --- a/hints/largest-rectangle-in-histogram.md +++ b/hints/largest-rectangle-in-histogram.md @@ -36,4 +36,4 @@

We can use a stack with a monotonically strictly increasing nature, but instead of storing values, we store indices in the stack and perform operations based on the values at those indices. The top of the stack will represent the smaller bar that we encounter while extending the current bar. To find the left and right boundaries, we perform this algorithm from left to right and vice versa, storing the boundaries. Then, we iterate through the array to find the area for each bar and return the maximum area we get.

- \ No newline at end of file + diff --git a/hints/last-stone-weight.md b/hints/last-stone-weight.md index 5404da55d..9422e4480 100644 --- a/hints/last-stone-weight.md +++ b/hints/last-stone-weight.md @@ -20,4 +20,4 @@

We can use a Max-Heap, which allows us to retrieve the maximum element in O(1) time. We initially insert all the weights into the Max-Heap, which takes O(logn) time per insertion. We then simulate the process until only one or no element remains in the Max-Heap. At each step, we pop two elements from the Max-Heap which takes O(logn) time. If they are equal, we do not insert anything back into the heap and continue. Otherwise, we insert the difference of the two elements back into the heap.

- \ No newline at end of file + diff --git a/hints/level-order-traversal-of-binary-tree.md b/hints/level-order-traversal-of-binary-tree.md index e59c454b5..3f65a426c 100644 --- a/hints/level-order-traversal-of-binary-tree.md +++ b/hints/level-order-traversal-of-binary-tree.md @@ -28,4 +28,4 @@

The number of times we iterate the queue corresponds to the number of levels in the tree. At each step, we pop all nodes from the queue for the current level and add them collectively to the resultant array. This ensures that we capture all nodes at each level of the tree.

- \ No newline at end of file + diff --git a/hints/linked-list-cycle-detection.md b/hints/linked-list-cycle-detection.md index 04c8f4623..79ee9808b 100644 --- a/hints/linked-list-cycle-detection.md +++ b/hints/linked-list-cycle-detection.md @@ -28,4 +28,4 @@

When there is no cycle in the list, the loop ends when the fast pointer becomes null. If a cycle exists, the fast pointer moves faster and continuously loops through the cycle. With each step, it reduces the gap between itself and the slow pointer by one node. For example, if the gap is 10, the slow pointer moves by 1, increasing the gap to 11, while the fast pointer moves by 2, reducing the gap to 9. This process continues until the fast pointer catches up to the slow pointer, confirming a cycle.

- \ No newline at end of file + diff --git a/hints/longest-common-subsequence.md b/hints/longest-common-subsequence.md index d25df25e5..a874fdde1 100644 --- a/hints/longest-common-subsequence.md +++ b/hints/longest-common-subsequence.md @@ -28,4 +28,4 @@

We return 0 if either index goes out of bounds. To optimize, we can use memoization to cache recursive call results and avoid redundant calculations. A hash map or a 2D array can be used to store these results.

- \ No newline at end of file + diff --git a/hints/longest-consecutive-sequence.md b/hints/longest-consecutive-sequence.md index 7065b8463..151b9f32b 100644 --- a/hints/longest-consecutive-sequence.md +++ b/hints/longest-consecutive-sequence.md @@ -28,4 +28,4 @@

We can consider a number num as the start of a sequence if and only if num - 1 does not exist in the given array. We iterate through the array and only start building the sequence if it is the start of a sequence. This avoids repeated work. We can use a hash set for O(1) lookups by converting the array to a hash set.

- \ No newline at end of file + diff --git a/hints/longest-increasing-path-in-matrix.md b/hints/longest-increasing-path-in-matrix.md index 8008fe73f..e202e0205 100644 --- a/hints/longest-increasing-path-in-matrix.md +++ b/hints/longest-increasing-path-in-matrix.md @@ -20,4 +20,4 @@

We can use memoization to cache the results of recursive calls and avoid redundant computations. A hash map or a 2D array can be used to store these results.

- \ No newline at end of file + diff --git a/hints/longest-increasing-subsequence.md b/hints/longest-increasing-subsequence.md index 36a4e3e78..f63de4455 100644 --- a/hints/longest-increasing-subsequence.md +++ b/hints/longest-increasing-subsequence.md @@ -44,4 +44,4 @@

The time complexity of this approach is exponential. We can use memoization to store results of recursive calls and avoid recalculations. A hash map or a 2D array can be used to cache these results.

- \ No newline at end of file + diff --git a/hints/longest-palindromic-substring.md b/hints/longest-palindromic-substring.md index 9d4dc9eb9..d9637bb74 100644 --- a/hints/longest-palindromic-substring.md +++ b/hints/longest-palindromic-substring.md @@ -36,4 +36,4 @@

For an even-length palindrome, consider expanding from indices i and i + 1. This two-pointer approach, extending from the center of the palindrome, will help find all palindromic substrings in the given string. Update the two result variables and return the substring starting at res with a length of resLen.

- \ No newline at end of file + diff --git a/hints/longest-repeating-substring-with-replacement.md b/hints/longest-repeating-substring-with-replacement.md index 808ff742f..7cd03766b 100644 --- a/hints/longest-repeating-substring-with-replacement.md +++ b/hints/longest-repeating-substring-with-replacement.md @@ -36,4 +36,4 @@

We can use the sliding window approach. The window size will be dynamic, and we will shrink the window when the number of replacements exceeds k. The result will be the maximum window size observed at each iteration.

- \ No newline at end of file + diff --git a/hints/longest-substring-without-duplicates.md b/hints/longest-substring-without-duplicates.md index 42c7ca28a..3ae36748f 100644 --- a/hints/longest-substring-without-duplicates.md +++ b/hints/longest-substring-without-duplicates.md @@ -28,4 +28,4 @@

We can iterate through the given string with index r as the right boundary and l as the left boundary of the window. We use a hash set to check if the character is present in the window or not. When we encounter a character at index r that is already present in the window, we shrink the window by incrementing the l pointer until the window no longer contains any duplicates. Also, we remove characters from the hash set that are excluded from the window as the l pointer moves. At each iteration, we update the result with the length of the current window, r - l + 1, if this length is greater than the current result.

- \ No newline at end of file + diff --git a/hints/lowest-common-ancestor-in-binary-search-tree.md b/hints/lowest-common-ancestor-in-binary-search-tree.md index b7357e2b3..780244839 100644 --- a/hints/lowest-common-ancestor-in-binary-search-tree.md +++ b/hints/lowest-common-ancestor-in-binary-search-tree.md @@ -36,4 +36,4 @@

The LCA can also be one of the nodes, p or q, if the current node is equal to either of them. This is because if we encounter either p or q during the traversal, that node is the LCA.

- \ No newline at end of file + diff --git a/hints/lru-cache.md b/hints/lru-cache.md index 7db2c01ef..34a265e39 100644 --- a/hints/lru-cache.md +++ b/hints/lru-cache.md @@ -44,4 +44,4 @@

We can use a doubly linked list where key-value pairs are stored as nodes, with the least recently used (LRU) node at the head and the most recently used (MRU) node at the tail. Whenever a key is accessed using get() or put(), we remove the corresponding node and reinsert it at the tail. When the cache reaches its capacity, we remove the LRU node from the head of the list. Additionally, we use a hash map to store each key and the corresponding address of its node, enabling efficient operations in O(1) time.

- \ No newline at end of file + diff --git a/hints/max-area-of-island.md b/hints/max-area-of-island.md index a8502e52a..ebcfe2c4d 100644 --- a/hints/max-area-of-island.md +++ b/hints/max-area-of-island.md @@ -28,4 +28,4 @@

We traverse the grid, and when we encounter a 1, we initialize a variable area. We then start a DFS from that cell to visit all connected 1's recursively, marking them as 0 to indicate they are visited. At each recursion step, we increment area. After completing the DFS, we update maxArea, which tracks the maximum area of an island in the grid, if maxArea < area. Finally, after traversing the grid, we return maxArea.

- \ No newline at end of file + diff --git a/hints/max-water-container.md b/hints/max-water-container.md index 02fb8859b..e70a10c7a 100644 --- a/hints/max-water-container.md +++ b/hints/max-water-container.md @@ -36,4 +36,4 @@

In the formula, the amount of water depends only on the minimum height. Therefore, it is appropriate to replace the smaller height value.

- \ No newline at end of file + diff --git a/hints/maximum-product-subarray.md b/hints/maximum-product-subarray.md index d46997d32..67d0db63c 100644 --- a/hints/maximum-product-subarray.md +++ b/hints/maximum-product-subarray.md @@ -28,4 +28,4 @@

We maintain both the minimum and maximum product values and update them when introducing a new element by considering three cases: starting a new subarray, multiplying with the previous max product, or multiplying with the previous min product. The max product is updated to the maximum of these three, while the min product is updated to the minimum. We also track a global max product for the result. This approach is known as Kadane's algorithm.

- \ No newline at end of file + diff --git a/hints/maximum-subarray.md b/hints/maximum-subarray.md index f8071b628..c536cb675 100644 --- a/hints/maximum-subarray.md +++ b/hints/maximum-subarray.md @@ -36,4 +36,4 @@

This algorithm is known as Kadane's algorithm.

- \ No newline at end of file + diff --git a/hints/median-of-two-sorted-arrays.md b/hints/median-of-two-sorted-arrays.md index bfbe9c032..72202ba47 100644 --- a/hints/median-of-two-sorted-arrays.md +++ b/hints/median-of-two-sorted-arrays.md @@ -44,4 +44,4 @@

For example, consider the arrays A = [1, 2, 3, 4, 5] and B = [1, 2, 3, 4, 5, 6, 7, 8]. When we select x = 2, we take 4 elements from array B. However, this partition is not valid because value 4 from the left partition of array B is greater than the value 3 from the right partition of array A. So, we should try to take more elements from array A to make the partition valid. Binary search will eventually help us find a valid partition.

- \ No newline at end of file + diff --git a/hints/meeting-schedule-ii.md b/hints/meeting-schedule-ii.md index 1342e260f..40b3cd26f 100644 --- a/hints/meeting-schedule-ii.md +++ b/hints/meeting-schedule-ii.md @@ -36,4 +36,4 @@

Then, we increment e and decrement count as a meeting has ended. At each step, we update the result with the maximum value of active meetings stored in count.

- \ No newline at end of file + diff --git a/hints/meeting-schedule.md b/hints/meeting-schedule.md index 0216b7b66..3f56c079b 100644 --- a/hints/meeting-schedule.md +++ b/hints/meeting-schedule.md @@ -28,4 +28,4 @@

We should sort the given intervals based on their start values, as this makes it easier to check for overlaps by comparing adjacent intervals. We then iterate through the intervals from left to right and return false if any adjacent intervals overlap.

- \ No newline at end of file + diff --git a/hints/merge-intervals.md b/hints/merge-intervals.md index 89af36fe5..829f38ed8 100644 --- a/hints/merge-intervals.md +++ b/hints/merge-intervals.md @@ -36,4 +36,4 @@

The two cases are: if the current interval overlaps with the last appended interval, we update its end value to the maximum of both intervals' end values and continue. Otherwise, we append the current interval and proceed.

- \ No newline at end of file + diff --git a/hints/merge-k-sorted-linked-lists.md b/hints/merge-k-sorted-linked-lists.md index aec8ab73a..e731fbeb0 100644 --- a/hints/merge-k-sorted-linked-lists.md +++ b/hints/merge-k-sorted-linked-lists.md @@ -28,4 +28,4 @@

We iterate through the list array with index i, starting at i = 1. We merge the linked lists using mergeTwoLists(lists[i], lists[i - 1]), which returns the head of the merged list. This head is stored in lists[i], and the process continues. Finally, the merged list is obtained at the last index, and we return its head.

- \ No newline at end of file + diff --git a/hints/merge-triplets-to-form-target.md b/hints/merge-triplets-to-form-target.md index fd475aa48..04490ad72 100644 --- a/hints/merge-triplets-to-form-target.md +++ b/hints/merge-triplets-to-form-target.md @@ -28,4 +28,4 @@

Now, from the remaining valid triplets, we only need to check whether the target triplet values exist. Since all values in the valid triplets are less than or equal to the corresponding values in the target triplet, finding the target triplet among them guarantees that we can achieve it.

- \ No newline at end of file + diff --git a/hints/merge-two-sorted-linked-lists.md b/hints/merge-two-sorted-linked-lists.md index 5fbfafd3c..4a64a6312 100644 --- a/hints/merge-two-sorted-linked-lists.md +++ b/hints/merge-two-sorted-linked-lists.md @@ -28,4 +28,4 @@ For example, consider list1 = [1, 2, 3] and list2 = [2, 3, 4]. While iterating through the lists, we move the pointers by comparing the node values from both lists. We link the next pointer of the iterator to the node with the smaller value. For instance, when l1 = 1 and l2 = 2, since l1 < l2, we point the iterator's next pointer to l1 and proceed.

- \ No newline at end of file + diff --git a/hints/min-cost-climbing-stairs.md b/hints/min-cost-climbing-stairs.md index 258121826..7114a62bf 100644 --- a/hints/min-cost-climbing-stairs.md +++ b/hints/min-cost-climbing-stairs.md @@ -36,4 +36,4 @@

The base condition would be to return 0 if we are at the top of the staircase i >= n. This is a one-dimensional dynamic programming problem. We can further optimize the memoization solution by using advanced techniques such as Bottom-Up dynamic programming based on the recurrance relation.

- \ No newline at end of file + diff --git a/hints/min-cost-to-connect-points.md b/hints/min-cost-to-connect-points.md index cc585977d..3f9d2c0fb 100644 --- a/hints/min-cost-to-connect-points.md +++ b/hints/min-cost-to-connect-points.md @@ -28,4 +28,4 @@

We create the possible edges by iterating through every pair of points and calculating the weights as the Manhattan distance between them. Next, we sort the edges in ascending order based on their weights, as we aim to minimize the cost. Then, we traverse through these edges, connecting the nodes and adding the weight of the edge to the total cost if the edge is successfully added. The final result will be the minimum cost.

- \ No newline at end of file + diff --git a/hints/minimum-interval-including-query.md b/hints/minimum-interval-including-query.md index 9b56faba2..e01b04e17 100644 --- a/hints/minimum-interval-including-query.md +++ b/hints/minimum-interval-including-query.md @@ -28,4 +28,4 @@

The min-heap is ordered by interval size. We remove elements from the heap while the top element’s end value is less than the current query. The result for the query is the top element’s size if the heap is non-empty; otherwise, it is -1.

- \ No newline at end of file + diff --git a/hints/minimum-stack.md b/hints/minimum-stack.md index 411e300dd..8a7776224 100644 --- a/hints/minimum-stack.md +++ b/hints/minimum-stack.md @@ -28,4 +28,4 @@

We use an additional stack to maintain the prefix minimum element. When popping elements from the main stack, we should also pop from this extra stack. However, when pushing onto the extra stack, we should push the minimum of the top element of the extra stack and the current element onto this extra stack.

- \ No newline at end of file + diff --git a/hints/minimum-window-with-characters.md b/hints/minimum-window-with-characters.md index 3df37fff9..c3a431b8a 100644 --- a/hints/minimum-window-with-characters.md +++ b/hints/minimum-window-with-characters.md @@ -36,4 +36,4 @@

We should ensure that we maintain the result substring and only update it if we find a shorter valid substring. Additionally, we need to keep track of the result substring's length so that we can return an empty string if no valid substring is found.

- \ No newline at end of file + diff --git a/hints/missing-number.md b/hints/missing-number.md index 2d5f6908b..be960c8fd 100644 --- a/hints/missing-number.md +++ b/hints/missing-number.md @@ -36,4 +36,4 @@

We first compute the bitwise XOR of numbers from 0 to n. Then, we iterate through the array and XOR its elements as well. The missing number remains in the final XOR result since all other numbers appear twice—once in the range and once in the array—while the missing number is XORed only once.

- \ No newline at end of file + diff --git a/hints/multiply-strings.md b/hints/multiply-strings.md index 193cc4c27..5ba886df0 100644 --- a/hints/multiply-strings.md +++ b/hints/multiply-strings.md @@ -36,4 +36,4 @@

In the main function, we iterate through num2 in reverse order, calling the helper function to multiply num1 with the current digit and append the appropriate number of padding zeros. We then call another helper function that takes this multiplication result and the global result string res, adds them, and updates res.

- \ No newline at end of file + diff --git a/hints/n-queens.md b/hints/n-queens.md index 60c5f6fef..0499f72c3 100644 --- a/hints/n-queens.md +++ b/hints/n-queens.md @@ -28,4 +28,4 @@

We initialize an empty board and recursively go through each column. For each column, we check each cell to see if we can place a queen there. We use a function to check if the cell is suitable by iterating along the left directions and verifying if the same row, left diagonal, or left bottom diagonal are free. If it is possible, we place the queen on the board, move along the recursive path, and then backtrack by removing the queen to continue to the next cell in the column.

- \ No newline at end of file + diff --git a/hints/network-delay-time.md b/hints/network-delay-time.md index 901cefb98..8a3688e94 100644 --- a/hints/network-delay-time.md +++ b/hints/network-delay-time.md @@ -28,4 +28,4 @@

We use a Min-Heap as we need to find the minimum time. We create an adjacency list for the given times (weighted edges). We also initialize an array dist[] of size n (number of nodes) which represents the distance from the source to all nodes, initialized with infinity. We put dist[source] = 0. Then we continue the algorithm. After the heap becomes empty, if we don't visit any node, we return -1; otherwise, we return the time.

- \ No newline at end of file + diff --git a/hints/non-cyclical-number.md b/hints/non-cyclical-number.md index 6672425b9..d8a3b3050 100644 --- a/hints/non-cyclical-number.md +++ b/hints/non-cyclical-number.md @@ -20,4 +20,4 @@

We can use a hash set to detect if a number has already been processed. At each step, we update n with the return value of the helper function. If the result is 1, we return true. If n is already in the set, we return false. Otherwise, we add n to the hash set and continue.

- \ No newline at end of file + diff --git a/hints/non-overlapping-intervals.md b/hints/non-overlapping-intervals.md index 1e07a9c0b..15c86ea85 100644 --- a/hints/non-overlapping-intervals.md +++ b/hints/non-overlapping-intervals.md @@ -36,4 +36,4 @@

We then iterate from the second interval. If the current interval doesn't overlap, we update prevEnd to the current interval's end and continue. Otherwise, we set prevEnd to the minimum of prevEnd and the current interval’s end, greedily removing the interval that ends last to retain as many intervals as possible.

- \ No newline at end of file + diff --git a/hints/number-of-one-bits.md b/hints/number-of-one-bits.md index 788499e2b..ed0db85d2 100644 --- a/hints/number-of-one-bits.md +++ b/hints/number-of-one-bits.md @@ -28,4 +28,4 @@

Since the mask has a set bit at the i-th position and all 0s elsewhere, we can perform a bitwise-AND with n. If n has a set bit at the i-th position, the result is positive; otherwise, it is 0. We increment the global count if the result is positive and return it after the iteration.

- \ No newline at end of file + diff --git a/hints/pacific-atlantic-water-flow.md b/hints/pacific-atlantic-water-flow.md index 6ed584779..e79541816 100644 --- a/hints/pacific-atlantic-water-flow.md +++ b/hints/pacific-atlantic-water-flow.md @@ -28,4 +28,4 @@

We perform DFS from the border cells, using their respective hash sets. During the DFS, we recursively visit the neighbouring cells that are unvisited and have height greater than or equal to the current cell's height and add the current cell's coordinates to the corresponding hash set. Once the DFS completes, we traverse the grid and check if a cell exists in both the hash sets. If so, we add that cell to the result list.

- \ No newline at end of file + diff --git a/hints/palindrome-partitioning.md b/hints/palindrome-partitioning.md index a2d81783f..d293d2ca7 100644 --- a/hints/palindrome-partitioning.md +++ b/hints/palindrome-partitioning.md @@ -28,4 +28,4 @@

We start with j = 0, i = 0 and a temporary list which stores the substrings from the partitions. Then we recursively iterate the string with the index i. At each step we apply the 2 decisions accordingly. At the base condition of the recursive path, we make a copy of the current partition list and add it to the result.

- \ No newline at end of file + diff --git a/hints/palindromic-substrings.md b/hints/palindromic-substrings.md index 5e994313c..607b4174f 100644 --- a/hints/palindromic-substrings.md +++ b/hints/palindromic-substrings.md @@ -36,4 +36,4 @@

For an even-length palindrome, consider expanding from indices i and i + 1. This two-pointer approach, extending from the center of the palindrome, will help find all palindromic substrings in the given string and return its count.

- \ No newline at end of file + diff --git a/hints/partition-equal-subset-sum.md b/hints/partition-equal-subset-sum.md index 6dfc98881..e0411dee4 100644 --- a/hints/partition-equal-subset-sum.md +++ b/hints/partition-equal-subset-sum.md @@ -36,4 +36,4 @@

If curSum equals half the sum of the array elements, we return true. If index i goes out of bounds, we return false. This solution is exponential, but we can use memoization to cache recursive call results and avoid redundant computations. We can use a hash map or a 2D array with dimensions n * t, where n is the size of the input array and t is half the sum of the input array elements.

- \ No newline at end of file + diff --git a/hints/partition-labels.md b/hints/partition-labels.md index c5e3551bb..57defc3df 100644 --- a/hints/partition-labels.md +++ b/hints/partition-labels.md @@ -28,4 +28,4 @@

We update the end of the current partition based on the maximum last index of the characters, extending the partition as needed. When the current index reaches the partition’s end, we finalize the partition, append its size to the output list, reset the size to 0, and continue the same process for the remaining string.

- \ No newline at end of file + diff --git a/hints/permutation-string.md b/hints/permutation-string.md index 5abcaddf0..d00c4e9e7 100644 --- a/hints/permutation-string.md +++ b/hints/permutation-string.md @@ -28,4 +28,4 @@

We use a sliding window approach on s2 with a fixed window size equal to the length of s1. To track the current window, we maintain a running frequency count of characters in s2. This frequency count represents the characters in the current window. At each step, if the frequency count matches that of s1, we return true.

- \ No newline at end of file + diff --git a/hints/permutations.md b/hints/permutations.md index 3f3d59477..f0cdd994c 100644 --- a/hints/permutations.md +++ b/hints/permutations.md @@ -28,4 +28,4 @@

We observe that every permutation has the same size as the input array. Therefore, we can append a copy of the list of chosen elements in the current path to the result list if the size of the list equals the size of the input array terminating the current recursive path.

- \ No newline at end of file + diff --git a/hints/plus-one.md b/hints/plus-one.md index ec62b78c9..9845a3840 100644 --- a/hints/plus-one.md +++ b/hints/plus-one.md @@ -20,4 +20,4 @@

We iterate through the given digits from right to left using index i. If the current digit is less than 9, we increment it and return the array. Otherwise, we set the digit to 0 and continue. If the loop completes without returning, we insert 1 at the beginning of the array and return it.

- \ No newline at end of file + diff --git a/hints/pow-x-n.md b/hints/pow-x-n.md index de42350f0..f66941947 100644 --- a/hints/pow-x-n.md +++ b/hints/pow-x-n.md @@ -36,4 +36,4 @@

We start the recursion with the absolute value of n. After computing the result as res, we return res if n is non-negative; otherwise, we return (1 / res).

- \ No newline at end of file + diff --git a/hints/products-of-array-discluding-self.md b/hints/products-of-array-discluding-self.md index bab9964c9..f1692f173 100644 --- a/hints/products-of-array-discluding-self.md +++ b/hints/products-of-array-discluding-self.md @@ -36,4 +36,4 @@

We can use the stored prefix and suffix products to compute the result array by iterating through the array and simply multiplying the prefix and suffix products at each index.

- \ No newline at end of file + diff --git a/hints/reconstruct-flight-path.md b/hints/reconstruct-flight-path.md index 43f336c17..326a59ac1 100644 --- a/hints/reconstruct-flight-path.md +++ b/hints/reconstruct-flight-path.md @@ -36,4 +36,4 @@

We can use Hierholzer's algorithm, a modified DFS approach. Instead of appending the node to the result list immediately, we first visit all its neighbors. This results in a post-order traversal. After completing all the DFS calls, we reverse the path to obtain the final path, which is also called Euler's path.

- \ No newline at end of file + diff --git a/hints/redundant-connection.md b/hints/redundant-connection.md index cdd3217fe..38a354115 100644 --- a/hints/redundant-connection.md +++ b/hints/redundant-connection.md @@ -28,4 +28,4 @@

We create an instance of the DSU object and traverse through the given edges. For each edge, we attempt to connect the nodes using the union function. If the union function returns false, indicating that the current edge forms a cycle, we immediately return that edge.

- \ No newline at end of file + diff --git a/hints/regular-expression-matching.md b/hints/regular-expression-matching.md index e17c78964..7afa136e0 100644 --- a/hints/regular-expression-matching.md +++ b/hints/regular-expression-matching.md @@ -36,4 +36,4 @@

We can use memoization to cache the results of recursive calls and avoid redundant calculations. A hash map or a 2D array can be used to store these results.

- \ No newline at end of file + diff --git a/hints/remove-node-from-end-of-linked-list.md b/hints/remove-node-from-end-of-linked-list.md index d73855f6f..227e124de 100644 --- a/hints/remove-node-from-end-of-linked-list.md +++ b/hints/remove-node-from-end-of-linked-list.md @@ -44,4 +44,4 @@

This greedy approach works because the second pointer is n nodes behind the first pointer. When the first pointer reaches the end, the second pointer is exactly n nodes from the end. This positioning allows us to remove the nth node from the end efficiently.

- \ No newline at end of file + diff --git a/hints/reverse-a-linked-list.md b/hints/reverse-a-linked-list.md index 9d8db81d4..d7cde3482 100644 --- a/hints/reverse-a-linked-list.md +++ b/hints/reverse-a-linked-list.md @@ -36,4 +36,4 @@

We can reverse the linked list in place by reversing the pointers between two nodes while keeping track of the next node's address. Before changing the next pointer of the current node, we must store the next node to ensure we don't lose the rest of the list during the reversal. This way, we can safely update the links between the previous and current nodes.

- \ No newline at end of file + diff --git a/hints/reverse-bits.md b/hints/reverse-bits.md index 0eb364ce9..72c3d9ba0 100644 --- a/hints/reverse-bits.md +++ b/hints/reverse-bits.md @@ -28,4 +28,4 @@

We initialize res to 0 and iterate through the bits of the given integer n. We extract the bit at the i-th position using ((n >> i) & 1). If it is 1, we set the corresponding bit in res at position (31 - i) using (res |= (1 << (31 - i))).

- \ No newline at end of file + diff --git a/hints/reverse-integer.md b/hints/reverse-integer.md index 23b4d9c75..63ffb1c5a 100644 --- a/hints/reverse-integer.md +++ b/hints/reverse-integer.md @@ -28,4 +28,4 @@

Let MAX be the maximum positive integer and MIN be the minimum negative integer. We iterate through each digit and check for overflow before updating res. If res > MAX / 10 or res < MIN / 10, return 0. If res == MAX / 10 and the current digit is greater than MAX % 10, return 0. If res == MIN / 10 and the current digit is less than MIN % 10, return 0. Otherwise, append the digit to res and continue.

- \ No newline at end of file + diff --git a/hints/reverse-nodes-in-k-group.md b/hints/reverse-nodes-in-k-group.md index b686ce645..3ee3fe0af 100644 --- a/hints/reverse-nodes-in-k-group.md +++ b/hints/reverse-nodes-in-k-group.md @@ -28,4 +28,4 @@

We create a dummy node to handle modifications to the head of the linked list, pointing its next pointer to the current head. We then iterate k nodes, storing the address of the next group's head and tracking the tail of the previous group. After reversing the current group, we reconnect it by linking the previous group's tail to the new head and the current group's tail to the next group's head. This process is repeated for all groups, and we return the new head of the linked list.

- \ No newline at end of file + diff --git a/hints/rotate-matrix.md b/hints/rotate-matrix.md index 3f5528d0f..983307b08 100644 --- a/hints/rotate-matrix.md +++ b/hints/rotate-matrix.md @@ -28,4 +28,4 @@

Since the given matrix is a square matrix, we only need to iterate over the upper triangular part, meaning the right upper portion of the main diagonal. In this way, we can transpose a matrix.

- \ No newline at end of file + diff --git a/hints/rotting-fruit.md b/hints/rotting-fruit.md index 76ce34b5b..6d9b27717 100644 --- a/hints/rotting-fruit.md +++ b/hints/rotting-fruit.md @@ -28,4 +28,4 @@

We traverse the grid and store the rotten oranges in a queue. We then run a BFS, processing the current level of rotten oranges and visiting the adjacent cells of each rotten orange. We only insert the adjacent cell into the queue if it contains a fresh orange. This process continues until the queue is empty. The level at which the BFS stops is the answer. However, we also need to check whether all oranges have rotted by traversing the grid. If any fresh orange is found, we return -1; otherwise, we return the level.

- \ No newline at end of file + diff --git a/hints/same-binary-tree.md b/hints/same-binary-tree.md index 3a79a39f2..096eca0dc 100644 --- a/hints/same-binary-tree.md +++ b/hints/same-binary-tree.md @@ -28,4 +28,4 @@

We traverse both trees starting from their root nodes. At each step in the recursion, we check if the current nodes in both trees are either null or have the same value. If one node is null while the other is not, or if their values differ, we return false. If the values match, we recursively check their left and right subtrees. If any recursive call returns false, the result for the current recursive call is false.

- \ No newline at end of file + diff --git a/hints/search-2d-matrix.md b/hints/search-2d-matrix.md index 53153f798..46743ed57 100644 --- a/hints/search-2d-matrix.md +++ b/hints/search-2d-matrix.md @@ -36,4 +36,4 @@

Once we identify the potential row where the target might exist, we can perform a binary search on that row which acts as a one dimensional array. It takes O(logn) time, where n is the number of columns in the row.

- \ No newline at end of file + diff --git a/hints/search-for-word-ii.md b/hints/search-for-word-ii.md index 205964c7e..cbfea32f0 100644 --- a/hints/search-for-word-ii.md +++ b/hints/search-for-word-ii.md @@ -36,4 +36,4 @@

We insert all the words into the Trie with their indices marked. Then, we iterate through each cell in the grid. At each cell, we start at the root of the Trie and explore all possible paths. As we traverse, we match characters in the cell with those in the Trie nodes. If we encounter the end of a word, we take the index at that node and add the corresponding word to the result list. Afterward, we unmark that index and continue exploring further paths.

- \ No newline at end of file + diff --git a/hints/search-for-word.md b/hints/search-for-word.md index 9dcdf4102..1c671ebd1 100644 --- a/hints/search-for-word.md +++ b/hints/search-for-word.md @@ -28,4 +28,4 @@

We can use backtracking, starting from each cell on the board with coordinates (row, col) and index i for the given word. We return false if (row, col) is out of bounds or if board[row][col] != word[i]. When i reaches the end of the word, we return true, indicating a valid path. At each step, we add (row, col) to a hash set to avoid revisiting cells. After exploring the four possible directions, we backtrack and remove (row, col) from the hash set.

- \ No newline at end of file + diff --git a/hints/serialize-and-deserialize-binary-tree.md b/hints/serialize-and-deserialize-binary-tree.md index a93feef8e..c3a00ebcd 100644 --- a/hints/serialize-and-deserialize-binary-tree.md +++ b/hints/serialize-and-deserialize-binary-tree.md @@ -28,4 +28,4 @@

We can use the Depth First Search (DFS) algorithm for both serialization and deserialization. During serialization, we traverse the tree and add node values to the result string separated by a delimiter, inserting N whenever we encounter a null node. During deserialization, we process the serialized string using an index i, create nodes for valid values, and return from the current path whenever we encounter N, reconstructing the tree accurately.

- \ No newline at end of file + diff --git a/hints/set-zeroes-in-matrix.md b/hints/set-zeroes-in-matrix.md index 663ff919e..27a9c7fee 100644 --- a/hints/set-zeroes-in-matrix.md +++ b/hints/set-zeroes-in-matrix.md @@ -36,4 +36,4 @@

In the second iteration, we update all cells that are not part of the top row or left column accordingly. After making the necessary changes, we check the top-leftmost cell and update the corresponding column. Finally, we check the extra variable and update the top row accordingly.

- \ No newline at end of file + diff --git a/hints/single-number.md b/hints/single-number.md index 6aab0485f..64bb2a062 100644 --- a/hints/single-number.md +++ b/hints/single-number.md @@ -36,4 +36,4 @@

When two identical numbers are XORed, they cancel out, resulting in zero. Since every number appears twice except for one, the XOR of the entire array gives the number that appears only once.

- \ No newline at end of file + diff --git a/hints/sliding-window-maximum.md b/hints/sliding-window-maximum.md index 3506407c3..8f8571cd2 100644 --- a/hints/sliding-window-maximum.md +++ b/hints/sliding-window-maximum.md @@ -36,4 +36,4 @@

We can ignore those elements that are no longer part of the current window, except when the maximum value is outside the window. In that case, we remove elements from the max-heap until the maximum value belongs to the current window. Why? Because those elements will be eventually removed when the maximum element goes out of the window.

- \ No newline at end of file + diff --git a/hints/spiral-matrix.md b/hints/spiral-matrix.md index 2b8eced0a..30cdc6d98 100644 --- a/hints/spiral-matrix.md +++ b/hints/spiral-matrix.md @@ -28,4 +28,4 @@

At each layer, four loops traverse the matrix: one moves left to right along the top row, another moves top to bottom along the right column, the next moves right to left along the bottom row, and the last moves bottom to top along the left column. This process generates the spiral order.

- \ No newline at end of file + diff --git a/hints/string-encode-and-decode.md b/hints/string-encode-and-decode.md index 82bc8fbcb..2dd2df0a4 100644 --- a/hints/string-encode-and-decode.md +++ b/hints/string-encode-and-decode.md @@ -28,4 +28,4 @@

We can use an encoding approach where we start with a number representing the length of the string, followed by a separator character (let's use # for simplicity), and then the string itself. To decode, we read the number until we reach a #, then use that number to read the specified number of characters as the string.

- \ No newline at end of file + diff --git a/hints/subsets-ii.md b/hints/subsets-ii.md index 4001ea052..ae0cc1186 100644 --- a/hints/subsets-ii.md +++ b/hints/subsets-ii.md @@ -28,4 +28,4 @@

We start by sorting the input array. Then, we recursively iterate through the array from left to right, extending recursive paths by including or excluding each element. To avoid duplicate subsets, we skip an element if it is the same as the previous one. Finally, we return the generated subsets as a list.

- \ No newline at end of file + diff --git a/hints/subsets.md b/hints/subsets.md index 63a694ba2..e4e038fa5 100644 --- a/hints/subsets.md +++ b/hints/subsets.md @@ -36,4 +36,4 @@

When the index i reaches the end of the array, we append a copy of the subset formed in that particular recursive path to the result list and return. All subsets of the given array are generated from these different recursive paths, which represent various combinations of "include" and "not include" steps for the elements of the array. As we are only iterating from left to right in the array, we don't pick an element more than once.

- \ No newline at end of file + diff --git a/hints/subtree-of-a-binary-tree.md b/hints/subtree-of-a-binary-tree.md index 79aaf1a57..c101a8622 100644 --- a/hints/subtree-of-a-binary-tree.md +++ b/hints/subtree-of-a-binary-tree.md @@ -28,4 +28,4 @@

We traverse the given root, and at each node, we check if the subtree rooted at that node is identical to the given subRoot. We use a helper function, sameTree(root1, root2), to determine whether the two trees passed to it are identical in both structure and values.

- \ No newline at end of file + diff --git a/hints/sum-of-two-integers.md b/hints/sum-of-two-integers.md index 340f197d0..d5aa04b02 100644 --- a/hints/sum-of-two-integers.md +++ b/hints/sum-of-two-integers.md @@ -36,4 +36,4 @@

To handle negative numbers, if the final result exceeds the maximum positive 32-bit integer, it means the number should be negative. We adjust it using bitwise operations: flipping the bits with res ^ ((2 ^ 32) - 1) and applying ~ to restore the correct two’s complement representation. This ensures the result correctly represents signed 32-bit integers.

- \ No newline at end of file + diff --git a/hints/surrounded-regions.md b/hints/surrounded-regions.md index d61a1db78..49e38646d 100644 --- a/hints/surrounded-regions.md +++ b/hints/surrounded-regions.md @@ -28,4 +28,4 @@

We run the DFS from every 'O' on the border of the matrix, visiting the neighboring cells that are equal to 'O' recursively and marking them as '#' to avoid revisiting. After completing all the DFS calls, we traverse the matrix again and capture the cells where matrix[i][j] == 'O', and unmark the cells back to 'O' where matrix[i][j] == '#'.

- \ No newline at end of file + diff --git a/hints/swim-in-rising-water.md b/hints/swim-in-rising-water.md index 5e098b6f0..432e6515e 100644 --- a/hints/swim-in-rising-water.md +++ b/hints/swim-in-rising-water.md @@ -28,4 +28,4 @@

We can use Dijkstra's algorithm. We initialize a Min-heap and a matrix with infinity. We run the algorithm starting from the source (0, 0), and we track the maximum elevation encountered along the paths. This maximum elevation is used as the key for comparison in Dijkstra's algorithm. If we encounter the destination (n - 1, n - 1), we return the maximum elevation of the path that reached the destination.

- \ No newline at end of file + diff --git a/hints/target-sum.md b/hints/target-sum.md index 06e9e9a3e..0ce4f950c 100644 --- a/hints/target-sum.md +++ b/hints/target-sum.md @@ -28,4 +28,4 @@

This approach is exponential. We can use memoization to cache recursive call results and avoid redundant calculations. A hash map or a 2D array with modifications can be used for caching. If using a 2D array, the dimensions can be (n * (2m + 1)), where n is the array size and m represents the sum of the array elements.

- \ No newline at end of file + diff --git a/hints/task-scheduling.md b/hints/task-scheduling.md index 1b351db49..f1e745890 100644 --- a/hints/task-scheduling.md +++ b/hints/task-scheduling.md @@ -36,4 +36,4 @@

We start by calculating the frequency of each task and initialize a variable time to track the total processing time. The task frequencies are inserted into a Max-Heap. We also use a queue to store tasks along with the time they become available after the cooldown. At each step, if the Max-Heap is empty, we update time to match the next available task in the queue, covering idle time. Otherwise, we process the most frequent task from the heap, decrement its frequency, and if it's still valid, add it back to the queue with its next available time. If the task at the front of the queue becomes available, we pop it and reinsert it into the heap.

- \ No newline at end of file + diff --git a/hints/time-based-key-value-store.md b/hints/time-based-key-value-store.md index 5b4e80ea6..2f2949ed0 100644 --- a/hints/time-based-key-value-store.md +++ b/hints/time-based-key-value-store.md @@ -36,4 +36,4 @@

We can use binary search because the timestamps in the values list are sorted in ascending order. This makes it straightforward to find the value with the most recent timestamp that is less than or equal to the given timestamp.

- \ No newline at end of file + diff --git a/hints/top-k-elements-in-list.md b/hints/top-k-elements-in-list.md index 566ec05de..e22b83718 100644 --- a/hints/top-k-elements-in-list.md +++ b/hints/top-k-elements-in-list.md @@ -28,4 +28,4 @@

Use the bucket sort algorithm to create n buckets, grouping numbers based on their frequencies from 1 to n. Then, pick the top k numbers from the buckets, starting from n down to 1.

- \ No newline at end of file + diff --git a/hints/trapping-rain-water.md b/hints/trapping-rain-water.md index 2ae54b063..1623cfc80 100644 --- a/hints/trapping-rain-water.md +++ b/hints/trapping-rain-water.md @@ -36,4 +36,4 @@

We can store the prefix maximum in an array by iterating from left to right and the suffix maximum in another array by iterating from right to left. For example, in [1, 5, 2, 3, 4], for the element 3, the prefix maximum is 5, and the suffix maximum is 4. Once these arrays are built, we can iterate through the array with index i and calculate the total water trapped at each position using the formula: min(prefix[i], suffix[i]) - height[i].

- \ No newline at end of file + diff --git a/hints/two-integer-sum-ii.md b/hints/two-integer-sum-ii.md index a07baf4ac..3d31dbae2 100644 --- a/hints/two-integer-sum-ii.md +++ b/hints/two-integer-sum-ii.md @@ -36,4 +36,4 @@

We keep two pointers, one at the start and the other at the end of the array. If the sum of the numbers at the two pointers is greater than the target, decrement the right pointer, else increment the left pointer. Repeat this process until you find a valid pair.

- \ No newline at end of file + diff --git a/hints/two-integer-sum.md b/hints/two-integer-sum.md index 948aae221..c517dd472 100644 --- a/hints/two-integer-sum.md +++ b/hints/two-integer-sum.md @@ -28,4 +28,4 @@

we can iterate through nums with index i. Let difference = target - nums[i] and check if difference exists in the hash map as we iterate through the array, else store the current element in the hashmap with its index and continue. We use a hashmap for O(1) lookups.

- \ No newline at end of file + diff --git a/hints/valid-binary-search-tree.md b/hints/valid-binary-search-tree.md index 9a691ece8..b6b87249d 100644 --- a/hints/valid-binary-search-tree.md +++ b/hints/valid-binary-search-tree.md @@ -28,4 +28,4 @@

We start with the interval [-infinity, infinity] for the root node. As we traverse the tree, when checking the left subtree, we update the maximum value limit because all values in the left subtree must be less than the current node's value. Conversely, when checking the right subtree, we update the minimum value limit because all values in the right subtree must be greater than the current node's value.

- \ No newline at end of file + diff --git a/hints/valid-parenthesis-string.md b/hints/valid-parenthesis-string.md index 29baed7d5..81ff9bcff 100644 --- a/hints/valid-parenthesis-string.md +++ b/hints/valid-parenthesis-string.md @@ -36,4 +36,4 @@

Now, we try to match the remaining left parentheses with stars, ensuring the stars appear after the left parentheses in the string. We simultaneously pop from both stacks, and if the index of a left parenthesis is greater than that of a star, the string is invalid as there is no matching right parenthesis. In this case, we return false.

- \ No newline at end of file + diff --git a/hints/valid-sudoku.md b/hints/valid-sudoku.md index 51655ed8b..6b10bc68e 100644 --- a/hints/valid-sudoku.md +++ b/hints/valid-sudoku.md @@ -28,4 +28,4 @@

We can find the index of each square by the equation (row / 3) * 3 + (col / 3). Then we use hash set for O(1) lookups while inserting the number into its row, column and square it belongs to. We use separate hash maps for rows, columns, and squares.

- \ No newline at end of file + diff --git a/hints/valid-tree.md b/hints/valid-tree.md index 7e7d37358..fbeebf0ae 100644 --- a/hints/valid-tree.md +++ b/hints/valid-tree.md @@ -28,4 +28,4 @@

We start DFS from node 0, assuming -1 as its parent. We initialize a hash set visit to track the visited nodes in the graph. During the DFS, we first check if the current node is already in visit. If it is, we return false, detecting a cycle. Otherwise, we mark the node as visited and perform DFS on its neighbors, skipping the parent node to avoid revisiting it. After all DFS calls, if we have visited all nodes, we return true, as the graph is connected. Otherwise, we return false because a tree must contain all nodes.

- \ No newline at end of file + diff --git a/hints/validate-parentheses.md b/hints/validate-parentheses.md index ec5216bb4..908d06dba 100644 --- a/hints/validate-parentheses.md +++ b/hints/validate-parentheses.md @@ -28,4 +28,4 @@

In a valid parenthesis expression, every opening bracket must have a corresponding closing bracket. The stack is used to process the valid string, and it should be empty after the entire process. This ensures that there is a valid substring between each opening and closing bracket.

- \ No newline at end of file + diff --git a/hints/word-break.md b/hints/word-break.md index cb850a49c..6b8b32d7f 100644 --- a/hints/word-break.md +++ b/hints/word-break.md @@ -28,4 +28,4 @@

We can avoid recalculating results for recursive calls by using memoization. Since we iterate with index i, we can use a hash map or an array of the same length as s to cache the results of recursive calls and prevent redundant computations.

- \ No newline at end of file + diff --git a/hints/word-ladder.md b/hints/word-ladder.md index efdd32a2c..5d065be31 100644 --- a/hints/word-ladder.md +++ b/hints/word-ladder.md @@ -28,4 +28,4 @@

When visiting a node during BFS, if the word matches the endWord, we immediately return true. Otherwise, we generate the pattern words that can be formed from the current word and attempt to visit the words connected to these pattern words. We add only unvisited words to the queue. If we exhaust all possibilities without finding the endWord, we return false.

- \ No newline at end of file + diff --git a/javascript/0001-two-sum.js b/javascript/0001-two-sum.js index 68c0fafce..272eb004d 100644 --- a/javascript/0001-two-sum.js +++ b/javascript/0001-two-sum.js @@ -7,19 +7,21 @@ * @return {number[]} */ var twoSum = (nums, target) => { - for (let curr = 0; curr < nums.length; curr++) {/* Time O(N) */ + for (let curr = 0; curr < nums.length; curr++) { + /* Time O(N) */ const complement = target - nums[curr]; - for (let next = (curr + 1); next < nums.length; next++) {/* Time O(N) */ + for (let next = curr + 1; next < nums.length; next++) { + /* Time O(N) */ const num = nums[next]; - const isTarget = num === complement - if (isTarget) return [ curr, next ]; + const isTarget = num === complement; + if (isTarget) return [curr, next]; } } - return [ -1, -1 ]; -} + return [-1, -1]; +}; /** * Hash Map - 2 Pass @@ -30,30 +32,32 @@ var twoSum = (nums, target) => { * @return {number[]} */ var twoSum = (nums, target) => { - const map = getMap(nums); /* Time O(N) | Space O(N) */ + const map = getMap(nums); /* Time O(N) | Space O(N) */ - return getSum(nums, target, map)/* Time O(N) */ -} + return getSum(nums, target, map); /* Time O(N) */ +}; const getMap = (nums, map = new Map()) => { - for (let index = 0; index < nums.length; index++) {/* Time O(N) */ - map.set(nums[index], index); /* Space O(N) */ + for (let index = 0; index < nums.length; index++) { + /* Time O(N) */ + map.set(nums[index], index); /* Space O(N) */ } - return map -} + return map; +}; const getSum = (nums, target, map) => { - for (let index = 0; index < nums.length; index++) {/* Time O(N) */ + for (let index = 0; index < nums.length; index++) { + /* Time O(N) */ const complement = target - nums[index]; const sumIndex = map.get(complement); - const isTarget = map.has(complement) && (map.get(complement) !== index) - if (isTarget) return [ index, sumIndex ] + const isTarget = map.has(complement) && map.get(complement) !== index; + if (isTarget) return [index, sumIndex]; } - return [ -1, -1 ]; -} + return [-1, -1]; +}; /** * Hash Map - 1 Pass @@ -64,16 +68,17 @@ const getSum = (nums, target, map) => { * @return {number[]} */ var twoSum = (nums, target, map = new Map()) => { - for (let index = 0; index < nums.length; index++) {/* Time O(N) */ + for (let index = 0; index < nums.length; index++) { + /* Time O(N) */ const num = nums[index]; - const complement = (target - num); + const complement = target - num; const sumIndex = map.get(complement); - const isTarget = map.has(complement) - if (isTarget) return [ index, sumIndex ]; + const isTarget = map.has(complement); + if (isTarget) return [index, sumIndex]; - map.set(num, index); /* Space O(N) */ + map.set(num, index); /* Space O(N) */ } - return [ -1, -1 ]; -} \ No newline at end of file + return [-1, -1]; +}; diff --git a/javascript/0002-add-two-numbers.js b/javascript/0002-add-two-numbers.js index 129cf39c8..4f4e5ff96 100644 --- a/javascript/0002-add-two-numbers.js +++ b/javascript/0002-add-two-numbers.js @@ -5,18 +5,29 @@ * @param {ListNode} l2 * @return {ListNode} */ -var addTwoNumbers = function(l1, l2) { - let sentinel = tail = new ListNode(); +var addTwoNumbers = function (l1, l2) { + let sentinel = (tail = new ListNode()); - return add(l1, l2, tail, sentinel); /* Time O(MAX(N, M)) | Space O(MAX(N, M)) */ -} + return add( + l1, + l2, + tail, + sentinel, + ); /* Time O(MAX(N, M)) | Space O(MAX(N, M)) */ +}; const add = (l1, l2, tail, sentinel, carry = 0) => { const isBaseCase = !(l1 || l2 || carry); if (isBaseCase) return sentinel.next; - return dfs(l1, l2, tail, sentinel, carry);/* Time O(MAX(N, M)) | Space O(MAX(N, M)) */ -} + return dfs( + l1, + l2, + tail, + sentinel, + carry, + ); /* Time O(MAX(N, M)) | Space O(MAX(N, M)) */ +}; const dfs = (l1, l2, tail, sentinel, carry) => { const sum = (l1?.val || 0) + (l2?.val || 0) + carry; @@ -29,10 +40,16 @@ const dfs = (l1, l2, tail, sentinel, carry) => { l1 = l1?.next || null; l2 = l2?.next || null; - add(l1, l2, tail, sentinel, carry); /* Time O(MAX(N, M)) | Space O(MAX(N, M)) */ + add( + l1, + l2, + tail, + sentinel, + carry, + ); /* Time O(MAX(N, M)) | Space O(MAX(N, M)) */ return sentinel.next; -} +}; /** * https://leetcode.com/problems/add-two-numbers/ @@ -41,10 +58,11 @@ const dfs = (l1, l2, tail, sentinel, carry) => { * @param {ListNode} l2 * @return {ListNode} */ -var addTwoNumbers = function(l1, l2, carry = 0) { - let sentinel = tail = new ListNode(); +var addTwoNumbers = function (l1, l2, carry = 0) { + let sentinel = (tail = new ListNode()); - while (l1 || l2 || carry) {/* Time O(MAX(N, M)) */ + while (l1 || l2 || carry) { + /* Time O(MAX(N, M)) */ const sum = (l1?.val || 0) + (l2?.val || 0) + carry; const val = sum % 10; carry = Math.floor(sum / 10); diff --git a/javascript/0004-median-of-two-sorted-arrays.js b/javascript/0004-median-of-two-sorted-arrays.js index 7aa178d9d..119ac337f 100644 --- a/javascript/0004-median-of-two-sorted-arrays.js +++ b/javascript/0004-median-of-two-sorted-arrays.js @@ -20,7 +20,7 @@ var findMedianSortedArrays = function (nums1, nums2) { nums1, mid1, nums2, - mid2 + mid2, ); const isTarget = aLeft <= bRight && bLeft <= aRight; diff --git a/javascript/0005-longest-palindromic-substring.js b/javascript/0005-longest-palindromic-substring.js index c52a3dbec..ae9e0b547 100644 --- a/javascript/0005-longest-palindromic-substring.js +++ b/javascript/0005-longest-palindromic-substring.js @@ -9,35 +9,42 @@ var longestPalindrome = (s) => { const isEmpty = s.length === 0; if (isEmpty) return ''; - const [ left, right ] = search(s);/* Time O(N * N) */ + const [left, right] = search(s); /* Time O(N * N) */ - return s.slice(left, (right + 1));/* Time O(N * N) | Ignore Auxillary Space (N) */ -} + return s.slice( + left, + right + 1, + ); /* Time O(N * N) | Ignore Auxillary Space (N) */ +}; const search = (s, left = 0, right = 0) => { - for (let index = 0; index < s.length; index++) {/* Time O(N) */ - const len1 = getLength(s, index, index); /* Time O(N) */ - const len2 = getLength(s, index, (index + 1)); /* Time O(N) */ - const [ length, window ] = [ (Math.max(len1, len2)), (right - left) ]; + for (let index = 0; index < s.length; index++) { + /* Time O(N) */ + const len1 = getLength(s, index, index); /* Time O(N) */ + const len2 = getLength(s, index, index + 1); /* Time O(N) */ + const [length, window] = [Math.max(len1, len2), right - left]; - const canSkip = (length <= window); + const canSkip = length <= window; if (canSkip) continue; - left = (index - ((length - 1) >> 1)); - right = (index + (length >> 1)); + left = index - ((length - 1) >> 1); + right = index + (length >> 1); } - return [ left, right ]; -} + return [left, right]; +}; const getLength = (s, left, right) => { - const canExpand = () => ((0 <= left) && (right < s.length)); - const isSame = () => (s[left] === s[right]); + const canExpand = () => 0 <= left && right < s.length; + const isSame = () => s[left] === s[right]; - const isPalindrome = () => (canExpand() && isSame()); - while (isPalindrome()) { left--; right++; }/* Time O(N) */ + const isPalindrome = () => canExpand() && isSame(); + while (isPalindrome()) { + left--; + right++; + } /* Time O(N) */ - const window = ((right - left) - 1); + const window = right - left - 1; return window; -} +}; diff --git a/javascript/0007-reverse-integer.js b/javascript/0007-reverse-integer.js index 551e87ad7..fa26a6d70 100644 --- a/javascript/0007-reverse-integer.js +++ b/javascript/0007-reverse-integer.js @@ -4,27 +4,27 @@ * @param {number} x * @return {number} */ -var reverse = function(x, result = 0) { +var reverse = function (x, result = 0) { while (x !== 0) { - const digit = (x % 10) + const digit = x % 10; if (isOutOfBounds(digit, result)) return 0; x = Math.trunc(x / 10); - result = (result * 10) + digit; + result = result * 10 + digit; } return result; }; const isOutOfBounds = (digit, result) => { - const [ max, min ] = [ ((2 ** 31) - 1), (-(2 ** 31)) ]; - const [ maxProduct, maxRemainder ] = [ (max / 10), (max % 10) ]; - const [ minProduct, minRemainder ] = [ (min / 10), (min % 10) ]; + const [max, min] = [2 ** 31 - 1, -(2 ** 31)]; + const [maxProduct, maxRemainder] = [max / 10, max % 10]; + const [minProduct, minRemainder] = [min / 10, min % 10]; const isTarget = result === maxProduct; - const isMaxOut = ((maxProduct < result) || (isTarget && (maxRemainder <= digit))); - const isMinOut = ((result < minProduct) || (isTarget && (digit <= minRemainder))); + const isMaxOut = maxProduct < result || (isTarget && maxRemainder <= digit); + const isMinOut = result < minProduct || (isTarget && digit <= minRemainder); return isMaxOut || isMinOut; -} +}; diff --git a/javascript/0009-palindrome-number.js b/javascript/0009-palindrome-number.js index 9312c1033..a53ac2113 100644 --- a/javascript/0009-palindrome-number.js +++ b/javascript/0009-palindrome-number.js @@ -27,7 +27,7 @@ var isPalindrome = function (x) { * @param {number} x * @return {boolean} */ - var isPalindrome = function(x) { +var isPalindrome = function (x) { if (x < 0) return false; const inputX = x; @@ -37,7 +37,7 @@ var isPalindrome = function (x) { revX += x % 10; x = Math.floor(x / 10); - if (x > 0) revX *= 10 + if (x > 0) revX *= 10; } return revX === inputX; diff --git a/javascript/0010-regular-expression-matching.js b/javascript/0010-regular-expression-matching.js index 81a21f2c9..a93f05c2d 100644 --- a/javascript/0010-regular-expression-matching.js +++ b/javascript/0010-regular-expression-matching.js @@ -7,17 +7,18 @@ * @return {boolean} */ var isMatch = (text, pattern) => { - const isBaseCase = (pattern.length === 0); - if (isBaseCase) return (text.length === 0); - - const isTextAndPatternEqual = (pattern[0] === text[0]), - isPatternPeriod = (pattern[0] === '.'), - isFirstMatch = (text && (isTextAndPatternEqual || isPatternPeriod)), - isNextPatternWildCard = (pattern.length >= 2 && pattern[1] === '*'); - - return isNextPatternWildCard/* Time O((N + M) * 2^(N + (M / 2))) | Space O(N^2 + M^2) */ - ? (isMatch(text, pattern.slice(2)) || (isFirstMatch && isMatch(text.slice(1), pattern))) - : (isFirstMatch && isMatch(text.slice(1), pattern.slice(1))); + const isBaseCase = pattern.length === 0; + if (isBaseCase) return text.length === 0; + + const isTextAndPatternEqual = pattern[0] === text[0], + isPatternPeriod = pattern[0] === '.', + isFirstMatch = text && (isTextAndPatternEqual || isPatternPeriod), + isNextPatternWildCard = pattern.length >= 2 && pattern[1] === '*'; + + return isNextPatternWildCard /* Time O((N + M) * 2^(N + (M / 2))) | Space O(N^2 + M^2) */ + ? isMatch(text, pattern.slice(2)) || + (isFirstMatch && isMatch(text.slice(1), pattern)) + : isFirstMatch && isMatch(text.slice(1), pattern.slice(1)); }; /** @@ -29,33 +30,52 @@ var isMatch = (text, pattern) => { * @param {string} p * @return {boolean} */ -var isMatch = (text, pattern, row = 0, col = 0, memo = initMemo(text, pattern)) => { - const hasSeen = (memo[row][col]); +var isMatch = ( + text, + pattern, + row = 0, + col = 0, + memo = initMemo(text, pattern), +) => { + const hasSeen = memo[row][col]; if (hasSeen) return memo[row][col]; - const isEqual = (col === pattern.length); + const isEqual = col === pattern.length; const ans = isEqual ? row === text.length - : check(text, pattern, row, col, memo);/* Time O(N * M) | Space O(N * M) */ + : check( + text, + pattern, + row, + col, + memo, + ); /* Time O(N * M) | Space O(N * M) */ memo[row][col] = ans; return ans; -} +}; -var initMemo = (text, pattern) => new Array((text.length + 1)).fill()/* Time O(N) | Space O(N) */ - .map(() => new Array((pattern.length + 1)).fill(false)) /* Time O(M) | Space O(M) */ +var initMemo = (text, pattern) => + new Array(text.length + 1) + .fill() /* Time O(N) | Space O(N) */ + .map(() => + new Array(pattern.length + 1).fill(false), + ); /* Time O(M) | Space O(M) */ var check = (text, pattern, row, col, memo) => { - const isTextDefined = (row < text.length), - isTextAndPatternEqual = (pattern[col] === text[row]), - isPatternPeriod = (pattern[col] === '.'), - isFirstMatch = (isTextDefined && (isTextAndPatternEqual || isPatternPeriod)), - isNextPatternWildCard = (((col + 1) < pattern.length) && pattern[col + 1] === '*'); - - return isNextPatternWildCard/* Time O(N * M) | Space O(N * M) */ - ? (isMatch(text, pattern, row, (col + 2), memo) || isFirstMatch && isMatch(text, pattern, (row + 1), col, memo)) - : (isFirstMatch && isMatch(text, pattern, (row + 1), (col + 1), memo)); -} + const isTextDefined = row < text.length, + isTextAndPatternEqual = pattern[col] === text[row], + isPatternPeriod = pattern[col] === '.', + isFirstMatch = + isTextDefined && (isTextAndPatternEqual || isPatternPeriod), + isNextPatternWildCard = + col + 1 < pattern.length && pattern[col + 1] === '*'; + + return isNextPatternWildCard /* Time O(N * M) | Space O(N * M) */ + ? isMatch(text, pattern, row, col + 2, memo) || + (isFirstMatch && isMatch(text, pattern, row + 1, col, memo)) + : isFirstMatch && isMatch(text, pattern, row + 1, col + 1, memo); +}; /** * Time O(N * M) | Space O(N * M) @@ -64,35 +84,41 @@ var check = (text, pattern, row, col, memo) => { * @return {boolean} */ var isMatch = (text, pattern) => { - const tabu = initTabu(text, pattern);/* Time O(N * M) | Space O(N * M) */ + const tabu = initTabu(text, pattern); /* Time O(N * M) | Space O(N * M) */ - search(text, pattern, tabu); /* Time O(N * M) | Space O(N * M) */ + search(text, pattern, tabu); /* Time O(N * M) | Space O(N * M) */ return tabu[0][0]; - -} +}; var initTabu = (text, pattern) => { - const tabu = new Array((text.length + 1)).fill() /* Time O(N) | Space O(N) */ - .map(() => new Array((pattern.length + 1)).fill(false));/* Time O(M) | Space O(M) */ + const tabu = new Array(text.length + 1) + .fill() /* Time O(N) | Space O(N) */ + .map(() => + new Array(pattern.length + 1).fill(false), + ); /* Time O(M) | Space O(M) */ - tabu[text.length][pattern.length] = true; /* | Space O(N * M) */ + tabu[text.length][pattern.length] = true; /* | Space O(N * M) */ - return tabu -} + return tabu; +}; var search = (text, pattern, tabu) => { - for (let row = text.length; 0 <= row; row--){ /* Time O(N) */ - for (let col = (pattern.length - 1); (0 <= col); col--){/* Time O(M) */ + for (let row = text.length; 0 <= row; row--) { + /* Time O(N) */ + for (let col = pattern.length - 1; 0 <= col; col--) { + /* Time O(M) */ const isTextDefined = row < text.length, isTextAndPatternEqual = pattern[col] === text[row], isPatternPeriod = pattern[col] === '.', - isFirstMatch = isTextDefined && (isTextAndPatternEqual || isPatternPeriod), - isNextPatternWildCard = col + 1 < pattern.length && pattern[col + 1] === '*'; + isFirstMatch = + isTextDefined && (isTextAndPatternEqual || isPatternPeriod), + isNextPatternWildCard = + col + 1 < pattern.length && pattern[col + 1] === '*'; - tabu[row][col] = isNextPatternWildCard /* Space O(N * M) */ + tabu[row][col] = isNextPatternWildCard /* Space O(N * M) */ ? tabu[row][col + 2] || (isFirstMatch && tabu[row + 1][col]) : isFirstMatch && tabu[row + 1][col + 1]; } } -} \ No newline at end of file +}; diff --git a/javascript/0012-integer-to-roman.js b/javascript/0012-integer-to-roman.js index 8f79ee3d2..503d864e6 100644 --- a/javascript/0012-integer-to-roman.js +++ b/javascript/0012-integer-to-roman.js @@ -4,80 +4,79 @@ * @return {string} */ -var intToRoman = function(num) { - let ans = ""; - - while(num !== 0){ +var intToRoman = function (num) { + let ans = ''; + while (num !== 0) { //M == 1000 - if(num >= 1000){ + if (num >= 1000) { num -= 1000; - ans += "M"; + ans += 'M'; } //CM == 900 - else if(num >= 900){ + else if (num >= 900) { num -= 900; - ans += "CM"; + ans += 'CM'; } //D == 500 - else if(num >= 500){ + else if (num >= 500) { num -= 500; - ans += "D"; + ans += 'D'; } //CD == 400 - else if(num >= 400){ + else if (num >= 400) { num -= 400; - ans += "CD" + ans += 'CD'; } //C == 100 - else if(num >= 100){ + else if (num >= 100) { num -= 100; - ans += "C"; + ans += 'C'; } //XC == 90 - else if(num >= 90){ + else if (num >= 90) { num -= 90; - ans += "XC"; + ans += 'XC'; } //L == 50; - else if(num >= 50){ + else if (num >= 50) { num -= 50; - ans += "L"; + ans += 'L'; } //XL == 40 - else if(num >= 40){ + else if (num >= 40) { num -= 40; - ans += "XL"; + ans += 'XL'; } //X == 10 - else if(num >= 10){ + else if (num >= 10) { num -= 10; - ans += "X"; + ans += 'X'; } //IX == 9 - else if(num >= 9){ + else if (num >= 9) { num -= 9; - ans += "IX"; + ans += 'IX'; } //V == 5 - else if(num >= 5){ + else if (num >= 5) { num -= 5; - ans += "V"; + ans += 'V'; } //IV == 4 - else if(num >= 4){ + else if (num >= 4) { num -= 4; - ans += "IV"; + ans += 'IV'; } //II == 2 - else if(num >= 2){ + else if (num >= 2) { num -= 2; - ans += "II"; + ans += 'II'; } //I == 1 - else{ + else { num -= 1; - ans += "I"; + ans += 'I'; } } return ans; diff --git a/javascript/0013-roman-to-integer.js b/javascript/0013-roman-to-integer.js index f6bd00410..0490953ae 100644 --- a/javascript/0013-roman-to-integer.js +++ b/javascript/0013-roman-to-integer.js @@ -65,29 +65,29 @@ var romanToInt = function (s) { // Memory Usage: 47.5 MB, less than 18.15% of JavaScript online submissions for Roman to Integer. function romanToInt(s) { - let sum = 0 - let next = null + let sum = 0; + let next = null; const romanArr = { - "I": 1, - "V": 5, - "X": 10, - "L": 50, - "C": 100, - "D": 500, - "M": 1000 - } - for (let i = 0; i < s.length; i++ ) { - next = s[i + 1] || null - const curr = s[i] + I: 1, + V: 5, + X: 10, + L: 50, + C: 100, + D: 500, + M: 1000, + }; + for (let i = 0; i < s.length; i++) { + next = s[i + 1] || null; + const curr = s[i]; if (romanArr[next] > romanArr[curr]) { - sum -= romanArr[curr] - continue + sum -= romanArr[curr]; + continue; } - sum += romanArr[curr] + sum += romanArr[curr]; } - return sum -}; + return sum; +} // Runtime 97 ms // Memory usage: 47.8 MB -// https://leetcode.com/problems/roman-to-integer/submissions/1020204566/ \ No newline at end of file +// https://leetcode.com/problems/roman-to-integer/submissions/1020204566/ diff --git a/javascript/0014-longest-common-prefix.js b/javascript/0014-longest-common-prefix.js index 783c06261..e31d59255 100644 --- a/javascript/0014-longest-common-prefix.js +++ b/javascript/0014-longest-common-prefix.js @@ -3,19 +3,16 @@ * @param {string[]} strs * @return {string} */ -var longestCommonPrefix = function(strs) { - +var longestCommonPrefix = function (strs) { let pre = strs[0]; - - for(let word of strs) { - - for(let i = pre.length - 1; i >= 0; i--) { - - if(pre[i] !== word[i]) { + + for (let word of strs) { + for (let i = pre.length - 1; i >= 0; i--) { + if (pre[i] !== word[i]) { pre = pre.slice(0, i); } } } - + return pre; }; diff --git a/javascript/0015-3sum.js b/javascript/0015-3sum.js index 1f099451a..680920659 100644 --- a/javascript/0015-3sum.js +++ b/javascript/0015-3sum.js @@ -2,9 +2,9 @@ * @param {number[]} nums * @return {number[][]} */ -var threeSum = function(nums) { +var threeSum = function (nums) { const res = []; - nums.sort((a,b) => a-b) + nums.sort((a, b) => a - b); for (let i = 0; i < nums.length; i++) { const a = nums[i]; @@ -30,5 +30,4 @@ var threeSum = function(nums) { } } return res; -} - +}; diff --git a/javascript/0017-letter-combinations-of-a-phone-number.js b/javascript/0017-letter-combinations-of-a-phone-number.js index 3aaa12557..44159caeb 100644 --- a/javascript/0017-letter-combinations-of-a-phone-number.js +++ b/javascript/0017-letter-combinations-of-a-phone-number.js @@ -1,39 +1,43 @@ -/** - * https://leetcode.com/problems/letter-combinations-of-a-phone-number/ - * Time O(N * 4^N) | Space O(N) - * @param {string} digits - * @return {string[]} - */ - var letterCombinations = function(digits, combination = [], combinations = []) { - const isBaseCase = !digits - if (isBaseCase) { - if (combination.length) combinations.push(combination.join('')) - - return combinations; - } - - const letters = phoneButtons[ digits[0] ]; - - for (const char of letters) { - backTrack(digits, char, combination, combinations); - } - - return combinations; -}; - -const backTrack = (digits, char, combination, combinations) => { - combination.push(char) - letterCombinations(digits.slice(1), combination, combinations) - combination.pop() -} - -const phoneButtons = ({ - 2: ['a', 'b', 'c'], - 3: ['d', 'e', 'f'], - 4: ['g', 'h', 'i'], - 5: ['j', 'k', 'l'], - 6: ['m', 'n', 'o'], - 7: ['p', 'q', 'r', 's'], - 8: ['t', 'u', 'v'], - 9: ['w', 'x', 'y', 'z'], -}) +/** + * https://leetcode.com/problems/letter-combinations-of-a-phone-number/ + * Time O(N * 4^N) | Space O(N) + * @param {string} digits + * @return {string[]} + */ +var letterCombinations = function ( + digits, + combination = [], + combinations = [], +) { + const isBaseCase = !digits; + if (isBaseCase) { + if (combination.length) combinations.push(combination.join('')); + + return combinations; + } + + const letters = phoneButtons[digits[0]]; + + for (const char of letters) { + backTrack(digits, char, combination, combinations); + } + + return combinations; +}; + +const backTrack = (digits, char, combination, combinations) => { + combination.push(char); + letterCombinations(digits.slice(1), combination, combinations); + combination.pop(); +}; + +const phoneButtons = { + 2: ['a', 'b', 'c'], + 3: ['d', 'e', 'f'], + 4: ['g', 'h', 'i'], + 5: ['j', 'k', 'l'], + 6: ['m', 'n', 'o'], + 7: ['p', 'q', 'r', 's'], + 8: ['t', 'u', 'v'], + 9: ['w', 'x', 'y', 'z'], +}; diff --git a/javascript/0018-4sum.js b/javascript/0018-4sum.js index fe342ed84..085350aa6 100644 --- a/javascript/0018-4sum.js +++ b/javascript/0018-4sum.js @@ -30,7 +30,7 @@ var fourSum = function (nums, target) { right--; } else { res.push( - quad.concat([sortedNums[left], sortedNums[right]]) + quad.concat([sortedNums[left], sortedNums[right]]), ); left++; while ( diff --git a/javascript/0019-remove-nth-node-from-end-of-list.js b/javascript/0019-remove-nth-node-from-end-of-list.js index 082779863..de5518cc4 100644 --- a/javascript/0019-remove-nth-node-from-end-of-list.js +++ b/javascript/0019-remove-nth-node-from-end-of-list.js @@ -5,13 +5,13 @@ * @param {number} n * @return {ListNode} */ - var removeNthFromEnd = function(head, n) { +var removeNthFromEnd = function (head, n) { const sentinel = new ListNode(); sentinel.next = head; - const fast = moveFast(sentinel, n); /* Time O(N) */ - const slow = moveSlow(sentinel, fast);/* Time O(N) */ + const fast = moveFast(sentinel, n); /* Time O(N) */ + const slow = moveSlow(sentinel, fast); /* Time O(N) */ slow.next = slow.next.next || null; @@ -19,21 +19,23 @@ }; const moveFast = (fast, n) => { - for (let i = 1; i <= (n + 1); i++) {/* Time O(N) */ + for (let i = 1; i <= n + 1; i++) { + /* Time O(N) */ fast = fast.next; } return fast; -} +}; const moveSlow = (slow, fast) => { - while (fast) { /* Time O(N) */ + while (fast) { + /* Time O(N) */ slow = slow.next; fast = fast.next; } return slow; -} +}; /** * https://leetcode.com/problems/remove-nth-node-from-end-of-list/ @@ -42,33 +44,35 @@ const moveSlow = (slow, fast) => { * @param {number} n * @return {ListNode} */ - var removeNthFromEnd = function(head, n) { - const length = getNthFromEnd(head, n);/* Time O(N) */ +var removeNthFromEnd = function (head, n) { + const length = getNthFromEnd(head, n); /* Time O(N) */ const isHead = length < 0; if (isHead) return head.next; - const curr = moveNode(head, length); /* Time O(N) */ + const curr = moveNode(head, length); /* Time O(N) */ curr.next = curr.next.next; - return head + return head; }; const getNthFromEnd = (curr, n, length = 0) => { - while (curr) { /* Time O(N) */ + while (curr) { + /* Time O(N) */ curr = curr.next; length++; } - return (length - n) - 1; -} + return length - n - 1; +}; const moveNode = (curr, length) => { - while (length) { /* Time O(N) */ + while (length) { + /* Time O(N) */ curr = curr.next; length--; } return curr; -} +}; diff --git a/javascript/0020-valid-parentheses.js b/javascript/0020-valid-parentheses.js index c262edd16..e064db845 100644 --- a/javascript/0020-valid-parentheses.js +++ b/javascript/0020-valid-parentheses.js @@ -4,16 +4,17 @@ * @param {string} s * @return {boolean} */ - var isValid = (s, stack = []) => { - for (const bracket of s.split('')) {/* Time O(N) */ +var isValid = (s, stack = []) => { + for (const bracket of s.split('')) { + /* Time O(N) */ const isParenthesis = bracket === '('; - if (isParenthesis) stack.push(')'); /* Space O(N) */ + if (isParenthesis) stack.push(')'); /* Space O(N) */ const isCurlyBrace = bracket === '{'; - if (isCurlyBrace) stack.push('}'); /* Space O(N) */ + if (isCurlyBrace) stack.push('}'); /* Space O(N) */ const isSquareBracket = bracket === '['; - if (isSquareBracket) stack.push(']');/* Space O(N) */ + if (isSquareBracket) stack.push(']'); /* Space O(N) */ const isOpenPair = isParenthesis || isCurlyBrace || isSquareBracket; if (isOpenPair) continue; @@ -24,7 +25,7 @@ if (isInvalid) return false; } - return (stack.length === 0); + return stack.length === 0; }; /** @@ -39,16 +40,23 @@ var isValid = (s, stack = []) => { ']': '[', ')': '(', }; - - for (const char of s) {/* Time O(N) */ - const isBracket = (char in map) - if (!isBracket) { stack.push(char); continue; }/* Space O(N) */ - const isEqual = (stack[stack.length - 1] === map[char]) - if (isEqual) { stack.pop(); continue; } + for (const char of s) { + /* Time O(N) */ + const isBracket = char in map; + if (!isBracket) { + stack.push(char); + continue; + } /* Space O(N) */ + + const isEqual = stack[stack.length - 1] === map[char]; + if (isEqual) { + stack.pop(); + continue; + } return false; } - return (stack.length === 0); + return stack.length === 0; }; diff --git a/javascript/0021-merge-two-sorted-lists.js b/javascript/0021-merge-two-sorted-lists.js index ede603e51..6f9f04dcf 100644 --- a/javascript/0021-merge-two-sorted-lists.js +++ b/javascript/0021-merge-two-sorted-lists.js @@ -5,7 +5,7 @@ * @param {ListNode} list2 * @return {ListNode} */ - var mergeTwoLists = function(list1, list2) { +var mergeTwoLists = function (list1, list2) { const isBaseCase1 = list1 === null; if (isBaseCase1) return list2; @@ -14,18 +14,24 @@ const isL2Greater = list1.val <= list2.val; if (isL2Greater) { - list1.next = mergeTwoLists(list1.next, list2);/* Time O(N + M) | Space O(N + M) */ + list1.next = mergeTwoLists( + list1.next, + list2, + ); /* Time O(N + M) | Space O(N + M) */ return list1; } const isL2Less = list2.val <= list1.val; if (isL2Less) { - list2.next = mergeTwoLists(list1, list2.next);/* Time O(N + M) | Space O(N + M) */ + list2.next = mergeTwoLists( + list1, + list2.next, + ); /* Time O(N + M) | Space O(N + M) */ return list2; } -} +}; /** * https://leetcode.com/problems/merge-two-sorted-lists/ @@ -34,10 +40,11 @@ * @param {ListNode} list2 * @return {ListNode} */ -var mergeTwoLists = function(list1, list2) { - let sentinel = tail = new ListNode(); +var mergeTwoLists = function (list1, list2) { + let sentinel = (tail = new ListNode()); - while (list1 && list2) {/* Time O(N + M) */ + while (list1 && list2) { + /* Time O(N + M) */ const isL2Greater = list1.val <= list2.val; if (isL2Greater) { @@ -54,4 +61,4 @@ var mergeTwoLists = function(list1, list2) { tail.next = list1 || list2; return sentinel.next; -}; \ No newline at end of file +}; diff --git a/javascript/0022-generate-parentheses.js b/javascript/0022-generate-parentheses.js index 436d607b7..3ad89766f 100644 --- a/javascript/0022-generate-parentheses.js +++ b/javascript/0022-generate-parentheses.js @@ -1,98 +1,115 @@ -/** - * DFS - * Time O(((4^N) / (N * SQRT(N)))) | Space O(((4^N) / (N * SQRT(N)))) - * Time O(2^N) | Space O(2^N) - * https://leetcode.com/problems/generate-parentheses - * @param {number} n - * @return {string[]} - */ -var generateParenthesis = (n) => dfs(n); - -const dfs = (n, combos = [], open = 0, close = 0, path = []) => { - const isBaseCase = (path.length === (n * 2)); - if (isBaseCase) { - combos.push(path.join(''));/* Space O(N + N) */ - - return combos; - } - - const isOpen = open < n; - if (isOpen) backTrackOpen(n, combos, open, close, path); /* Time O(2^N) | Space O(2^N) */ - - const isClose = close < open; - if (isClose) backTrackClose(n, combos, open, close, path);/* Time O(2^N) | Space O(2^N) */ - - return combos; -} - -const backTrackOpen = (n, combos, open, close, path) => { - path.push('(');/* Space O(N) */ - dfs(n, combos, (open + 1), close, path);/* Time O(2^N) | Space O(2^N) */ - path.pop(); -} - -const backTrackClose = (n, combos, open, close, path) => { - path.push(')');/* Space O(N) */ - dfs(n, combos, open, (close + 1), path);/* Time O(2^N) | Space O(2^N) */ - path.pop(); -} - -/** - * BFS - * Time O(((4^N) / (N * SQRT(N)))) | Space O(((4^N) / (N * SQRT(N)))) - * Time O(2^N) | Space O(2^N) - * https://leetcode.com/problems/generate-parentheses - * @param {number} n - * @return {string[]} - */ -var generateParenthesis = (n) => bfs(n); - -const bfs = (n, combos = []) => { - const queue = new Queue([ ['', 0, 0] ]); - - while (!queue.isEmpty()) {/* Time O(2^N) */ - const [ str, open, close ] = queue.dequeue(); - - const isBaseCase = ((open === n) && (close === n)); - if (isBaseCase) { - combos.push(str); /* Space O(N) */ - - continue; - } - - const isOpen = open < n; - if (isOpen) queue.enqueue([ (`${str}(`), (open + 1), close ]); /* Space O(2^N) */ - - const isClose = close < open; - if (isClose) queue.enqueue([ (`${str})`), open, (close + 1) ]);/* Space O(2^N) */ - } - - return combos; -} - -/** - * DFS - * Time O(((4^N) / (N * SQRT(N)))) | Space O(((4^N) / (N * SQRT(N)))) - * Time O(2^N) | Space O(2^N) - * https://leetcode.com/problems/generate-parentheses - * @param {number} n - * @return {string[]} - */ -var generateParenthesis = (n, combos = []) => { - const isBaseCase = (n === 0); - if (isBaseCase) { - combos.push(''); - - return combos - } - - for (let c = 0; (c < n); c++) { - for (const left of generateParenthesis(c)) { - for (const right of generateParenthesis(((n - 1) - c))) { - combos.push(`(${left})${right}`); - } - } - } - - return combos -} +/** + * DFS + * Time O(((4^N) / (N * SQRT(N)))) | Space O(((4^N) / (N * SQRT(N)))) + * Time O(2^N) | Space O(2^N) + * https://leetcode.com/problems/generate-parentheses + * @param {number} n + * @return {string[]} + */ +var generateParenthesis = (n) => dfs(n); + +const dfs = (n, combos = [], open = 0, close = 0, path = []) => { + const isBaseCase = path.length === n * 2; + if (isBaseCase) { + combos.push(path.join('')); /* Space O(N + N) */ + + return combos; + } + + const isOpen = open < n; + if (isOpen) + backTrackOpen( + n, + combos, + open, + close, + path, + ); /* Time O(2^N) | Space O(2^N) */ + + const isClose = close < open; + if (isClose) + backTrackClose( + n, + combos, + open, + close, + path, + ); /* Time O(2^N) | Space O(2^N) */ + + return combos; +}; + +const backTrackOpen = (n, combos, open, close, path) => { + path.push('('); /* Space O(N) */ + dfs(n, combos, open + 1, close, path); /* Time O(2^N) | Space O(2^N) */ + path.pop(); +}; + +const backTrackClose = (n, combos, open, close, path) => { + path.push(')'); /* Space O(N) */ + dfs(n, combos, open, close + 1, path); /* Time O(2^N) | Space O(2^N) */ + path.pop(); +}; + +/** + * BFS + * Time O(((4^N) / (N * SQRT(N)))) | Space O(((4^N) / (N * SQRT(N)))) + * Time O(2^N) | Space O(2^N) + * https://leetcode.com/problems/generate-parentheses + * @param {number} n + * @return {string[]} + */ +var generateParenthesis = (n) => bfs(n); + +const bfs = (n, combos = []) => { + const queue = new Queue([['', 0, 0]]); + + while (!queue.isEmpty()) { + /* Time O(2^N) */ + const [str, open, close] = queue.dequeue(); + + const isBaseCase = open === n && close === n; + if (isBaseCase) { + combos.push(str); /* Space O(N) */ + + continue; + } + + const isOpen = open < n; + if (isOpen) + queue.enqueue([`${str}(`, open + 1, close]); /* Space O(2^N) */ + + const isClose = close < open; + if (isClose) + queue.enqueue([`${str})`, open, close + 1]); /* Space O(2^N) */ + } + + return combos; +}; + +/** + * DFS + * Time O(((4^N) / (N * SQRT(N)))) | Space O(((4^N) / (N * SQRT(N)))) + * Time O(2^N) | Space O(2^N) + * https://leetcode.com/problems/generate-parentheses + * @param {number} n + * @return {string[]} + */ +var generateParenthesis = (n, combos = []) => { + const isBaseCase = n === 0; + if (isBaseCase) { + combos.push(''); + + return combos; + } + + for (let c = 0; c < n; c++) { + for (const left of generateParenthesis(c)) { + for (const right of generateParenthesis(n - 1 - c)) { + combos.push(`(${left})${right}`); + } + } + } + + return combos; +}; diff --git a/javascript/0023-merge-k-sorted-lists.js b/javascript/0023-merge-k-sorted-lists.js index b84454b1e..3ed4f8f0d 100644 --- a/javascript/0023-merge-k-sorted-lists.js +++ b/javascript/0023-merge-k-sorted-lists.js @@ -4,7 +4,7 @@ * @param {ListNode[]} lists * @return {ListNode} */ - var mergeKLists = function(lists) { +var mergeKLists = function (lists) { let previous = null; for (let i = 0; i < lists.length; i++) { @@ -14,8 +14,8 @@ return previous; }; -var mergeTwoLists = function(list1, list2) { - let sentinel = tail = new ListNode(0); +var mergeTwoLists = function (list1, list2) { + let sentinel = (tail = new ListNode(0)); while (list1 && list2) { const canAddL1 = list1.val <= list2.val; @@ -41,10 +41,10 @@ var mergeTwoLists = function(list1, list2) { * @param {ListNode[]} lists * @return {ListNode} */ - var mergeKLists = function(lists) { +var mergeKLists = function (lists) { const minHeap = getMinHeap(lists); - return mergeLists(minHeap) + return mergeLists(minHeap); }; const getMinHeap = (lists) => { @@ -57,11 +57,10 @@ const getMinHeap = (lists) => { } return heap; -} - +}; const mergeLists = (minHeap) => { - let sentinel = tail = new ListNode(); + let sentinel = (tail = new ListNode()); while (!minHeap.isEmpty()) { const node = minHeap.dequeue().element; @@ -75,4 +74,4 @@ const mergeLists = (minHeap) => { } return sentinel.next; -} +}; diff --git a/javascript/0025-reverse-nodes-in-k-group.js b/javascript/0025-reverse-nodes-in-k-group.js index 26504326c..24f9b8882 100644 --- a/javascript/0025-reverse-nodes-in-k-group.js +++ b/javascript/0025-reverse-nodes-in-k-group.js @@ -5,14 +5,14 @@ * @param {number} k * @return {ListNode} */ - var reverseKGroup = function(head, k) { - const sentinel = tail = new ListNode(0, head); +var reverseKGroup = function (head, k) { + const sentinel = (tail = new ListNode(0, head)); while (true) { - let [ start, last ]= moveNode(tail, k); + let [start, last] = moveNode(tail, k); if (!last) break; - reverse([ start, tail.next, start ]) + reverse([start, tail.next, start]); const next = tail.next; tail.next = last; @@ -29,10 +29,10 @@ const moveNode = (curr, k) => { k--; } - return [ (curr?.next || null), curr ]; -} + return [curr?.next || null, curr]; +}; -const reverse = ([ prev, curr, start ]) => { +const reverse = ([prev, curr, start]) => { const isSame = () => curr === start; while (!isSame()) { const next = curr.next; @@ -41,4 +41,4 @@ const reverse = ([ prev, curr, start ]) => { prev = curr; curr = next; } -} +}; diff --git a/javascript/0026-remove-duplicates-from-sorted-array.js b/javascript/0026-remove-duplicates-from-sorted-array.js index cc4ae0995..7f103276c 100644 --- a/javascript/0026-remove-duplicates-from-sorted-array.js +++ b/javascript/0026-remove-duplicates-from-sorted-array.js @@ -6,13 +6,13 @@ * @return {number} */ var removeDuplicates = function (nums) { - let swap = 1; + let swap = 1; - for (let i = 1; i < nums.length; i++) { - if (nums[i] != nums[i - 1]) { - nums[swap] = nums[i]; - swap++; + for (let i = 1; i < nums.length; i++) { + if (nums[i] != nums[i - 1]) { + nums[swap] = nums[i]; + swap++; + } } - } - return swap; + return swap; }; diff --git a/javascript/0027-remove-element.js b/javascript/0027-remove-element.js index 236c11b7a..4a8256abf 100644 --- a/javascript/0027-remove-element.js +++ b/javascript/0027-remove-element.js @@ -4,52 +4,49 @@ * @param {number} val * @return {number} */ -var removeElement = function(nums, val) { +var removeElement = function (nums, val) { let ptr1 = nums.length - 2; let ptr2 = nums.length - 1; - - if(!nums) return 0; - if(nums.length === 1) { - if(nums[0] === val) return 0; + + if (!nums) return 0; + if (nums.length === 1) { + if (nums[0] === val) return 0; return 1; } - - while(ptr1 > -1) { - if(nums[ptr2] === val) { + + while (ptr1 > -1) { + if (nums[ptr2] === val) { ptr2--; - - while(nums[ptr1] === val) { + + while (nums[ptr1] === val) { ptr2--; ptr1--; - } - } - else if(nums[ptr1] === val) { + } + } else if (nums[ptr1] === val) { let temp = nums[ptr1]; nums[ptr1] = nums[ptr2]; nums[ptr2] = temp; ptr2--; - } ptr1--; } - + return ptr2 + 1; }; - /** * @param {number[]} nums * @param {number} val * @return {number} */ -var removeElement = function(nums, val) { - for(let i = 0; i < nums.length; i++) { - if(nums[i] === val) { +var removeElement = function (nums, val) { + for (let i = 0; i < nums.length; i++) { + if (nums[i] === val) { nums.splice(i, 1); - i--; + i--; } } - + return nums.length; }; diff --git a/javascript/0028-find-the-index-of-the-first-occurrence-in-a-string.js b/javascript/0028-find-the-index-of-the-first-occurrence-in-a-string.js index b1bd50934..9d019eb9a 100644 --- a/javascript/0028-find-the-index-of-the-first-occurrence-in-a-string.js +++ b/javascript/0028-find-the-index-of-the-first-occurrence-in-a-string.js @@ -1,5 +1,5 @@ /** - * Submission Details: + * Submission Details: * https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/ * Time O(n * m), Space O(1) * Runtime: 48ms (beats 91.92%) || 41.6mb (beats 78.25%) @@ -10,14 +10,15 @@ * @param {string} needle * @return {number} */ -var strStr = function(haystack, needle) { +var strStr = function (haystack, needle) { if (needle.length == 0) return 0; for (let i = 0; i < haystack.length; i++) { - let k = i, j = 0; + let k = i, + j = 0; while (haystack[k] == needle[j] && j < needle.length) { - k++, j++; + (k++, j++); } if (j == needle.length) return i; } - return -1; -} \ No newline at end of file + return -1; +}; diff --git a/javascript/0034-find-first-and-last-position-of-element-in-sorted-array.js b/javascript/0034-find-first-and-last-position-of-element-in-sorted-array.js index c11490e11..fbee52dbe 100644 --- a/javascript/0034-find-first-and-last-position-of-element-in-sorted-array.js +++ b/javascript/0034-find-first-and-last-position-of-element-in-sorted-array.js @@ -6,8 +6,7 @@ * @param {number} target * @return {number[]} */ -var searchRange = function(nums, target) { - +var searchRange = function (nums, target) { const result = []; result.push(binarySearch(true, nums, target)); @@ -17,31 +16,30 @@ var searchRange = function(nums, target) { }; var binarySearch = (isLeftBias, nums, target) => { - let left = 0; - let right = nums.length - 1; - let index = -1; + let left = 0; + let right = nums.length - 1; + let index = -1; - while(left <= right) { - + while (left <= right) { const mid = (left + right) >> 1; - if(target > nums[mid]) { - left = mid+1; + if (target > nums[mid]) { + left = mid + 1; } - if(target < nums[mid]) { - right = mid-1; + if (target < nums[mid]) { + right = mid - 1; } - + const isTarget = target === nums[mid]; - if(isTarget) { - if(isLeftBias) { - index = mid; - right = mid - 1; - } else { - index = mid; - left = mid + 1; - } + if (isTarget) { + if (isLeftBias) { + index = mid; + right = mid - 1; + } else { + index = mid; + left = mid + 1; + } } - } - return index; -} + } + return index; +}; diff --git a/javascript/0036-valid-sudoku.js b/javascript/0036-valid-sudoku.js index dd1256860..8b550066e 100644 --- a/javascript/0036-valid-sudoku.js +++ b/javascript/0036-valid-sudoku.js @@ -6,7 +6,7 @@ * @return {boolean} */ - var isValidSudoku = function (board) { +var isValidSudoku = function (board) { let row = []; let col = []; let squares = new Map(); @@ -20,7 +20,7 @@ squares.set(`${Math.floor(i / 3)}:${Math.floor(j / 3)}`, new Set()); } } - + for (let i = 0; i < 9; i++) { for (let j = 0; j < 9; j++) { if (board[i][j] === '.') { @@ -52,45 +52,55 @@ * @param {character[][]} board * @return {boolean} */ - var isValidSudoku = (board) => { +var isValidSudoku = (board) => { const boards = 3; - const [ boxes, cols, rows ] = getBoards(boards);/* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ - - return searchGrid(board, boxes, cols, rows); /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ + const [boxes, cols, rows] = + getBoards(boards); /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ + + return searchGrid( + board, + boxes, + cols, + rows, + ); /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ }; -var initBoard = (rows, cols) => new Array(rows).fill() - .map(() => new Array(cols).fill(false)); +var initBoard = (rows, cols) => + new Array(rows).fill().map(() => new Array(cols).fill(false)); var getBoards = (boards) => { - const [ rows, cols ] = [ 9, 9 ]; + const [rows, cols] = [9, 9]; - return new Array(boards).fill() - .map(() => initBoard(rows, cols)) -} + return new Array(boards).fill().map(() => initBoard(rows, cols)); +}; var searchGrid = (board, boxes, cols, rows) => { - const [ _rows, _cols ] = [ 9, 9 ]; + const [_rows, _cols] = [9, 9]; - for (let row = 0; row < _rows; row++) {/* Time O(ROWS)*/ - for (let col = 0; col < _cols; col++) {/* Time O(COLS)*/ + for (let row = 0; row < _rows; row++) { + /* Time O(ROWS)*/ + for (let col = 0; col < _cols; col++) { + /* Time O(COLS)*/ const char = board[row][col]; - const index = (Math.floor(row / 3) * 3) + Math.floor(col / 3); + const index = Math.floor(row / 3) * 3 + Math.floor(col / 3); const isEmpty = char === '.'; if (isEmpty) continue; - const hasMoved = boxes[index][(char - 1)] || cols[col][(char - 1)] || rows[row][(char - 1)]; + const hasMoved = + boxes[index][char - 1] || + cols[col][char - 1] || + rows[row][char - 1]; if (hasMoved) return false; - rows[row][(char - 1)] = true; /* Space O(ROWS * COLS)*/ - cols[col][(char - 1)] = true; /* Space O(ROWS * COLS)*/ - boxes[index][(char - 1)] = true; /* Space O(ROWS * COLS)*/ + rows[row][char - 1] = true; /* Space O(ROWS * COLS)*/ + cols[col][char - 1] = true; /* Space O(ROWS * COLS)*/ + boxes[index][char - 1] = true; /* Space O(ROWS * COLS)*/ } } return true; -} +}; /** * Array - Fixed Size @@ -99,36 +109,49 @@ var searchGrid = (board, boxes, cols, rows) => { * @param {character[][]} board * @return {boolean} */ - var isValidSudoku = (board) => { - const [ boards, cells ] = [ 3, 9]; - const [ boxes, rows, cols ] = getBoards(boards, cells);/* Time O(ROWS * COLS) | Space O(CELLS) */ - - return searchGrid(board, boxes, rows, cols); /* Time O(ROWS * COLS) | Space O(CELLS) */ -} +var isValidSudoku = (board) => { + const [boards, cells] = [3, 9]; + const [boxes, rows, cols] = getBoards( + boards, + cells, + ); /* Time O(ROWS * COLS) | Space O(CELLS) */ + + return searchGrid( + board, + boxes, + rows, + cols, + ); /* Time O(ROWS * COLS) | Space O(CELLS) */ +}; -var getBoards = (boards, cells) => new Array(boards).fill() - .map(() => new Array(cells).fill(0)); +var getBoards = (boards, cells) => + new Array(boards).fill().map(() => new Array(cells).fill(0)); var searchGrid = (board, boxes, rows, cols) => { - const [ _rows, _cols ] = [ 9, 9 ]; + const [_rows, _cols] = [9, 9]; - for (let row = 0; row < _rows; row++) {/* Time O(ROWS)*/ - for (let col = 0; col < _cols; col++) {/* Time O(COLS)*/ + for (let row = 0; row < _rows; row++) { + /* Time O(ROWS)*/ + for (let col = 0; col < _cols; col++) { + /* Time O(COLS)*/ const char = board[row][col]; const position = 1 << (char - 1); - const index = (Math.floor(row / 3) * 3) + Math.floor(col / 3); + const index = Math.floor(row / 3) * 3 + Math.floor(col / 3); const isEmpty = char === '.'; if (isEmpty) continue; - const hasMoved = (boxes[index] & position) || (cols[col] & position) || (rows[row] & position); + const hasMoved = + boxes[index] & position || + cols[col] & position || + rows[row] & position; if (hasMoved) return false; - rows[row] |= position; /* Space O(CELLS)*/ - cols[col] |= position; /* Space O(CELLS)*/ - boxes[index] |= position; /* Space O(CELLS)*/ + rows[row] |= position; /* Space O(CELLS)*/ + cols[col] |= position; /* Space O(CELLS)*/ + boxes[index] |= position; /* Space O(CELLS)*/ } } return true; -} +}; diff --git a/javascript/0039-combination-sum.js b/javascript/0039-combination-sum.js index 4850e5c9c..185826ee7 100644 --- a/javascript/0039-combination-sum.js +++ b/javascript/0039-combination-sum.js @@ -5,7 +5,13 @@ * @param {number} target * @return {number[][]} */ - var combinationSum = function (candidates, target, index = 0, combination = [], combinations = []) { +var combinationSum = function ( + candidates, + target, + index = 0, + combination = [], + combinations = [], +) { const isBaseCase = target < 0; if (isBaseCase) return combinations; @@ -17,10 +23,16 @@ } return combinations; -} +}; const backTrack = (candidates, target, i, combination, combinations) => { combination.push(candidates[i]); - combinationSum(candidates, (target - candidates[i]), i, combination, combinations); + combinationSum( + candidates, + target - candidates[i], + i, + combination, + combinations, + ); combination.pop(); -} \ No newline at end of file +}; diff --git a/javascript/0040-combination-sum-ii.js b/javascript/0040-combination-sum-ii.js index 8002c31db..c726a9ccc 100644 --- a/javascript/0040-combination-sum-ii.js +++ b/javascript/0040-combination-sum-ii.js @@ -5,13 +5,19 @@ * @param {number} target * @return {number[][]} */ - var combinationSum2 = function(candidates, target) { - candidates.sort((a, b) => a - b) +var combinationSum2 = function (candidates, target) { + candidates.sort((a, b) => a - b); - return dfs(candidates, target) + return dfs(candidates, target); }; -const dfs = (candidates, target, index = 0, combination = [], combinations = []) => { +const dfs = ( + candidates, + target, + index = 0, + combination = [], + combinations = [], +) => { const isBaseCase = target < 0; if (isBaseCase) return combinations; @@ -19,21 +25,21 @@ const dfs = (candidates, target, index = 0, combination = [], combinations = []) if (isTarget) { if (combination.length) combinations.push(combination.slice()); - return combinations + return combinations; } for (let i = index; i < candidates.length; i++) { - const isDuplicate = (index < i) && (candidates[i - 1] === candidates[i]); + const isDuplicate = index < i && candidates[i - 1] === candidates[i]; if (isDuplicate) continue; backTrack(candidates, target, i, combination, combinations); } return combinations; -} +}; const backTrack = (candidates, target, i, combination, combinations) => { - combination.push(candidates[i]) - dfs(candidates, (target - candidates[i]), (i + 1), combination, combinations) - combination.pop() -} + combination.push(candidates[i]); + dfs(candidates, target - candidates[i], i + 1, combination, combinations); + combination.pop(); +}; diff --git a/javascript/0041-first-missing-positive.js b/javascript/0041-first-missing-positive.js index a22dc1cc8..32f38aee2 100644 --- a/javascript/0041-first-missing-positive.js +++ b/javascript/0041-first-missing-positive.js @@ -6,51 +6,47 @@ * @return {number} */ var firstMissingPositive = (nums) => { - cyclicSort(nums); + cyclicSort(nums); - return search(nums); + return search(nums); }; const cyclicSort = (nums, index = 0) => { - while (index < nums.length) { - const num = nums[index]; - const indexKey = (num - 1); - const indexNum = nums[indexKey]; - - if (canSwap(nums, num, indexNum)) { - swap(nums, index, indexKey); - continue; - } + while (index < nums.length) { + const num = nums[index]; + const indexKey = num - 1; + const indexNum = nums[indexKey]; + + if (canSwap(nums, num, indexNum)) { + swap(nums, index, indexKey); + continue; + } - index += 1; - } -} + index += 1; + } +}; const search = (nums, index = 0) => { - while (index < nums.length) { - const num = nums[index]; - const indexKey = (index + 1); + while (index < nums.length) { + const num = nums[index]; + const indexKey = index + 1; - if (!isEqual(num, indexKey)) return indexKey; + if (!isEqual(num, indexKey)) return indexKey; - index += 1; - } + index += 1; + } - return (nums.length + 1); -} + return nums.length + 1; +}; const canSwap = (nums, num, indexNum) => - isPositive(num) && - isInBound(num, nums) && - !isEqual(num, indexNum); - -const swap = (nums, index, indexKey) => - [nums[index], nums[indexKey]] = [nums[indexKey], nums[index]]; - -const isPositive = (num) => (0 < num); + isPositive(num) && isInBound(num, nums) && !isEqual(num, indexNum); -const isInBound = (num, nums) => (num <= nums.length); +const swap = (nums, index, indexKey) => + ([nums[index], nums[indexKey]] = [nums[indexKey], nums[index]]); -const isEqual = (num, indexNum) => (num === indexNum); +const isPositive = (num) => 0 < num; +const isInBound = (num, nums) => num <= nums.length; +const isEqual = (num, indexNum) => num === indexNum; diff --git a/javascript/0042-trapping-rain-water.js b/javascript/0042-trapping-rain-water.js index 299612d4c..ded4c4682 100644 --- a/javascript/0042-trapping-rain-water.js +++ b/javascript/0042-trapping-rain-water.js @@ -1,38 +1,37 @@ /** * Linear - * Time O(n) | Space O(n) + * Time O(n) | Space O(n) * https://leetcode.com/problems/trapping-rain-water * @param {number[]} height * @return {number} - * + * */ -var trap = function(height) { - +var trap = function (height) { const maxLeft = []; const maxRight = []; const minLeftRight = []; let current = 0; - for(let i = 0; i < height.length; i++) { - maxLeft.push(current); - current = Math.max(current, height[i]); + for (let i = 0; i < height.length; i++) { + maxLeft.push(current); + current = Math.max(current, height[i]); } current = 0; - for(let i = height.length - 1; i > -1; i--) { + for (let i = height.length - 1; i > -1; i--) { maxRight.push(current); current = Math.max(current, height[i]); } - // because the elements were added reverse. + // because the elements were added reverse. maxRight.reverse(); - for(let i = 0; i < height.length; i++) { - const minofLeftRight = Math.min(maxLeft[i],maxRight[i]); + for (let i = 0; i < height.length; i++) { + const minofLeftRight = Math.min(maxLeft[i], maxRight[i]); minLeftRight.push(minofLeftRight); } let water = 0; - for(let i = 0; i < height.length; i++) { - if(minLeftRight[i] - height[i] > 0) { + for (let i = 0; i < height.length; i++) { + if (minLeftRight[i] - height[i] > 0) { water += minLeftRight[i] - height[i]; } } @@ -40,7 +39,6 @@ var trap = function(height) { return water; }; - /** * https://leetcode.com/problems/trapping-rain-water/ * Time O(N) | Space O(1) @@ -58,7 +56,7 @@ var trap = function (height) { left, maxLeft, right, - maxRight + maxRight, ); const isRightGreater = leftHeight <= rightHeight; diff --git a/javascript/0043-multiply-strings.js b/javascript/0043-multiply-strings.js index 8a1e007ec..d95d17f13 100644 --- a/javascript/0043-multiply-strings.js +++ b/javascript/0043-multiply-strings.js @@ -7,58 +7,60 @@ * @return {string} */ var multiply = (num1, num2) => { - const isZero = ((num1 === '0') || (num2 === '0')); + const isZero = num1 === '0' || num2 === '0'; if (isZero) return '0'; - const buffer = initBuffer(num1, num2);/* | Space (N + M) */ + const buffer = initBuffer(num1, num2); /* | Space (N + M) */ - multiplication(num1, num2, buffer) /* Time O(N * M) */ - removeLeadingZero(buffer); /* Time O(N + M) | Time O(N + M)*/ + multiplication(num1, num2, buffer); /* Time O(N * M) */ + removeLeadingZero(buffer); /* Time O(N + M) | Time O(N + M)*/ - return buffer.join(''); /* Time O(N + M) | Space O(N + M) */ + return buffer.join(''); /* Time O(N + M) | Space O(N + M) */ }; var initBuffer = (num1, num2) => { - const size = (num1.length + num2.length); - - return new Array(size).fill(0);/* Space (N + M) */ -} + const size = num1.length + num2.length; + + return new Array(size).fill(0); /* Space (N + M) */ +}; var multiplication = (num1, num2, buffer) => { - for (let i = (num1.length - 1); (0 <= i); i--) {/* Time O(N) */ - for (let j = (num2.length - 1); (0 <= j); j--) {/* Time O(M) */ - update(num1, i, num2, j, buffer); /* Space O(N + M) */ + for (let i = num1.length - 1; 0 <= i; i--) { + /* Time O(N) */ + for (let j = num2.length - 1; 0 <= j; j--) { + /* Time O(M) */ + update(num1, i, num2, j, buffer); /* Space O(N + M) */ } } -} +}; var removeLeadingZero = (buffer) => { - const isLeadZero = (buffer[0] === 0); + const isLeadZero = buffer[0] === 0; if (!isLeadZero) return; - buffer.shift();/* Time O(N + M) | Time O(N + M) */ -} + buffer.shift(); /* Time O(N + M) | Time O(N + M) */ +}; var update = (num1, i, num2, j, buffer) => { - const curPos = (i + j); + const curPos = i + j; const prevPos = curPos + 1; const carry = buffer[prevPos]; const product = getProduct(num1, i, num2, j); - const sum = (carry + product); + const sum = carry + product; - const remainder = (sum % 10); - const value = ((sum - remainder) / 10); + const remainder = sum % 10; + const value = (sum - remainder) / 10; - buffer[prevPos] = remainder;/* Space O(N + M) */ - buffer[curPos] += value; /* Space O(N + M) */ -} + buffer[prevPos] = remainder; /* Space O(N + M) */ + buffer[curPos] += value; /* Space O(N + M) */ +}; var getProduct = (num1, i, num2, j) => { - const [ iNum, jNum ] = [ Number(num1[i]), Number(num2[j]) ]; + const [iNum, jNum] = [Number(num1[i]), Number(num2[j])]; - return (iNum * jNum); -} + return iNum * jNum; +}; /** * Matrix @@ -69,48 +71,51 @@ var getProduct = (num1, i, num2, j) => { * @return {string} */ var multiply = (num1, num2) => { - const isZero = ((num1 === '0') || (num2 === '0')); + const isZero = num1 === '0' || num2 === '0'; if (isZero) return '0'; - const buffer = initBuffer(num1, num2);/* | Space O(N + M) */ + const buffer = initBuffer(num1, num2); /* | Space O(N + M) */ - multiplication(num1, num2, buffer); /* Time O(N * M) | Space O(N + M) */ - removeLeadingZero(buffer); /* Time O(N + M) | Space O(N + M) */ + multiplication(num1, num2, buffer); /* Time O(N * M) | Space O(N + M) */ + removeLeadingZero(buffer); /* Time O(N + M) | Space O(N + M) */ - return buffer.join(''); /* Time O(N + M) | Space O(N + M) */ + return buffer.join(''); /* Time O(N + M) | Space O(N + M) */ }; -var initBuffer = (num1, num2) => new Array(num1.length + num2.length).fill(0);/* Space O(N + M) */ +var initBuffer = (num1, num2) => + new Array(num1.length + num2.length).fill(0); /* Space O(N + M) */ var multiplication = (num1, num2, buffer) => { - [ num1, num2 ] = /* Time O(N + M) */ - [ reverse(num1), reverse(num2) ]; + [num1, num2] = /* Time O(N + M) */ [reverse(num1), reverse(num2)]; - for (var i1 in num1) {/* Time O(N) */ - for (var i2 in num2) {/* Time O(M) */ - update(num1, i1, num2, i2, buffer);/* Space O(N + M) */ + for (var i1 in num1) { + /* Time O(N) */ + for (var i2 in num2) { + /* Time O(M) */ + update(num1, i1, num2, i2, buffer); /* Space O(N + M) */ } } - buffer.reverse();/* Time O(N + M) */ -} + buffer.reverse(); /* Time O(N + M) */ +}; -const reverse = (s) => s - .split('') /* Time O(K) | Space O (K) */ - .reverse();/* Time O(K) */ +const reverse = (s) => + s + .split('') /* Time O(K) | Space O (K) */ + .reverse(); /* Time O(K) */ var update = (num1, i1, num2, i2, buffer) => { const product = num1[i1] * num2[i2]; const index = Number(i1) + Number(i2); - buffer[index] += product; /* Space O(N + M) */ - buffer[(index + 1)] += Math.floor(buffer[index] / 10);/* Space O(N + M) */ - buffer[index] = (buffer[index] % 10); /* Space O(N + M) */ -} + buffer[index] += product; /* Space O(N + M) */ + buffer[index + 1] += Math.floor(buffer[index] / 10); /* Space O(N + M) */ + buffer[index] = buffer[index] % 10; /* Space O(N + M) */ +}; var removeLeadingZero = (buffer) => { - const isZero = (buffer[0] === 0); + const isZero = buffer[0] === 0; if (!isZero) return; - buffer.shift();/* Time O(N + M) | Space O(N + M) */ -} \ No newline at end of file + buffer.shift(); /* Time O(N + M) | Space O(N + M) */ +}; diff --git a/javascript/0045-jump-game-ii.js b/javascript/0045-jump-game-ii.js index 1fe87cf54..43bdcd08f 100644 --- a/javascript/0045-jump-game-ii.js +++ b/javascript/0045-jump-game-ii.js @@ -5,7 +5,7 @@ * @return {number} */ var jump = function (nums) { - let [ left, right, jumps ] = [ 0, 0, 0 ]; + let [left, right, jumps] = [0, 0, 0]; while (right < nums.length - 1) { const maxReach = getMaxReach(nums, left, right); @@ -25,7 +25,7 @@ const getMaxReach = (nums, left, right, maxReach = 0) => { } return maxReach; -} +}; /** * https://leetcode.com/problems/jump-game-ii/ @@ -33,15 +33,18 @@ const getMaxReach = (nums, left, right, maxReach = 0) => { * @param {number[]} nums * @return {number} */ - var jump = function(nums) { - let [ jumps, currentJumpEnd, farthest ] = [ 0, 0, 0]; - +var jump = function (nums) { + let [jumps, currentJumpEnd, farthest] = [0, 0, 0]; + for (let i = 0; i < nums.length - 1; i++) { - farthest = Math.max(farthest, (i + nums[i])); + farthest = Math.max(farthest, i + nums[i]); - const canJump = i === currentJumpEnd - if (canJump) { jumps++; currentJumpEnd = farthest; } + const canJump = i === currentJumpEnd; + if (canJump) { + jumps++; + currentJumpEnd = farthest; + } } return jumps; -} \ No newline at end of file +}; diff --git a/javascript/0046-permutations.js b/javascript/0046-permutations.js index aec6eda35..6f724df0d 100644 --- a/javascript/0046-permutations.js +++ b/javascript/0046-permutations.js @@ -1,66 +1,69 @@ -/** - * https://leetcode.com/problems/permutations/solution/ - * Time O(N!) | Space(N!) - * @param {number[]} nums - * @return {number[][]} - */ - var permute = function(nums) { - return dfs(nums) -} - -var dfs = function(nums, permutation = [], permutations = []) { - const isBaseCase = nums.length === permutation.length - if (isBaseCase) return permutations.push(permutation.slice()) - - for (let i = 0; i < nums.length; i++) { - if (permutation.includes(nums[i])) continue; - - backTrack(nums, i, permutation, permutations); - } - - return permutations; -} - -const backTrack = (nums, i, permutation, permutations) => { - permutation.push(nums[i]) - dfs(nums, permutation, permutations) - permutation.pop() -} - -/** - * https://leetcode.com/problems/permutations/solution/ - * Time O(N!) | Space(N!) - * @param {number[]} nums - * @return {number[][]} - */ -var permute = function(nums) { - return bfs(nums) -} - -const bfs = (nums, levels = [[]], permutations = []) => { - for (const num of nums) { - for (let i = (levels.length - 1); 0 <= i; i--) { - const previousLevel = levels.shift() - - for (let index = 0; index < (previousLevel.length + 1); index++) { - const level = reArrangeSet(previousLevel, num, index) - - const isBaseCase = level.length === nums.length; - if (isBaseCase) { - permutations.push(level); - continue - } - - levels.push(level) - } - } - } - - return permutations -} - -const reArrangeSet = (previousLevel, num, index) => { - const [ before, after ] = [ previousLevel.slice(0, index), previousLevel.slice(index) ] - - return [...before, num, ...after] -} +/** + * https://leetcode.com/problems/permutations/solution/ + * Time O(N!) | Space(N!) + * @param {number[]} nums + * @return {number[][]} + */ +var permute = function (nums) { + return dfs(nums); +}; + +var dfs = function (nums, permutation = [], permutations = []) { + const isBaseCase = nums.length === permutation.length; + if (isBaseCase) return permutations.push(permutation.slice()); + + for (let i = 0; i < nums.length; i++) { + if (permutation.includes(nums[i])) continue; + + backTrack(nums, i, permutation, permutations); + } + + return permutations; +}; + +const backTrack = (nums, i, permutation, permutations) => { + permutation.push(nums[i]); + dfs(nums, permutation, permutations); + permutation.pop(); +}; + +/** + * https://leetcode.com/problems/permutations/solution/ + * Time O(N!) | Space(N!) + * @param {number[]} nums + * @return {number[][]} + */ +var permute = function (nums) { + return bfs(nums); +}; + +const bfs = (nums, levels = [[]], permutations = []) => { + for (const num of nums) { + for (let i = levels.length - 1; 0 <= i; i--) { + const previousLevel = levels.shift(); + + for (let index = 0; index < previousLevel.length + 1; index++) { + const level = reArrangeSet(previousLevel, num, index); + + const isBaseCase = level.length === nums.length; + if (isBaseCase) { + permutations.push(level); + continue; + } + + levels.push(level); + } + } + } + + return permutations; +}; + +const reArrangeSet = (previousLevel, num, index) => { + const [before, after] = [ + previousLevel.slice(0, index), + previousLevel.slice(index), + ]; + + return [...before, num, ...after]; +}; diff --git a/javascript/0048-rotate-image.js b/javascript/0048-rotate-image.js index 5dde51336..45003145c 100644 --- a/javascript/0048-rotate-image.js +++ b/javascript/0048-rotate-image.js @@ -4,36 +4,48 @@ * @param {number[][]} matrix * @return {void} Do not return anything, modify matrix in-place instead. */ - var rotate = (matrix) => { - transpose(matrix);/* Time O(ROWS * COLS) */ - reflect(matrix); /* Time O(ROWS * COLS) */ +var rotate = (matrix) => { + transpose(matrix); /* Time O(ROWS * COLS) */ + reflect(matrix); /* Time O(ROWS * COLS) */ }; var transpose = (matrix) => { const rows = matrix.length; - for (let row = 0; (row < rows); row++) {/* Time O(ROWS) */ - for (let col = (row + 1); (col < rows); col++) {/* Time O(COLS) */ + for (let row = 0; row < rows; row++) { + /* Time O(ROWS) */ + for (let col = row + 1; col < rows; col++) { + /* Time O(COLS) */ swap1(matrix, row, col); } } }; -var swap1 = (matrix, row, col) => [matrix[row][col], matrix[col][row]] = [matrix[col][row], matrix[row][col]]; +var swap1 = (matrix, row, col) => + ([matrix[row][col], matrix[col][row]] = [ + matrix[col][row], + matrix[row][col], + ]); var reflect = (matrix) => { const rows = matrix.length; - for (let row = 0; (row < rows); row++) {/* Time O(ROWS) */ - for (let col = 0; (col < (rows / 2)); col++) {/* Time O(COLS) */ - const reflection = ((rows - col) - 1); + for (let row = 0; row < rows; row++) { + /* Time O(ROWS) */ + for (let col = 0; col < rows / 2; col++) { + /* Time O(COLS) */ + const reflection = rows - col - 1; swap2(matrix, row, col, reflection); } } -} +}; -var swap2 = (matrix, row, col, reflection) => [matrix[row][col], matrix[row][reflection]] = [matrix[row][reflection], matrix[row][col]]; +var swap2 = (matrix, row, col, reflection) => + ([matrix[row][col], matrix[row][reflection]] = [ + matrix[row][reflection], + matrix[row][col], + ]); /** * Time O(ROWS * COLS) | Space O(1) @@ -41,9 +53,9 @@ var swap2 = (matrix, row, col, reflection) => [matrix[row][col], matrix[row][ref * @param {number[][]} matrix * @return {void} Do not return anything, modify matrix in-place instead. */ - var rotate = (matrix) => { - reverse(matrix); /* Time O(ROWS) */ - transpose(matrix);/* Time O(ROWS * COLS) */ +var rotate = (matrix) => { + reverse(matrix); /* Time O(ROWS) */ + transpose(matrix); /* Time O(ROWS * COLS) */ }; var reverse = (matrix) => matrix.reverse(); @@ -51,11 +63,17 @@ var reverse = (matrix) => matrix.reverse(); var transpose = (matrix) => { const rows = matrix.length; - for (let row = 0; (row < rows); row++) {/* Time O(ROWS) */ - for (let col = 0; (col < row); col++) {/* Time O(COLS) */ + for (let row = 0; row < rows; row++) { + /* Time O(ROWS) */ + for (let col = 0; col < row; col++) { + /* Time O(COLS) */ swap(matrix, row, col); } } -} +}; -var swap = (matrix, row, col) => [matrix[row][col], matrix[col][row]] = [matrix[col][row], matrix[row][col]]; \ No newline at end of file +var swap = (matrix, row, col) => + ([matrix[row][col], matrix[col][row]] = [ + matrix[col][row], + matrix[row][col], + ]); diff --git a/javascript/0049-group-anagrams.js b/javascript/0049-group-anagrams.js index 409d31a36..5c9c24bbe 100644 --- a/javascript/0049-group-anagrams.js +++ b/javascript/0049-group-anagrams.js @@ -9,25 +9,29 @@ var groupAnagrams = (words, map = new Map()) => { if (!words.length) return []; - groupWords(words, map); /* Time O(N * (K * log(K)) | Space O(N * K) */ + groupWords(words, map); /* Time O(N * (K * log(K)) | Space O(N * K) */ - return [ ...map.values() ];/* Time O(N) | Space O(N * K) */ + return [...map.values()]; /* Time O(N) | Space O(N * K) */ }; var groupWords = (words, map) => { - for (const original of words) {/* Time O(N) */ - const sorted = reorder(original);/* Time O(K * log(K)) | Space O(K) */ + for (const original of words) { + /* Time O(N) */ + const sorted = reorder(original); /* Time O(K * log(K)) | Space O(K) */ const values = map.get(sorted) || []; - values.push(original); /* | Space O(N) */ - map.set(sorted, values); /* | Space O(N * K) */ + values.push(original); /* | Space O(N) */ + map.set(sorted, values); /* | Space O(N * K) */ } -} +}; -const reorder = (str) => str - .split('') /* Time O(K) | Space O(K) */ - .sort((a, b) => a.localeCompare(b))/* Time O(K * log(K)) | Space O(1 || log(K)) */ - .join(''); /* Time O(K) | Space O(K) */ +const reorder = (str) => + str + .split('') /* Time O(K) | Space O(K) */ + .sort((a, b) => + a.localeCompare(b), + ) /* Time O(K * log(K)) | Space O(1 || log(K)) */ + .join(''); /* Time O(K) | Space O(K) */ /** * Hash Map @@ -39,35 +43,35 @@ const reorder = (str) => str var groupAnagrams = (words, map = new Map()) => { if (!words.length) return []; - groupWords(words, map); /* Time O(N * K) | Space O(N * K) */ + groupWords(words, map); /* Time O(N * K) | Space O(N * K) */ - return [ ...map.values() ];/* Time O(N) | Space O(N * K) */ -} + return [...map.values()]; /* Time O(N) | Space O(N * K) */ +}; var groupWords = (words, map) => { - for (const original of words) {/* Time O(N) */ + for (const original of words) { + /* Time O(N) */ const hash = getHash(original); /* Time O(K) | Space O(1) */ const values = map.get(hash) || []; - values.push(original); /* | Space O(N) */ - map.set(hash, values); /* | Space O(N * K) */ + values.push(original); /* | Space O(N) */ + map.set(hash, values); /* | Space O(N * K) */ } -} +}; const getHash = (word) => { const frequency = new Array(26).fill(0); - for (const char of word) {/* Time O(K) */ - const charCode = getCode(char);/* Time O(1) | Space (1) */ + for (const char of word) { + /* Time O(K) */ + const charCode = getCode(char); /* Time O(1) | Space (1) */ - frequency[charCode]++; /* | Space O(1) */ + frequency[charCode]++; /* | Space O(1) */ } - return buildHash(frequency) -} + return buildHash(frequency); +}; const getCode = (char) => char.charCodeAt(0) - 'a'.charCodeAt(0); const buildHash = (frequency) => frequency.toString(); - - diff --git a/javascript/0050-powx-n.js b/javascript/0050-powx-n.js index 8e8c03b7a..6eda4c383 100644 --- a/javascript/0050-powx-n.js +++ b/javascript/0050-powx-n.js @@ -6,25 +6,26 @@ * @param {number} n * @return {number} */ - var myPow = (x, n) => { +var myPow = (x, n) => { if (n < 0) { - x = (1 / x); - n = (-n); + x = 1 / x; + n = -n; } - return getPow(x, n);/* Time O(N) */ -} + return getPow(x, n); /* Time O(N) */ +}; var getPow = (x, n, pow = 1) => { - for (let i = 0; i < n; i++) {/* Time O(N) */ + for (let i = 0; i < n; i++) { + /* Time O(N) */ pow = pow * x; } return pow; -} +}; /** - * DFS + * DFS * Time (log(N)) | Space O(log(N)) * https://leetcode.com/problems/powx-n/ * @param {number} x @@ -32,19 +33,21 @@ var getPow = (x, n, pow = 1) => { * @return {number} */ var myPow = (x, n) => { - const isBaseCase1 = ((x === 1.0) || (n === 0)); + const isBaseCase1 = x === 1.0 || n === 0; if (isBaseCase1) return 1; - const isBaseCase2 = (n === 1); + const isBaseCase2 = n === 1; if (isBaseCase2) return x; - const isEven = ((n % 2) === 0); - if (isEven) return myPow((x * x), (n / 2));/* Time O(log(N)) | Space O(log(N)) */ + const isEven = n % 2 === 0; + if (isEven) + return myPow(x * x, n / 2); /* Time O(log(N)) | Space O(log(N)) */ - const isOdd = ((n % 2) === 1); - if (isOdd) return (x * myPow(x, (n - 1)));/* Time O(log(N)) | Space O(log(N)) */ + const isOdd = n % 2 === 1; + if (isOdd) + return x * myPow(x, n - 1); /* Time O(log(N)) | Space O(log(N)) */ - return (1 / myPow(x, -n)); + return 1 / myPow(x, -n); }; /** @@ -56,52 +59,51 @@ var myPow = (x, n) => { * @return {number} */ var myPow = (x, n) => { - const isBaseCase = (n === 0); + const isBaseCase = n === 0; if (isBaseCase) return 1; const abs = Math.abs(n); - const isEven = ((abs % 2) === 0); + const isEven = abs % 2 === 0; const power = isEven - ? myPow((x * x), (abs / 2)) /* Time O(log(N)) | Space O(log(N)) */ - : (myPow((x * x), ((abs - 1) / 2)) * x);/* Time O(log(N)) | Space O(log(N)) */ + ? myPow(x * x, abs / 2) /* Time O(log(N)) | Space O(log(N)) */ + : myPow(x * x, (abs - 1) / 2) * + x; /* Time O(log(N)) | Space O(log(N)) */ - const isNegative = (n < 0); + const isNegative = n < 0; - return isNegative - ? (1 / power) - : power; + return isNegative ? 1 / power : power; }; /** - * Fast Power - Recursive + * Fast Power - Recursive * Time O(log(N)) | Space O(log(N)) * https://leetcode.com/problems/powx-n/ * @param {number} x * @param {number} n * @return {number} */ - var myPow = (x, n) => { +var myPow = (x, n) => { if (n < 0) { x = 1 / x; n = -n; } - return fastPow(x, n);/* Time O(log(N)) | Space O(log(N)) */ -} + return fastPow(x, n); /* Time O(log(N)) | Space O(log(N)) */ +}; var fastPow = (x, n) => { const isBaseCase = n === 0; if (isBaseCase) return 1.0; - const half = fastPow(x, n / 2);/* Time O(log(N)) | Space O(log(N)) */ + const half = fastPow(x, n / 2); /* Time O(log(N)) | Space O(log(N)) */ - const isEven = ((n % 2) === 0); - if (isEven) return (half * half); + const isEven = n % 2 === 0; + if (isEven) return half * half; - const isOdd = ((n % 2) === 1); - if (isOdd) return ((half * half) * x); -} + const isOdd = n % 2 === 1; + if (isOdd) return half * half * x; +}; /** * Fast Power - Iterative @@ -111,25 +113,26 @@ var fastPow = (x, n) => { * @param {number} n * @return {number} */ - var myPow = (x, n) => { +var myPow = (x, n) => { if (n < 0) { - x = (1 / x); - n = (-n); + x = 1 / x; + n = -n; } - let [ pow, product ] = [ 1, x ]; + let [pow, product] = [1, x]; - for (let i = n; (0 < i); i = (i >> 1)) {/* Time O(log(N)) */ - const isOdd = ((i % 2) === 1); - if (isOdd) pow = (pow * product); + for (let i = n; 0 < i; i = i >> 1) { + /* Time O(log(N)) */ + const isOdd = i % 2 === 1; + if (isOdd) pow = pow * product; - product = (product * product); + product = product * product; } return pow; -} - - /** +}; + +/** * Number - Math * Time O(1) | Space O(1) * https://leetcode.com/problems/powx-n/ @@ -137,6 +140,6 @@ var fastPow = (x, n) => { * @param {number} n * @return {number} */ - var myPow = (x, n) => { - return Math.pow(x,n).toFixed(5); -} +var myPow = (x, n) => { + return Math.pow(x, n).toFixed(5); +}; diff --git a/javascript/0051-n-queens.js b/javascript/0051-n-queens.js index ad9d7a37b..ab78d40ed 100644 --- a/javascript/0051-n-queens.js +++ b/javascript/0051-n-queens.js @@ -4,7 +4,12 @@ * @param {number} n * @return {string[][]} */ -function solveNQueens(n, colSet = new Set(), posDiagSet = new Set(), negDiagSet = new Set()) { +function solveNQueens( + n, + colSet = new Set(), + posDiagSet = new Set(), + negDiagSet = new Set(), +) { const board = new Array(n).fill().map(() => new Array(n).fill('.')); return dfs(board, n, colSet, posDiagSet, negDiagSet); @@ -13,7 +18,7 @@ function solveNQueens(n, colSet = new Set(), posDiagSet = new Set(), negDiagSet const dfs = (board, n, colSet, posDiagSet, negDiagSet, row = 0, moves = []) => { const isBaseCase = row === n; if (isBaseCase) { - const rows = board.map((_row) => _row.join('')) + const rows = board.map((_row) => _row.join('')); moves.push(rows); @@ -21,25 +26,37 @@ const dfs = (board, n, colSet, posDiagSet, negDiagSet, row = 0, moves = []) => { } for (let col = 0; col < n; col++) { - const hasQueen = colSet.has(col) || posDiagSet.has(row + col) || negDiagSet.has(row - col) + const hasQueen = + colSet.has(col) || + posDiagSet.has(row + col) || + negDiagSet.has(row - col); if (hasQueen) continue; backTrack(board, n, row, col, colSet, posDiagSet, negDiagSet, moves); } - return moves -} - -const backTrack = (board, n, row, col, colSet, posDiagSet, negDiagSet, moves) => { + return moves; +}; + +const backTrack = ( + board, + n, + row, + col, + colSet, + posDiagSet, + negDiagSet, + moves, +) => { colSet.add(col); posDiagSet.add(row + col); negDiagSet.add(row - col); - board[row][col] = "Q"; + board[row][col] = 'Q'; - dfs(board, n, colSet, posDiagSet, negDiagSet, (row + 1), moves); + dfs(board, n, colSet, posDiagSet, negDiagSet, row + 1, moves); colSet.delete(col); posDiagSet.delete(row + col); negDiagSet.delete(row - col); - board[row][col] = "."; -} + board[row][col] = '.'; +}; diff --git a/javascript/0053-maximum-subarray.js b/javascript/0053-maximum-subarray.js index 3280515a9..6f22d2a2f 100644 --- a/javascript/0053-maximum-subarray.js +++ b/javascript/0053-maximum-subarray.js @@ -4,7 +4,7 @@ * @param {number[]} nums * @return {number} */ - var maxSubArray = function(nums, maxSum = -Infinity) { +var maxSubArray = function (nums, maxSum = -Infinity) { for (let i = 0, sum = 0; i < nums.length; i++) { for (let j = i; j < nums.length; j++) { sum += nums[j]; @@ -13,7 +13,7 @@ } return maxSum; -} +}; /** * https://leetcode.com/problems/maximum-subarray/ @@ -21,39 +21,39 @@ * @param {number[]} nums * @return {number} */ -var maxSubArray = function(nums, left = 0, right = nums.length - 1) { - const isBaseCase = (right < left) +var maxSubArray = function (nums, left = 0, right = nums.length - 1) { + const isBaseCase = right < left; if (isBaseCase) return -Infinity; const mid = (left + right) >> 1; const guess = nums[mid]; - const leftSum = getLeftSumFromMid(nums, mid, left) - const rightSum = getRightSumFromMid(nums, mid, right) + const leftSum = getLeftSumFromMid(nums, mid, left); + const rightSum = getRightSumFromMid(nums, mid, right); const sum = guess + leftSum + rightSum; - - const leftHalf = maxSubArray(nums, left, (mid - 1)); - const rightHalf = maxSubArray(nums, (mid + 1), right); + + const leftHalf = maxSubArray(nums, left, mid - 1); + const rightHalf = maxSubArray(nums, mid + 1, right); return Math.max(sum, leftHalf, rightHalf); -} +}; const getLeftSumFromMid = (nums, mid, left, sum = 0, maxSum = 0) => { - for (let i = (mid - 1); left <= i; i--) { + for (let i = mid - 1; left <= i; i--) { sum += nums[i]; maxSum = Math.max(maxSum, sum); } - + return maxSum; -} +}; const getRightSumFromMid = (nums, mid, right, sum = 0, maxSum = 0) => { - for (let i = (mid + 1); i <= right; i++) { + for (let i = mid + 1; i <= right; i++) { sum += nums[i]; maxSum = Math.max(maxSum, sum); } - + return maxSum; -} +}; /** * https://leetcode.com/problems/maximum-subarray/ @@ -61,16 +61,16 @@ const getRightSumFromMid = (nums, mid, right, sum = 0, maxSum = 0) => { * @param {number[]} nums * @return {number} */ -var maxSubArray = function(nums) { - let [ runningSum, maxSum ] = [ nums[0], nums[0] ] - +var maxSubArray = function (nums) { + let [runningSum, maxSum] = [nums[0], nums[0]]; + for (let i = 1; i < nums.length; i++) { - const num = nums[i] - const sum = runningSum + num - - runningSum = Math.max(num, sum) - maxSum = Math.max(maxSum, runningSum) + const num = nums[i]; + const sum = runningSum + num; + + runningSum = Math.max(num, sum); + maxSum = Math.max(maxSum, runningSum); } - - return maxSum -}; \ No newline at end of file + + return maxSum; +}; diff --git a/javascript/0054-spiral-matrix.js b/javascript/0054-spiral-matrix.js index 9eb94dcb4..f065f1ccc 100644 --- a/javascript/0054-spiral-matrix.js +++ b/javascript/0054-spiral-matrix.js @@ -6,65 +6,98 @@ * @param {number[][]} matrix * @return {number[]} */ - var spiralOrder = function(matrix, order = []) { - const [ rows, cols ] = [ (matrix.length - 1), (matrix[0].length - 1) ]; - let [ top, bot, left, right ] = [ 0, rows, 0, cols ]; +var spiralOrder = function (matrix, order = []) { + const [rows, cols] = [matrix.length - 1, matrix[0].length - 1]; + let [top, bot, left, right] = [0, rows, 0, cols]; - const isInBounds = () => ((left <= right) && (top <= bot)); - while (isInBounds()) {/* Time O(ROWS * COLS) */ + const isInBounds = () => left <= right && top <= bot; + while (isInBounds()) { + /* Time O(ROWS * COLS) */ addTop( - matrix, top, bot, left, right, order - ); /* Time O(COLS) | Ignore Auxilary Spsace O(ROWS * COLS) */ + matrix, + top, + bot, + left, + right, + order, + ); /* Time O(COLS) | Ignore Auxilary Spsace O(ROWS * COLS) */ top++; addRight( - matrix, top, bot, left, right, order - ); /* Time O(ROWS) | Ignore Auxilary Spsace O(ROWS * COLS) */ + matrix, + top, + bot, + left, + right, + order, + ); /* Time O(ROWS) | Ignore Auxilary Spsace O(ROWS * COLS) */ right--; - const hasRow = (top <= bot); + const hasRow = top <= bot; if (hasRow) { addBot( - matrix, top, bot, left, right, order - ); /* Time O(COLS) | Ignore Auxilary Spsace O(ROWS * COLS) */ + matrix, + top, + bot, + left, + right, + order, + ); /* Time O(COLS) | Ignore Auxilary Spsace O(ROWS * COLS) */ bot--; } - const hasCol = (left <= right); + const hasCol = left <= right; if (hasCol) { addLeft( - matrix, top, bot, left, right, order - ); /* Time O(ROWS) | Ignore Auxilary Spsace O(ROWS * COLS) */ + matrix, + top, + bot, + left, + right, + order, + ); /* Time O(ROWS) | Ignore Auxilary Spsace O(ROWS * COLS) */ left++; } } - + return order; }; var addTop = (matrix, top, bot, left, right, order) => { - for (let col = left; col <= right; col++) {/* Time O(COLS) */ - order.push(matrix[top][col]); /* Ignore Auxilary Spsace O(ROWS * COLS) */ + for (let col = left; col <= right; col++) { + /* Time O(COLS) */ + order.push( + matrix[top][col], + ); /* Ignore Auxilary Spsace O(ROWS * COLS) */ } -} +}; var addRight = (matrix, top, bot, left, right, order) => { - for (let row = top; row <= bot; row++) {/* Time O(ROWS) */ - order.push(matrix[row][right]); /* Ignore Auxilary Spsace O(ROWS * COLS) */ + for (let row = top; row <= bot; row++) { + /* Time O(ROWS) */ + order.push( + matrix[row][right], + ); /* Ignore Auxilary Spsace O(ROWS * COLS) */ } -} +}; var addBot = (matrix, top, bot, left, right, order) => { - for (let col = right; left <= col; col--) {/* Time O(COLS) */ - order.push(matrix[bot][col]); /* Ignore Auxilary Spsace O(ROWS * COLS) */ + for (let col = right; left <= col; col--) { + /* Time O(COLS) */ + order.push( + matrix[bot][col], + ); /* Ignore Auxilary Spsace O(ROWS * COLS) */ } -} +}; var addLeft = (matrix, top, bot, left, right, order) => { - for (let row = bot; top <= row; row--) {/* Time O(ROWS) */ - order.push(matrix[row][left]); /* Ignore Auxilary Spsace O(ROWS * COLS) */ + for (let row = bot; top <= row; row--) { + /* Time O(ROWS) */ + order.push( + matrix[row][left], + ); /* Ignore Auxilary Spsace O(ROWS * COLS) */ } -} +}; /** * Matrix - Spiral Traversal Post Update @@ -75,58 +108,106 @@ var addLeft = (matrix, top, bot, left, right, order) => { * @return {number[]} */ var spiralOrder = (matrix, order = []) => { - const [ rows, cols ] = [ matrix.length, matrix[0].length ]; - const cells = (rows * cols); - let [ top, bot, left, right ] = [ 0, (rows - 1), 0, (cols - 1) ]; + const [rows, cols] = [matrix.length, matrix[0].length]; + const cells = rows * cols; + let [top, bot, left, right] = [0, rows - 1, 0, cols - 1]; - while (order.length < cells) {/* Time O(ROWS * COLS) */ + while (order.length < cells) { + /* Time O(ROWS * COLS) */ traverse( - matrix, top, bot, left, right, order - ); /* Time O(ROWS * COLS) | Ignore Auxilary Spsace O(ROWS * COLS) */ + matrix, + top, + bot, + left, + right, + order, + ); /* Time O(ROWS * COLS) | Ignore Auxilary Spsace O(ROWS * COLS) */ - top++; bot--; - left++; right--; + top++; + bot--; + left++; + right--; } - + return order; -} +}; var traverse = (matrix, top, bot, left, right, order) => { - addTop(matrix, top, bot, left, right, order); /* Time O(COLS) | Ignore Auxilary Spsace O(ROWS * COLS) */ - addRight(matrix, top, bot, left, right, order);/* Time O(ROWS) | Ignore Auxilary Spsace O(ROWS * COLS)*/ - addBot(matrix, top, bot, left, right, order); /* Time O(COLS) | Ignore Auxilary Spsace O(ROWS * COLS)*/ - addLeft(matrix, top, bot, left, right, order); /* Time O(ROWS) | Ignore Auxilary Spsace O(ROWS * COLS. */ -} + addTop( + matrix, + top, + bot, + left, + right, + order, + ); /* Time O(COLS) | Ignore Auxilary Spsace O(ROWS * COLS) */ + addRight( + matrix, + top, + bot, + left, + right, + order, + ); /* Time O(ROWS) | Ignore Auxilary Spsace O(ROWS * COLS)*/ + addBot( + matrix, + top, + bot, + left, + right, + order, + ); /* Time O(COLS) | Ignore Auxilary Spsace O(ROWS * COLS)*/ + addLeft( + matrix, + top, + bot, + left, + right, + order, + ); /* Time O(ROWS) | Ignore Auxilary Spsace O(ROWS * COLS. */ +}; var addTop = (matrix, top, bot, left, right, order) => { - for (let col = left; (col <= right); col++) {/* Time O(COLS) */ - order.push(matrix[top][col]); /* Ignore Auxilary Spsace O(ROWS * COLS) */ + for (let col = left; col <= right; col++) { + /* Time O(COLS) */ + order.push( + matrix[top][col], + ); /* Ignore Auxilary Spsace O(ROWS * COLS) */ } -} +}; var addRight = (matrix, top, bot, left, right, order) => { - for (let row = (top + 1); (row <= bot); row++) {/* Time O(ROWS) */ - order.push(matrix[row][right]); /* Ignore Auxilary Spsace O(ROWS * COLS) */ + for (let row = top + 1; row <= bot; row++) { + /* Time O(ROWS) */ + order.push( + matrix[row][right], + ); /* Ignore Auxilary Spsace O(ROWS * COLS) */ } -} +}; var addBot = (matrix, top, bot, left, right, order) => { - for (let col = (right - 1); (left <= col); col--) {/* Time O(COLS) */ + for (let col = right - 1; left <= col; col--) { + /* Time O(COLS) */ const isOutOfBounds = top === bot; if (isOutOfBounds) return; - - order.push(matrix[bot][col]); /* Ignore Auxilary Spsace O(ROWS * COLS) */ + + order.push( + matrix[bot][col], + ); /* Ignore Auxilary Spsace O(ROWS * COLS) */ } -} +}; var addLeft = (matrix, top, bot, left, right, order) => { - for (let row = bot - 1; row >= top + 1; row--) {/* Time O(ROWS) */ + for (let row = bot - 1; row >= top + 1; row--) { + /* Time O(ROWS) */ const isOutOfBounds = left === right; if (isOutOfBounds) return; - order.push(matrix[row][left]); /* Ignore Auxilary Spsace O(ROWS * COLS) */ + order.push( + matrix[row][left], + ); /* Ignore Auxilary Spsace O(ROWS * COLS) */ } -} +}; /** * Matrix - Mark Visited In Place @@ -136,84 +217,109 @@ var addLeft = (matrix, top, bot, left, right, order) => { * @param {number[][]} matrix * @return {number[]} */ - var spiralOrder = (matrix) => { - const order = initOrder(matrix);/* | Ignore Auxilary Spsace O(ROWS * COLS) */ +var spiralOrder = (matrix) => { + const order = + initOrder( + matrix, + ); /* | Ignore Auxilary Spsace O(ROWS * COLS) */ - spiral(matrix, order); /* Time O(ROWS * COLS) | Ignore Auxilary Spsace O(ROWS * COLS) */ + spiral( + matrix, + order, + ); /* Time O(ROWS * COLS) | Ignore Auxilary Spsace O(ROWS * COLS) */ return order; -} +}; const initOrder = (matrix, VISITED = 101) => { - const order = [ matrix[0][0] ];/* Ignore Auxilary Spsace O(ROWS * COLS) */ + const order = [matrix[0][0]]; /* Ignore Auxilary Spsace O(ROWS * COLS) */ - matrix[0][0] = VISITED; /* Ignore Auxilary Spsace O(ROWS * COLS) */ + matrix[0][0] = VISITED; /* Ignore Auxilary Spsace O(ROWS * COLS) */ return order; -} +}; var spiral = (matrix, order) => { - let [ row, col, direction, changeDirection ] = [ 0, 0, 0, 0 ]; + let [row, col, direction, changeDirection] = [0, 0, 0, 0]; - while (changeDirection < 2) { /* Time O(ROWS * COLS) | Ignore Auxilary Spsace O(ROWS * COLS) */ - [ row, col, direction, changeDirection ] =/* Time O(ROWS * COLS) | Ignore Auxilary Spsace O(ROWS * COLS) */ + while (changeDirection < 2) { + /* Time O(ROWS * COLS) | Ignore Auxilary Spsace O(ROWS * COLS) */ + [row, col, direction, changeDirection] = + /* Time O(ROWS * COLS) | Ignore Auxilary Spsace O(ROWS * COLS) */ getPointers(matrix, row, col, direction, changeDirection, order); } -} +}; const getPointers = (matrix, row, col, direction, changeDirection, order) => { - [ row, col, direction, changeDirection ] =/* Time O(ROWS * COLS) | Ignore Auxilary Spsace O(ROWS * COLS) */ + [row, col, direction, changeDirection] = + /* Time O(ROWS * COLS) | Ignore Auxilary Spsace O(ROWS * COLS) */ move(matrix, row, col, direction, changeDirection, order); - direction = ((direction + 1) % 4); + direction = (direction + 1) % 4; changeDirection += 1; - return [ row, col, direction, changeDirection ]; -} - -const move = (matrix, row, col, direction, changeDirection, order, VISITED = 101) => { - const [ rows, cols ] = [ matrix.length, matrix[0].length ]; - - while (canMove(matrix, row, rows, col, cols, direction)) {/* Time O(ROWS * COLS) */ - [ row, col ] = getCell(row, col, direction); + return [row, col, direction, changeDirection]; +}; - order.push(matrix[row][col]); /* | Ignore Auxilary Spsace O(ROWS * COLS) */ +const move = ( + matrix, + row, + col, + direction, + changeDirection, + order, + VISITED = 101, +) => { + const [rows, cols] = [matrix.length, matrix[0].length]; + + while (canMove(matrix, row, rows, col, cols, direction)) { + /* Time O(ROWS * COLS) */ + [row, col] = getCell(row, col, direction); + + order.push( + matrix[row][col], + ); /* | Ignore Auxilary Spsace O(ROWS * COLS) */ matrix[row][col] = VISITED; changeDirection = 0; } - return [ row, col, direction, changeDirection ]; -} + return [row, col, direction, changeDirection]; +}; const canMove = (matrix, row, rows, col, cols, direction) => { if (!isInBounds(row, rows, col, cols, direction)) return false; - return !hasSeen(matrix, row, col, direction) -} + return !hasSeen(matrix, row, col, direction); +}; const isInBounds = (row, rows, col, cols, direction) => { - const [ _row, _col ] = getCell(row, col, direction); - const isRowInBounds = ((0 <= _row) && (_row < rows)); - const isColInBounds = ((0 <= _col) && (_col < cols)); + const [_row, _col] = getCell(row, col, direction); + const isRowInBounds = 0 <= _row && _row < rows; + const isColInBounds = 0 <= _col && _col < cols; - return (isRowInBounds && isColInBounds); -} + return isRowInBounds && isColInBounds; +}; const hasSeen = (matrix, row, col, direction, VISITED = 101) => { - const [ _row, _col ] = getCell(row, col, direction); + const [_row, _col] = getCell(row, col, direction); - return (matrix[_row][_col] === VISITED); -} + return matrix[_row][_col] === VISITED; +}; const getDirection = (direction) => { - const directions = [ [0, 1], [1, 0], [0, -1], [-1, 0] ]; - /* RIGHT BOT LEFT TOP */ + const directions = [ + [0, 1], + [1, 0], + [0, -1], + [-1, 0], + ]; + /* RIGHT BOT LEFT TOP */ return directions[direction]; -} +}; const getCell = (row, col, direction) => { - const [ _row, _col ] = getDirection(direction); + const [_row, _col] = getDirection(direction); - return [ (row + _row), (col + _col) ]; -} + return [row + _row, col + _col]; +}; diff --git a/javascript/0055-jump-game.js b/javascript/0055-jump-game.js index 7441763d8..f600fc7cc 100644 --- a/javascript/0055-jump-game.js +++ b/javascript/0055-jump-game.js @@ -3,17 +3,17 @@ * @param {number[]} nums * @return {boolean} */ - var canJump = (nums, index = 0) => { +var canJump = (nums, index = 0) => { const isBaseCase = index === nums.length - 1; if (isBaseCase) return true; - const furthestJump = Math.min(index + nums[index], (nums.length - 1)); - for (let nextIndex = (index + 1); nextIndex <= furthestJump; nextIndex++) { + const furthestJump = Math.min(index + nums[index], nums.length - 1); + for (let nextIndex = index + 1; nextIndex <= furthestJump; nextIndex++) { if (canJump(nums, nextIndex)) return true; } return false; -} +}; /** * Time O(N^2) | Space O(N) @@ -23,16 +23,16 @@ var canJump = (nums) => { const memo = new Array(nums.length).fill(0); memo[memo.length - 1] = 1; - + return canJumpFromIndex(nums, memo); -} +}; const canJumpFromIndex = (nums, memo, index = 0) => { if (memo[index] !== 0) return memo[index] === 1; const furthestJump = Math.min(index + nums[index], nums.length - 1); - for (let nextIndex = (index + 1); nextIndex <= furthestJump; nextIndex++) { - if (!canJumpFromIndex(nums, memo, nextIndex)) continue + for (let nextIndex = index + 1; nextIndex <= furthestJump; nextIndex++) { + if (!canJumpFromIndex(nums, memo, nextIndex)) continue; memo[index] = 1; return true; @@ -40,7 +40,7 @@ const canJumpFromIndex = (nums, memo, index = 0) => { memo[index] = -1; return false; -} +}; /** * Time O(N^2) | Space O(N) @@ -48,19 +48,22 @@ const canJumpFromIndex = (nums, memo, index = 0) => { * @return {boolean} */ var canJump = (nums) => { - const memo = new Array(nums.length).fill(0) + const memo = new Array(nums.length).fill(0); memo[memo.length - 1] = 1; - for (let i = (nums.length - 2); 0 <= i; i--) { + for (let i = nums.length - 2; 0 <= i; i--) { const furthestJump = Math.min(i + nums[i], nums.length - 1); - for (let j = (i + 1); j <= furthestJump; j++) { - const isGood = memo[j] === 1 - if (isGood) { memo[i] = 1; break; } + for (let j = i + 1; j <= furthestJump; j++) { + const isGood = memo[j] === 1; + if (isGood) { + memo[i] = 1; + break; + } } } return memo[0] === 1; -} +}; /** * Time O(N) | Space O(1) @@ -69,18 +72,18 @@ var canJump = (nums) => { */ var canJump = (nums, max = 0, index = 0) => { while (index < nums.length) { - const num = nums[index] - const jumps = num + index - - const canNotReachEnd = max < index - if (canNotReachEnd) return false - - max = Math.max(max, jumps) - index++ + const num = nums[index]; + const jumps = num + index; + + const canNotReachEnd = max < index; + if (canNotReachEnd) return false; + + max = Math.max(max, jumps); + index++; } - return true -} + return true; +}; /** * Time O(N) | Space O(1) @@ -89,10 +92,9 @@ var canJump = (nums, max = 0, index = 0) => { */ var canJump = (nums, right = nums.length - 1) => { for (let i = right; 0 <= i; i--) { - const isJumpable = right <= (i + nums[i]) + const isJumpable = right <= i + nums[i]; if (isJumpable) right = i; } return right === 0; -} - +}; diff --git a/javascript/0056-merge-intervals.js b/javascript/0056-merge-intervals.js index 9ef5779d0..7fb625db6 100644 --- a/javascript/0056-merge-intervals.js +++ b/javascript/0056-merge-intervals.js @@ -6,7 +6,7 @@ */ var merge = function (intervals) { intervals.sort(([aStart, aEnd], [bStart, bEnd]) => - aStart !== bStart ? aStart - bStart : aEnd - bEnd + aStart !== bStart ? aStart - bStart : aEnd - bEnd, ); return mergerInterval(intervals); diff --git a/javascript/0058-length-of-last-word.js b/javascript/0058-length-of-last-word.js index 4ecad082f..d2b940207 100644 --- a/javascript/0058-length-of-last-word.js +++ b/javascript/0058-length-of-last-word.js @@ -2,12 +2,12 @@ * @param {string} s * @return {number} */ - var lengthOfLastWord = function(s) { +var lengthOfLastWord = function (s) { let len = 0; - - for(let i in s) { - if(s[i] != ' ') { - if(s[i-1] == ' ') len = 1; + + for (let i in s) { + if (s[i] != ' ') { + if (s[i - 1] == ' ') len = 1; else len += 1; } } @@ -15,17 +15,16 @@ }; // another approach. starting out from the last so we don't have to go all the way to the end. -var lengthOfLastWord = function(s) { - +var lengthOfLastWord = function (s) { let firstCharOccurance = false; let lastWordLen = 0; - for(let i = s.length - 1; i > -1; i--) { - if(s[i] !== ' ') { + for (let i = s.length - 1; i > -1; i--) { + if (s[i] !== ' ') { firstCharOccurance = true; lastWordLen++; } - if(firstCharOccurance && s[i] === ' ') { + if (firstCharOccurance && s[i] === ' ') { break; } } diff --git a/javascript/0059-spiral-matrix-ii.js b/javascript/0059-spiral-matrix-ii.js index a644bb094..970a24ff2 100644 --- a/javascript/0059-spiral-matrix-ii.js +++ b/javascript/0059-spiral-matrix-ii.js @@ -3,30 +3,32 @@ * @param {number} n * @return {number[][]} */ -var generateMatrix = function(n) { - let matrix = Array.from(Array(n),() => Array(n)); - - let top = 0,bottom = n-1,left = 0,right = n-1; - let element = 1; +var generateMatrix = function (n) { + let matrix = Array.from(Array(n), () => Array(n)); - while(top <= bottom && left <= right){ + let top = 0, + bottom = n - 1, + left = 0, + right = n - 1; + let element = 1; - for(let i = left;i <= right; i++){ + while (top <= bottom && left <= right) { + for (let i = left; i <= right; i++) { matrix[top][i] = element++; } top++; - for(let i = top;i <= bottom; i++){ + for (let i = top; i <= bottom; i++) { matrix[i][right] = element++; } right--; - for(let i = right; i>= left; i--){ + for (let i = right; i >= left; i--) { matrix[bottom][i] = element++; } bottom--; - for(let i = bottom;i >= top; i--){ + for (let i = bottom; i >= top; i--) { matrix[i][left] = element++; } left++; diff --git a/javascript/0062-unique-paths.js b/javascript/0062-unique-paths.js index 9859331d3..c1c0b1e06 100644 --- a/javascript/0062-unique-paths.js +++ b/javascript/0062-unique-paths.js @@ -6,19 +6,19 @@ * @param {number} n * @return {number} */ - var uniquePaths = (row, col) => { - const isBaseCase = ((row == 1) || (col == 1)); +var uniquePaths = (row, col) => { + const isBaseCase = row == 1 || col == 1; if (isBaseCase) return 1; - return dfs(row, col);/* Time O(2^N) | Space O(HEIGHT) */ -} + return dfs(row, col); /* Time O(2^N) | Space O(HEIGHT) */ +}; var dfs = (row, col) => { - const left = uniquePaths((row - 1), col); /* Time O(2^N) | Space O(HEIGHT) */ - const right = uniquePaths(row, (col - 1));/* Time O(2^N) | Space O(HEIGHT) */ + const left = uniquePaths(row - 1, col); /* Time O(2^N) | Space O(HEIGHT) */ + const right = uniquePaths(row, col - 1); /* Time O(2^N) | Space O(HEIGHT) */ - return (left + right); -} + return left + right; +}; /** * DP - Top Down @@ -30,25 +30,42 @@ var dfs = (row, col) => { * @return {number} */ var uniquePaths = (row, col, memo = getMemo(row, col)) => { - const isBaseCase = ((row === 1) || (col === 1)); + const isBaseCase = row === 1 || col === 1; if (isBaseCase) return 1; - const hasSeen = (memo[row][col] !== 0); + const hasSeen = memo[row][col] !== 0; if (hasSeen) return memo[row][col]; - return dfs(row, col, memo);/* Time O(ROWS * COLS) | Space O((ROWS * COLS) + HEIGHT) */ + return dfs( + row, + col, + memo, + ); /* Time O(ROWS * COLS) | Space O((ROWS * COLS) + HEIGHT) */ }; -var getMemo = (row, col) => new Array((row + 1)).fill()/* Time O(ROWS)| Space O(ROWS) */ - .map(() => new Array((col + 1)).fill(0)); /* Time O(COLS)| Space O(COLS) */ +var getMemo = (row, col) => + new Array(row + 1) + .fill() /* Time O(ROWS)| Space O(ROWS) */ + .map(() => + new Array(col + 1).fill(0), + ); /* Time O(COLS)| Space O(COLS) */ var dfs = (row, col, memo) => { - const left = uniquePaths((row - 1), col, memo); /* Time O(ROWS * COLS) | Space O(HEIGHT) */ - const right = uniquePaths(row, (col - 1), memo);/* Time O(ROWS * COLS) | Space O(HEIGHT) */ - - memo[row][col] = (left + right); /* | Space O(ROWS * COLS) */ + const left = uniquePaths( + row - 1, + col, + memo, + ); /* Time O(ROWS * COLS) | Space O(HEIGHT) */ + const right = uniquePaths( + row, + col - 1, + memo, + ); /* Time O(ROWS * COLS) | Space O(HEIGHT) */ + + memo[row][col] = + left + right; /* | Space O(ROWS * COLS) */ return memo[row][col]; -} +}; /** * DP - Bottom Up @@ -60,38 +77,46 @@ var dfs = (row, col, memo) => { * @return {number} */ var uniquePaths = (row, col) => { - const tabu = initTabu(row, col);/* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ + const tabu = initTabu( + row, + col, + ); /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ - search(row, col, tabu); /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ + search(row, col, tabu); /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ return tabu[row - 1][col - 1]; }; var search = (row, col, tabu) => { - for (let _row = 1; (_row < row); _row++) {/* Time O(ROWS)*/ - for (let _col = 1; (_col < col); _col++) {/* Time O(COLS)*/ - const left = (tabu[(_row - 1)][_col]) - const right = (tabu[_row][(_col - 1)]); - - tabu[_row][_col] = (left + right); /* Space O(ROWS * COLS) */ + for (let _row = 1; _row < row; _row++) { + /* Time O(ROWS)*/ + for (let _col = 1; _col < col; _col++) { + /* Time O(COLS)*/ + const left = tabu[_row - 1][_col]; + const right = tabu[_row][_col - 1]; + + tabu[_row][_col] = left + right; /* Space O(ROWS * COLS) */ } } -} +}; var initTabu = (row, col) => { - const tabu = new Array(row).fill() /* Time O(ROWS) | Space O(ROWS) */ - .map(() => new Array(col).fill(0)); /* Time O(COLS) | Space O(COLS) */ - - for (let _row = 0; (_row < row); _row++) {/* Time O(ROWS) */ - tabu[_row][0] = 1; /* | Space O(ROWS * COLS) */ + const tabu = new Array(row) + .fill() /* Time O(ROWS) | Space O(ROWS) */ + .map(() => new Array(col).fill(0)); /* Time O(COLS) | Space O(COLS) */ + + for (let _row = 0; _row < row; _row++) { + /* Time O(ROWS) */ + tabu[_row][0] = 1; /* | Space O(ROWS * COLS) */ } - for (let _col = 0; (_col < col); _col++) {/* Time O(COLS) */ - tabu[0][_col] = 1; /* | Space O(ROWS * COLS) */ + for (let _col = 0; _col < col; _col++) { + /* Time O(COLS) */ + tabu[0][_col] = 1; /* | Space O(ROWS * COLS) */ } return tabu; -} +}; /** * DP - Bottom Up @@ -103,21 +128,24 @@ var initTabu = (row, col) => { * @return {number} */ var uniquePaths = (row, col) => { - const tabu = initTabu(col);/* Time O(COLS) | Space O(COLS) */ + const tabu = initTabu(col); /* Time O(COLS) | Space O(COLS) */ - search(row, col, tabu); /* Time O(ROWS * COLS) | Space O(COLS) */ + search(row, col, tabu); /* Time O(ROWS * COLS) | Space O(COLS) */ - return tabu[(col - 1)]; + return tabu[col - 1]; }; -var initTabu = (col) => new Array(col).fill(1); /* Time O(COLS) | Space O(COLS) */ +var initTabu = (col) => + new Array(col).fill(1); /* Time O(COLS) | Space O(COLS) */ var search = (row, col, tabu) => { - for (let _row = 1; (_row < row); _row++) {/* Time O(ROWS) */ - for (let _col = 1; (_col < col); _col++) {/* Time O(COLS) */ - const prev = tabu[(_col - 1)]; + for (let _row = 1; _row < row; _row++) { + /* Time O(ROWS) */ + for (let _col = 1; _col < col; _col++) { + /* Time O(COLS) */ + const prev = tabu[_col - 1]; - tabu[_col] += prev; /* Space O(COLS) */ + tabu[_col] += prev; /* Space O(COLS) */ } } -} \ No newline at end of file +}; diff --git a/javascript/0066-plus-one.js b/javascript/0066-plus-one.js index a8d528f19..16b29abc8 100644 --- a/javascript/0066-plus-one.js +++ b/javascript/0066-plus-one.js @@ -4,33 +4,34 @@ * @param {number[]} digits * @return {number[]} */ - var plusOne = (digits) => { +var plusOne = (digits) => { add(digits); - carry(digits); /* Time O(N) */ - addLeading(digits);/* | Space O(N) */ + carry(digits); /* Time O(N) */ + addLeading(digits); /* | Space O(N) */ return digits; }; -var add = (digits) => digits[digits.length - 1] += 1; +var add = (digits) => (digits[digits.length - 1] += 1); var carry = (digits) => { - for (let digit = (digits.length - 1); (0 < digit); digit--) {/* Time O(N) */ - const canCarry = (digits[digit] === 10); + for (let digit = digits.length - 1; 0 < digit; digit--) { + /* Time O(N) */ + const canCarry = digits[digit] === 10; if (!canCarry) break; - + digits[digit] = 0; - digits[(digit - 1)] += 1; + digits[digit - 1] += 1; } -} +}; const addLeading = (digits) => { - const canCarry = (digits[0] === 10); + const canCarry = digits[0] === 10; if (!canCarry) return; digits[0] = 1; - digits.push(0);/* Space O(N) */ -} + digits.push(0); /* Space O(N) */ +}; /** * Time O(N) | Space O(N) @@ -39,16 +40,20 @@ const addLeading = (digits) => { * @return {number[]} */ var plusOne = (digits) => { - for (let digit = (digits.length - 1); (0 <= digit); digit--) {/* Time O(N) */ + for (let digit = digits.length - 1; 0 <= digit; digit--) { + /* Time O(N) */ const canCarry = digits[digit] === 9; - if (canCarry) { digits[digit] = 0; continue; } + if (canCarry) { + digits[digit] = 0; + continue; + } digits[digit]++; return digits; } - digits.unshift(1); /* Time O(N) | Space O(N) */ + digits.unshift(1); /* Time O(N) | Space O(N) */ return digits; }; @@ -59,19 +64,19 @@ var plusOne = (digits) => { * @param {number[]} digits * @return {number[]} */ -var plusOne = function(digits) { - var i = digits.length - 1 +var plusOne = function (digits) { + var i = digits.length - 1; while (digits[i] + 1 === 10) { - digits[i] = 0 - i -= 1 + digits[i] = 0; + i -= 1; } if (i < 0) { - digits.unshift(1) + digits.unshift(1); } else { - digits[i] += 1 + digits[i] += 1; } - return digits + return digits; }; diff --git a/javascript/0069-sqrtx.js b/javascript/0069-sqrtx.js index 62f41b53b..923de2635 100644 --- a/javascript/0069-sqrtx.js +++ b/javascript/0069-sqrtx.js @@ -1,24 +1,24 @@ /** - * Binary Search + * Binary Search * https://leetcode.com/problems/sqrtx/ - * + * * Time O(log(n)) | Space O(1) * @param {number} x * @return {number} */ -var mySqrt = function(x) { +var mySqrt = function (x) { let left = 1; let right = x; - - while(left <= right) { + + while (left <= right) { const mid = (left + right) >> 1; - if(mid * mid <= x && (mid+1) * (mid+1) > x) return mid; - if(mid * mid < x) { + if (mid * mid <= x && (mid + 1) * (mid + 1) > x) return mid; + if (mid * mid < x) { left = mid + 1; } else { - right = mid -1; + right = mid - 1; } - } - + } + return 0; - }; +}; diff --git a/javascript/0070-climbing-stairs.js b/javascript/0070-climbing-stairs.js index 4a9cf40e7..30d5dbb2e 100644 --- a/javascript/0070-climbing-stairs.js +++ b/javascript/0070-climbing-stairs.js @@ -5,19 +5,19 @@ * @param {number} n * @return {number} */ - var climbStairs = (n, index = 0) => { - const isBaseCase1 = (n < index); +var climbStairs = (n, index = 0) => { + const isBaseCase1 = n < index; if (isBaseCase1) return 0; - const isBaseCase2 = (index === n); + const isBaseCase2 = index === n; if (isBaseCase2) return 1; - const [ next, nextNext ] = [ (index + 1), (index + 2) ]; - const left = climbStairs(n, next); /* Time O(2^N) | Space O(N) */ - const right = climbStairs(n, nextNext);/* Time O(2^N) | Space O(N) */ + const [next, nextNext] = [index + 1, index + 2]; + const left = climbStairs(n, next); /* Time O(2^N) | Space O(N) */ + const right = climbStairs(n, nextNext); /* Time O(2^N) | Space O(N) */ - return (left + right); -} + return left + right; +}; /** * DP - Top Down @@ -28,20 +28,20 @@ * @return {number} */ var climbStairs = (n, index = 0, memo = Array(n + 1).fill(0)) => { - const isBaseCase1 = (n < index); + const isBaseCase1 = n < index; if (isBaseCase1) return 0; - const isBaseCase2 = (index === n); + const isBaseCase2 = index === n; if (isBaseCase2) return 1; - const hasSeen = (memo[index] !== 0); + const hasSeen = memo[index] !== 0; if (hasSeen) return memo[index]; - const [ next, nextNext ] = [ (index + 1), (index + 2) ]; - const left = climbStairs(n, next, memo); /* Time O(N) | Space O(N) */ - const right = climbStairs(n, nextNext, memo);/* Time O(N) | Space O(N) */ + const [next, nextNext] = [index + 1, index + 2]; + const left = climbStairs(n, next, memo); /* Time O(N) | Space O(N) */ + const right = climbStairs(n, nextNext, memo); /* Time O(N) | Space O(N) */ - memo[index] = (left + right); /* | Space O(N) */ + memo[index] = left + right; /* | Space O(N) */ return memo[index]; }; @@ -54,10 +54,10 @@ var climbStairs = (n, index = 0, memo = Array(n + 1).fill(0)) => { * @return {number} */ var climbStairs = (n) => { - const isBaseCase = (n === 1); + const isBaseCase = n === 1; if (isBaseCase) return 1; - const tabu = initTabu(n);/* Space O(N) */ + const tabu = initTabu(n); /* Space O(N) */ search(n, tabu); @@ -71,15 +71,16 @@ var initTabu = (n) => { tabu[2] = 2; return tabu; -} +}; var search = (n, tabu) => { - for (let index = 3; (index <= n); index++) {/* Time O(N) */ - const [ prev, prevPrev ] = [ (index - 1), (index - 2) ]; + for (let index = 3; index <= n; index++) { + /* Time O(N) */ + const [prev, prevPrev] = [index - 1, index - 2]; - tabu[index] = (tabu[prev] + tabu[prevPrev]);/* Space O(N) */ + tabu[index] = tabu[prev] + tabu[prevPrev]; /* Space O(N) */ } -} +}; /** * DP - Fibonacci Number @@ -89,14 +90,15 @@ var search = (n, tabu) => { * @return {number} */ var climbStairs = (n) => { - const isBaseCase = (n === 1); + const isBaseCase = n === 1; if (isBaseCase) return 1; - let [ next, nextNext ] = [ 1, 2 ]; + let [next, nextNext] = [1, 2]; + + for (let index = 3; index <= n; index++) { + /* Time O(N) */ + const temp = next + nextNext; - for (let index = 3; (index <= n); index++) {/* Time O(N) */ - const temp = (next + nextNext); - next = nextNext; nextNext = temp; } @@ -111,44 +113,50 @@ var climbStairs = (n) => { * @param {number} n * @return {number} */ - var climbStairs = (n) => { - const prev = [ [1, 1], [1, 0] ]; - const next = power(n, prev);/* Time O(log(N)) */ +var climbStairs = (n) => { + const prev = [ + [1, 1], + [1, 0], + ]; + const next = power(n, prev); /* Time O(log(N)) */ return next[0][0]; -} +}; -const power = (n, prev) => { - let next = [ [1, 0], [0, 1] ]; +const power = (n, prev) => { + let next = [ + [1, 0], + [0, 1], + ]; const isEmpty = () => n === 0; - while (!isEmpty()) {/* Time O(log(N)) */ + while (!isEmpty()) { + /* Time O(log(N)) */ const isBit = (n & 1) === 1; - if (isBit) next = multiply(next, prev);/* Time O(1) | Space O(1) */ + if (isBit) next = multiply(next, prev); /* Time O(1) | Space O(1) */ n >>= 1; - prev = multiply(prev, prev); /* Time O(1) | Space O(1) */ + prev = multiply(prev, prev); /* Time O(1) | Space O(1) */ } return next; -} +}; const multiply = (prev, next) => { - const [ rows, cols ] = [ 2, 2 ]; - const matrix = new Array(rows).fill() - .map(() => new Array(cols).fill(0)); + const [rows, cols] = [2, 2]; + const matrix = new Array(rows).fill().map(() => new Array(cols).fill(0)); - for (let row = 0; (row < rows); row++) { - for (let col = 0; (col < cols); col++) { - const left = (prev[row][0] * next[0][col]); - const right = (prev[row][1] * next[1][col]); + for (let row = 0; row < rows; row++) { + for (let col = 0; col < cols; col++) { + const left = prev[row][0] * next[0][col]; + const right = prev[row][1] * next[1][col]; - matrix[row][col] = (left + right); + matrix[row][col] = left + right; } } return matrix; -} +}; /** * Math - Fibonacci Formula @@ -158,11 +166,11 @@ const multiply = (prev, next) => { * @return {number} */ var climbStairs = (n, sqrt5 = Math.sqrt(5)) => { - const phi = ((sqrt5 + 1) / 2); - const psi = ((sqrt5 - 1) / 2); + const phi = (sqrt5 + 1) / 2; + const psi = (sqrt5 - 1) / 2; - const phiPow = Math.pow(phi, (n + 1)); - const psiPow = Math.pow(psi, (n + 1)); + const phiPow = Math.pow(phi, n + 1); + const psiPow = Math.pow(psi, n + 1); - return ((phiPow - psiPow) / sqrt5); -} + return (phiPow - psiPow) / sqrt5; +}; diff --git a/javascript/0071-simplify-path.js b/javascript/0071-simplify-path.js index 0bdaef80b..4089b0962 100644 --- a/javascript/0071-simplify-path.js +++ b/javascript/0071-simplify-path.js @@ -1,4 +1,3 @@ - /** * Stack * Time O(N) | Space O(N) @@ -6,7 +5,7 @@ * @param {string} path * @return {string} */ -var simplifyPath = (path, slash = '/', stack = []) => { +var simplifyPath = (path, slash = '/', stack = []) => { const paths = path.split(slash).filter(Boolean); for (const _path of paths) traversePath(_path, stack); @@ -20,17 +19,13 @@ const traversePath = (path, stack) => { if (canPop(path, stack)) stack.pop(); }; -const canPush = (path) => !( - isCurrentDirectory(path) || - isParentDirectory(path) -); +const canPush = (path) => + !(isCurrentDirectory(path) || isParentDirectory(path)); -const canPop = (path, stack) => - isParentDirectory(path) && - !isEmpty(stack); +const canPop = (path, stack) => isParentDirectory(path) && !isEmpty(stack); -const isCurrentDirectory = (path) => (path === '.'); +const isCurrentDirectory = (path) => path === '.'; -const isParentDirectory = (path) => (path === '..'); +const isParentDirectory = (path) => path === '..'; -const isEmpty = ({ length }) => (0 === length); +const isEmpty = ({ length }) => 0 === length; diff --git a/javascript/0072-edit-distance.js b/javascript/0072-edit-distance.js index d4522c974..7303c0b67 100644 --- a/javascript/0072-edit-distance.js +++ b/javascript/0072-edit-distance.js @@ -6,29 +6,55 @@ * @param {string} word2 * @return {number} */ - var minDistance = (word1, word2, i = 0, j = 0) => { - const isBaseCase1 = ((word1.length * word2.length) === 0); - if (isBaseCase1) return (word1.length + word2.length); +var minDistance = (word1, word2, i = 0, j = 0) => { + const isBaseCase1 = word1.length * word2.length === 0; + if (isBaseCase1) return word1.length + word2.length; - const isBaseCase2 = (word1.length === i); - if (isBaseCase2) return (word2.length - j); + const isBaseCase2 = word1.length === i; + if (isBaseCase2) return word2.length - j; - const isBaseCase3 = (word2.length === j); - if (isBaseCase3) return (word1.length - i); + const isBaseCase3 = word2.length === j; + if (isBaseCase3) return word1.length - i; - return dfs(word1, word2, i, j);/* Time O(2^(N + M)) | Space O((N * M) + HEIGHT) */ -} + return dfs( + word1, + word2, + i, + j, + ); /* Time O(2^(N + M)) | Space O((N * M) + HEIGHT) */ +}; var dfs = (word1, word2, i, j) => { - const isEqual = (word1[i] === word2[j]); - if (isEqual) return minDistance(word1, word2, (i + 1), (j + 1));/* Time O(2^(N + M)) | Space O((N * M) + HEIGHT) */ - - const insert = minDistance(word1, word2, i, (j + 1)); /* Time O(2^(N + M)) | Space O((N * M) + HEIGHT) */ - const _delete = minDistance(word1, word2, (i + 1), j); /* Time O(2^(N + M)) | Space O((N * M) + HEIGHT) */ - const replace = minDistance(word1, word2, (i + 1), (j + 1)); /* Time O(2^(N + M)) | Space O((N * M) + HEIGHT) */ - - return (Math.min(insert, _delete, replace) + 1); -} + const isEqual = word1[i] === word2[j]; + if (isEqual) + return minDistance( + word1, + word2, + i + 1, + j + 1, + ); /* Time O(2^(N + M)) | Space O((N * M) + HEIGHT) */ + + const insert = minDistance( + word1, + word2, + i, + j + 1, + ); /* Time O(2^(N + M)) | Space O((N * M) + HEIGHT) */ + const _delete = minDistance( + word1, + word2, + i + 1, + j, + ); /* Time O(2^(N + M)) | Space O((N * M) + HEIGHT) */ + const replace = minDistance( + word1, + word2, + i + 1, + j + 1, + ); /* Time O(2^(N + M)) | Space O((N * M) + HEIGHT) */ + + return Math.min(insert, _delete, replace) + 1; +}; /** * DP - Top Down @@ -39,39 +65,81 @@ var dfs = (word1, word2, i, j) => { * @param {string} word2 * @return {number} */ - var minDistance = (word1, word2, i = 0, j = 0, memo = initMemo(word1, word2)) => { - const isBaseCase1 = ((word1.length * word2.length) === 0); - if (isBaseCase1) return (word1.length + word2.length); - - const isBaseCase2 = (word1.length === i); - if (isBaseCase2) return (word2.length - j); - - const isBaseCase3 = (word2.length === j); - if (isBaseCase3) return (word1.length - i); - - const hasSeen = (memo[i][j] !== -1); +var minDistance = ( + word1, + word2, + i = 0, + j = 0, + memo = initMemo(word1, word2), +) => { + const isBaseCase1 = word1.length * word2.length === 0; + if (isBaseCase1) return word1.length + word2.length; + + const isBaseCase2 = word1.length === i; + if (isBaseCase2) return word2.length - j; + + const isBaseCase3 = word2.length === j; + if (isBaseCase3) return word1.length - i; + + const hasSeen = memo[i][j] !== -1; if (hasSeen) return memo[i][j]; - return dfs(word1, word2, i, j, memo);/* Time O(N * M) | Space O((N * M) + HEIGHT) */ -} - -var initMemo = (word1, word2) => new Array(word1.length).fill()/* Time O(N) | Space O(N) */ - .map(() => new Array(word2.length).fill(-1)); /* Time O(N) | Space O(N) */ + return dfs( + word1, + word2, + i, + j, + memo, + ); /* Time O(N * M) | Space O((N * M) + HEIGHT) */ +}; + +var initMemo = (word1, word2) => + new Array(word1.length) + .fill() /* Time O(N) | Space O(N) */ + .map(() => + new Array(word2.length).fill(-1), + ); /* Time O(N) | Space O(N) */ var dfs = (word1, word2, i, j, memo) => { - const isEqual = (word1[i] === word2[j]); + const isEqual = word1[i] === word2[j]; if (isEqual) { - memo[i][j] = minDistance(word1, word2, (i + 1), (j + 1), memo);/* Time O(N * M) | Space O(HEIGHT) */ + memo[i][j] = minDistance( + word1, + word2, + i + 1, + j + 1, + memo, + ); /* Time O(N * M) | Space O(HEIGHT) */ return memo[i][j]; } - const insert = minDistance(word1, word2, i, (j + 1), memo); /* Time O(N * M) | Space O(HEIGHT) */ - const _delete = minDistance(word1, word2, (i + 1), j, memo); /* Time O(N * M) | Space O(HEIGHT) */ - const replace = minDistance(word1, word2, (i + 1), (j + 1), memo); /* Time O(N * M) | Space O(HEIGHT) */ - - memo[i][j] = (Math.min(insert, _delete, replace) + 1); /* | Space O(N * M) */ + const insert = minDistance( + word1, + word2, + i, + j + 1, + memo, + ); /* Time O(N * M) | Space O(HEIGHT) */ + const _delete = minDistance( + word1, + word2, + i + 1, + j, + memo, + ); /* Time O(N * M) | Space O(HEIGHT) */ + const replace = minDistance( + word1, + word2, + i + 1, + j + 1, + memo, + ); /* Time O(N * M) | Space O(HEIGHT) */ + + memo[i][j] = + Math.min(insert, _delete, replace) + + 1; /* | Space O(N * M) */ return memo[i][j]; -} +}; /** * DP - Bottom Up @@ -83,44 +151,51 @@ var dfs = (word1, word2, i, j, memo) => { * @return {number} */ var minDistance = (word1, word2) => { - const isEmpty = ((word1.length * word2.length) === 0); - if (isEmpty) return (word1.length + word2.length); + const isEmpty = word1.length * word2.length === 0; + if (isEmpty) return word1.length + word2.length; - const tabu = initTabu(word1, word2);/* Time O(N * M) | Space O(N * M) */ + const tabu = initTabu(word1, word2); /* Time O(N * M) | Space O(N * M) */ - search(word1, word2, tabu); /* Time O(N * M) | Space O(N * M) */ + search(word1, word2, tabu); /* Time O(N * M) | Space O(N * M) */ return tabu[word1.length][word2.length]; -} +}; var initTabu = (word1, word2) => { - const tabu = new Array((word1.length + 1)).fill()/* Time O(N) | Space O(N) */ - .map(() => new Array((word2.length + 1)).fill(0));/* Time O(M) | Space O(M) */ - - for (let i = 0; (i < (word1.length + 1)); i++) { /* Time O(N) */ - tabu[i][0] = i; /* | Space O(N * M) */ + const tabu = new Array(word1.length + 1) + .fill() /* Time O(N) | Space O(N) */ + .map(() => + new Array(word2.length + 1).fill(0), + ); /* Time O(M) | Space O(M) */ + + for (let i = 0; i < word1.length + 1; i++) { + /* Time O(N) */ + tabu[i][0] = i; /* | Space O(N * M) */ } - for (let j = 0; (j < (word2.length + 1)); j++) { /* Time O(M) */ - tabu[0][j] = j; /* | Space O(N * M) */ + for (let j = 0; j < word2.length + 1; j++) { + /* Time O(M) */ + tabu[0][j] = j; /* | Space O(N * M) */ } return tabu; -} +}; var search = (word1, word2, tabu) => { - for (let i = 1; (i < (word1.length + 1)); i++) {/* Time O(N) */ - for (let j = 1; (j < (word2.length + 1)); j++) {/* Time O(M) */ - const left = (tabu[(i - 1)][j] + 1); - const down = (tabu[i][(j - 1)] + 1); + for (let i = 1; i < word1.length + 1; i++) { + /* Time O(N) */ + for (let j = 1; j < word2.length + 1; j++) { + /* Time O(M) */ + const left = tabu[i - 1][j] + 1; + const down = tabu[i][j - 1] + 1; - const isEqual = (word1[(i - 1)] === word2[(j - 1)]); - const leftDown = (tabu[(i - 1)][(j - 1)] + Number(!isEqual)); + const isEqual = word1[i - 1] === word2[j - 1]; + const leftDown = tabu[i - 1][j - 1] + Number(!isEqual); - tabu[i][j] = Math.min(left, down, leftDown); /* Space O(N * M) */ + tabu[i][j] = Math.min(left, down, leftDown); /* Space O(N * M) */ } } -} +}; /** * DP - Bottom Up @@ -131,42 +206,52 @@ var search = (word1, word2, tabu) => { * @param {string} word2 * @return {number} */ - var minDistance = (word1, word2) => { - const tabu = initTabu(word2);/* Time O(M) | Space O(M) */ +var minDistance = (word1, word2) => { + const tabu = initTabu(word2); /* Time O(M) | Space O(M) */ - search(word1, word2, tabu); /* Time O(N * M) | Space O(M) */ + search(word1, word2, tabu); /* Time O(N * M) | Space O(M) */ return tabu[word2.length]; -} +}; var initTabu = (word2) => { - const tabu = new Array((word2.length + 1)).fill(0);/* Time O(M) | Space O(M) */ + const tabu = new Array(word2.length + 1).fill( + 0, + ); /* Time O(M) | Space O(M) */ - for (let j = 1; (j <= word2.length); j++) { /* Time O(M) */ - tabu[j] = j; /* | Space O(M) */ + for (let j = 1; j <= word2.length; j++) { + /* Time O(M) */ + tabu[j] = j; /* | Space O(M) */ } return tabu; -} +}; var search = (word1, word2, tabu) => { - for (let i = 1; (i <= word1.length); i++) {/* Time O(N) */ - tabu[word2.length] = update(word1, word2, i, tabu);/* Time O(M) | Space (M) */ + for (let i = 1; i <= word1.length; i++) { + /* Time O(N) */ + tabu[word2.length] = update( + word1, + word2, + i, + tabu, + ); /* Time O(M) | Space (M) */ } -} +}; const update = (word1, word2, i, tabu) => { let temp = i; - for (let j = 1; (j <= word2.length); ++j) {/* Time O(M */ - const isEqual = (word1[(i - 1)] === word2[(j - 1)]) + for (let j = 1; j <= word2.length; ++j) { + /* Time O(M */ + const isEqual = word1[i - 1] === word2[j - 1]; const cur = isEqual - ? tabu[(j - 1)] - : (Math.min(tabu[(j - 1)], tabu[j], temp) + 1); + ? tabu[j - 1] + : Math.min(tabu[j - 1], tabu[j], temp) + 1; - tabu[(j - 1)] = temp; /* Space (M) */ + tabu[j - 1] = temp; /* Space (M) */ temp = cur; } return temp; -} \ No newline at end of file +}; diff --git a/javascript/0073-set-matrix-zeroes.js b/javascript/0073-set-matrix-zeroes.js index 1d34684c6..e0f1ee4d0 100644 --- a/javascript/0073-set-matrix-zeroes.js +++ b/javascript/0073-set-matrix-zeroes.js @@ -6,45 +6,53 @@ * @param {number[][]} matrix * @return {void} Do not return anything, modify matrix in-place instead. */ - var setZeroes = function (matrix) { - const [ rows, cols ] = [ matrix.length, matrix[0].length ]; - const [ _row, _col ] = initTabu(rows, cols);/* Space (ROWS + COLS) */ - - fillPlacements(matrix, _row, _col); /* Time O(ROWS * COLS) | Space (ROWS + COLS) */ - setZero(matrix, _row, _col); /* Time O(ROWS * COLS) */ +var setZeroes = function (matrix) { + const [rows, cols] = [matrix.length, matrix[0].length]; + const [_row, _col] = initTabu(rows, cols); /* Space (ROWS + COLS) */ + + fillPlacements( + matrix, + _row, + _col, + ); /* Time O(ROWS * COLS) | Space (ROWS + COLS) */ + setZero(matrix, _row, _col); /* Time O(ROWS * COLS) */ }; const initTabu = (rows, cols) => [ - new Array(rows).fill(1),/* Space O(ROWS) */ - new Array(cols).fill(1) /* Space O(COLS) */ + new Array(rows).fill(1) /* Space O(ROWS) */, + new Array(cols).fill(1) /* Space O(COLS) */, ]; const fillPlacements = (matrix, _row, _col) => { - const [ rows, cols ] = [ matrix.length, matrix[0].length ]; + const [rows, cols] = [matrix.length, matrix[0].length]; - for (let row = 0; (row < rows); row++) {/* Time (ROWS) */ - for (let col = 0; (col < cols); col++) {/* Time (COLS) */ - const isZero = (matrix[row][col] === 0); + for (let row = 0; row < rows; row++) { + /* Time (ROWS) */ + for (let col = 0; col < cols; col++) { + /* Time (COLS) */ + const isZero = matrix[row][col] === 0; if (!isZero) continue; - _row[row] = 0; /* Space (ROWS) */ - _col[col] = 0; /* Space (COLS) */ + _row[row] = 0; /* Space (ROWS) */ + _col[col] = 0; /* Space (COLS) */ } } -} +}; const setZero = (matrix, _row, _col) => { - const [ rows, cols ] = [ matrix.length, matrix[0].length ]; + const [rows, cols] = [matrix.length, matrix[0].length]; - for (let row = 0; (row < rows); row++) {/* Time (ROWS) */ - for (let col = 0; (col < cols); col++) {/* Time (COLS) */ - const canSet = ((_row[row] === 0) || (_col[col] === 0)); + for (let row = 0; row < rows; row++) { + /* Time (ROWS) */ + for (let col = 0; col < cols; col++) { + /* Time (COLS) */ + const canSet = _row[row] === 0 || _col[col] === 0; if (!canSet) continue; matrix[row][col] = 0; } } -} +}; /** * Constant Space @@ -54,20 +62,22 @@ const setZero = (matrix, _row, _col) => { * @return {void} Do not return anything, modify matrix in-place instead. */ var setZeroes = (matrix) => { - const _isColZero = isColZero(matrix);/* Time O(ROWS) */ + const _isColZero = isColZero(matrix); /* Time O(ROWS) */ - setEdgesToZero(matrix); /* Time O(ROWS) */ - setCellsToZero(matrix, _isColZero); /* Time O(ROWS * COLS) */ -} + setEdgesToZero(matrix); /* Time O(ROWS) */ + setCellsToZero(matrix, _isColZero); /* Time O(ROWS * COLS) */ +}; -var isColZero = (matrix) => matrix - .some((row) => row[0] === 0);/* Time O(ROWS) */ +var isColZero = (matrix) => + matrix.some((row) => row[0] === 0); /* Time O(ROWS) */ var setEdgesToZero = (matrix) => { - const [ rows, cols ] = [ matrix.length, matrix[0].length ]; + const [rows, cols] = [matrix.length, matrix[0].length]; - for (let row = 0; (row < rows); row++) {/* Time (ROWS) */ - for (let col = 1; (col < cols); col++) {/* Time (COLS) */ + for (let row = 0; row < rows; row++) { + /* Time (ROWS) */ + for (let col = 1; col < cols; col++) { + /* Time (COLS) */ const canSet = matrix[row][col] === 0; if (!canSet) continue; @@ -75,13 +85,15 @@ var setEdgesToZero = (matrix) => { matrix[0][col] = 0; } } -} +}; var setCellsToZero = (matrix, isColZero) => { - const [ rows, cols ] = [ matrix.length, matrix[0].length ]; + const [rows, cols] = [matrix.length, matrix[0].length]; - for (let row = (rows - 1); (0 <= row); row--) {/* Time (ROWS) */ - for (let col = (cols - 1); (1 <= col); col--) {/* Time (COLS) */ + for (let row = rows - 1; 0 <= row; row--) { + /* Time (ROWS) */ + for (let col = cols - 1; 1 <= col; col--) { + /* Time (COLS) */ if (!isZero(matrix, row, col)) continue; matrix[row][col] = 0; @@ -89,13 +101,13 @@ var setCellsToZero = (matrix, isColZero) => { if (isColZero) matrix[row][0] = 0; } -} +}; var isZero = (matrix, row, col) => { - const [ rowLeftEdge, colTopEdge ] = [ matrix[row][0], matrix[0][col] ]; + const [rowLeftEdge, colTopEdge] = [matrix[row][0], matrix[0][col]]; - return ((rowLeftEdge === 0) || (colTopEdge === 0)); -} + return rowLeftEdge === 0 || colTopEdge === 0; +}; /** * Constant Space @@ -104,56 +116,62 @@ var isZero = (matrix, row, col) => { * @param {number[][]} matrix * @return {void} Do not return anything, modify matrix in-place instead. */ - var setZeroes = (matrix) => { - const isColZero = setEdgesToZero(matrix);/* Time O(ROWS * COLS) */ +var setZeroes = (matrix) => { + const isColZero = setEdgesToZero(matrix); /* Time O(ROWS * COLS) */ - setCellsToZero(matrix); /* Time O(ROWS * COLS) */ + setCellsToZero(matrix); /* Time O(ROWS * COLS) */ - const isZero = (matrix[0][0] === 0); - if (isZero) setFirstRowZero(matrix); /* Time O(COLS) */ + const isZero = matrix[0][0] === 0; + if (isZero) setFirstRowZero(matrix); /* Time O(COLS) */ - if (isColZero) setFirstColZero(matrix); /* Time O(ROWS) */ -} + if (isColZero) setFirstColZero(matrix); /* Time O(ROWS) */ +}; var setCellsToZero = (matrix) => { - const [ rows, cols ] = [ matrix.length, matrix[0].length ]; + const [rows, cols] = [matrix.length, matrix[0].length]; - for (let row = 1; (row < rows); row++) {/* Time O(ROWS) */ - for (let col = 1; (col < cols); col++) {/* Time O(COLS) */ - const isZero = ((matrix[row][0] === 0) || (matrix[0][col] == 0)); + for (let row = 1; row < rows; row++) { + /* Time O(ROWS) */ + for (let col = 1; col < cols; col++) { + /* Time O(COLS) */ + const isZero = matrix[row][0] === 0 || matrix[0][col] == 0; if (!isZero) continue; matrix[row][col] = 0; } } -} +}; var setEdgesToZero = (matrix, isColZero = false) => { - const [ rows, cols ] = [ matrix.length, matrix[0].length ]; + const [rows, cols] = [matrix.length, matrix[0].length]; - for (let row = 0; (row < rows); row++) {/* Time O(ROWS) */ + for (let row = 0; row < rows; row++) { + /* Time O(ROWS) */ if (matrix[row][0] === 0) isColZero = true; - for (let col = 1; (col < cols); col++) {/* Time O(COLS) */ - const canSet = (matrix[row][col] === 0); + for (let col = 1; col < cols; col++) { + /* Time O(COLS) */ + const canSet = matrix[row][col] === 0; if (!canSet) continue; - + matrix[0][col] = 0; matrix[row][0] = 0; } } return isColZero; -} +}; -var setFirstRowZero = (matrix, cols = matrix[0].length) => { - for (let col = 0; (col < cols); col++) {/* Time O(COLS) */ +var setFirstRowZero = (matrix, cols = matrix[0].length) => { + for (let col = 0; col < cols; col++) { + /* Time O(COLS) */ matrix[0][col] = 0; } -} +}; var setFirstColZero = (matrix, rows = matrix.length) => { - for (let row = 0; (row < rows); row++) {/* Time O(ROWS) */ + for (let row = 0; row < rows; row++) { + /* Time O(ROWS) */ matrix[row][0] = 0; } -} \ No newline at end of file +}; diff --git a/javascript/0074-search-a-2d-matrix.js b/javascript/0074-search-a-2d-matrix.js index d5231ee86..52169916e 100644 --- a/javascript/0074-search-a-2d-matrix.js +++ b/javascript/0074-search-a-2d-matrix.js @@ -7,34 +7,34 @@ * @param {number} target * @return {boolean} */ -var searchMatrix = function(matrix, target) { +var searchMatrix = function (matrix, target) { let [rows, cols] = [matrix.length, matrix[0].length]; - let [top, bot] = [0, rows-1]; - - while(top <= bot){ - let row = Math.floor((top + bot) / 2); - if(target > matrix[row][cols-1]) { + let [top, bot] = [0, rows - 1]; + + while (top <= bot) { + let row = Math.floor((top + bot) / 2); + if (target > matrix[row][cols - 1]) { top = row + 1; - } else if(target < matrix[row][0]) { - bot = row - 1; + } else if (target < matrix[row][0]) { + bot = row - 1; } else { break; } } - - if(!(top <= bot)) { + + if (!(top <= bot)) { return false; } - + let row = Math.floor((top + bot) / 2); - let [l, r] = [0, cols-1]; - while(l<=r){ - let m = Math.floor((l + r) /2); - if(target > matrix[row][m]) { - l = m +1; - } else if(target < matrix[row][m]) { + let [l, r] = [0, cols - 1]; + while (l <= r) { + let m = Math.floor((l + r) / 2); + if (target > matrix[row][m]) { + l = m + 1; + } else if (target < matrix[row][m]) { r = m - 1; - } else if(target == matrix[row][m]) { + } else if (target == matrix[row][m]) { return true; } } diff --git a/javascript/0075-sort-colors.js b/javascript/0075-sort-colors.js index ec2d37752..f827004f5 100644 --- a/javascript/0075-sort-colors.js +++ b/javascript/0075-sort-colors.js @@ -1,21 +1,19 @@ // problem link https://leetcode.com/problems/sort-colors // brute force approche O(n^2); -var sortColors = function(nums) { - - for(let i = 0; i < nums.length; i++) { - for(let j = i +1; j < nums.length; j++) { - if(nums[j] < nums[i]) { +var sortColors = function (nums) { + for (let i = 0; i < nums.length; i++) { + for (let j = i + 1; j < nums.length; j++) { + if (nums[j] < nums[i]) { swap(nums, j, i); } } - } - + } + return nums; - }; - -function swap(nums, j, i) { +}; +function swap(nums, j, i) { const temp = nums[j]; nums[j] = nums[i]; nums[i] = temp; @@ -24,28 +22,27 @@ function swap(nums, j, i) { // optimized approche O(n); function sortColors(nums) { - let i = 0; let l = 0; let r = nums.length - 1; - - while(i <= r) { + + while (i <= r) { const num = nums[i]; - if(num === 0) { - swap(nums,i,l); + if (num === 0) { + swap(nums, i, l); i++; l++; - } else if(num === 2) { - swap(nums,i,r); + } else if (num === 2) { + swap(nums, i, r); r--; } else { i++; } - } - + } + return nums; - } - - function swap(nums,i,j) { - [nums[i], nums[j]] = [nums[j],nums[i]]; - } +} + +function swap(nums, i, j) { + [nums[i], nums[j]] = [nums[j], nums[i]]; +} diff --git a/javascript/0078-subsets.js b/javascript/0078-subsets.js index e467f0ea8..fa6850a73 100644 --- a/javascript/0078-subsets.js +++ b/javascript/0078-subsets.js @@ -1,53 +1,53 @@ -/** - * https://leetcode.com/problems/subsets/ - * Time O(N * 2^N) | Space(N) - * @param {number[]} nums - * @return {number[][]} - */ - var subsets = (nums) => { - nums.sort((a, b) => a -b); - - return dfs(nums) -} - -var dfs = (nums, level = 0, set = [], subset = []) => { - subset.push(set.slice()); - - for (let i = level; i < nums.length; i++){ - backTrack(nums, i, set, subset); - } - - return subset -} - -const backTrack = (nums, i, set, subset) => { - set.push(nums[i]); - dfs(nums, (i + 1), set, subset); - set.pop(); -} - -/** - * https://leetcode.com/problems/subsets/ - * Time O(N * 2^N) | Space(N * 2^N) - * @param {number[]} nums - * @return {number[][]} - */ - var subsets = (nums) => { - nums.sort((a, b) => a -b); - - return bfs(nums) -} - -const bfs = (nums, subsets = [[]]) => { - for (const num of nums) { - const levels = subsets.length - - for (let level = 0; level < levels; level++) { - const nextLevel = [ ...subsets[level], num ] - - subsets.push(nextLevel) - } - } - - return subsets -} +/** + * https://leetcode.com/problems/subsets/ + * Time O(N * 2^N) | Space(N) + * @param {number[]} nums + * @return {number[][]} + */ +var subsets = (nums) => { + nums.sort((a, b) => a - b); + + return dfs(nums); +}; + +var dfs = (nums, level = 0, set = [], subset = []) => { + subset.push(set.slice()); + + for (let i = level; i < nums.length; i++) { + backTrack(nums, i, set, subset); + } + + return subset; +}; + +const backTrack = (nums, i, set, subset) => { + set.push(nums[i]); + dfs(nums, i + 1, set, subset); + set.pop(); +}; + +/** + * https://leetcode.com/problems/subsets/ + * Time O(N * 2^N) | Space(N * 2^N) + * @param {number[]} nums + * @return {number[][]} + */ +var subsets = (nums) => { + nums.sort((a, b) => a - b); + + return bfs(nums); +}; + +const bfs = (nums, subsets = [[]]) => { + for (const num of nums) { + const levels = subsets.length; + + for (let level = 0; level < levels; level++) { + const nextLevel = [...subsets[level], num]; + + subsets.push(nextLevel); + } + } + + return subsets; +}; diff --git a/javascript/0079-word-search.js b/javascript/0079-word-search.js index f483a1831..5808ee855 100644 --- a/javascript/0079-word-search.js +++ b/javascript/0079-word-search.js @@ -5,41 +5,40 @@ * @param {string} word * @return {boolean} */ -var exist = function(board, word) { - for(let row = 0; row < board.length; row++) { - for(let col = 0; col < board[0].length; col++){ +var exist = function (board, word) { + for (let row = 0; row < board.length; row++) { + for (let col = 0; col < board[0].length; col++) { if (dfs(board, row, col, word, 0)) return true; } } return false; -} +}; const dfs = (board, row, col, word, index) => { if (index === word.length) return true; if (isOutOfBound(board, row, col)) return false; - if (board[row][col] !== word[index]) return false - + if (board[row][col] !== word[index]) return false; + board[row][col] = '*'; - - const hasWord = Object - .values(directions(row, col)) - .filter(([r, c]) => dfs(board, r, c, word, index + 1)) - .length - + + const hasWord = Object.values(directions(row, col)).filter(([r, c]) => + dfs(board, r, c, word, index + 1), + ).length; + board[row][col] = word[index]; return hasWord; -} +}; const isOutOfBound = (board, row, col) => { - const isRowOutOfBound = row < 0 || board.length - 1 < row - const isColOutOfBound = col < 0 || board[0].length - 1 < col - return isRowOutOfBound || isColOutOfBound -} + const isRowOutOfBound = row < 0 || board.length - 1 < row; + const isColOutOfBound = col < 0 || board[0].length - 1 < col; + return isRowOutOfBound || isColOutOfBound; +}; const directions = (row, col) => ({ up: [row - 1, col], down: [row + 1, col], - left: [row, col - 1,], - right: [row, col + 1] -}) + left: [row, col - 1], + right: [row, col + 1], +}); diff --git a/javascript/0080-remove-duplicates-from-sorted-array-ii.js b/javascript/0080-remove-duplicates-from-sorted-array-ii.js index 15eb88c99..c3a51b22a 100644 --- a/javascript/0080-remove-duplicates-from-sorted-array-ii.js +++ b/javascript/0080-remove-duplicates-from-sorted-array-ii.js @@ -1,44 +1,44 @@ /** -* https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ -* -* Time O(n) | Space O(1) -* @param {number[]} nums -* @return {number} -*/ -var removeDuplicates = function(nums) { - let current = nums[0]; - let sameElCount = 0; + * https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ + * + * Time O(n) | Space O(1) + * @param {number[]} nums + * @return {number} + */ +var removeDuplicates = function (nums) { + let current = nums[0]; + let sameElCount = 0; - for(let i = 0; i < nums.length; i++) { - if(current === nums[i]) { - sameElCount++; - } - if(current !== nums[i]) { - current = nums[i]; - sameElCount = 1; - } - if(sameElCount > 2) { - nums.splice(i,1); - i--; + for (let i = 0; i < nums.length; i++) { + if (current === nums[i]) { + sameElCount++; + } + if (current !== nums[i]) { + current = nums[i]; + sameElCount = 1; + } + if (sameElCount > 2) { + nums.splice(i, 1); + i--; + } } - } }; - /** -* Two pointer -* Time O(n^2) | Space O(1) -* @param {number[]} nums -* @return {number} -*/ -var removeDuplicates2 = function(nums) { - const isEdgeCase = (nums.length < 2) + * Two pointer + * Time O(n^2) | Space O(1) + * @param {number[]} nums + * @return {number} + */ +var removeDuplicates2 = function (nums) { + const isEdgeCase = nums.length < 2; if (isEdgeCase) return nums.length; - let [ left, right ] = [ 2, 2 ]; + let [left, right] = [2, 2]; - while (right < nums.length) {/* Time O(N) */ - const isEqual = (nums[(left - 2)] === nums[right]); + while (right < nums.length) { + /* Time O(N) */ + const isEqual = nums[left - 2] === nums[right]; if (!isEqual) { nums[left] = nums[right]; left += 1; diff --git a/javascript/0084-largest-rectangle-in-histogram.js b/javascript/0084-largest-rectangle-in-histogram.js index a05690713..e52d385a2 100644 --- a/javascript/0084-largest-rectangle-in-histogram.js +++ b/javascript/0084-largest-rectangle-in-histogram.js @@ -4,23 +4,26 @@ * @param {number[]} heights * @return {number} */ -var largestRectangleArea = function(heights, maxArea = 0) { - for (let i = 0; i < heights.length; i++) {/* Time O(N) */ - for (let j = i; j < heights.length; j++) {/* Time O(N) */ +var largestRectangleArea = function (heights, maxArea = 0) { + for (let i = 0; i < heights.length; i++) { + /* Time O(N) */ + for (let j = i; j < heights.length; j++) { + /* Time O(N) */ let min = Infinity; - for (let k = i; k <= j; k++) { /* Time O(N) */ + for (let k = i; k <= j; k++) { + /* Time O(N) */ min = Math.min(min, heights[k]); } - const area = min * ((j - i) + 1); + const area = min * (j - i + 1); maxArea = Math.max(maxArea, area); } } return maxArea; -} +}; /** * https://leetcode.com/problems/largest-rectangle-in-histogram/solution/ @@ -28,21 +31,23 @@ var largestRectangleArea = function(heights, maxArea = 0) { * @param {number[]} heights * @return {number} */ -var largestRectangleArea = function(heights, maxArea = 0) { - for (let i = 0; i < heights.length; i++) {/* Time O(N) */ +var largestRectangleArea = function (heights, maxArea = 0) { + for (let i = 0; i < heights.length; i++) { + /* Time O(N) */ let min = Infinity; - for (let j = i; j < heights.length; j++) {/* Time O(N) */ + for (let j = i; j < heights.length; j++) { + /* Time O(N) */ min = Math.min(min, heights[j]); - const area = min * ((j - i) + 1); + const area = min * (j - i + 1); maxArea = Math.max(maxArea, area); } } return maxArea; -} +}; /** * https://leetcode.com/problems/largest-rectangle-in-histogram/solution/ @@ -50,29 +55,46 @@ var largestRectangleArea = function(heights, maxArea = 0) { * @param {number[]} heights * @return {number} */ -var largestRectangleArea = function(heights, left = 0, right = (heights.length - 1)) { +var largestRectangleArea = function ( + heights, + left = 0, + right = heights.length - 1, +) { const isBaseCase = right < left; if (isBaseCase) return 0; - return divideAndConquer(heights, left, right); /* Time O(N^2) | Space O(N) */ -} + return divideAndConquer( + heights, + left, + right, + ); /* Time O(N^2) | Space O(N) */ +}; const divideAndConquer = (heights, left, right, min = left) => { - for (let i = left; i <= right; i++) { /* Time O(N) */ + for (let i = left; i <= right; i++) { + /* Time O(N) */ const isMinGreater = heights[i] < heights[min]; if (!isMinGreater) continue; min = i; } - const window = (right - left) + 1; + const window = right - left + 1; const area = heights[min] * window; - const leftArea = largestRectangleArea(heights, (min + 1), right)/* Time O(N^2) | Space O(N) */ - const rightArea = largestRectangleArea(heights, left, (min - 1))/* Time O(N^2) | Space O(N) */ + const leftArea = largestRectangleArea( + heights, + min + 1, + right, + ); /* Time O(N^2) | Space O(N) */ + const rightArea = largestRectangleArea( + heights, + left, + min - 1, + ); /* Time O(N^2) | Space O(N) */ return Math.max(area, leftArea, rightArea); -} +}; /** * https://leetcode.com/problems/largest-rectangle-in-histogram/solution/ @@ -80,20 +102,24 @@ const divideAndConquer = (heights, left, right, min = left) => { * @param {number[]} heights * @return {number} */ -var largestRectangleArea = function(heights) { - const { stack, maxArea } = fillStack(heights); /* Time O(N) | Space O(N) */ +var largestRectangleArea = function (heights) { + const { stack, maxArea } = fillStack(heights); /* Time O(N) | Space O(N) */ - return getMaxArea(heights, stack, maxArea); /* Time O(N) */ + return getMaxArea(heights, stack, maxArea); /* Time O(N) */ }; const fillStack = (heights, stack = [], maxArea = 0) => { - for (let index = 0; index < heights.length; index++) {/* Time O(N + N) */ + for (let index = 0; index < heights.length; index++) { + /* Time O(N + N) */ let start = index; - const isCurrHeightLess = ([ prevIndex, prevHeight ], currHeight) => currHeight < prevHeight; - const canShrink = () => isCurrHeightLess(stack[stack.length - 1], heights[index]); - while (stack.length && canShrink()) { /* Time O(N + N) */ - const [ _index, _height ] = stack.pop(); + const isCurrHeightLess = ([prevIndex, prevHeight], currHeight) => + currHeight < prevHeight; + const canShrink = () => + isCurrHeightLess(stack[stack.length - 1], heights[index]); + while (stack.length && canShrink()) { + /* Time O(N + N) */ + const [_index, _height] = stack.pop(); const width = index - _index; const area = _height * width; @@ -101,14 +127,15 @@ const fillStack = (heights, stack = [], maxArea = 0) => { start = _index; } - stack.push([ start, heights[index] ]); /* Space O(N) */ + stack.push([start, heights[index]]); /* Space O(N) */ } - return { stack, maxArea } -} + return { stack, maxArea }; +}; const getMaxArea = (heights, stack, maxArea) => { - for (const [ index, height ] of stack) { /* Time O(N) */ + for (const [index, height] of stack) { + /* Time O(N) */ const width = heights.length - index; const area = height * width; @@ -116,7 +143,4 @@ const getMaxArea = (heights, stack, maxArea) => { } return maxArea; -} - - - +}; diff --git a/javascript/0088-merge-sorted-array.js b/javascript/0088-merge-sorted-array.js index f6b3ac58c..875d1bfcc 100644 --- a/javascript/0088-merge-sorted-array.js +++ b/javascript/0088-merge-sorted-array.js @@ -1,5 +1,5 @@ /** - * Linear + * Linear * Time O(N) | Space O(1) * https://leetcode.com/problems/merge-sorted-array/ * @param {number[]} nums1 @@ -8,8 +8,7 @@ * @param {number} n * @return {void} Do not return anything, modify nums1 in-place instead. */ -var merge = function(nums1, m, nums2, n) { - +var merge = function (nums1, m, nums2, n) { let k = m + n - 1; m = m - 1; n = n - 1; diff --git a/javascript/0090-subsets-ii.js b/javascript/0090-subsets-ii.js index fd614fec8..57b49ddc2 100644 --- a/javascript/0090-subsets-ii.js +++ b/javascript/0090-subsets-ii.js @@ -4,31 +4,30 @@ * @param {number[]} nums * @return {number[][]} */ - var subsetsWithDup = function(nums) { +var subsetsWithDup = function (nums) { nums.sort((a, b) => a - b); return dfs(nums); }; const dfs = (nums, index = 0, set = [], subset = []) => { - subset.push(set.slice()) + subset.push(set.slice()); for (let i = index; i < nums.length; i++) { - const isDuplicate = (index < i) && (nums[i - 1] === nums[i]) + const isDuplicate = index < i && nums[i - 1] === nums[i]; if (isDuplicate) continue; backTrack(nums, i, set, subset); } - return subset -} + return subset; +}; const backTrack = (nums, i, set, subset) => { set.push(nums[i]); - dfs(nums, (i + 1), set, subset); + dfs(nums, i + 1, set, subset); set.pop(); -} - +}; /** * https://leetcode.com/problems/subsets-ii/ @@ -36,29 +35,27 @@ const backTrack = (nums, i, set, subset) => { * @param {number[]} nums * @return {number[][]} */ - var subsetsWithDup = (nums) => { +var subsetsWithDup = (nums) => { nums.sort((a, b) => a - b); - return bfs(nums) -} + return bfs(nums); +}; const bfs = (nums, subsets = [[]]) => { - let levels = subsets.length - 1 + let levels = subsets.length - 1; for (let i = 0; i < nums.length; i++) { - const isPrevDuplicate = (0 < i) && (nums[i - 1] === nums[i]) - const start = isPrevDuplicate - ? (levels + 1) - : 0 + const isPrevDuplicate = 0 < i && nums[i - 1] === nums[i]; + const start = isPrevDuplicate ? levels + 1 : 0; - levels = subsets.length - 1 + levels = subsets.length - 1; - for (let level = start; level < (levels + 1); level++) { - const nextLevel = [ ...subsets[level], nums[i] ] + for (let level = start; level < levels + 1; level++) { + const nextLevel = [...subsets[level], nums[i]]; - subsets.push(nextLevel) + subsets.push(nextLevel); } } - return subsets -} \ No newline at end of file + return subsets; +}; diff --git a/javascript/0091-decode-ways.js b/javascript/0091-decode-ways.js index 74962cf5c..f1dc8a506 100644 --- a/javascript/0091-decode-ways.js +++ b/javascript/0091-decode-ways.js @@ -7,7 +7,7 @@ * @return {number} */ var numDecodings = (str, index = 0, memo = new Map()) => { - const isBaseCase1 = !str.length || (str[index] === '0'); + const isBaseCase1 = !str.length || str[index] === '0'; if (isBaseCase1) return 0; const isisBaseCase2 = index === str.length; @@ -19,22 +19,22 @@ var numDecodings = (str, index = 0, memo = new Map()) => { }; const dfs = (str, index, memo) => { - let count = numDecodings(str, (index + 1), memo); + let count = numDecodings(str, index + 1, memo); if (isTwoDigit(str, index)) { - count += numDecodings(str, (index + 2), memo); + count += numDecodings(str, index + 2, memo); } memo.set(index, count); return count; -} +}; var isTwoDigit = (str, index) => { - const twoDigit = Number(str.slice(index, (index + 2))); + const twoDigit = Number(str.slice(index, index + 2)); - return (10 <= twoDigit) && (twoDigit <= 26); -} + return 10 <= twoDigit && twoDigit <= 26; +}; /** * DP - Bottom Up @@ -45,7 +45,7 @@ var isTwoDigit = (str, index) => { * @return {number} */ var numDecodings = (s) => { - const isBaseCase = !s.length || s[0] === '0' + const isBaseCase = !s.length || s[0] === '0'; if (isBaseCase) return 0; const tabu = getTabu(s); @@ -53,34 +53,32 @@ var numDecodings = (s) => { decode(s, tabu); return tabu[s.length]; -} +}; const getTabu = (s) => { const tabu = new Array(s.length + 1).fill(0); tabu[0] = 1; - tabu[1] = (s[1] === '0') - ? 0 - : 1; + tabu[1] = s[1] === '0' ? 0 : 1; return tabu; -} +}; var decode = (s, tabu) => { for (let curr = 2; curr < tabu.length; curr++) { - const [ prev, prevPrev ] = [ (curr - 1), (curr - 2) ]; + const [prev, prevPrev] = [curr - 1, curr - 2]; const isEqual = s[prev] === '0'; if (!isEqual) tabu[curr] += tabu[prev]; if (isTwoDigit(s, curr)) tabu[curr] += tabu[prevPrev]; } -} +}; var isTwoDigit = (s, index) => { - const twoDigit = Number(s.slice((index - 2), index)); + const twoDigit = Number(s.slice(index - 2, index)); return 10 <= twoDigit && twoDigit <= 26; -} +}; /** * 2 Pointer - previous + previousPrevious @@ -94,10 +92,10 @@ var numDecodings = (s) => { if (isBaseCase) return 0; return decode(s); -} +}; var decode = (s) => { - let [ prev, prevPrev ] = [ 1, 1 ]; + let [prev, prevPrev] = [1, 1]; for (let curr = 1; curr < s.length; curr++) { const temp = prev; @@ -111,12 +109,12 @@ var decode = (s) => { } return prev; -} +}; var isTwoDigit = (s, i) => { - const [ prevChar, curChar ] = [ (s[i - 1]), s[i] ]; + const [prevChar, curChar] = [s[i - 1], s[i]]; const is10 = prevChar === '1'; - const is20 = (prevChar === '2' && curChar <= '6'); + const is20 = prevChar === '2' && curChar <= '6'; return is10 || is20; -} \ No newline at end of file +}; diff --git a/javascript/0093-restore-ip-addresses.js b/javascript/0093-restore-ip-addresses.js index 4e670d8ee..0133cb31f 100644 --- a/javascript/0093-restore-ip-addresses.js +++ b/javascript/0093-restore-ip-addresses.js @@ -26,7 +26,7 @@ var restoreIpAddresses = function (s) { backtracking( j + 1, dots + 1, - currentIP + s.slice(i, j + 1) + '.' + currentIP + s.slice(i, j + 1) + '.', ); } } diff --git a/javascript/0094-binary-tree-inorder-traversal.js b/javascript/0094-binary-tree-inorder-traversal.js index a590b39e7..ceda5b7d5 100644 --- a/javascript/0094-binary-tree-inorder-traversal.js +++ b/javascript/0094-binary-tree-inorder-traversal.js @@ -1,22 +1,21 @@ -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @return {number[]} - */ - var inorderTraversal = function (root, list = []) { - - if (!root) return []; - - inorderTraversal(root.left, list); - list.push(root.val) - inorderTraversal(root.right, list); - - return list -}; +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @return {number[]} + */ +var inorderTraversal = function (root, list = []) { + if (!root) return []; + + inorderTraversal(root.left, list); + list.push(root.val); + inorderTraversal(root.right, list); + + return list; +}; diff --git a/javascript/0095-unique-binary-search-trees-ii.js b/javascript/0095-unique-binary-search-trees-ii.js index 7810bb5e1..1ccf54afe 100644 --- a/javascript/0095-unique-binary-search-trees-ii.js +++ b/javascript/0095-unique-binary-search-trees-ii.js @@ -9,39 +9,37 @@ /** * Recursion * Time O(4^n) | Space O(n) - * https://leetcode.com/problems/unique-binary-search-trees-ii/ + * https://leetcode.com/problems/unique-binary-search-trees-ii/ * @param {number} n * @return {TreeNode[]} */ -var generateTrees = function(n) { - +var generateTrees = function (n) { const dfs = (start, end) => { - const result = []; - if(start === end) { + if (start === end) { result.push(new TreeNode(start)); return result; - }; - if(start > end) { + } + if (start > end) { result.push(null); return result; - }; + } - for(let i = start; i < end + 1; i++) { + for (let i = start; i < end + 1; i++) { const leftSubTrees = dfs(start, i - 1); - const rightSubTrees = dfs(i + 1 , end); + const rightSubTrees = dfs(i + 1, end); leftSubTrees.forEach((leftSubTree) => { rightSubTrees.forEach((rightSubTree) => { - const root = new TreeNode(i, leftSubTree, rightSubTree); + const root = new TreeNode(i, leftSubTree, rightSubTree); result.push(root); }); - }); + }); } return result; - } + }; return dfs(1, n); }; diff --git a/javascript/0096-unique-binary-search-trees.js b/javascript/0096-unique-binary-search-trees.js index eabc140d7..fddd021be 100644 --- a/javascript/0096-unique-binary-search-trees.js +++ b/javascript/0096-unique-binary-search-trees.js @@ -5,22 +5,21 @@ * @param {number} n * @return {number} */ -var numTrees = function(n) { - +var numTrees = function (n) { const cache = {}; const dfs = (n) => { - if(n <= 1) return 1; - if(cache[n]) return cache[n]; + if (n <= 1) return 1; + if (cache[n]) return cache[n]; let total = 0; - for(let i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { total += dfs(i) * dfs(n - 1 - i); } cache[n] = total; return total; - } + }; return dfs(n); }; diff --git a/javascript/0097-interleaving-string.js b/javascript/0097-interleaving-string.js index edb454ed9..dec1eba5f 100644 --- a/javascript/0097-interleaving-string.js +++ b/javascript/0097-interleaving-string.js @@ -7,25 +7,41 @@ * @param {string} s3 * @return {boolean} */ - var isInterleave = (s1, s2, s3, i = 0, j = 0, res = '') => { - const isBaseCase1 = (s3.length !== (s1.length + s2.length)); +var isInterleave = (s1, s2, s3, i = 0, j = 0, res = '') => { + const isBaseCase1 = s3.length !== s1.length + s2.length; if (isBaseCase1) return false; - const isBaseCase2 = ((res === s3) && (i == s1.length) && (j == s2.length)); + const isBaseCase2 = res === s3 && i == s1.length && j == s2.length; if (isBaseCase2) return true; - return dfs(s1, s2, s3, i, j, res);/* Time O(2^(N + M)) | Space O(N + M) */ -} + return dfs(s1, s2, s3, i, j, res); /* Time O(2^(N + M)) | Space O(N + M) */ +}; var dfs = (s1, s2, s3, i, j, res, ans = false) => { - const hasLeft = (i < s1.length); - if (hasLeft) ans |= isInterleave(s1, s2, s3, (i + 1), j, `${res}${s1[i]}`); /* Time O(2^(N + M)) | Space O(N) */ - - const hasRight = (j < s2.length); - if (hasRight) ans |= isInterleave(s1, s2, s3, i, (j + 1), `${res}${s2[j]}`);/* Time O(2^(N + M)) | Space O(M) */ + const hasLeft = i < s1.length; + if (hasLeft) + ans |= isInterleave( + s1, + s2, + s3, + i + 1, + j, + `${res}${s1[i]}`, + ); /* Time O(2^(N + M)) | Space O(N) */ + + const hasRight = j < s2.length; + if (hasRight) + ans |= isInterleave( + s1, + s2, + s3, + i, + j + 1, + `${res}${s2[j]}`, + ); /* Time O(2^(N + M)) | Space O(M) */ return ans; -} +}; /** * DP - Top Down @@ -37,32 +53,74 @@ var dfs = (s1, s2, s3, i, j, res, ans = false) => { * @param {string} s3 * @return {boolean} */ -var isInterleave = (s1, s2, s3, i = 0, j = 0, k = 0, memo = initMemo(s1, s2)) => { - const isBaseCase1 = (s3.length !== (s1.length + s2.length)); +var isInterleave = ( + s1, + s2, + s3, + i = 0, + j = 0, + k = 0, + memo = initMemo(s1, s2), +) => { + const isBaseCase1 = s3.length !== s1.length + s2.length; if (isBaseCase1) return false; - const isBaseCase2 = (i === s1.length); - if (isBaseCase2) return (s2.slice(j) === s3.slice(k));/* Time O(M + K) | Space O(M + K) */ + const isBaseCase2 = i === s1.length; + if (isBaseCase2) + return s2.slice(j) === s3.slice(k); /* Time O(M + K) | Space O(M + K) */ - const isBaseCase3 = (j === s2.length); - if (isBaseCase3) return (s1.slice(i) === s3.slice(k));/* Time O(N + K) | Space O(N + K) */ + const isBaseCase3 = j === s2.length; + if (isBaseCase3) + return s1.slice(i) === s3.slice(k); /* Time O(N + K) | Space O(N + K) */ - const hasSeen = (memo[i][j] !== null); + const hasSeen = memo[i][j] !== null; if (hasSeen) return memo[i][j]; - return dfs(s1, s2, s3, i, j, k, memo);/* Time O(N * M) | Space O((N * M) + HEIGHT) */ -} + return dfs( + s1, + s2, + s3, + i, + j, + k, + memo, + ); /* Time O(N * M) | Space O((N * M) + HEIGHT) */ +}; -var initMemo = (s1, s2) => new Array(s1.length).fill()/* Time O(N) | Space O(N) */ - .map(() => new Array(s2.length).fill(null)); /* Time O(M) | Space O(M) */ +var initMemo = (s1, s2) => + new Array(s1.length) + .fill() /* Time O(N) | Space O(N) */ + .map(() => + new Array(s2.length).fill(null), + ); /* Time O(M) | Space O(M) */ var dfs = (s1, s2, s3, i, j, k, memo) => { - const left = ((s3[k] === s1[i]) && isInterleave(s1, s2, s3, (i + 1), j, (k + 1), memo)); /* Time O(N) | Space O(HEIGHT) */ - const right = ((s3[k] === s2[j]) && isInterleave(s1, s2, s3, i, (j + 1), (k + 1), memo));/* Time O(M) | Space O(HEIGHT) */ - - memo[i][j] = left || right; /* | Space O(N * M) */ + const left = + s3[k] === s1[i] && + isInterleave( + s1, + s2, + s3, + i + 1, + j, + k + 1, + memo, + ); /* Time O(N) | Space O(HEIGHT) */ + const right = + s3[k] === s2[j] && + isInterleave( + s1, + s2, + s3, + i, + j + 1, + k + 1, + memo, + ); /* Time O(M) | Space O(HEIGHT) */ + + memo[i][j] = left || right; /* | Space O(N * M) */ return memo[i][j]; -} +}; /** * DP - Bottom Up @@ -75,49 +133,58 @@ var dfs = (s1, s2, s3, i, j, k, memo) => { * @return {boolean} */ var isInterleave = (s1, s2, s3) => { - const isBaseCase = (s3.length !== s1.length + s2.length); + const isBaseCase = s3.length !== s1.length + s2.length; if (isBaseCase) return false; - const tabu = initTabu(s1, s2);/* Time O(N * M) | Space O(N * M) */ + const tabu = initTabu(s1, s2); /* Time O(N * M) | Space O(N * M) */ - search(s1, s2, s3, tabu); /* Time O(N * M) | Space O(N * M) */ + search(s1, s2, s3, tabu); /* Time O(N * M) | Space O(N * M) */ return tabu[s1.length][s2.length]; -} +}; -var initTabu = (s1, s2) => new Array((s1.length + 1)).fill()/* Time O(N) | Space O(N) */ - .map(() => new Array((s2.length + 1)).fill(null)) /* Time O(M) | Space O(M) */ +var initTabu = (s1, s2) => + new Array(s1.length + 1) + .fill() /* Time O(N) | Space O(N) */ + .map(() => + new Array(s2.length + 1).fill(null), + ); /* Time O(M) | Space O(M) */ var search = (s1, s2, s3, tabu) => { - const [ rows, cols ] = [ s1.length, s2.length ]; - - for (let row = 0; (row <= rows); row++) {/* Time O(N) */ - for (let col = 0; (col <= cols); col++) {/* Time O(M) */ - tabu[row][col] = /* Space O(N * M) */ + const [rows, cols] = [s1.length, s2.length]; + + for (let row = 0; row <= rows; row++) { + /* Time O(N) */ + for (let col = 0; col <= cols; col++) { + /* Time O(M) */ + tabu[row][col] = + /* Space O(N * M) */ hasMatch(s1, s2, s3, row, col, tabu); } } -} +}; var hasMatch = (s1, s2, s3, i, j, tabu) => { - const isBaseCase1 = ((i === 0) && (j === 0)); + const isBaseCase1 = i === 0 && j === 0; if (isBaseCase1) return true; - const isBaseCase2 = (i === 0); + const isBaseCase2 = i === 0; if (isBaseCase2) return getRight(i, j, s2, s3, tabu); - const isBaseCase3 = (j === 0); + const isBaseCase3 = j === 0; if (isBaseCase3) return getLeft(i, j, s1, s3, tabu); const left = getLeft(i, j, s1, s3, tabu); - const right = getRight(i, j, s2, s3, tabu) + const right = getRight(i, j, s2, s3, tabu); - return (left || right); -} + return left || right; +}; -var getLeft = (i, j, s1, s3, tabu) => ((tabu[(i - 1)][j] && s1[(i - 1)]) === s3[((i + j) - 1)]); +var getLeft = (i, j, s1, s3, tabu) => + (tabu[i - 1][j] && s1[i - 1]) === s3[i + j - 1]; -var getRight = (i, j, s2, s3, tabu) => ((tabu[i][(j - 1)] && s2[(j - 1)]) === s3[((i + j) - 1)]); +var getRight = (i, j, s2, s3, tabu) => + (tabu[i][j - 1] && s2[j - 1]) === s3[i + j - 1]; /** * DP - Bottom Up @@ -130,43 +197,45 @@ var getRight = (i, j, s2, s3, tabu) => ((tabu[i][(j - 1)] && s2[(j - 1)]) === s3 * @return {boolean} */ var isInterleave = (s1, s2, s3) => { - const isBaseCase = (s3.length !== (s1.length + s2.length)); + const isBaseCase = s3.length !== s1.length + s2.length; if (isBaseCase) return false; - const tabu = initTabu(s2);/* Time O(M) | Space O(M) */ + const tabu = initTabu(s2); /* Time O(M) | Space O(M) */ search(s1, s2, s3, tabu); /* Time O(N * M) | Space O(M) */ return tabu[s2.length]; }; -var initTabu = (s2) => new Array((s2.length + 1)).fill(false);/* Time O(M) | Space O(M) */ +var initTabu = (s2) => + new Array(s2.length + 1).fill(false); /* Time O(M) | Space O(M) */ var search = (s1, s2, s3, tabu) => { - const [ rows, cols ] = [ s1.length, s2.length ]; + const [rows, cols] = [s1.length, s2.length]; - for (let row = 0; (row <= rows); row++) {/* Time O(N)*/ - for (let col = 0; (col <= cols); col++) {/* Time O(M)*/ - tabu[col] = /* Space O(M)*/ - hasMatch(s1, s2, s3, row, col, tabu); + for (let row = 0; row <= rows; row++) { + /* Time O(N)*/ + for (let col = 0; col <= cols; col++) { + /* Time O(M)*/ + tabu[col] = /* Space O(M)*/ hasMatch(s1, s2, s3, row, col, tabu); } } -} +}; var hasMatch = (s1, s2, s3, i, j, tabu) => { - const isBaseCase1 = ((i === 0) && (j === 0)); + const isBaseCase1 = i === 0 && j === 0; if (isBaseCase1) return true; - const isBaseCase2 = (i === 0); - if (isBaseCase2) return getRight(i, j, s2, s3, tabu) + const isBaseCase2 = i === 0; + if (isBaseCase2) return getRight(i, j, s2, s3, tabu); - const isBaseCase3 = (j === 0); - if (isBaseCase3) return getLeft(i, j, s1, s3, tabu);; + const isBaseCase3 = j === 0; + if (isBaseCase3) return getLeft(i, j, s1, s3, tabu); return getLeft(i, j, s1, s3, tabu) || getRight(i, j, s2, s3, tabu); -} - -var getLeft = (i, j, s1, s3, tabu) => (tabu[j] && (s1[(i - 1)] === s3[((i + j) - 1)])); +}; -var getRight = (i, j, s2, s3, tabu) => (tabu[(j - 1)] && (s2[(j - 1)] === s3[((i + j) - 1)])); +var getLeft = (i, j, s1, s3, tabu) => tabu[j] && s1[i - 1] === s3[i + j - 1]; +var getRight = (i, j, s2, s3, tabu) => + tabu[j - 1] && s2[j - 1] === s3[i + j - 1]; diff --git a/javascript/0098-validate-binary-search-tree.js b/javascript/0098-validate-binary-search-tree.js index 6b6cc12ee..16c2dffd8 100644 --- a/javascript/0098-validate-binary-search-tree.js +++ b/javascript/0098-validate-binary-search-tree.js @@ -4,11 +4,11 @@ * @param {TreeNode} root * @return {boolean} */ -var isValidBST = function(root, min = -Infinity, max = Infinity) { +var isValidBST = function (root, min = -Infinity, max = Infinity) { const isBaseCase = root === null; if (isBaseCase) return true; - const isInvalid = (root.val <= min) || (max <= root.val); + const isInvalid = root.val <= min || max <= root.val; if (isInvalid) return false; return dfs(root, min, max); @@ -19,7 +19,7 @@ const dfs = (root, min, max) => { const right = isValidBST(root.right, root.val, max); return left && right; -} +}; // TODO /** * https://leetcode.com/problems/validate-binary-search-tree/ @@ -27,19 +27,19 @@ const dfs = (root, min, max) => { * @param {TreeNode} root * @return {boolean} */ - var isValidBST = function(root, prev = [ null ]) { +var isValidBST = function (root, prev = [null]) { const isBaseCase = root === null; if (isBaseCase) return true; if (!isValidBST(root.left, prev)) return false; - const isInvalid = (prev[0] !== null) && (root.val <= prev[0]); + const isInvalid = prev[0] !== null && root.val <= prev[0]; if (isInvalid) return false; prev[0] = root.val; return isValidBST(root.right, prev); -} +}; /** * https://leetcode.com/problems/validate-binary-search-tree/ @@ -47,14 +47,14 @@ const dfs = (root, min, max) => { * @param {TreeNode} root * @return {boolean} */ -var isValidBST = function(root, stack = []) { +var isValidBST = function (root, stack = []) { let prev = null; while (stack.length || root) { moveLeft(stack, root); root = stack.pop(); - const isInvalid = prev && (root.val <= prev.val); + const isInvalid = prev && root.val <= prev.val; if (isInvalid) return false; prev = root; @@ -62,11 +62,11 @@ var isValidBST = function(root, stack = []) { } return true; -} +}; const moveLeft = (stack, root) => { while (root) { stack.push(root); root = root.left; } -} \ No newline at end of file +}; diff --git a/javascript/0101-symmetric-tree.js b/javascript/0101-symmetric-tree.js index 8c311f51f..e956fda43 100644 --- a/javascript/0101-symmetric-tree.js +++ b/javascript/0101-symmetric-tree.js @@ -13,12 +13,11 @@ * @param {TreeNode} root * @return {boolean} */ -var isSymmetric = function(root) { +var isSymmetric = function (root) { return dfs(root.left, root.right); }; - -const dfs = (node1, node2) => { +const dfs = (node1, node2) => { if (!node1 && !node2) return true; if (node1 && !node2) return false; @@ -26,4 +25,4 @@ const dfs = (node1, node2) => { if (node1.val !== node2.val) return false; return dfs(node1.right, node2.left) && dfs(node1.left, node2.right); -} +}; diff --git a/javascript/0102-binary-tree-level-order-traversal.js b/javascript/0102-binary-tree-level-order-traversal.js index 62e4d2d83..7e2cc5fce 100644 --- a/javascript/0102-binary-tree-level-order-traversal.js +++ b/javascript/0102-binary-tree-level-order-traversal.js @@ -5,18 +5,19 @@ * @param {TreeNode} root * @return {number[][]} */ -var levelOrder = function(root) { +var levelOrder = function (root) { const isBaseCase = root === null; if (isBaseCase) return []; - return bfs([ root ]); + return bfs([root]); }; const bfs = (queue /* Space O(W) */, levels = []) => { - while (queue.length) { // Time O(N) + while (queue.length) { + // Time O(N) const level = []; - for (let i = (queue.length - 1); 0 <= i; i--) { + for (let i = queue.length - 1; 0 <= i; i--) { const node = queue.shift(); // Time O(N) ... This can be O(1) if we use an actual queue data structure if (node.left) queue.push(node.left); @@ -29,7 +30,7 @@ const bfs = (queue /* Space O(W) */, levels = []) => { } return levels; -} +}; /** * https://leetcode.com/problems/binary-tree-level-order-traversal/ @@ -37,7 +38,7 @@ const bfs = (queue /* Space O(W) */, levels = []) => { * @param {TreeNode} root * @return {number[]} */ - var levelOrder = function(root, level = 0, levels = []) { +var levelOrder = function (root, level = 0, levels = []) { const isBaseCase = root === null; if (isBaseCase) return levels; @@ -47,11 +48,11 @@ const bfs = (queue /* Space O(W) */, levels = []) => { levels[level].push(root.val); return dfs(root, level, levels); // Time O(N) | Space O(H) -} +}; const dfs = (root, level, levels) => { - if (root.left) levelOrder(root.left, (level + 1), levels); - if (root.right) levelOrder(root.right, (level + 1), levels); + if (root.left) levelOrder(root.left, level + 1, levels); + if (root.right) levelOrder(root.right, level + 1, levels); return levels; -} +}; diff --git a/javascript/0103-binary-tree-zigzag-level-order-traversal.js b/javascript/0103-binary-tree-zigzag-level-order-traversal.js index fccd8f7bf..a83e68076 100644 --- a/javascript/0103-binary-tree-zigzag-level-order-traversal.js +++ b/javascript/0103-binary-tree-zigzag-level-order-traversal.js @@ -6,36 +6,37 @@ * @return {number[][]} */ var zigzagLevelOrder = (root) => { - const isEdgeBase = (root === null); + const isEdgeBase = root === null; if (isEdgeBase) return []; - - return search(root);/* Time O(N) | Space O(N) */ + + return search(root); /* Time O(N) | Space O(N) */ }; var search = (root, isZigZag = true, order = []) => { - const queue = new Queue([ root ]); - - while (!queue.isEmpty()) { /* Time O(N) */ + const queue = new Queue([root]); + + while (!queue.isEmpty()) { + /* Time O(N) */ const levels = []; bfs(queue, isZigZag, levels); /* Time O(WIDTH) | Space O(WIDTH) */ - order.push(levels); /* Space O(N) */ + order.push(levels); /* Space O(N) */ isZigZag = !isZigZag; } - + return order; -} +}; const bfs = (queue, isZigZag, levels) => { - for (let level = queue.size(); (0 < level); level--) {/* Time O(WIDTH) */ + for (let level = queue.size(); 0 < level; level--) { + /* Time O(WIDTH) */ const { left, val, right } = queue.dequeue(); - - if (left) queue.enqueue(left); /* Space O(WIDTH) */ - if (right) queue.enqueue(right);/* Space O(WIDTH) */ - - levels.push(val); /* Space O(N) */ + + if (left) queue.enqueue(left); /* Space O(WIDTH) */ + if (right) queue.enqueue(right); /* Space O(WIDTH) */ + + levels.push(val); /* Space O(N) */ } if (!isZigZag) levels.reverse(); -} - +}; diff --git a/javascript/0104-maximum-depth-of-binary-tree.js b/javascript/0104-maximum-depth-of-binary-tree.js index 9b2b7a8af..ffb4310f3 100644 --- a/javascript/0104-maximum-depth-of-binary-tree.js +++ b/javascript/0104-maximum-depth-of-binary-tree.js @@ -4,7 +4,7 @@ * @param {TreeNode} root * @return {number} */ -var maxDepth = function(root) { +var maxDepth = function (root) { const isBaseCase = root === null; if (isBaseCase) return 0; @@ -26,7 +26,7 @@ const dfs = (root) => { * @param {TreeNode} root * @return {number} */ -var maxDepth = function(root) { +var maxDepth = function (root) { const isBaseCase = root === null; if (isBaseCase) return 0; @@ -52,22 +52,22 @@ const iterativeDfs = (stack, height = 0) => { * @param {TreeNode} root * @return {number} */ -var maxDepth = function(root) { +var maxDepth = function (root) { const isBaseCase = root === null; if (isBaseCase) return 0; - return bfs([[ root, 0 ]]); + return bfs([[root, 0]]); }; const bfs = (queue, height = 0) => { while (queue.length) { - for (let i = (queue.length - 1); 0 <= i; i--) { - const [ root, depth ] = queue.shift(); + for (let i = queue.length - 1; 0 <= i; i--) { + const [root, depth] = queue.shift(); - height = Math.max(height, (depth + 1)); + height = Math.max(height, depth + 1); - if (root.left) queue.push([ root.left, (depth + 1) ]); - if (root.right) queue.push([ root.right, (depth + 1) ]); + if (root.left) queue.push([root.left, depth + 1]); + if (root.right) queue.push([root.right, depth + 1]); } } diff --git a/javascript/0105-construct-binary-tree-from-preorder-and-inorder-traversal.js b/javascript/0105-construct-binary-tree-from-preorder-and-inorder-traversal.js index 53a6fccda..7267d0cde 100644 --- a/javascript/0105-construct-binary-tree-from-preorder-and-inorder-traversal.js +++ b/javascript/0105-construct-binary-tree-from-preorder-and-inorder-traversal.js @@ -1,62 +1,67 @@ -/** - * https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ - * Time O(N^2) | Space(H) - * @param {number[]} preorder - * @param {number[]} inorder - * @return {TreeNode} - */ - var buildTree = function(preorder, inorder) { - const isBaseCase = !preorder.length || !inorder.length; - if (isBaseCase) return null; - - return dfs(preorder, inorder); -} - -var dfs = (preorder, inorder) => { - const { leftInorder, mid, rightInorder } = getPointers(preorder, inorder); - const root = new TreeNode(inorder[mid]); - - root.left = buildTree(preorder, leftInorder); - root.right = buildTree(preorder, rightInorder); - - return root; -} - -const getPointers = (preorder, inorder) => { - const next = preorder.shift(); - const mid = inorder.indexOf(next); - const leftInorder = inorder.slice(0, mid); - const rightInorder = inorder.slice(mid + 1); - - return { leftInorder, mid, rightInorder }; -} - -/** - * https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ - * Time O(N) | Space(H) - * @param {number[]} preorder - * @param {number[]} inorder - * @return {TreeNode} - */ - var buildTree = function(preorder, inorder, max = -Infinity, indices = { preorder: 0, inorder: 0 }) { - const isBaseCase = preorder.length <= indices.inorder; - if (isBaseCase) return null; - - const isAtEnd = inorder[indices.inorder] === max; - if (isAtEnd) { - indices.inorder++; - return null; - } - - return dfs(preorder, inorder, max, indices); -} - -var dfs = (preorder, inorder, max, indices) => { - const val = preorder[indices.preorder++] - const root = new TreeNode(val); - - root.left = buildTree(preorder, inorder, root.val, indices); - root.right = buildTree(preorder, inorder, max, indices); - - return root; -} +/** + * https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ + * Time O(N^2) | Space(H) + * @param {number[]} preorder + * @param {number[]} inorder + * @return {TreeNode} + */ +var buildTree = function (preorder, inorder) { + const isBaseCase = !preorder.length || !inorder.length; + if (isBaseCase) return null; + + return dfs(preorder, inorder); +}; + +var dfs = (preorder, inorder) => { + const { leftInorder, mid, rightInorder } = getPointers(preorder, inorder); + const root = new TreeNode(inorder[mid]); + + root.left = buildTree(preorder, leftInorder); + root.right = buildTree(preorder, rightInorder); + + return root; +}; + +const getPointers = (preorder, inorder) => { + const next = preorder.shift(); + const mid = inorder.indexOf(next); + const leftInorder = inorder.slice(0, mid); + const rightInorder = inorder.slice(mid + 1); + + return { leftInorder, mid, rightInorder }; +}; + +/** + * https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/ + * Time O(N) | Space(H) + * @param {number[]} preorder + * @param {number[]} inorder + * @return {TreeNode} + */ +var buildTree = function ( + preorder, + inorder, + max = -Infinity, + indices = { preorder: 0, inorder: 0 }, +) { + const isBaseCase = preorder.length <= indices.inorder; + if (isBaseCase) return null; + + const isAtEnd = inorder[indices.inorder] === max; + if (isAtEnd) { + indices.inorder++; + return null; + } + + return dfs(preorder, inorder, max, indices); +}; + +var dfs = (preorder, inorder, max, indices) => { + const val = preorder[indices.preorder++]; + const root = new TreeNode(val); + + root.left = buildTree(preorder, inorder, root.val, indices); + root.right = buildTree(preorder, inorder, max, indices); + + return root; +}; diff --git a/javascript/0106-construct-binary-tree-from-inorder-and-postorder-traversal.js b/javascript/0106-construct-binary-tree-from-inorder-and-postorder-traversal.js index a5fa99148..a902086c9 100644 --- a/javascript/0106-construct-binary-tree-from-inorder-and-postorder-traversal.js +++ b/javascript/0106-construct-binary-tree-from-inorder-and-postorder-traversal.js @@ -14,23 +14,21 @@ * @param {number[]} postorder * @return {TreeNode} */ -var buildTree = function(inorder, postorder) { - - +var buildTree = function (inorder, postorder) { let globleIdx = inorder.length - 1; const dfs = (start, end) => { - if(start === end) { + if (start === end) { globleIdx--; return new TreeNode(inorder[start]); } - if(start > end) return null; + if (start > end) return null; let i = start; - while(i < end + 1){ - if(inorder[i] === postorder[globleIdx]) break; + while (i < end + 1) { + if (inorder[i] === postorder[globleIdx]) break; i++; } @@ -41,7 +39,7 @@ var buildTree = function(inorder, postorder) { currRoot.left = dfs(start, i - 1); return currRoot; - } + }; return dfs(0, globleIdx); }; diff --git a/javascript/0108-convert-sorted-array-to-binary-search-tree.js b/javascript/0108-convert-sorted-array-to-binary-search-tree.js index 77f799832..76a9cf56d 100644 --- a/javascript/0108-convert-sorted-array-to-binary-search-tree.js +++ b/javascript/0108-convert-sorted-array-to-binary-search-tree.js @@ -14,23 +14,33 @@ * @param {number[]} nums * @return {TreeNode} */ -var sortedArrayToBST = (nums, left = 0, right = (nums.length - 1)) => { - const isBaseCase = (right < left); +var sortedArrayToBST = (nums, left = 0, right = nums.length - 1) => { + const isBaseCase = right < left; if (isBaseCase) return null; - return dfs(nums, left, right);/* Time O(N) | Space O(log(N)) */ + return dfs(nums, left, right); /* Time O(N) | Space O(log(N)) */ }; var dfs = (nums, left, right) => { const mid = (left + right) >> 1; - const root = new TreeNode(nums[mid]); /* | Ignore Auxillary Space O(N) */ - - root.left = sortedArrayToBST(nums, left, (mid - 1)); /* Time O(N) | Space O(log(N)) */ - root.right = sortedArrayToBST(nums, (mid + 1), right);/* Time O(N) | Space O(log(N)) */ - + const root = new TreeNode( + nums[mid], + ); /* | Ignore Auxillary Space O(N) */ + + root.left = sortedArrayToBST( + nums, + left, + mid - 1, + ); /* Time O(N) | Space O(log(N)) */ + root.right = sortedArrayToBST( + nums, + mid + 1, + right, + ); /* Time O(N) | Space O(log(N)) */ + return root; -} +}; /** * DFS - Preorder | Right as mid @@ -39,26 +49,36 @@ var dfs = (nums, left, right) => { * @param {number[]} nums * @return {TreeNode} */ -var sortedArrayToBST = (nums, left = 0, right = (nums.length - 1)) => { - const isBaseCase = (right < left); +var sortedArrayToBST = (nums, left = 0, right = nums.length - 1) => { + const isBaseCase = right < left; if (isBaseCase) return null; - return dfs(nums, left, right);/* Time O(N) | Space O(log(N)) */ + return dfs(nums, left, right); /* Time O(N) | Space O(log(N)) */ }; var dfs = (nums, left, right) => { let mid = (left + right) >> 1; - - const isOdd = (((left + right) % 2) === 1); + + const isOdd = (left + right) % 2 === 1; if (isOdd) mid += 1; - const root = new TreeNode(nums[mid]); /* | Ignore Auxillary Space O(N) */ - - root.left = sortedArrayToBST(nums, left, (mid - 1)); /* Time O(N) | Space O(log(N)) */ - root.right = sortedArrayToBST(nums, (mid + 1), right);/* Time O(N) | Space O(log(N)) */ - + const root = new TreeNode( + nums[mid], + ); /* | Ignore Auxillary Space O(N) */ + + root.left = sortedArrayToBST( + nums, + left, + mid - 1, + ); /* Time O(N) | Space O(log(N)) */ + root.right = sortedArrayToBST( + nums, + mid + 1, + right, + ); /* Time O(N) | Space O(log(N)) */ + return root; -} +}; /** * DFS - Preorder | Random as mid @@ -67,23 +87,33 @@ var dfs = (nums, left, right) => { * @param {number[]} nums * @return {TreeNode} */ -var sortedArrayToBST = (nums, left = 0, right = (nums.length - 1)) => { - const isBaseCase = (right < left); +var sortedArrayToBST = (nums, left = 0, right = nums.length - 1) => { + const isBaseCase = right < left; if (isBaseCase) return null; - return dfs(nums, left, right);/* Time O(N) | Space O(log(N)) */ + return dfs(nums, left, right); /* Time O(N) | Space O(log(N)) */ }; var dfs = (nums, left, right) => { let mid = (left + right) >> 1; - - const isOdd = (((left + right) % 2) === 1); + + const isOdd = (left + right) % 2 === 1; if (isOdd) mid += Math.floor(Math.random() * 2); - const root = new TreeNode(nums[mid]); /* | Ignore Auxillary Space O(N) */ - - root.left = sortedArrayToBST(nums, left, (mid - 1)); /* Time O(N) | Space O(log(N)) */ - root.right = sortedArrayToBST(nums, (mid + 1), right);/* Time O(N) | Space O(log(N)) */ - + const root = new TreeNode( + nums[mid], + ); /* | Ignore Auxillary Space O(N) */ + + root.left = sortedArrayToBST( + nums, + left, + mid - 1, + ); /* Time O(N) | Space O(log(N)) */ + root.right = sortedArrayToBST( + nums, + mid + 1, + right, + ); /* Time O(N) | Space O(log(N)) */ + return root; -} +}; diff --git a/javascript/0110-balanced-binary-tree.js b/javascript/0110-balanced-binary-tree.js index 30dacdd8c..5b5e51252 100644 --- a/javascript/0110-balanced-binary-tree.js +++ b/javascript/0110-balanced-binary-tree.js @@ -4,21 +4,21 @@ * @param {TreeNode} root * @return {boolean} */ -var isBalanced = function(root) { +var isBalanced = function (root) { const isBaseCase = root === null; if (isBaseCase) return true; if (!isAcceptableHeight(root)) return false; if (!isChildBalanced(root)) return false; return true; -} +}; const isChildBalanced = (root) => { const left = isBalanced(root.left); const right = isBalanced(root.right); - return left && right -} + return left && right; +}; const isAcceptableHeight = (root) => { const left = getHeight(root.left); @@ -27,23 +27,23 @@ const isAcceptableHeight = (root) => { const difference = Math.abs(left - right); return difference <= 1; -} +}; const getHeight = (root) => { const isBaseCase = root === null; if (isBaseCase) return 0; return dfs(root); -} +}; var dfs = (root) => { - const left = getHeight(root.left) + const left = getHeight(root.left); const right = getHeight(root.right); const height = Math.max(left, right); return height + 1; -} +}; /** * https://leetcode.com/problems/balanced-binary-tree/ @@ -51,28 +51,31 @@ var dfs = (root) => { * @param {TreeNode} root * @return {boolean} */ - var isBalanced = function (root) { - const [ _height, _isBalanced ] = isRootBalanced(root); +var isBalanced = function (root) { + const [_height, _isBalanced] = isRootBalanced(root); return _isBalanced; }; var isRootBalanced = (root) => { - const isBaseCase = root === null - if (isBaseCase) return [ -1, true ]; + const isBaseCase = root === null; + if (isBaseCase) return [-1, true]; - return dfs(root) -} + return dfs(root); +}; var dfs = (root) => { - const [ left, isLeftBalanced ] = isRootBalanced(root.left); - const [ right, isRightBalanced ] = isRootBalanced(root.right); - const [ height, difference ] = [ Math.max(left, right), Math.abs(left - right) ]; + const [left, isLeftBalanced] = isRootBalanced(root.left); + const [right, isRightBalanced] = isRootBalanced(root.right); + const [height, difference] = [ + Math.max(left, right), + Math.abs(left - right), + ]; const isAcceptableHeight = difference <= 1; const _isBalanced = isLeftBalanced && isRightBalanced; const _isRootBalanced = _isBalanced && isAcceptableHeight; - return [ (height + 1), _isRootBalanced ]; -} + return [height + 1, _isRootBalanced]; +}; diff --git a/javascript/0112-path-sum.js b/javascript/0112-path-sum.js index 626496eb0..0d491ef3f 100644 --- a/javascript/0112-path-sum.js +++ b/javascript/0112-path-sum.js @@ -1,21 +1,19 @@ // problem link https://leetcode.com/problems/path-sum/ // time complexity O(n) // whatever the number of nodes are. -var hasPathSum = function(root, targetSum) { - +var hasPathSum = function (root, targetSum) { const ans = []; function goDFS(node, curruntSum) { - - if(!node) return; - - if(!node.left && !node.right) { + if (!node) return; + + if (!node.left && !node.right) { ans.push(node.val + curruntSum); } - + goDFS(node.left, curruntSum + node.val); goDFS(node.right, curruntSum + node.val); } goDFS(root, 0); - + return ans.includes(targetSum); }; diff --git a/javascript/0115-distinct-subsequences.js b/javascript/0115-distinct-subsequences.js index 440d0094c..c5fd61070 100644 --- a/javascript/0115-distinct-subsequences.js +++ b/javascript/0115-distinct-subsequences.js @@ -7,37 +7,55 @@ * @param {string} t * @return {number} */ - var numDistinct = (s, t, i = 0, j = 0, memo = initMemo(s, t)) => { - const isBaseCase1 = (s.length < t.length); +var numDistinct = (s, t, i = 0, j = 0, memo = initMemo(s, t)) => { + const isBaseCase1 = s.length < t.length; if (isBaseCase1) return 0; - const isBaseCase2 = (j === t.length); + const isBaseCase2 = j === t.length; if (isBaseCase2) return 1; - const isBaseCase3 = (i === s.length); + const isBaseCase3 = i === s.length; if (isBaseCase3) return 0; - const hasSeen = (memo[i][j] !== null); + const hasSeen = memo[i][j] !== null; if (hasSeen) return memo[i][j]; - return dfs(s, t, i, j, memo);/* Time O(N * M) | Space O((N * M) + HEIGHT) */ -} + return dfs( + s, + t, + i, + j, + memo, + ); /* Time O(N * M) | Space O((N * M) + HEIGHT) */ +}; -var initMemo = (s, t) => new Array(s.length).fill() - .map(() => new Array(t.length).fill(null)); +var initMemo = (s, t) => + new Array(s.length).fill().map(() => new Array(t.length).fill(null)); var dfs = (s, t, i, j, memo) => { - const left = numDistinct(s, t, (i + 1), j, memo);/* Time O(N * M) | Space O(HEIGHT) */ + const left = numDistinct( + s, + t, + i + 1, + j, + memo, + ); /* Time O(N * M) | Space O(HEIGHT) */ - const isEqual = (s[i] === t[j]); + const isEqual = s[i] === t[j]; const right = isEqual - ? numDistinct(s, t, (i + 1), (j + 1), memo) /* Time O(N * M) | Space O(HEIGHT) */ + ? numDistinct( + s, + t, + i + 1, + j + 1, + memo, + ) /* Time O(N * M) | Space O(HEIGHT) */ : 0; - memo[i][j] = (left + right); /* | Space O(N * M) */ + memo[i][j] = left + right; /* | Space O(N * M) */ return memo[i][j]; -} +}; /** * DP - Bottom Up @@ -49,41 +67,43 @@ var dfs = (s, t, i, j, memo) => { * @return {number} */ var numDistinct = (s, t) => { - const tabu = initTabu(s, t);/* Time O(N * M) | Space O(N * M) */ + const tabu = initTabu(s, t); /* Time O(N * M) | Space O(N * M) */ - search(s, t, tabu); /* Time O(N * M) | Space O(N * M) */ + search(s, t, tabu); /* Time O(N * M) | Space O(N * M) */ return tabu[0][0]; -} +}; var initTabu = (s, t) => { - const tabu = new Array(s.length + 1).fill()/* Time O(N) | Space O(N) */ - .map(() => new Array(t.length + 1)); /* Time O(M) | Space O(M) */ + const tabu = new Array(s.length + 1) + .fill() /* Time O(N) | Space O(N) */ + .map(() => new Array(t.length + 1)); /* Time O(M) | Space O(M) */ - tabu[s.length].fill(0); /* | Space O(N * M) */ + tabu[s.length].fill(0); /* | Space O(N * M) */ - for (let r = 0; r <= s.length; ++r) { /* Time O(N) */ - tabu[r][t.length] = 1; /* | Space O(N * M) */ + for (let r = 0; r <= s.length; ++r) { + /* Time O(N) */ + tabu[r][t.length] = 1; /* | Space O(N * M) */ } return tabu; -} +}; var search = (s, t, tabu) => { - for (let r = (s.length - 1); (0 <= r); r--) {/* Time O(N) */ - for (let c = (t.length - 1); (0 <= c); c--) {/* Time O(M) */ + for (let r = s.length - 1; 0 <= r; r--) { + /* Time O(N) */ + for (let c = t.length - 1; 0 <= c; c--) { + /* Time O(M) */ const left = tabu[r + 1][c]; - const isEqual = (s[r] === t[c]); + const isEqual = s[r] === t[c]; - const right = isEqual - ? tabu[r + 1][c + 1] - : 0 - - tabu[r][c] = left + right; /* Space O(N * M) */ + const right = isEqual ? tabu[r + 1][c + 1] : 0; + + tabu[r][c] = left + right; /* Space O(N * M) */ } } -} +}; /** * DP - Bottom Up @@ -95,26 +115,28 @@ var search = (s, t, tabu) => { * @return {number} */ var numDistinct = (s, t) => { - const tabu = initTabu(t);/* Time O(M) | Space O(M) */ + const tabu = initTabu(t); /* Time O(M) | Space O(M) */ - search(s, t, tabu); /* Time O(N * M) | Space O(M) */ + search(s, t, tabu); /* Time O(N * M) | Space O(M) */ return tabu[0]; -} +}; -var initTabu = (t) => new Array(t.length).fill(0);/* Time O(M) | Space O(M) */ +var initTabu = (t) => new Array(t.length).fill(0); /* Time O(M) | Space O(M) */ var search = (s, t, tabu) => { - for (let row = (s.length - 1); (0 <= row); row--) {/* Time O(N) */ + for (let row = s.length - 1; 0 <= row; row--) { + /* Time O(N) */ let prev = 1; - for (let col = (t.length - 1); (0 <= col); col--) {/* Time O(M) */ + for (let col = t.length - 1; 0 <= col; col--) { + /* Time O(M) */ const curr = tabu[col]; - const isEqual = (s[row] === t[col]); - if (isEqual) tabu[col] += prev; /* Space O(M) */ + const isEqual = s[row] === t[col]; + if (isEqual) tabu[col] += prev; /* Space O(M) */ prev = curr; } } -} +}; diff --git a/javascript/0116-populating-next-right-pointers-in-each-node.js b/javascript/0116-populating-next-right-pointers-in-each-node.js index e9e11cd6c..5359e10e0 100644 --- a/javascript/0116-populating-next-right-pointers-in-each-node.js +++ b/javascript/0116-populating-next-right-pointers-in-each-node.js @@ -1,7 +1,7 @@ /** * BFS * Time O(n) | Space O(1) - * + * * https://leetcode.com/problems/populating-next-right-pointers-in-each-node/ * // Definition for a Node. * function Node(val, left, right, next) { @@ -16,18 +16,17 @@ * @return {Node} */ -var connect = function(root) { - +var connect = function (root) { let currentNode = root; let nextLevelNode = root && root.left; - while(currentNode && nextLevelNode) { + while (currentNode && nextLevelNode) { currentNode.left.next = currentNode.right; - if(currentNode.next) { + if (currentNode.next) { currentNode.right.next = currentNode.next.left; } currentNode = currentNode.next; - if(!currentNode) { + if (!currentNode) { currentNode = nextLevelNode; nextLevelNode = currentNode.left; } diff --git a/javascript/0118-pascals-triangle.js b/javascript/0118-pascals-triangle.js index 9d2152d3f..9acb9a980 100644 --- a/javascript/0118-pascals-triangle.js +++ b/javascript/0118-pascals-triangle.js @@ -1,17 +1,16 @@ - // link to the problem https://leetcode.com/problems/pascals-triangle/ // the time complexity will basically be the number of elements in pascale tringle. roughly height of tringle * number of honeycomb in each row. // O(n^2); var generate = function (numRows) { - const res = [[1]]; + const res = [[1]]; - for (let i = 1; i < numRows; i++) { + for (let i = 1; i < numRows; i++) { res[i] = []; - for (let k = 0; k < i + 1; k++) { - res[i][k] = (res[i - 1][k] || 0) + (res[i - 1][k - 1] || 0); - } - } + for (let k = 0; k < i + 1; k++) { + res[i][k] = (res[i - 1][k] || 0) + (res[i - 1][k - 1] || 0); + } + } return res; }; diff --git a/javascript/0122-best-time-to-buy-and-sell-stock-ii.js b/javascript/0122-best-time-to-buy-and-sell-stock-ii.js index 9057b1fe1..245de778a 100644 --- a/javascript/0122-best-time-to-buy-and-sell-stock-ii.js +++ b/javascript/0122-best-time-to-buy-and-sell-stock-ii.js @@ -1,11 +1,11 @@ // problem link https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii // time coplexity O(n) -var maxProfit = function(prices) { +var maxProfit = function (prices) { let maxProfit = 0; - for(let i = 0; i < prices.length; i++) { - if(prices[i] < prices[i+1]) { - maxProfit += prices[i+1] - prices[i]; + for (let i = 0; i < prices.length; i++) { + if (prices[i] < prices[i + 1]) { + maxProfit += prices[i + 1] - prices[i]; } } diff --git a/javascript/0124-binary-tree-maximum-path-sum.js b/javascript/0124-binary-tree-maximum-path-sum.js index ad41a02c3..8bc5a6d26 100644 --- a/javascript/0124-binary-tree-maximum-path-sum.js +++ b/javascript/0124-binary-tree-maximum-path-sum.js @@ -4,7 +4,7 @@ * @param {TreeNode} root * @return {number} */ - var maxPathSum = function(root, maxValue = [ -Infinity ]) { +var maxPathSum = function (root, maxValue = [-Infinity]) { pathSum(root, maxValue); return maxValue[0]; @@ -15,7 +15,7 @@ const pathSum = (root, maxValue) => { if (isBaseCase) return 0; return dfs(root, maxValue); -} +}; const dfs = (node, maxValue) => { const left = Math.max(0, pathSum(node.left, maxValue)); @@ -25,4 +25,4 @@ const dfs = (node, maxValue) => { maxValue[0] = Math.max(maxValue[0], sum); return Math.max(left, right) + node.val; -} +}; diff --git a/javascript/0125-valid-palindrome.js b/javascript/0125-valid-palindrome.js index 7e3785007..c68e9e1b8 100644 --- a/javascript/0125-valid-palindrome.js +++ b/javascript/0125-valid-palindrome.js @@ -5,23 +5,28 @@ * @param {string} s * @return {boolean} */ -var isPalindrome = function(s) { +var isPalindrome = function (s) { if (!s.length) return true; - - const alphaNumeric = filterAlphaNumeric(s);/* Time O(N) | Space O(N) */ - const reversed = reverse(alphaNumeric); /* Time O(N) | Space O(N) */ - + + const alphaNumeric = filterAlphaNumeric(s); /* Time O(N) | Space O(N) */ + const reversed = reverse(alphaNumeric); /* Time O(N) | Space O(N) */ + return alphaNumeric === reversed; }; -const filterAlphaNumeric = (s, nonAlphaNumeric = new RegExp('[^a-z0-9]','gi')) => s - .toLowerCase() /* Time O(N) | Space O(N) */ - .replace(nonAlphaNumeric, '')/* Time O(N) | Space O(N) */ +const filterAlphaNumeric = ( + s, + nonAlphaNumeric = new RegExp('[^a-z0-9]', 'gi'), +) => + s + .toLowerCase() /* Time O(N) | Space O(N) */ + .replace(nonAlphaNumeric, ''); /* Time O(N) | Space O(N) */ -const reverse = (s) => s - .split('')/* Time O(N) | Space O(N) */ - .reverse()/* Time O(N) | Space O(N) */ - .join('');/* Time O(N) | Space O(N) */ +const reverse = (s) => + s + .split('') /* Time O(N) | Space O(N) */ + .reverse() /* Time O(N) | Space O(N) */ + .join(''); /* Time O(N) | Space O(N) */ /** * 2 Pointer | Midde Convergence @@ -30,15 +35,15 @@ const reverse = (s) => s * @param {string} s * @return {boolean} */ -var isPalindrome = function(s) { +var isPalindrome = function (s) { if (s.length <= 1) return true; - + let [left, right] = [0, s.length - 1]; let leftChar, rightChar; while (left < right) { leftChar = s[left]; rightChar = s[right]; - + // skip char if non-alphanumeric if (!/[a-zA-Z0-9]/.test(leftChar)) { left++; @@ -64,24 +69,35 @@ var isPalindrome = function(s) { * @return {boolean} */ var isPalindrome = function (s) { - const isAlphaNumeric = c => (c.toLowerCase() >= 'a' && c.toLowerCase() <= 'z') || c >= '0' && c <= '9' + const isAlphaNumeric = (c) => + (c.toLowerCase() >= 'a' && c.toLowerCase() <= 'z') || + (c >= '0' && c <= '9'); + + let left = 0; + let right = s.length - 1; + let skipLeft, + skipRight, + endsEqual = false; - let left = 0; - let right = s.length - 1; - let skipLeft, skipRight, endsEqual = false; - - while (left < right) { - skipLeft = !isAlphaNumeric(s.charAt(left)) - if (skipLeft) { left++; continue; } + while (left < right) { + skipLeft = !isAlphaNumeric(s.charAt(left)); + if (skipLeft) { + left++; + continue; + } - skipRight = !isAlphaNumeric(s.charAt(right)) - if (skipRight) { right--; continue; } + skipRight = !isAlphaNumeric(s.charAt(right)); + if (skipRight) { + right--; + continue; + } - endsEqual = s.charAt(left).toLowerCase() === s.charAt(right).toLowerCase() - if (!endsEqual) return false + endsEqual = + s.charAt(left).toLowerCase() === s.charAt(right).toLowerCase(); + if (!endsEqual) return false; - left++ - right-- - } - return true + left++; + right--; + } + return true; }; diff --git a/javascript/0127-word-ladder.js b/javascript/0127-word-ladder.js index cb8d991b7..2e2ae3991 100644 --- a/javascript/0127-word-ladder.js +++ b/javascript/0127-word-ladder.js @@ -6,26 +6,35 @@ * @param {string[]} wordList * @return {number} */ - var ladderLength = function(beginWord, endWord, wordList) { - const [ queue, wordSet, seen ] = [ new Queue([[ beginWord, 1 ]]), new Set(wordList), new Set([ beginWord ]) ]; - - return bfs(queue, wordSet, seen, endWord);/* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ +var ladderLength = function (beginWord, endWord, wordList) { + const [queue, wordSet, seen] = [ + new Queue([[beginWord, 1]]), + new Set(wordList), + new Set([beginWord]), + ]; + + return bfs( + queue, + wordSet, + seen, + endWord, + ); /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ }; const bfs = (queue, wordSet, seen, endWord) => { while (!queue.isEmpty()) { - for (let i = (queue.size() - 1); 0 <= i; i--) { - const [ word, depth ] = queue.dequeue(); + for (let i = queue.size() - 1; 0 <= i; i--) { + const [word, depth] = queue.dequeue(); - const isTarget = word === endWord - if (isTarget) return depth + const isTarget = word === endWord; + if (isTarget) return depth; - transform(queue, wordSet, seen, word, depth) + transform(queue, wordSet, seen, word, depth); } } - return 0 -} + return 0; +}; const transform = (queue, wordSet, seen, word, depth) => { for (const index in word) { @@ -35,11 +44,11 @@ const transform = (queue, wordSet, seen, word, depth) => { const hasSeen = !wordSet.has(neighbor) || seen.has(neighbor); if (hasSeen) continue; - queue.enqueue([ neighbor, (depth + 1) ]); + queue.enqueue([neighbor, depth + 1]); seen.add(neighbor); } } -} +}; const getNeighbor = (word, index, char) => { const neighbor = word.split(''); @@ -47,4 +56,4 @@ const getNeighbor = (word, index, char) => { neighbor[index] = char; return neighbor.join(''); -} +}; diff --git a/javascript/0128-longest-consecutive-sequence.js b/javascript/0128-longest-consecutive-sequence.js index 02e753678..72a2b3dba 100644 --- a/javascript/0128-longest-consecutive-sequence.js +++ b/javascript/0128-longest-consecutive-sequence.js @@ -6,11 +6,13 @@ * @param {number[]} nums * @return {number} */ - var longestConsecutive = (nums, maxScore = 0) => { - for (const num of nums) {/* Time O(N) */ - let [ currNum, score ] = [ num, 1 ]; +var longestConsecutive = (nums, maxScore = 0) => { + for (const num of nums) { + /* Time O(N) */ + let [currNum, score] = [num, 1]; - while (isStreak(nums, (currNum + 1))) {/* Time O(N * N) */ + while (isStreak(nums, currNum + 1)) { + /* Time O(N * N) */ currNum++; score++; } @@ -19,16 +21,17 @@ } return maxScore; -} +}; const isStreak = (nums, num) => { - for (let i = 0; i < nums.length; i++) {/* Time O(N) */ - const isEqual = nums[i] === num + for (let i = 0; i < nums.length; i++) { + /* Time O(N) */ + const isEqual = nums[i] === num; if (isEqual) return true; } return false; -} +}; /** * Sort - HeapSort Space O(1) | QuickSort Space O(log(K)) @@ -38,30 +41,34 @@ const isStreak = (nums, num) => { * @param {number[]} nums * @return {number} */ - var longestConsecutive = (nums) => { +var longestConsecutive = (nums) => { if (!nums.length) return 0; - nums.sort((a, b) => a - b);/* Time O(N * log(N)) | Space O(1 || log(N)) */ + nums.sort((a, b) => a - b); /* Time O(N * log(N)) | Space O(1 || log(N)) */ - return search(nums); /* Time O(N) */ -} + return search(nums); /* Time O(N) */ +}; const search = (nums) => { - let [ maxScore, score ] = [ 1, 1 ]; + let [maxScore, score] = [1, 1]; - for (let i = 1; i < nums.length; i++) {/* Time O(N) */ - const isPrevDuplicate = nums[i - 1] === nums[i] - if (isPrevDuplicate) continue + for (let i = 1; i < nums.length; i++) { + /* Time O(N) */ + const isPrevDuplicate = nums[i - 1] === nums[i]; + if (isPrevDuplicate) continue; - const isStreak = nums[i] === ((nums[i - 1]) + 1) - if (isStreak) { score++; continue; } + const isStreak = nums[i] === nums[i - 1] + 1; + if (isStreak) { + score++; + continue; + } maxScore = Math.max(maxScore, score); score = 1; } return Math.max(maxScore, score); -} +}; /** * Hash Set - Intelligent Sequence @@ -71,18 +78,20 @@ const search = (nums) => { * @param {number[]} nums * @return {number} */ - var longestConsecutive = (nums, maxScore = 0) => { - const numSet = new Set(nums); /* Time O(N) | Space O(N) */ +var longestConsecutive = (nums, maxScore = 0) => { + const numSet = new Set(nums); /* Time O(N) | Space O(N) */ - for (const num of [ ...numSet ]) { /* Time O(N) */ + for (const num of [...numSet]) { + /* Time O(N) */ const prevNum = num - 1; - if (numSet.has(prevNum)) continue;/* Time O(N) */ + if (numSet.has(prevNum)) continue; /* Time O(N) */ - let [ currNum, score ] = [ num, 1 ]; + let [currNum, score] = [num, 1]; - const isStreak = () => numSet.has(currNum + 1) - while (isStreak()) { /* Time O(N) */ + const isStreak = () => numSet.has(currNum + 1); + while (isStreak()) { + /* Time O(N) */ currNum++; score++; } @@ -91,4 +100,4 @@ const search = (nums) => { } return maxScore; -} \ No newline at end of file +}; diff --git a/javascript/0129-sum-root-to-leaf-numbers.js b/javascript/0129-sum-root-to-leaf-numbers.js index 45a4883b6..beb7f3e69 100644 --- a/javascript/0129-sum-root-to-leaf-numbers.js +++ b/javascript/0129-sum-root-to-leaf-numbers.js @@ -13,20 +13,19 @@ * @param {TreeNode} root * @return {number} */ -var sumNumbers = function(root) { - - let total = 0; - const dfs = (node, num) => { - if(!node.left && !node.right) { - num = num + node.val; - total += +num; - return; - } +var sumNumbers = function (root) { + let total = 0; + const dfs = (node, num) => { + if (!node.left && !node.right) { + num = num + node.val; + total += +num; + return; + } - node.left && dfs(node.left, num + node.val); - node.right && dfs(node.right, num + node.val); - } + node.left && dfs(node.left, num + node.val); + node.right && dfs(node.right, num + node.val); + }; - dfs(root, ""); - return total; + dfs(root, ''); + return total; }; diff --git a/javascript/0130-surrounded-regions.js b/javascript/0130-surrounded-regions.js index 3fb409c1d..ff097cb91 100644 --- a/javascript/0130-surrounded-regions.js +++ b/javascript/0130-surrounded-regions.js @@ -4,35 +4,39 @@ * @param {character[][]} board * @return {void} Do not return anything, modify board in-place instead. */ - var solve = function solve(board) { - searchRows(board);/* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ - searchCols(board);/* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ - searchGrid(board);/* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ -} +var solve = function solve(board) { + searchRows(board); /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ + searchCols(board); /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ + searchGrid(board); /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ +}; var searchRows = (board) => { - const [ rows, cols ] = [ board.length, board[0].length ]; + const [rows, cols] = [board.length, board[0].length]; - for (let row = 0; row < rows; row++) { /* Time O(ROWS) */ - dfs(board, row, rows, 0, cols); /* Space O(ROWS) */ - dfs(board, row, rows, (cols - 1), cols);/* Space O(ROWS) */ + for (let row = 0; row < rows; row++) { + /* Time O(ROWS) */ + dfs(board, row, rows, 0, cols); /* Space O(ROWS) */ + dfs(board, row, rows, cols - 1, cols); /* Space O(ROWS) */ } -} +}; var searchCols = (board) => { - const [ rows, cols ] = [ board.length, board[0].length ]; + const [rows, cols] = [board.length, board[0].length]; - for (let col = 1; col < (cols - 1); col++) {/* Time O(COLS) */ - dfs(board, 0, rows, col, cols); /* Space O(COLS) */ - dfs(board, (rows - 1), rows, col, cols);/* Space O(COLS) */ + for (let col = 1; col < cols - 1; col++) { + /* Time O(COLS) */ + dfs(board, 0, rows, col, cols); /* Space O(COLS) */ + dfs(board, rows - 1, rows, col, cols); /* Space O(COLS) */ } -} +}; var searchGrid = (board) => { - const [ rows, cols ] = [ board.length, board[0].length ]; + const [rows, cols] = [board.length, board[0].length]; - for (let row = 0; row < rows; row++) {/* Time O(ROWS) */ - for (let col = 0; col < cols; col++) {/* Time O(COLS) */ + for (let row = 0; row < rows; row++) { + /* Time O(ROWS) */ + for (let col = 0; col < cols; col++) { + /* Time O(COLS) */ const isO = board[row][col] === 'O'; if (isO) board[row][col] = 'X'; @@ -40,7 +44,7 @@ var searchGrid = (board) => { if (isStar) board[row][col] = 'O'; } } -} +}; const dfs = (board, row, rows, col, cols) => { const isBaseCase = board[row][col] !== 'O'; @@ -48,15 +52,29 @@ const dfs = (board, row, rows, col, cols) => { board[row][col] = '*'; - for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) { - dfs(board, _row, rows, _col, cols);/* Time O(HEIGHT) | Space O(HEIGHT) */ + for (const [_row, _col] of getNeighbors(row, rows, col, cols)) { + dfs( + board, + _row, + rows, + _col, + cols, + ); /* Time O(HEIGHT) | Space O(HEIGHT) */ } -} - -var getNeighbors = (row, rows, col, cols) => [ [0, 1], [0, -1], [1, 0], [-1, 0] ] - .map(([ _row, _col ]) => [ (row + _row), (col + _col)]) - .filter(([ _row, _col ]) => (0 <= _row) && (_row < rows) && (0 <= _col) && (_col < cols)) - +}; + +var getNeighbors = (row, rows, col, cols) => + [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ] + .map(([_row, _col]) => [row + _row, col + _col]) + .filter( + ([_row, _col]) => + 0 <= _row && _row < rows && 0 <= _col && _col < cols, + ); /** * https://leetcode.com/problems/surrounded-regions/ @@ -64,55 +82,60 @@ var getNeighbors = (row, rows, col, cols) => [ [0, 1], [0, -1], [1, 0], [-1, 0] * @param {character[][]} board * @return {void} Do not return anything, modify board in-place instead. */ - var solve = function solve(board, queue = new Queue([])) { - searchRows(board, queue);/* Time O(ROWS + COLS) | Space O(ROWS + COLS) */ - searchCols(board, queue);/* Time O(ROWS + COLS) | Space O(ROWS + COLS) */ - bfs(board, queue); /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ - searchGrid(board); /* Time O(ROWS * COLS) */ -} +var solve = function solve(board, queue = new Queue([])) { + searchRows(board, queue); /* Time O(ROWS + COLS) | Space O(ROWS + COLS) */ + searchCols(board, queue); /* Time O(ROWS + COLS) | Space O(ROWS + COLS) */ + bfs(board, queue); /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ + searchGrid(board); /* Time O(ROWS * COLS) */ +}; var searchRows = (board, queue) => { - const [ rows, cols ] = [ board.length, board[0].length ] + const [rows, cols] = [board.length, board[0].length]; - for (let row = 0; row < rows; row++) { /* Time O(ROWS) */ - queue.enqueue([ row, 0 ]); /* Space O(ROWS) */ - queue.enqueue([ row, (cols - 1) ]);/* Space O(ROWS) */ + for (let row = 0; row < rows; row++) { + /* Time O(ROWS) */ + queue.enqueue([row, 0]); /* Space O(ROWS) */ + queue.enqueue([row, cols - 1]); /* Space O(ROWS) */ } -} +}; var searchCols = (board, queue) => { - const [ rows, cols ] = [ board.length, board[0].length ] + const [rows, cols] = [board.length, board[0].length]; - for (let col = 0; col < (cols - 1); col++) {/* Time O(COLS) */ - queue.enqueue([ 0, col ]); /* Space O(COLS) */ - queue.enqueue([ (rows - 1), col ]); /* Space O(COLS) */ + for (let col = 0; col < cols - 1; col++) { + /* Time O(COLS) */ + queue.enqueue([0, col]); /* Space O(COLS) */ + queue.enqueue([rows - 1, col]); /* Space O(COLS) */ } -} +}; var bfs = (board, queue) => { - const [ rows, cols ] = [ board.length, board[0].length ]; + const [rows, cols] = [board.length, board[0].length]; while (!queue.isEmpty()) { - for (let i = (queue.size() - 1); 0 <= i; i--) {/* Time O(WIDTH) */ - const [ row, col ] = queue.dequeue(); + for (let i = queue.size() - 1; 0 <= i; i--) { + /* Time O(WIDTH) */ + const [row, col] = queue.dequeue(); const isBaseCase = board[row][col] !== 'O'; if (isBaseCase) continue; board[row][col] = '*'; - for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) { - queue.enqueue([ _row, _col ]); /* Space O(WIDTH) */ + for (const [_row, _col] of getNeighbors(row, rows, col, cols)) { + queue.enqueue([_row, _col]); /* Space O(WIDTH) */ } } - } -} + } +}; var searchGrid = (board) => { - const [ rows, cols ] = [ board.length, board[0].length ]; + const [rows, cols] = [board.length, board[0].length]; - for (let row = 0; row < rows; row++) {/* Time O(ROWS) */ - for (let col = 0; col < cols; col++) {/* Time O(COLS) */ + for (let row = 0; row < rows; row++) { + /* Time O(ROWS) */ + for (let col = 0; col < cols; col++) { + /* Time O(COLS) */ const isO = board[row][col] === 'O'; if (isO) board[row][col] = 'X'; @@ -120,4 +143,4 @@ var searchGrid = (board) => { if (isStar) board[row][col] = 'O'; } } -} \ No newline at end of file +}; diff --git a/javascript/0131-palindrome-partitioning.js b/javascript/0131-palindrome-partitioning.js index 7c904589e..dcced546e 100644 --- a/javascript/0131-palindrome-partitioning.js +++ b/javascript/0131-palindrome-partitioning.js @@ -1,39 +1,40 @@ -/** - * https://leetcode.com/problems/palindrome-partitioning/ - * Time O(N * 2^N) | Space O(N^2) - * @param {string} s - * @return {string[][]} - */ -function partition(s, left = 0, _partition = [], partitions = []) { - const isBaseCase = s.length <= left - if (isBaseCase) { - if (_partition.length) partitions.push(_partition.slice()); - - return partitions - } - - for (let right = left; right < s.length; right++) { - if (!isPalindrome(s, left, right)) continue; - - backTrack(s, left, right, _partition, partitions) - } - - return partitions -} - -const backTrack = (s, left, right, _partition, partitions) => { - _partition.push(s.slice(left, (right + 1))); - partition(s, (right + 1), _partition, partitions); - _partition.pop(); -} - -const isPalindrome = (str, left, right) => { - while (left < right) { - const isSame = str[left] === str[right]; - if (!isSame) return false; - - left++; right--; - } - - return true; -} +/** + * https://leetcode.com/problems/palindrome-partitioning/ + * Time O(N * 2^N) | Space O(N^2) + * @param {string} s + * @return {string[][]} + */ +function partition(s, left = 0, _partition = [], partitions = []) { + const isBaseCase = s.length <= left; + if (isBaseCase) { + if (_partition.length) partitions.push(_partition.slice()); + + return partitions; + } + + for (let right = left; right < s.length; right++) { + if (!isPalindrome(s, left, right)) continue; + + backTrack(s, left, right, _partition, partitions); + } + + return partitions; +} + +const backTrack = (s, left, right, _partition, partitions) => { + _partition.push(s.slice(left, right + 1)); + partition(s, right + 1, _partition, partitions); + _partition.pop(); +}; + +const isPalindrome = (str, left, right) => { + while (left < right) { + const isSame = str[left] === str[right]; + if (!isSame) return false; + + left++; + right--; + } + + return true; +}; diff --git a/javascript/0133-clone-graph.js b/javascript/0133-clone-graph.js index 5cd7f307d..289eb8235 100644 --- a/javascript/0133-clone-graph.js +++ b/javascript/0133-clone-graph.js @@ -4,28 +4,33 @@ * @param {Node} node * @return {Node} */ -var cloneGraph = function(node, seen = new Map()) { +var cloneGraph = function (node, seen = new Map()) { const isBaseCase = node === null; if (isBaseCase) return null; if (seen.has(node)) return seen.get(node); - return dfs(node, seen); /* Time O(V + E) | Space O(N) */ -} + return dfs(node, seen); /* Time O(V + E) | Space O(N) */ +}; const dfs = (node, seen) => { const clone = new Node(node.val); - seen.set(node, clone); /* | Space O(N) */ + seen.set(node, clone); /* | Space O(N) */ for (const neighbor of node.neighbors) { - const cloneNeighbor = cloneGraph(neighbor, seen);/* Time O(V + E) | Space O(H) */ - - clone.neighbors.push(cloneNeighbor); /* | Space O(V + E) */ + const cloneNeighbor = cloneGraph( + neighbor, + seen, + ); /* Time O(V + E) | Space O(H) */ + + clone.neighbors.push( + cloneNeighbor, + ); /* | Space O(V + E) */ } return clone; -} +}; /** * https://leetcode.com/problems/clone-graph/ @@ -33,36 +38,41 @@ const dfs = (node, seen) => { * @param {Node} node * @return {Node} */ - var cloneGraph = function(node, seen = new Map()) { +var cloneGraph = function (node, seen = new Map()) { const isBaseCase = node === null; if (isBaseCase) return null; - seen.set(node, new Node(node.val)); /* | Space O(N) */ + seen.set(node, new Node(node.val)); /* | Space O(N) */ - bfs(new Queue([ node ]), seen); /* Time O(V + E) | Space O(N) */ + bfs(new Queue([node]), seen); /* Time O(V + E) | Space O(N) */ return seen.get(node); }; const bfs = (queue, seen) => { - while (!queue.isEmpty()) { /* Time O(V + E) */ - for (let i = (queue.size() - 1); 0 <= i; i--) {/* Time O(W) */ + while (!queue.isEmpty()) { + /* Time O(V + E) */ + for (let i = queue.size() - 1; 0 <= i; i--) { + /* Time O(W) */ const node = queue.dequeue(); - cloneNeighbors(node, seen, queue); /* Space O(N) */ + cloneNeighbors(node, seen, queue); /* Space O(N) */ } } -} +}; const cloneNeighbors = (node, seen, queue) => { for (const neighbor of node.neighbors) { if (!seen.has(neighbor)) { - seen.set(neighbor, new Node(neighbor.val));/* Space O(N) */ - queue.enqueue(neighbor); /* Space O(W) */ + seen.set(neighbor, new Node(neighbor.val)); /* Space O(N) */ + queue.enqueue(neighbor); /* Space O(W) */ } - const [ parentClone, neighborClone ] = [ seen.get(node), seen.get(neighbor) ]; + const [parentClone, neighborClone] = [ + seen.get(node), + seen.get(neighbor), + ]; - parentClone.neighbors.push(neighborClone); /* Space O(V + E) */ + parentClone.neighbors.push(neighborClone); /* Space O(V + E) */ } -} +}; diff --git a/javascript/0134-gas-station.js b/javascript/0134-gas-station.js index 3f4404917..ff8537d28 100644 --- a/javascript/0134-gas-station.js +++ b/javascript/0134-gas-station.js @@ -10,7 +10,8 @@ var canCompleteCircuit = function (gas, cost) { let res = 0; //Checks if theres enough gas to complete a cycle - if (gas.reduce((a, b) => a + b) - cost.reduce((a, b) => a + b) < 0) return -1; + if (gas.reduce((a, b) => a + b) - cost.reduce((a, b) => a + b) < 0) + return -1; // Finds the first appearence of a positive netDistance, if the cycle can't // be completed (netDistance < 0), starts cycle again @ the next positive netDistance value. @@ -22,7 +23,7 @@ var canCompleteCircuit = function (gas, cost) { res = i + 1; } } - + return res; }; @@ -31,18 +32,19 @@ var canCompleteCircuit = function (gas, cost) { * @param {number[]} cost * @return {number} */ - var canCompleteCircuit = function(gas, cost) { - let [ totalTank, currTank, startingStation ] = [ 0, 0, 0 ] +var canCompleteCircuit = function (gas, cost) { + let [totalTank, currTank, startingStation] = [0, 0, 0]; for (let i = 0; i < gas.length; i++) { totalTank += gas[i] - cost[i]; currTank += gas[i] - cost[i]; - + const isEmpty = currTank < 0; - if (isEmpty) { startingStation = (i + 1); currTank = 0; } + if (isEmpty) { + startingStation = i + 1; + currTank = 0; + } } - - return 0 <= totalTank - ? startingStation - : -1; -} \ No newline at end of file + + return 0 <= totalTank ? startingStation : -1; +}; diff --git a/javascript/0135-candy.js b/javascript/0135-candy.js index f3d275b81..80b0d05d9 100644 --- a/javascript/0135-candy.js +++ b/javascript/0135-candy.js @@ -5,27 +5,26 @@ * @param {number[]} ratings * @return {number} */ -var candy = function(ratings) { - +var candy = function (ratings) { const ltr = new Array(ratings.length).fill(1); const rtl = new Array(ratings.length).fill(1); // go from left to right for (let i = 1; i < ratings.length; i++) { - if (ratings[i] > ratings[i - 1]) { - ltr[i] = ltr[i - 1] + 1; - } + if (ratings[i] > ratings[i - 1]) { + ltr[i] = ltr[i - 1] + 1; + } } // go from right to left for (let i = ratings.length - 2; i > -1; i--) { - if (ratings[i] > ratings[i + 1]) { - rtl[i] = rtl[i + 1] + 1; - } + if (ratings[i] > ratings[i + 1]) { + rtl[i] = rtl[i + 1] + 1; + } } - // calc minimum + // calc minimum let candy = 0; for (let i = 0; i < ratings.length; i++) { - candy += Math.max(ltr[i], rtl[i]); + candy += Math.max(ltr[i], rtl[i]); } return candy; }; diff --git a/javascript/0138-copy-list-with-random-pointer.js b/javascript/0138-copy-list-with-random-pointer.js index 5536d3b03..9aa2d6ae8 100644 --- a/javascript/0138-copy-list-with-random-pointer.js +++ b/javascript/0138-copy-list-with-random-pointer.js @@ -4,18 +4,21 @@ * @param {Node} head * @return {Node} */ -var copyRandomList = function(head, map = new Map()) { +var copyRandomList = function (head, map = new Map()) { if (!head) return null; if (map.has(head)) return map.get(head); const clone = new Node(head.val); - map.set(head, clone); /* | Space O(N) */ - clone.next = copyRandomList(head.next, map); /* Time O(N) | Space O(N) */ - clone.random = copyRandomList(head.random, map);/* Time O(N) | Space O(N) */ + map.set(head, clone); /* | Space O(N) */ + clone.next = copyRandomList(head.next, map); /* Time O(N) | Space O(N) */ + clone.random = copyRandomList( + head.random, + map, + ); /* Time O(N) | Space O(N) */ return clone; -} +}; /** * https://leetcode.com/problems/copy-list-with-random-pointer/ @@ -23,17 +26,18 @@ var copyRandomList = function(head, map = new Map()) { * @param {Node} head * @return {Node} */ -var copyRandomList = function(head) { +var copyRandomList = function (head) { if (!head) return null; - cloneNode(head); /* Time O(N) */ + cloneNode(head); /* Time O(N) */ connectRandomNode(head); /* Time O(N) */ - return connectNode(head);/* Time O(N) */ + return connectNode(head); /* Time O(N) */ }; const cloneNode = (curr) => { - while (curr) { /* Time O(N) */ + while (curr) { + /* Time O(N) */ const node = new Node(curr.val); node.next = curr.next; @@ -42,24 +46,26 @@ const cloneNode = (curr) => { } return curr; -} +}; const connectRandomNode = (curr) => { - while (curr) { /* Time O(N) */ + while (curr) { + /* Time O(N) */ curr.next.random = curr.random?.next || null; curr = curr.next.next; } -} +}; const connectNode = (head) => { - let [ prev, curr, next ] = [ head, head.next, head.next ]; + let [prev, curr, next] = [head, head.next, head.next]; - while (prev) { /* Time O(N) */ + while (prev) { + /* Time O(N) */ prev.next = prev.next.next; curr.next = curr?.next?.next || null; prev = prev.next; curr = curr.next; } - return next -} \ No newline at end of file + return next; +}; diff --git a/javascript/0139-word-break.js b/javascript/0139-word-break.js index 42daf415b..24e095ac8 100644 --- a/javascript/0139-word-break.js +++ b/javascript/0139-word-break.js @@ -7,30 +7,32 @@ * @param {string[]} wordDict * @return {boolean} */ - var wordBreak = (s, wordDict) => { - const wordSet = new Set(wordDict);/* Time O(N) | Space O(N) */ +var wordBreak = (s, wordDict) => { + const wordSet = new Set(wordDict); /* Time O(N) | Space O(N) */ - return canBreak(s, wordSet); /* Time O(2^N) | Space O(N) */ + return canBreak(s, wordSet); /* Time O(2^N) | Space O(N) */ }; var canBreak = (s, wordSet, start = 0) => { - const isBaseCase = (start === s.length); + const isBaseCase = start === s.length; if (isBaseCase) return true; - return dfs(s, wordSet, start);/* Time O(2^N) | Space O(N) */ -} + return dfs(s, wordSet, start); /* Time O(2^N) | Space O(N) */ +}; var dfs = (s, wordSet, start) => { - for (let end = (start + 1); end <= s.length; end++) {/* Time O(N) */ - const word = s.slice(start, end); /* Time O(N) | Space O(N) */ + for (let end = start + 1; end <= s.length; end++) { + /* Time O(N) */ + const word = s.slice(start, end); /* Time O(N) | Space O(N) */ - const _canBreak = wordSet.has(word) - && canBreak(s, wordSet, end); /* Time O(2^N) | Space O(N) */ + const _canBreak = + wordSet.has(word) && + canBreak(s, wordSet, end); /* Time O(2^N) | Space O(N) */ if (_canBreak) return true; } return false; -} +}; /** * DP - Top Down @@ -43,29 +45,38 @@ var dfs = (s, wordSet, start) => { * @return {boolean} */ var wordBreak = (s, wordDict) => { - const wordSet = new Set(wordDict); /* Time O(N) | Space O(N) */ - const memo = new Array(s.length).fill(null); /* | Space O(N) */ + const wordSet = new Set(wordDict); /* Time O(N) | Space O(N) */ + const memo = new Array(s.length).fill( + null, + ); /* | Space O(N) */ const start = 0; - return canBreak(s, wordSet, start, memo); /* Time O(N * N * N) | Space O(N) */ -} + return canBreak( + s, + wordSet, + start, + memo, + ); /* Time O(N * N * N) | Space O(N) */ +}; var canBreak = (s, wordSet, start, memo) => { - const isBaseCase1 = (s.length === start); + const isBaseCase1 = s.length === start; if (isBaseCase1) return true; - const hasSeen = (memo[start] !== null); + const hasSeen = memo[start] !== null; if (hasSeen) return memo[start]; - return dfs(s, wordSet, start, memo);/* Time O(N * N * N) | Space O(N) */ -} + return dfs(s, wordSet, start, memo); /* Time O(N * N * N) | Space O(N) */ +}; var dfs = (s, wordSet, start, memo) => { - for (let end = (start + 1); (end <= s.length); end++) {/* Time O(N) */ - const word = s.slice(start, end); /* Time O(N) | Space O(N) */ + for (let end = start + 1; end <= s.length; end++) { + /* Time O(N) */ + const word = s.slice(start, end); /* Time O(N) | Space O(N) */ - const _canBreak = wordSet.has(word) - && canBreak(s, wordSet, end, memo); /* Time O(N * N) */ + const _canBreak = + wordSet.has(word) && + canBreak(s, wordSet, end, memo); /* Time O(N * N) */ if (_canBreak) { memo[start] = true; return true; @@ -74,7 +85,7 @@ var dfs = (s, wordSet, start, memo) => { memo[start] = false; return false; -} +}; /** * DP - Bottom Up @@ -86,32 +97,34 @@ var dfs = (s, wordSet, start, memo) => { * @param {string[]} wordDict * @return {boolean} */ - var wordBreak = (s, wordDict) => { - const wordSet = new Set(wordDict);/* Time O(N) | Space O(N) */ - const tabu = initTabu(s); /* | Space O(N) */ +var wordBreak = (s, wordDict) => { + const wordSet = new Set(wordDict); /* Time O(N) | Space O(N) */ + const tabu = initTabu(s); /* | Space O(N) */ - canBreak(s, wordSet, tabu); /* Time O(N * N * N) | Space O(N) */ + canBreak(s, wordSet, tabu); /* Time O(N * N * N) | Space O(N) */ return tabu[s.length]; -} +}; const initTabu = (s) => { - const tabu = new Array((s.length + 1)).fill(false);/* Space O(N) */ + const tabu = new Array(s.length + 1).fill(false); /* Space O(N) */ tabu[0] = true; return tabu; -} +}; var canBreak = (s, wordSet, tabu) => { - for (let end = 1; (end <= s.length); end++) {/* Time O(N) */ - checkWord(s, wordSet, end, tabu); /* Time O(N * N) | Space O(N) */ + for (let end = 1; end <= s.length; end++) { + /* Time O(N) */ + checkWord(s, wordSet, end, tabu); /* Time O(N * N) | Space O(N) */ } -} +}; var checkWord = (s, wordSet, end, tabu) => { - for (let start = 0; (start < end); start++) {/* Time O(N) */ - const word = s.slice(start, end); /* Time O(N) | Space O(N) */ + for (let start = 0; start < end; start++) { + /* Time O(N) */ + const word = s.slice(start, end); /* Time O(N) | Space O(N) */ const canBreak = tabu[start] && wordSet.has(word); if (!canBreak) continue; @@ -120,7 +133,7 @@ var checkWord = (s, wordSet, end, tabu) => { return; } -} +}; /** * Tree Traversal - BFS @@ -133,23 +146,32 @@ var checkWord = (s, wordSet, end, tabu) => { * @param {string[]} wordDict * @return {boolean} */ -var wordBreak = function(s, wordDict) { - const wordSet = new Set(wordDict); /* Time O(N) | Space O(N) */ - const queue = new Queue([ 0 ]); /* | Space O(N) */ - const seen = new Array(s.length).fill(false);/* | Space O(N) */ - - return bfs(queue, s, wordSet, seen); /* Time O(N * N * N) | Space O(N + WIDTH) */ -} +var wordBreak = function (s, wordDict) { + const wordSet = new Set(wordDict); /* Time O(N) | Space O(N) */ + const queue = new Queue([0]); /* | Space O(N) */ + const seen = new Array(s.length).fill( + false, + ); /* | Space O(N) */ + + return bfs( + queue, + s, + wordSet, + seen, + ); /* Time O(N * N * N) | Space O(N + WIDTH) */ +}; const bfs = (queue, s, wordSet, seen) => { while (!queue.isEmpty()) { - for (let level = (queue.size() - 1); (0 <= level); level--) {/* Time O(N) */ - if (canWordBreak(queue, s, wordSet, seen)) return true; /* Time O(N * N) | Space O(N + WIDTH) */ + for (let level = queue.size() - 1; 0 <= level; level--) { + /* Time O(N) */ + if (canWordBreak(queue, s, wordSet, seen)) + return true; /* Time O(N * N) | Space O(N + WIDTH) */ } } return false; -} +}; var canWordBreak = (queue, s, wordSet, seen) => { const start = queue.dequeue(); @@ -157,23 +179,25 @@ var canWordBreak = (queue, s, wordSet, seen) => { const hasSeen = seen[start]; if (hasSeen) return false; - if (canBreak(queue, s, start, wordSet)) return true;/* Time O(N * N) | Space O(N + WIDTH) */ + if (canBreak(queue, s, start, wordSet)) + return true; /* Time O(N * N) | Space O(N + WIDTH) */ - seen[start] = true; /* | Space O(N) */ + seen[start] = true; /* | Space O(N) */ return false; -} +}; var canBreak = (queue, s, start, wordSet) => { - for (let end = start + 1; end <= s.length; end++) {/* Time O(N) */ - const word = s.slice(start, end); /* Time O(N) | Space O(N) */ + for (let end = start + 1; end <= s.length; end++) { + /* Time O(N) */ + const word = s.slice(start, end); /* Time O(N) | Space O(N) */ if (!wordSet.has(word)) continue; - queue.enqueue(end); /* | Space O(WIDTH) */ + queue.enqueue(end); /* | Space O(WIDTH) */ const _canBreak = end === s.length; if (_canBreak) return true; } - return false -} + return false; +}; diff --git a/javascript/0141-linked-list-cycle.js b/javascript/0141-linked-list-cycle.js index 7ea5826e3..6de880470 100644 --- a/javascript/0141-linked-list-cycle.js +++ b/javascript/0141-linked-list-cycle.js @@ -4,16 +4,17 @@ * @param {ListNode} head * @return {boolean} */ -var hasCycle = function(head, seen = new Set()) { - while (head) {/* Time O(N) */ +var hasCycle = function (head, seen = new Set()) { + while (head) { + /* Time O(N) */ if (seen.has(head)) return true; - seen.add(head);/* Space O(N) */ + seen.add(head); /* Space O(N) */ head = head.next; } return false; -} +}; /** * https://leetcode.com/problems/linked-list-cycle/ @@ -21,10 +22,11 @@ var hasCycle = function(head, seen = new Set()) { * @param {ListNode} head * @return {boolean} */ -var hasCycle = function(head) { - let [ slow, fast ] = [ head, head]; +var hasCycle = function (head) { + let [slow, fast] = [head, head]; - while (fast && fast.next) {/* Time O(N) */ + while (fast && fast.next) { + /* Time O(N) */ slow = slow.next; fast = fast.next.next; @@ -33,4 +35,4 @@ var hasCycle = function(head) { } return false; -}; \ No newline at end of file +}; diff --git a/javascript/0143-reorder-list.js b/javascript/0143-reorder-list.js index 690ba2a12..b4c5ef3e6 100644 --- a/javascript/0143-reorder-list.js +++ b/javascript/0143-reorder-list.js @@ -4,28 +4,30 @@ * @param {ListNode} head * @return {void} Do not return anything, modify head in-place instead. */ -var reorderList = function(head) { - const mid = getMid(head); /* Time O(N) */ - const reversedFromMid = reverse(mid);/* Time O(N) */ +var reorderList = function (head) { + const mid = getMid(head); /* Time O(N) */ + const reversedFromMid = reverse(mid); /* Time O(N) */ - reorder(head, reversedFromMid); /* Time O(N) */ + reorder(head, reversedFromMid); /* Time O(N) */ }; const getMid = (head) => { - let [ slow, fast ] = [ head, head ]; + let [slow, fast] = [head, head]; - while (fast && fast.next) { /* Time O(N) */ + while (fast && fast.next) { + /* Time O(N) */ slow = slow.next; fast = fast.next.next; } return slow; -} +}; const reverse = (head) => { - let [ prev, curr, next ] = [ null, head, null ]; + let [prev, curr, next] = [null, head, null]; - while (curr) { /* Time O(N) */ + while (curr) { + /* Time O(N) */ next = curr.next; curr.next = prev; @@ -34,12 +36,13 @@ const reverse = (head) => { } return prev; -} +}; const reorder = (l1, l2) => { - let [ first, next, second ] = [ l1, null, l2 ]; + let [first, next, second] = [l1, null, l2]; - while (second.next) { /* Time O(N) */ + while (second.next) { + /* Time O(N) */ next = first.next; first.next = second; first = next; @@ -48,4 +51,4 @@ const reorder = (l1, l2) => { second.next = first; second = next; } -} +}; diff --git a/javascript/0144-binary-tree-preorder-traversal.js b/javascript/0144-binary-tree-preorder-traversal.js index 8ba1f7cf8..88f2f4247 100644 --- a/javascript/0144-binary-tree-preorder-traversal.js +++ b/javascript/0144-binary-tree-preorder-traversal.js @@ -13,15 +13,14 @@ * @param {TreeNode} root * @return {number[]} */ -var preorderTraversal = function(root) { - +var preorderTraversal = function (root) { const dfs = (node, pre) => { if (!node) return pre; pre.push(node.val); dfs(node.left, pre); dfs(node.right, pre); return pre; - } + }; return dfs(root, []); }; diff --git a/javascript/0145-binary-tree-postorder-traversal.js b/javascript/0145-binary-tree-postorder-traversal.js index 7092bc337..aed30cdee 100644 --- a/javascript/0145-binary-tree-postorder-traversal.js +++ b/javascript/0145-binary-tree-postorder-traversal.js @@ -13,14 +13,13 @@ * @param {TreeNode} root * @return {number[]} */ -var postorderTraversal = function(root) { - +var postorderTraversal = function (root) { const dfs = (node, pot) => { if (!node) return pot; dfs(node.left, pot); dfs(node.right, pot); pot.push(node.val); return pot; - } + }; return dfs(root, []); }; diff --git a/javascript/0146-lru-cache.js b/javascript/0146-lru-cache.js index 2d450f135..b54df21b9 100644 --- a/javascript/0146-lru-cache.js +++ b/javascript/0146-lru-cache.js @@ -1,4 +1,4 @@ -/** +/** * https://leetcode.com/problems/lru-cache/ * Time O(1) | Space O(N) * Your LRUCache object will be instantiated and called as such: @@ -6,7 +6,7 @@ * var param_1 = obj.get(key) * obj.put(key,value) */ - class LRUCache { +class LRUCache { constructor(capacity) { this.capacity = capacity; this.map = new Map(); @@ -18,18 +18,22 @@ this.tail.prev = this.head; } - removeLastUsed () { - const [ key, next, prev ] = [ this.head.next.key, this.head.next.next, this.head ]; + removeLastUsed() { + const [key, next, prev] = [ + this.head.next.key, + this.head.next.next, + this.head, + ]; this.map.delete(key); this.head.next = next; this.head.next.prev = prev; } - put (key, value) { + put(key, value) { const hasKey = this.get(key) !== -1; const isAtCapacity = this.map.size === this.capacity; - + if (hasKey) return (this.tail.prev.value = value); if (isAtCapacity) this.removeLastUsed(); @@ -38,32 +42,32 @@ this.moveToFront(node); } - moveToFront (node) { - const [ prev, next ] = [ this.tail.prev, this.tail ]; + moveToFront(node) { + const [prev, next] = [this.tail.prev, this.tail]; this.tail.prev.next = node; this.connectNode(node, { prev, next }); this.tail.prev = node; } - connectNode (node, top) { + connectNode(node, top) { node.prev = top.prev; node.next = top.next; } - get (key) { + get(key) { const hasKey = this.map.has(key); if (!hasKey) return -1; const node = this.map.get(key); - + this.disconnectNode(node); this.moveToFront(node); return node.value; } - disconnectNode (node) { + disconnectNode(node) { node.next.prev = node.prev; node.prev.next = node.next; } diff --git a/javascript/0150-evaluate-reverse-polish-notation.js b/javascript/0150-evaluate-reverse-polish-notation.js index 26160454e..bc63b9c80 100644 --- a/javascript/0150-evaluate-reverse-polish-notation.js +++ b/javascript/0150-evaluate-reverse-polish-notation.js @@ -4,15 +4,16 @@ * @param {string[]} tokens * @return {number} */ -var evalRPN = function(tokens, index = 0) { - while (1 < tokens.length) {/* Time O(N) */ +var evalRPN = function (tokens, index = 0) { + while (1 < tokens.length) { + /* Time O(N) */ const isOperation = () => tokens[index] in OPERATORS; - while (!isOperation()) index++;/* Time O(N) */ + while (!isOperation()) index++; /* Time O(N) */ const value = performOperation(tokens, index); tokens[index] = value; - tokens.splice((index - 2), 2);/* Time O(N) */ + tokens.splice(index - 2, 2); /* Time O(N) */ index--; } @@ -27,11 +28,14 @@ var OPERATORS = { }; var performOperation = (tokens, index) => { - const [ rightNum, leftNum ] = [ Number(tokens[index - 1]), Number(tokens[index - 2]) ] + const [rightNum, leftNum] = [ + Number(tokens[index - 1]), + Number(tokens[index - 2]), + ]; const operation = OPERATORS[tokens[index]]; return operation(leftNum, rightNum); -} +}; /** * https://leetcode.com/problems/evaluate-reverse-polish-notation @@ -40,32 +44,33 @@ var performOperation = (tokens, index) => { * @return {number} */ var evalRPN = function (tokens, stack = []) { - for (const char of tokens) {/* Time O(N) */ + for (const char of tokens) { + /* Time O(N) */ const isOperation = char in OPERATORS; if (isOperation) { const value = performOperation(char, stack); - stack.push(value); /* Space O(N) */ + stack.push(value); /* Space O(N) */ continue; } - stack.push(Number(char)); /* Space O(N) */ + stack.push(Number(char)); /* Space O(N) */ } return stack.pop(); -} +}; var OPERATORS = { '+': (a, b) => a + b, '-': (a, b) => a - b, '*': (a, b) => a * b, - '/': (a, b) => Math.trunc(a / b) + '/': (a, b) => Math.trunc(a / b), }; var performOperation = (char, stack) => { - const [ rightNum, leftNum ] = [ stack.pop(), stack.pop() ]; + const [rightNum, leftNum] = [stack.pop(), stack.pop()]; const operation = OPERATORS[char]; return operation(leftNum, rightNum); -} \ No newline at end of file +}; diff --git a/javascript/0152-maximum-product-subarray.js b/javascript/0152-maximum-product-subarray.js index b2ceeb9fa..33c680939 100644 --- a/javascript/0152-maximum-product-subarray.js +++ b/javascript/0152-maximum-product-subarray.js @@ -5,29 +5,31 @@ * @param {number[]} nums * @return {number} */ - var maxProduct = (nums) => { +var maxProduct = (nums) => { const isEmpty = nums.length === 0; if (isEmpty) return 0; - return linearSearch(nums);/* Time O(N * N) */ -} + return linearSearch(nums); /* Time O(N * N) */ +}; const linearSearch = (nums, max = nums[0]) => { - for (let index = 0; index < nums.length; index++) {/* Time O(N) */ - max = getMax(nums, index, max); /* Time O(N) */ + for (let index = 0; index < nums.length; index++) { + /* Time O(N) */ + max = getMax(nums, index, max); /* Time O(N) */ } return max; -} +}; const getMax = (nums, index, max, product = 1) => { - for (let num = index; num < nums.length; num++) {/* Time O(N) */ + for (let num = index; num < nums.length; num++) { + /* Time O(N) */ product *= nums[num]; max = Math.max(max, product); } return max; -} +}; /** * Greedy - product @@ -40,14 +42,15 @@ var maxProduct = (nums) => { const isEmpty = nums.length === 0; if (isEmpty) return 0; - return greedySearch(nums);/* Time O(N) */ + return greedySearch(nums); /* Time O(N) */ }; const greedySearch = (nums) => { - let min = max = product = nums[0]; + let min = (max = product = nums[0]); - for (let num = 1; num < nums.length; num++) {/* Time O(N) */ - const [ minProduct, maxProduct ] = [ (min * nums[num]), (max * nums[num]) ]; + for (let num = 1; num < nums.length; num++) { + /* Time O(N) */ + const [minProduct, maxProduct] = [min * nums[num], max * nums[num]]; min = Math.min(maxProduct, minProduct, nums[num]); max = Math.max(maxProduct, minProduct, nums[num]); @@ -56,4 +59,4 @@ const greedySearch = (nums) => { } return product; -} \ No newline at end of file +}; diff --git a/javascript/0155-min-stack.js b/javascript/0155-min-stack.js index a84c66b5b..7dfb08b93 100644 --- a/javascript/0155-min-stack.js +++ b/javascript/0155-min-stack.js @@ -1,4 +1,4 @@ -/** +/** * https://leetcode.com/problems/min-stack * Time O(1) | Space O(N) * Your MinStack object will be instantiated and called as such: @@ -12,7 +12,7 @@ class MinStack { /** * @constructor */ - constructor () { + constructor() { this.stack = []; this.minStack = []; } @@ -21,45 +21,42 @@ class MinStack { * @param {number} val * @return {void} */ - push (val, { minStack } = this) { - this.stack.push(val); /* Space O(N) */ + push(val, { minStack } = this) { + this.stack.push(val); /* Space O(N) */ const isMinEmpty = !minStack.length; const hasNewMin = val <= this.top(minStack); const canAddMin = isMinEmpty || hasNewMin; - if (canAddMin) minStack.push(val);/* Space O(N) */ + if (canAddMin) minStack.push(val); /* Space O(N) */ } /** * @return {void} */ - pop ({ stack, minStack } = this) { - const top = stack.pop(); /* Time O(1) */ + pop({ stack, minStack } = this) { + const top = stack.pop(); /* Time O(1) */ const canPopMin = top === this.getMin(); - if (canPopMin) minStack.pop(); /* Time O(1) */ + if (canPopMin) minStack.pop(); /* Time O(1) */ } /** * @param {Array} * @return {number} */ - top (stack = this.stack) { - return stack.length - ? stack[stack.length - 1] /* Time O(1) */ - : null; + top(stack = this.stack) { + return stack.length ? stack[stack.length - 1] /* Time O(1) */ : null; } /** * @return {number} */ - getMin (minStack = this.minStack) { - return this.top(minStack); /* Time O(1) */ + getMin(minStack = this.minStack) { + return this.top(minStack); /* Time O(1) */ } } - -/** +/** * https://leetcode.com/problems/min-stack * Time O(1) | Space O(1) * Your MinStack object will be instantiated and called as such: @@ -70,31 +67,31 @@ class MinStack { * var param_4 = obj.getMin() */ class MinStack { - constructor () { - this.head = null + constructor() { + this.head = null; } - push (val) { - this.head = (!this.head) /* Space O(1) */ + push(val) { + this.head = !this.head /* Space O(1) */ ? new Node(val, val, null) : new Node(val, Math.min(val, this.head.min), this.head); } - pop () { - this.head = this.head.next;/* Time O(1) */ + pop() { + this.head = this.head.next; /* Time O(1) */ } - top () { - return this.head.val; /* Time O(1) */ + top() { + return this.head.val; /* Time O(1) */ } - getMin () { - return this.head.min; /* Time O(1) */ + getMin() { + return this.head.min; /* Time O(1) */ } } class Node { - constructor (val, min, next) { + constructor(val, min, next) { this.val = val; this.min = min; this.next = next; diff --git a/javascript/0162-find-peak-element.js b/javascript/0162-find-peak-element.js index cabcc5fc5..88f3589e2 100644 --- a/javascript/0162-find-peak-element.js +++ b/javascript/0162-find-peak-element.js @@ -3,18 +3,16 @@ * @param {number[]} nums * @return {number} */ -var findPeakElement = function(nums) { +var findPeakElement = function (nums) { let [l, r] = [0, nums.length - 1]; let mid = null; - while (l <= r){ + while (l <= r) { mid = (l + r) >> 1; - if (mid < nums.length - 1 && nums[mid] < nums[mid+1]){ + if (mid < nums.length - 1 && nums[mid] < nums[mid + 1]) { l = mid + 1; - } - else if (mid > 0 && nums[mid] < nums[mid-1]) { + } else if (mid > 0 && nums[mid] < nums[mid - 1]) { r = mid - 1; - } - else { + } else { break; } } diff --git a/javascript/0169-majority-element.js b/javascript/0169-majority-element.js index 97b4f366d..c491e68e6 100644 --- a/javascript/0169-majority-element.js +++ b/javascript/0169-majority-element.js @@ -7,18 +7,18 @@ */ var majorityElement = function (nums) { - let res = nums[0]; - let count = 1; + let res = nums[0]; + let count = 1; - for (let i = 1; i < nums.length - 1; i++) { - if (nums[i] === res) count++; - else if (!--count) { - res = nums[i + 1]; - count = 0; - } - } + for (let i = 1; i < nums.length - 1; i++) { + if (nums[i] === res) count++; + else if (!--count) { + res = nums[i + 1]; + count = 0; + } + } - return res; + return res; }; /** @@ -30,18 +30,18 @@ var majorityElement = function (nums) { */ var majorityElement = function (nums) { - const occuranceOfElement = new Map(); - - for (let i = 0; i < nums.length; i++) { - if (occuranceOfElement.has(nums[i])) { - let occurance = occuranceOfElement.get(nums[i]); - occuranceOfElement.set(nums[i], occurance + 1); - } else { - occuranceOfElement.set(nums[i], 1); - } - } + const occuranceOfElement = new Map(); - for (let [key, value] of occuranceOfElement) { - if (value > nums.length / 2) return key; - } + for (let i = 0; i < nums.length; i++) { + if (occuranceOfElement.has(nums[i])) { + let occurance = occuranceOfElement.get(nums[i]); + occuranceOfElement.set(nums[i], occurance + 1); + } else { + occuranceOfElement.set(nums[i], 1); + } + } + + for (let [key, value] of occuranceOfElement) { + if (value > nums.length / 2) return key; + } }; diff --git a/javascript/0173-binary-search-tree-iterator.js b/javascript/0173-binary-search-tree-iterator.js index ae547001b..5da2d3e99 100644 --- a/javascript/0173-binary-search-tree-iterator.js +++ b/javascript/0173-binary-search-tree-iterator.js @@ -14,18 +14,19 @@ * @param {TreeNode} root */ class BSTIterator { - constructor (root) { - this.stack = []; /* | Space O(N) */ - this.getLeft(root);/* Time O(N) | Space O(N)*/ + constructor(root) { + this.stack = []; /* | Space O(N) */ + this.getLeft(root); /* Time O(N) | Space O(N)*/ } /** * Time O(N) | Space O(H) * @return {number} */ - getLeft (root, { stack } = this) { - while (root !== null) {/* Time O(N) */ - stack.push(root); /* Space O(N) */ + getLeft(root, { stack } = this) { + while (root !== null) { + /* Time O(N) */ + stack.push(root); /* Space O(N) */ root = root.left; } } @@ -35,25 +36,25 @@ class BSTIterator { * @return the next smallest number * @return {number} */ - next ({ stack } = this) { + next({ stack } = this) { const node = stack.pop(); - if (node.right) this.getLeft(node.right);/* Time O(N) | Space O(N) */ + if (node.right) this.getLeft(node.right); /* Time O(N) | Space O(N) */ return node.val; - }; + } /** * Time O(1) | Space O(1) * @return whether we have a next smallest number * @return {boolean} */ - hasNext ({ stack } = this) { - return (stack.length !== 0); + hasNext({ stack } = this) { + return stack.length !== 0; } } -/** +/** * Your BSTIterator object will be instantiated and called as such: * var obj = new BSTIterator(root) * var param_1 = obj.next() diff --git a/javascript/0189-rotate-array.js b/javascript/0189-rotate-array.js index b8ff1562c..4442d98d7 100644 --- a/javascript/0189-rotate-array.js +++ b/javascript/0189-rotate-array.js @@ -1,64 +1,60 @@ /** * Two Pointers * https://leetcode.com/problems/rotate-array/ - * + * * Time O(n) | Space O(1) * @param {number[]} nums * @param {number} k * @return {void} Do not return anything, modify nums in-place instead. */ - var rotate = function(nums, k) { - +var rotate = function (nums, k) { // if the k exceeds the length of nums. k = k % nums.length; nums.reverse(); reversePortionOfArray(nums, 0, k - 1); - reversePortionOfArray(nums,k, nums.length - 1); + reversePortionOfArray(nums, k, nums.length - 1); }; -var reversePortionOfArray = function(nums,start,end) { - while(start < end) { - [nums[start],nums[end]] = [nums[end],nums[start]]; +var reversePortionOfArray = function (nums, start, end) { + while (start < end) { + [nums[start], nums[end]] = [nums[end], nums[start]]; start++; end--; - } -} - + } +}; /** * Two Pointers * https://leetcode.com/problems/rotate-array/ - * + * * Time O(n) | Space O(1) * @param {number[]} nums * @param {number} k * @return {void} Do not return anything, modify nums in-place instead. */ -var rotate = function(nums, k) { - - k = k % nums.length; - - let l = 0; - let r = nums.length - 1; +var rotate = function (nums, k) { + k = k % nums.length; + + let l = 0; + let r = nums.length - 1; - while (l < r) { - [nums[l], nums[r]] = [nums[r], nums[l]]; - l += 1; - r -= 1; - } - l = 0, - r = k - 1; - while (l < r) { - [nums[l], nums[r]] = [nums[r], nums[l]]; - l += 1; - r -= 1; - } - l = k; - r = nums.length - 1; - while (l < r) { - [nums[l], nums[r]] = [nums[r], nums[l]]; - l += 1; - r -= 1; - } + while (l < r) { + [nums[l], nums[r]] = [nums[r], nums[l]]; + l += 1; + r -= 1; + } + ((l = 0), (r = k - 1)); + while (l < r) { + [nums[l], nums[r]] = [nums[r], nums[l]]; + l += 1; + r -= 1; + } + l = k; + r = nums.length - 1; + while (l < r) { + [nums[l], nums[r]] = [nums[r], nums[l]]; + l += 1; + r -= 1; + } }; diff --git a/javascript/0190-reverse-bits.js b/javascript/0190-reverse-bits.js index fc286c4a7..20d55ba2e 100644 --- a/javascript/0190-reverse-bits.js +++ b/javascript/0190-reverse-bits.js @@ -6,9 +6,9 @@ */ var reverseBits = function (n, bit = 0) { for (let i = 0; i < 32; i++) { - bit <<= 1; // Double * 2 - bit |= (n & 1); // Flip - n >>= 1; // Reduce * 0.5 + bit <<= 1; // Double * 2 + bit |= n & 1; // Flip + n >>= 1; // Reduce * 0.5 } return bit >>> 0; diff --git a/javascript/0191-number-of-1-bits.js b/javascript/0191-number-of-1-bits.js index d98d2e8eb..259509bd1 100644 --- a/javascript/0191-number-of-1-bits.js +++ b/javascript/0191-number-of-1-bits.js @@ -4,17 +4,17 @@ * @param {number} n - a positive integer * @return {number} */ - var hammingWeight = function(n) { - let [ bits, mask ] = [ 0, 1 ] - +var hammingWeight = function (n) { + let [bits, mask] = [0, 1]; + for (let i = 0; i < 32; i++) { - const hasBit = ((n & mask) !== 0) - if (hasBit) bits++ - - mask <<= 1 + const hasBit = (n & mask) !== 0; + if (hasBit) bits++; + + mask <<= 1; } - - return bits + + return bits; }; /** @@ -23,11 +23,11 @@ * @param {number} n - a positive integer * @return {number} */ - var hammingWeight = function(n, sum = 0) { +var hammingWeight = function (n, sum = 0) { while (n !== 0) { - n &= (n - 1) - sum++ + n &= n - 1; + sum++; } - - return sum -} + + return sum; +}; diff --git a/javascript/0198-house-robber.js b/javascript/0198-house-robber.js index 34ef665c5..c41e0d1da 100644 --- a/javascript/0198-house-robber.js +++ b/javascript/0198-house-robber.js @@ -9,10 +9,10 @@ var rob = (nums, i = 0) => { const isBaseCase = nums <= i; if (isBaseCase) return 0; - const [ next, nextNext ] = [ (i + 1), (i + 2) ]; + const [next, nextNext] = [i + 1, i + 2]; const right = nums[i]; - const mid = rob(nums, next); /* Time O(2^N) | Space O(N) */ - const left = rob(nums, nextNext);/* Time O(2^N) | Space O(N) */ + const mid = rob(nums, next); /* Time O(2^N) | Space O(N) */ + const left = rob(nums, nextNext); /* Time O(2^N) | Space O(N) */ const house = left + right; return Math.max(house, mid); @@ -33,13 +33,13 @@ var rob = (nums, i = 0, memo = initMemo(nums)) => { const hasSeen = 0 <= memo[i]; if (hasSeen) return memo[i]; - const [ next, nextNext ] = [ (i + 1), (i + 2) ]; + const [next, nextNext] = [i + 1, i + 2]; const right = nums[i]; - const mid = rob(nums, next, memo); /* Time O(N) | Space O(N) */ - const left = rob(nums, nextNext, memo);/* Time O(N) | Space O(N) */ + const mid = rob(nums, next, memo); /* Time O(N) | Space O(N) */ + const left = rob(nums, nextNext, memo); /* Time O(N) | Space O(N) */ const house = left + right; - memo[i] = Math.max(mid, house); /* | Space O(N) */ + memo[i] = Math.max(mid, house); /* | Space O(N) */ return memo[i]; }; @@ -59,16 +59,17 @@ var rob = (nums) => { const tabu = initTabu(nums); - for (let i = 1; i < nums.length; i++) {/* Time O(N) */ + for (let i = 1; i < nums.length; i++) { + /* Time O(N) */ const right = nums[i]; const mid = tabu[i]; const left = tabu[i - 1]; const house = left + right; - tabu[i + 1] = Math.max(mid, house); /* Space O(N) */ + tabu[i + 1] = Math.max(mid, house); /* Space O(N) */ } - return tabu[nums.length] + return tabu[nums.length]; }; const initTabu = (nums) => { @@ -77,7 +78,7 @@ const initTabu = (nums) => { tabu[1] = nums[0]; return tabu; -} +}; /** * DP - Bottom Up @@ -89,9 +90,10 @@ const initTabu = (nums) => { var rob = (nums) => { if (!nums.length) return 0; - let [ left, mid ] = [ 0, 0 ]; + let [left, mid] = [0, 0]; - for (const right of nums) {/* Time O(N) */ + for (const right of nums) { + /* Time O(N) */ const temp = mid; const house = left + right; @@ -100,4 +102,4 @@ var rob = (nums) => { } return mid; -}; \ No newline at end of file +}; diff --git a/javascript/0199-binary-tree-right-side-view.js b/javascript/0199-binary-tree-right-side-view.js index 35fb95b62..37e7a08d5 100644 --- a/javascript/0199-binary-tree-right-side-view.js +++ b/javascript/0199-binary-tree-right-side-view.js @@ -4,18 +4,18 @@ * @param {TreeNode} root * @return {number[]} */ - var rightSideView = function(root) { +var rightSideView = function (root) { const isBaseCase = root === null; if (isBaseCase) return []; - return bfs([ root ]); + return bfs([root]); }; const bfs = (queue, rightSide = []) => { while (queue.length) { let prev = null; - for (let i = (queue.length - 1); 0 <= i; i--) { + for (let i = queue.length - 1; 0 <= i; i--) { const node = queue.shift(); prev = node; @@ -28,7 +28,7 @@ const bfs = (queue, rightSide = []) => { } return rightSide; -} +}; /** * https://leetcode.com/problems/binary-tree-right-side-view/ @@ -36,20 +36,19 @@ const bfs = (queue, rightSide = []) => { * @param {TreeNode} root * @return {number[]} */ - var rightSideView = function(root, level = 0, rightSide = []) { +var rightSideView = function (root, level = 0, rightSide = []) { const isBaseCase = root === null; if (isBaseCase) return rightSide; - const isLastNode = level === rightSide.length + const isLastNode = level === rightSide.length; if (isLastNode) rightSide.push(root.val); - return dfs(root, level, rightSide) -} + return dfs(root, level, rightSide); +}; const dfs = (root, level, rightSide) => { - if (root.right) rightSideView(root.right, (level + 1), rightSide); - if (root.left) rightSideView(root.left, (level + 1), rightSide); - - return rightSide -} + if (root.right) rightSideView(root.right, level + 1, rightSide); + if (root.left) rightSideView(root.left, level + 1, rightSide); + return rightSide; +}; diff --git a/javascript/0200-number-of-islands.js b/javascript/0200-number-of-islands.js index e0ba467a4..b1bfd473f 100644 --- a/javascript/0200-number-of-islands.js +++ b/javascript/0200-number-of-islands.js @@ -4,19 +4,21 @@ * @param {character[][]} grid * @return {number} */ -var numIslands = function(grid, connectedComponents = 0) { - const [ rows, cols ] = [ grid.length, grid[0].length ] +var numIslands = function (grid, connectedComponents = 0) { + const [rows, cols] = [grid.length, grid[0].length]; - for (let row = 0; row < rows; row++) {/* Time O(ROWS) */ - for (let col = 0; col < cols; col++) {/* Time O(COLS) */ - const isIsland = grid[row][col] === '1' - if (isIsland) connectedComponents++ + for (let row = 0; row < rows; row++) { + /* Time O(ROWS) */ + for (let col = 0; col < cols; col++) { + /* Time O(COLS) */ + const isIsland = grid[row][col] === '1'; + if (isIsland) connectedComponents++; - dfs(grid, row, rows, col, cols); /* Space O(ROWS * COLS) */ + dfs(grid, row, rows, col, cols); /* Space O(ROWS * COLS) */ } } - return connectedComponents + return connectedComponents; }; const dfs = (grid, row, rows, col, cols) => { @@ -25,14 +27,23 @@ const dfs = (grid, row, rows, col, cols) => { grid[row][col] = '0'; - for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) { - dfs(grid, _row, rows, _col, cols); /* Space O(ROWS * COLS) */ + for (const [_row, _col] of getNeighbors(row, rows, col, cols)) { + dfs(grid, _row, rows, _col, cols); /* Space O(ROWS * COLS) */ } -} +}; -var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ], [ 0, -1 ], [ 1, 0 ], [ -1, 0 ] ] - .map(([ _row, _col ]) => [ (row + _row), (col + _col) ]) - .filter(([ _row, _col ]) => (0 <= _row) && (_row < rows) && (0 <= _col) && (_col < cols)) +var getNeighbors = (row, rows, col, cols) => + [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ] + .map(([_row, _col]) => [row + _row, col + _col]) + .filter( + ([_row, _col]) => + 0 <= _row && _row < rows && 0 <= _col && _col < cols, + ); /** * https://leetcode.com/problems/number-of-islands/ @@ -40,41 +51,58 @@ var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ], [ 0, -1 ], [ 1, 0 ], [ * @param {character[][]} grid * @return {number} */ - var numIslands = function(grid, connectedComponents = 0) { - const [ rows, cols ] = [ grid.length, grid[0].length ] +var numIslands = function (grid, connectedComponents = 0) { + const [rows, cols] = [grid.length, grid[0].length]; - for (let row = 0; row < rows; row++) {/* Time O(ROWS) */ - for (let col = 0; col < cols; col++) {/* Time O(COLS) */ + for (let row = 0; row < rows; row++) { + /* Time O(ROWS) */ + for (let col = 0; col < cols; col++) { + /* Time O(COLS) */ const isIsland = grid[row][col] === '1'; if (isIsland) connectedComponents++; - bfs(grid, rows, cols, new Queue([ [ row, col ] ]));/* Space O(MIN(ROWS,COLS)) */ + bfs( + grid, + rows, + cols, + new Queue([[row, col]]), + ); /* Space O(MIN(ROWS,COLS)) */ } } - return connectedComponents - } + return connectedComponents; +}; - const bfs = (grid, rows, cols, queue) => { +const bfs = (grid, rows, cols, queue) => { while (!queue.isEmpty()) { - for (let i = (queue.size() - 1); 0 <= i; i--) {/* Time O(WIDTH) */ - const [ row, col ] = queue.dequeue(); + for (let i = queue.size() - 1; 0 <= i; i--) { + /* Time O(WIDTH) */ + const [row, col] = queue.dequeue(); const isWater = grid[row][col] === '0'; if (isWater) continue; grid[row][col] = '0'; - for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) { - queue.enqueue([ _row, _col ]); /* Space O(MIN(ROWS,COLS)) */ + for (const [_row, _col] of getNeighbors(row, rows, col, cols)) { + queue.enqueue([_row, _col]); /* Space O(MIN(ROWS,COLS)) */ } } } - } +}; -var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ], [ 0, -1 ], [ 1, 0 ], [ -1, 0 ] ] - .map(([ _row, _col]) => [ (row + _row), (col + _col) ]) - .filter(([ _row, _col ]) => (0 <= _row) && (_row < rows) && (0 <= _col) && (_col < cols)); +var getNeighbors = (row, rows, col, cols) => + [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ] + .map(([_row, _col]) => [row + _row, col + _col]) + .filter( + ([_row, _col]) => + 0 <= _row && _row < rows && 0 <= _col && _col < cols, + ); /** * https://leetcode.com/problems/number-of-islands/ @@ -83,18 +111,22 @@ var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ], [ 0, -1 ], [ 1, 0 ], [ * @return {number} */ var numIslands = function (grid) { - const unionFind = new UnionFind(grid);/* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ + const unionFind = new UnionFind( + grid, + ); /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ - searchGrid(grid, unionFind); /* Time O(ROWS * COLS) */ + searchGrid(grid, unionFind); /* Time O(ROWS * COLS) */ return unionFind.connectedComponents; -} +}; var searchGrid = (grid, unionFind) => { - const [ rows, cols ] = [ grid.length, grid[0].length ]; + const [rows, cols] = [grid.length, grid[0].length]; - for (let row = 0; row < rows; row++) {/* Time O(ROWS) */ - for (let col = 0; col < cols; col++) {/* Time O(COLS) */ + for (let row = 0; row < rows; row++) { + /* Time O(ROWS) */ + for (let col = 0; col < cols; col++) { + /* Time O(COLS) */ const isWater = grid[row][col] === '0'; if (isWater) continue; @@ -104,27 +136,29 @@ var searchGrid = (grid, unionFind) => { searchCols(unionFind, grid, row, rows, col, cols); } } -} +}; -const searchRows = (unionFind, grid, row, rows, col, cols) => [ 1, -1 ] - .map((_row) => row + _row) - .filter((_row) => isInBound(_row, rows) && isIsland(grid[_row][col])) - .map((_row) => [ index(row, cols, col), index(_row, cols, col) ]) - .forEach(([ x, y ]) => unionFind.union(x, y)); +const searchRows = (unionFind, grid, row, rows, col, cols) => + [1, -1] + .map((_row) => row + _row) + .filter((_row) => isInBound(_row, rows) && isIsland(grid[_row][col])) + .map((_row) => [index(row, cols, col), index(_row, cols, col)]) + .forEach(([x, y]) => unionFind.union(x, y)); -const isInBound = (val, vals) => (0 <= val) && (val < vals) -const isIsland = (cell) => cell === '1' -const index = (row, cols, col) => ((row * cols) + col) +const isInBound = (val, vals) => 0 <= val && val < vals; +const isIsland = (cell) => cell === '1'; +const index = (row, cols, col) => row * cols + col; -const searchCols = (unionFind, grid, row, rows, col, cols) => [ 1, -1 ] - .map((_col) => col + _col) - .filter((_col) => isInBound(_col, cols) && isIsland(grid[row][_col])) - .map((_col) => [ index(row, cols, col), index(row, cols, _col) ]) - .forEach(([ x, y ]) => unionFind.union(x, y)); +const searchCols = (unionFind, grid, row, rows, col, cols) => + [1, -1] + .map((_col) => col + _col) + .filter((_col) => isInBound(_col, cols) && isIsland(grid[row][_col])) + .map((_col) => [index(row, cols, col), index(row, cols, _col)]) + .forEach(([x, y]) => unionFind.union(x, y)); class UnionFind { - constructor (grid) { - const [ rows, cols ] = [ grid.length, grid[0].length ]; + constructor(grid) { + const [rows, cols] = [grid.length, grid[0].length]; this.connectedComponents = 0; this.grid = grid; @@ -136,21 +170,23 @@ class UnionFind { this.findIslands(); } - findIslands ({ grid, rows, cols, parent } = this) { - for (let row = 0; row < rows; row++) {/* Time O(ROWS) */ - for (let col = 0; col < cols; col++) {/* Time O(COLS) */ + findIslands({ grid, rows, cols, parent } = this) { + for (let row = 0; row < rows; row++) { + /* Time O(ROWS) */ + for (let col = 0; col < cols; col++) { + /* Time O(COLS) */ const isWater = grid[row][col] === '0'; if (isWater) continue; - const index = (row * cols) + col; + const index = row * cols + col; - parent[index] = index;/* Space O(ROWS * COLS) */ + parent[index] = index; /* Space O(ROWS * COLS) */ this.connectedComponents++; } } } - find (index, { parent } = this) { + find(index, { parent } = this) { const isEqual = () => parent[index] === index; while (!isEqual()) { index = parent[index]; @@ -159,8 +195,8 @@ class UnionFind { return parent[index]; } - union (x, y, { parent, rank } = this) { - const [ rootX, rootY ] = [ this.find(x), this.find(y) ]; + union(x, y, { parent, rank } = this) { + const [rootX, rootY] = [this.find(x), this.find(y)]; const hasCycle = rootX === rootY; if (hasCycle) return; @@ -168,12 +204,12 @@ class UnionFind { this.connectedComponents--; const isXGreater = rank[rootY] < rank[rootX]; - if (isXGreater) return parent[rootY] = rootX; + if (isXGreater) return (parent[rootY] = rootX); const isYGreater = rank[rootX] < rank[rootY]; - if (isYGreater) return parent[rootX] = rootY; + if (isYGreater) return (parent[rootX] = rootY); - parent[rootY] = rootX; /* Space O(ROWS * COLS) */ - rank[rootX]++; /* Space O(ROWS * COLS) */ + parent[rootY] = rootX; /* Space O(ROWS * COLS) */ + rank[rootX]++; /* Space O(ROWS * COLS) */ } } diff --git a/javascript/0202-happy-number.js b/javascript/0202-happy-number.js index c2a2efece..faa6c4917 100644 --- a/javascript/0202-happy-number.js +++ b/javascript/0202-happy-number.js @@ -5,26 +5,28 @@ * @param {number} n * @return {boolean} */ - var isHappy = (n, seen = new Set()) => { - const hasCycle = () => ((n === 1) || (seen.has(n))); - while (!hasCycle()) {/* Time O(log(N)) */ - seen.add(n); /* Space O(log(N)) */ - n = getNext(n); /* Time O(log(N)) */ +var isHappy = (n, seen = new Set()) => { + const hasCycle = () => n === 1 || seen.has(n); + while (!hasCycle()) { + /* Time O(log(N)) */ + seen.add(n); /* Space O(log(N)) */ + n = getNext(n); /* Time O(log(N)) */ } - return (n === 1); + return n === 1; }; var getNext = (n, sum = 0) => { - while (0 < n) {/* Time O(log(N)) */ - const remainder = (n % 10); + while (0 < n) { + /* Time O(log(N)) */ + const remainder = n % 10; - n = Math.floor((n / 10)); - sum += (remainder * remainder); + n = Math.floor(n / 10); + sum += remainder * remainder; } return sum; -} +}; /** * Hash Set - seen static @@ -34,27 +36,29 @@ var getNext = (n, sum = 0) => { * @return {boolean} */ var isHappy = (n) => { - const cycles = [ 4, 16, 37, 58, 89, 145, 42, 20 ]; - const seen = new Set(cycles);/* Time O(1) | Space O(1) */ + const cycles = [4, 16, 37, 58, 89, 145, 42, 20]; + const seen = new Set(cycles); /* Time O(1) | Space O(1) */ - const hasCycle = () => ((n === 1) || (seen.has(n))); - while (!hasCycle()) { /* Time O(log(N)) | Space O(1) */ + const hasCycle = () => n === 1 || seen.has(n); + while (!hasCycle()) { + /* Time O(log(N)) | Space O(1) */ n = getNext(n); } return n === 1; -} +}; var getNext = (n, sum = 0) => { - while (0 < n) {/* Time O(log(N)) */ - const remainder = (n % 10); + while (0 < n) { + /* Time O(log(N)) */ + const remainder = n % 10; - n = Math.floor((n / 10)); - sum += (remainder * remainder); + n = Math.floor(n / 10); + sum += remainder * remainder; } return sum; -} +}; /** * Pointer - n === 1 || n === 4 @@ -64,24 +68,26 @@ var getNext = (n, sum = 0) => { * @return {boolean} */ var isHappy = (n) => { - const hasCycle = () => ((n === 1) || (n === 4)); - while (!hasCycle()) {/* Time O(log(N)) */ - n = getNext(n); /* Time O(log(N)) */ + const hasCycle = () => n === 1 || n === 4; + while (!hasCycle()) { + /* Time O(log(N)) */ + n = getNext(n); /* Time O(log(N)) */ } return n === 1; -} +}; var getNext = (n, sum = 0) => { - while (0 < n) {/* Time O(log(N)) */ - const remainder = (n % 10); - - n = Math.floor((n / 10)); - sum += (remainder * remainder); + while (0 < n) { + /* Time O(log(N)) */ + const remainder = n % 10; + + n = Math.floor(n / 10); + sum += remainder * remainder; } return sum; -} +}; /** * Slow Fast @@ -91,24 +97,26 @@ var getNext = (n, sum = 0) => { * @return {boolean} */ var isHappy = (n) => { - let [ slow, fast ] = [ n, getNext(n) ]; - - const hasCyle = () => ((fast === 1) || (slow === fast)); - while (!hasCyle()) { /* Time O(log(N)) */ - slow = getNext(slow); /* Time O(log(N)) */ - fast = getNext(getNext(fast));/* Time O(log(N)) */ + let [slow, fast] = [n, getNext(n)]; + + const hasCyle = () => fast === 1 || slow === fast; + while (!hasCyle()) { + /* Time O(log(N)) */ + slow = getNext(slow); /* Time O(log(N)) */ + fast = getNext(getNext(fast)); /* Time O(log(N)) */ } - return (fast === 1); -} + return fast === 1; +}; var getNext = (n, sum = 0) => { - while (0 < n) {/* Time O(log(N)) */ - const remainder = (n % 10); + while (0 < n) { + /* Time O(log(N)) */ + const remainder = n % 10; - n = Math.floor((n / 10)); - sum += (remainder * remainder); + n = Math.floor(n / 10); + sum += remainder * remainder; } return sum; -} \ No newline at end of file +}; diff --git a/javascript/0203-remove-linked-list-elements.js b/javascript/0203-remove-linked-list-elements.js index 298626e72..f4f30b356 100644 --- a/javascript/0203-remove-linked-list-elements.js +++ b/javascript/0203-remove-linked-list-elements.js @@ -1,32 +1,31 @@ -/** - * Definition for singly-linked list. - * function ListNode(val, next) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * } - */ -/** - * @param {ListNode} head - * @param {number} val - * @return {ListNode} - */ -var removeElements = function (head, val) { - - let sentinel_node = new ListNode(0, head); - let slow_pointer = sentinel_node; - let fast_pointer = null; - - while (slow_pointer) { - // get next legible node - fast_pointer = slow_pointer.next; - while (fast_pointer && fast_pointer.val === val) { - fast_pointer = fast_pointer.next; - } - - // Set next node to the legible node - slow_pointer.next = fast_pointer; - slow_pointer = slow_pointer.next; - } - - return sentinel_node.next; -}; +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} head + * @param {number} val + * @return {ListNode} + */ +var removeElements = function (head, val) { + let sentinel_node = new ListNode(0, head); + let slow_pointer = sentinel_node; + let fast_pointer = null; + + while (slow_pointer) { + // get next legible node + fast_pointer = slow_pointer.next; + while (fast_pointer && fast_pointer.val === val) { + fast_pointer = fast_pointer.next; + } + + // Set next node to the legible node + slow_pointer.next = fast_pointer; + slow_pointer = slow_pointer.next; + } + + return sentinel_node.next; +}; diff --git a/javascript/0206-reverse-linked-list.js b/javascript/0206-reverse-linked-list.js index 5ad06b365..798c8ff85 100644 --- a/javascript/0206-reverse-linked-list.js +++ b/javascript/0206-reverse-linked-list.js @@ -8,17 +8,17 @@ var reverseList = function (head) { const isBaseCase = !head?.next; if (isBaseCase) return head; - return dfs(head); /* Time O(N) | Space O(N) */ -} + return dfs(head); /* Time O(N) | Space O(N) */ +}; const dfs = (curr) => { - const prev = reverseList(curr.next);/* Time O(N) | Space O(N) */ + const prev = reverseList(curr.next); /* Time O(N) | Space O(N) */ curr.next.next = curr; curr.next = null; return prev; -} +}; /** * https://leetcode.com/problems/reverse-linked-list/ @@ -26,10 +26,11 @@ const dfs = (curr) => { * @param {ListNode} head * @return {ListNode} */ - var reverseList = function (head) { - let [ prev, curr, next ] = [ null, head, null ]; +var reverseList = function (head) { + let [prev, curr, next] = [null, head, null]; - while (curr) {/* Time O(N) */ + while (curr) { + /* Time O(N) */ next = curr.next; curr.next = prev; @@ -38,4 +39,4 @@ const dfs = (curr) => { } return prev; -}; \ No newline at end of file +}; diff --git a/javascript/0207-course-schedule.js b/javascript/0207-course-schedule.js index 7f604d3a8..c211ff747 100644 --- a/javascript/0207-course-schedule.js +++ b/javascript/0207-course-schedule.js @@ -5,22 +5,22 @@ * @param {number[][]} prerequisites * @return {boolean} */ -var canFinish = function(numCourses, prerequisites) { +var canFinish = function (numCourses, prerequisites) { const { graph, path } = buildGraph(numCourses, prerequisites); return hasPath(numCourses, graph, path); -} +}; var initGraph = (numCourses) => ({ graph: new Array(numCourses).fill().map(() => []), - path: new Array(numCourses).fill(false) -}) + path: new Array(numCourses).fill(false), +}); var buildGraph = (numCourses, prerequisites) => { const { graph, path } = initGraph(numCourses); - for (const [ src, dst ] of prerequisites) { - const neighbors = (graph[dst] || []); + for (const [src, dst] of prerequisites) { + const neighbors = graph[dst] || []; neighbors.push(src); @@ -28,7 +28,7 @@ var buildGraph = (numCourses, prerequisites) => { } return { graph, path }; -} +}; var hasPath = (numCourses, graph, path) => { for (let course = 0; course < numCourses; course++) { @@ -36,33 +36,33 @@ var hasPath = (numCourses, graph, path) => { } return true; -} +}; var isCyclic = (currCourse, graph, path) => { - const hasSeen = path[currCourse] - if (hasSeen) return true + const hasSeen = path[currCourse]; + if (hasSeen) return true; - const isMissingNext = !(currCourse in graph) + const isMissingNext = !(currCourse in graph); if (isMissingNext) return false; return backTrack(currCourse, graph, path); -} +}; var backTrack = (currCourse, graph, path) => { path[currCourse] = true; - const _hasCycle = hasCycle(currCourse, graph, path) + const _hasCycle = hasCycle(currCourse, graph, path); path[currCourse] = false; - return _hasCycle -} + return _hasCycle; +}; var hasCycle = (currCourse, graph, path) => { for (const neighbor of graph[currCourse]) { if (isCyclic(neighbor, graph, path)) return true; } - return false -} + return false; +}; /** * https://leetcode.com/problems/course-schedule/ @@ -71,27 +71,27 @@ var hasCycle = (currCourse, graph, path) => { * @param {number[][]} prerequisites * @return {boolean} */ -var canFinish = function(numCourses, prerequisites) { - const { graph, visited, path } = buildGraph(numCourses, prerequisites); +var canFinish = function (numCourses, prerequisites) { + const { graph, visited, path } = buildGraph(numCourses, prerequisites); for (let currCourse = 0; currCourse < numCourses; currCourse++) { if (isCyclic(currCourse, graph, visited, path)) return false; } return true; -} +}; var initGraph = (numCourses) => ({ graph: new Array(numCourses).fill().map(() => []), visited: new Array(numCourses).fill(false), - path: new Array(numCourses).fill(false) -}) + path: new Array(numCourses).fill(false), +}); var buildGraph = (numCourses, prerequisites) => { const { graph, visited, path } = initGraph(numCourses); - for (const [ src, dst ] of prerequisites) { - const neighbors = (graph[dst] || []); + for (const [src, dst] of prerequisites) { + const neighbors = graph[dst] || []; neighbors.push(src); @@ -99,40 +99,40 @@ var buildGraph = (numCourses, prerequisites) => { } return { graph, visited, path }; -} +}; var isCyclic = (currCourse, graph, visited, path) => { - const isVisited = visited[currCourse] + const isVisited = visited[currCourse]; if (isVisited) return false; - const hasSeen = path[currCourse] + const hasSeen = path[currCourse]; if (hasSeen) return true; - const isMissingNext = !(currCourse in graph) + const isMissingNext = !(currCourse in graph); if (isMissingNext) return false; const _isCyclic = backTrack(currCourse, graph, visited, path); visited[currCourse] = true; - return _isCyclic -} + return _isCyclic; +}; var backTrack = (currCourse, graph, visited, path) => { path[currCourse] = true; - const _hasCycle = hasCycle(currCourse, graph, visited, path) + const _hasCycle = hasCycle(currCourse, graph, visited, path); path[currCourse] = false; - return _hasCycle -} + return _hasCycle; +}; var hasCycle = (currCourse, graph, visited, path) => { for (const neighbor of graph[currCourse]) { if (isCyclic(neighbor, graph, visited, path)) return true; } - return false -} + return false; +}; /** * https://leetcode.com/problems/course-schedule/ @@ -141,7 +141,7 @@ var hasCycle = (currCourse, graph, visited, path) => { * @param {number[][]} prerequisites * @return {boolean} */ -var canFinish = function(numCourses, prerequisites) { +var canFinish = function (numCourses, prerequisites) { const { graph, indegree } = buildGraph(numCourses, prerequisites); const topologicalOrder = topologicalSort(graph, indegree); const isDirectedAcyclicGraph = topologicalOrder.length === numCourses; @@ -151,19 +151,19 @@ var canFinish = function(numCourses, prerequisites) { var initGraph = (numCourses) => ({ graph: new Array(numCourses).fill().map(() => []), - indegree: new Array(numCourses).fill(0) -}) + indegree: new Array(numCourses).fill(0), +}); var buildGraph = (numCourses, prerequisites) => { const { graph, indegree } = initGraph(numCourses); - for (const [ src, dst ] of prerequisites){ + for (const [src, dst] of prerequisites) { graph[src].push(dst); indegree[dst]++; } return { graph, indegree }; -} +}; var topologicalSort = (graph, indegree, order = []) => { const queue = searchGraph(graph, indegree); @@ -171,7 +171,7 @@ var topologicalSort = (graph, indegree, order = []) => { bfs(graph, indegree, queue, order); return order; -} +}; var searchGraph = (graph, indegree, queue = new Queue([])) => { for (const node in graph) { @@ -180,15 +180,15 @@ var searchGraph = (graph, indegree, queue = new Queue([])) => { } return queue; -} +}; var bfs = (graph, indegree, queue, order) => { while (!queue.isEmpty()) { - for (let i = (queue.size() - 1); 0 <= i; i--) { + for (let i = queue.size() - 1; 0 <= i; i--) { checkNeighbors(graph, indegree, queue, order); } } -} +}; var checkNeighbors = (graph, indegree, queue, order) => { const node = queue.dequeue(); @@ -201,4 +201,4 @@ var checkNeighbors = (graph, indegree, queue, order) => { const isSource = indegree[neighbor] === 0; if (isSource) queue.enqueue(neighbor); } -} +}; diff --git a/javascript/0210-course-schedule-ii.js b/javascript/0210-course-schedule-ii.js index 33ccf0b1f..988d312c7 100644 --- a/javascript/0210-course-schedule-ii.js +++ b/javascript/0210-course-schedule-ii.js @@ -5,67 +5,105 @@ * @param {number[][]} prerequisites * @return {number[]} */ -var findOrder = function(numCourses, prerequisites) { - const { graph, color, isDirectedAcyclicGraph, topologicalOrder } = buildGraph(numCourses, prerequisites); +var findOrder = function (numCourses, prerequisites) { + const { graph, color, isDirectedAcyclicGraph, topologicalOrder } = + buildGraph(numCourses, prerequisites); - search(numCourses, graph, color, topologicalOrder, isDirectedAcyclicGraph) + search(numCourses, graph, color, topologicalOrder, isDirectedAcyclicGraph); - return isDirectedAcyclicGraph[0] - ? topologicalOrder.reverse() - : [] -} + return isDirectedAcyclicGraph[0] ? topologicalOrder.reverse() : []; +}; var initGraph = (numCourses) => ({ graph: new Array(numCourses).fill().map(() => []), color: new Array(numCourses).fill(1), // White - isDirectedAcyclicGraph: [ true ], - topologicalOrder: [] -}) + isDirectedAcyclicGraph: [true], + topologicalOrder: [], +}); var buildGraph = (numCourses, prerequisites) => { - const { graph, color, isDirectedAcyclicGraph, topologicalOrder } = initGraph(numCourses); + const { graph, color, isDirectedAcyclicGraph, topologicalOrder } = + initGraph(numCourses); - for (const [ src, dst ] of prerequisites) { - const neighbors = (graph[dst] || []); + for (const [src, dst] of prerequisites) { + const neighbors = graph[dst] || []; neighbors.push(src); graph[dst] = neighbors; } - return { graph, color, isDirectedAcyclicGraph, topologicalOrder } -} + return { graph, color, isDirectedAcyclicGraph, topologicalOrder }; +}; -var search = (numCourses, graph, color, topologicalOrder, isDirectedAcyclicGraph) => { +var search = ( + numCourses, + graph, + color, + topologicalOrder, + isDirectedAcyclicGraph, +) => { for (let i = 0; i < numCourses; i++) { - const isNew = color[i] === 1 // White - if (isNew) dfs(i, graph, color, topologicalOrder, isDirectedAcyclicGraph); + const isNew = color[i] === 1; // White + if (isNew) + dfs(i, graph, color, topologicalOrder, isDirectedAcyclicGraph); } -} +}; var dfs = (node, graph, color, topologicalOrder, isDirectedAcyclicGraph) => { - const hasCycle = !isDirectedAcyclicGraph[0] + const hasCycle = !isDirectedAcyclicGraph[0]; if (hasCycle) return; - colorBackTrack(node, graph, color, topologicalOrder, isDirectedAcyclicGraph) + colorBackTrack( + node, + graph, + color, + topologicalOrder, + isDirectedAcyclicGraph, + ); topologicalOrder.push(node); -} +}; -const colorBackTrack = (node, graph, color, topologicalOrder, isDirectedAcyclicGraph) => { +const colorBackTrack = ( + node, + graph, + color, + topologicalOrder, + isDirectedAcyclicGraph, +) => { color[node] = 2; // Grey - checkNeighbors(node, graph, color, topologicalOrder, isDirectedAcyclicGraph) + checkNeighbors( + node, + graph, + color, + topologicalOrder, + isDirectedAcyclicGraph, + ); color[node] = 3; // Black -} +}; -var checkNeighbors = (node, graph, color, topologicalOrder, isDirectedAcyclicGraph) => { +var checkNeighbors = ( + node, + graph, + color, + topologicalOrder, + isDirectedAcyclicGraph, +) => { for (const neighbor of graph[node]) { - const isNew = color[neighbor] === 1 // White - if (isNew) dfs(neighbor, graph, color, topologicalOrder, isDirectedAcyclicGraph); - - const isCycle = color[neighbor] === 2 // Grey + const isNew = color[neighbor] === 1; // White + if (isNew) + dfs( + neighbor, + graph, + color, + topologicalOrder, + isDirectedAcyclicGraph, + ); + + const isCycle = color[neighbor] === 2; // Grey if (isCycle) isDirectedAcyclicGraph[0] = false; } -} +}; /** * https://leetcode.com/problems/course-schedule-ii/ @@ -74,37 +112,36 @@ var checkNeighbors = (node, graph, color, topologicalOrder, isDirectedAcyclicGra * @param {number[][]} prerequisites * @return {number[]} */ -var findOrder = function(numCourses, prerequisites) { +var findOrder = function (numCourses, prerequisites) { const { graph, indegree } = buildGraph(numCourses, prerequisites); const reversedTopologicalOrder = topologicalSort(graph, indegree); - const isDirectedAcyclicGraph = reversedTopologicalOrder.length === numCourses; + const isDirectedAcyclicGraph = + reversedTopologicalOrder.length === numCourses; - return isDirectedAcyclicGraph - ? reversedTopologicalOrder - : []; + return isDirectedAcyclicGraph ? reversedTopologicalOrder : []; }; var initGraph = (numCourses) => ({ graph: new Array(numCourses).fill().map(() => []), - indegree: new Array(numCourses).fill(0) -}) + indegree: new Array(numCourses).fill(0), +}); var buildGraph = (numCourses, prerequisites) => { const { graph, indegree } = initGraph(numCourses); - for (const [ src, dst ] of prerequisites){ + for (const [src, dst] of prerequisites) { graph[src].push(dst); indegree[dst]++; } return { graph, indegree }; -} +}; var topologicalSort = (graph, indegree) => { const queue = searchGraph(graph, indegree); return bfs(graph, indegree, queue); -} +}; var isSource = (count) => count === 0; @@ -114,17 +151,17 @@ var searchGraph = (graph, indegree, queue = new Queue([])) => { } return queue; -} +}; var bfs = (graph, indegree, queue, reversedOrder = []) => { while (!queue.isEmpty()) { - for (let i = (queue.size() - 1); 0 <= i; i--) { + for (let i = queue.size() - 1; 0 <= i; i--) { checkNeighbors(graph, indegree, queue, reversedOrder); } } return reversedOrder.reverse(); -} +}; var checkNeighbors = (graph, indegree, queue, reversedOrder) => { const node = queue.dequeue(); @@ -136,4 +173,4 @@ var checkNeighbors = (graph, indegree, queue, reversedOrder) => { if (isSource(indegree[neighbor])) queue.enqueue(neighbor); } -} \ No newline at end of file +}; diff --git a/javascript/0213-house-robber-ii.js b/javascript/0213-house-robber-ii.js index c23a7c691..694cf3b01 100644 --- a/javascript/0213-house-robber-ii.js +++ b/javascript/0213-house-robber-ii.js @@ -6,22 +6,23 @@ * @return {number} */ var rob = (nums) => { - const isBaseCase1 = (nums.length === 0); + const isBaseCase1 = nums.length === 0; if (isBaseCase1) return 0; - const isBaseCase2 = (nums.length === 1); - if (isBaseCase2) return nums[0] + const isBaseCase2 = nums.length === 1; + if (isBaseCase2) return nums[0]; - const left = search(nums, 0, (nums.length - 2)); /* Time O(N) */ - const right = search(nums, 1, (nums.length - 1));/* Time O(N) */ + const left = search(nums, 0, nums.length - 2); /* Time O(N) */ + const right = search(nums, 1, nums.length - 1); /* Time O(N) */ return Math.max(left, right); }; const search = (nums, start, end) => { - let [ left, mid ] = [ 0, 0 ]; + let [left, mid] = [0, 0]; - for (let i = start; i <= end; i++) {/* Time O(N) */ + for (let i = start; i <= end; i++) { + /* Time O(N) */ const temp = mid; const right = nums[i]; const house = left + right; @@ -31,6 +32,4 @@ const search = (nums, start, end) => { } return mid; -} - - +}; diff --git a/javascript/0215-kth-largest-element-in-an-array.js b/javascript/0215-kth-largest-element-in-an-array.js index 8204d4aaa..22f45ee42 100644 --- a/javascript/0215-kth-largest-element-in-an-array.js +++ b/javascript/0215-kth-largest-element-in-an-array.js @@ -5,11 +5,12 @@ * @param {number} k * @return {number} */ - var findKthLargest = function(nums, k) { return nums - .sort((a, b) => a - b) - .reverse() - .slice(k - 1) - .shift() +var findKthLargest = function (nums, k) { + return nums + .sort((a, b) => a - b) + .reverse() + .slice(k - 1) + .shift(); }; /** @@ -19,8 +20,8 @@ * @param {number} k * @return {number} */ - var findKthLargest = function(nums, k) { - const minHeap = new MinPriorityQueue() +var findKthLargest = function (nums, k) { + const minHeap = new MinPriorityQueue(); for (const num of nums) { minHeap.enqueue(num); @@ -29,5 +30,5 @@ if (isAtCapacity) minHeap.dequeue(); } - return minHeap.front().element + return minHeap.front().element; }; diff --git a/javascript/0217-contains-duplicate.js b/javascript/0217-contains-duplicate.js index 7242fe2dd..ed946be59 100644 --- a/javascript/0217-contains-duplicate.js +++ b/javascript/0217-contains-duplicate.js @@ -6,15 +6,17 @@ * @return {boolean} */ var containsDuplicate = (nums) => { - for (let right = 0; right < nums.length; right++) {/* Time O(N) */ - for (let left = 0; left < right; left++) { /* Time O(N) */ + for (let right = 0; right < nums.length; right++) { + /* Time O(N) */ + for (let left = 0; left < right; left++) { + /* Time O(N) */ const isDuplicate = nums[left] === nums[right]; if (isDuplicate) return true; } } return false; -} +}; /** * Sort - HeapSort Space O(1) | QuickSort Space O(log(N)) @@ -24,21 +26,22 @@ var containsDuplicate = (nums) => { * @return {boolean} */ var containsDuplicate = (nums) => { - nums.sort((a, b) => a - b);/* Time O(N * log(N)) | Space O(1 || log(N)) */ + nums.sort((a, b) => a - b); /* Time O(N * log(N)) | Space O(1 || log(N)) */ return hasDuplicate(nums); -} +}; const hasDuplicate = (nums) => { - for (let curr = 0; curr < (nums.length - 1); curr++) {/* Time O(N) */ - const next = (curr + 1); + for (let curr = 0; curr < nums.length - 1; curr++) { + /* Time O(N) */ + const next = curr + 1; const isNextDuplicate = nums[curr] === nums[next]; if (isNextDuplicate) return true; } return false; -} +}; /** * Hash Set @@ -48,7 +51,7 @@ const hasDuplicate = (nums) => { * @return {boolean} */ var containsDuplicate = (nums) => { - const numsSet = new Set(nums);/* Time O(N) | Space O(N) */ + const numsSet = new Set(nums); /* Time O(N) | Space O(N) */ const isEqual = numsSet.size === nums.length; return !isEqual; @@ -62,11 +65,12 @@ var containsDuplicate = (nums) => { * @return {boolean} */ var containsDuplicate = (nums, numsSet = new Set()) => { - for (const num of nums) {/* Time O(N) */ + for (const num of nums) { + /* Time O(N) */ if (numsSet.has(num)) return true; - numsSet.add(num); /* Space O(N) */ + numsSet.add(num); /* Space O(N) */ } return false; -}; \ No newline at end of file +}; diff --git a/javascript/0219-contains-duplicate-ii.js b/javascript/0219-contains-duplicate-ii.js index a72e225f8..1cd15b3fb 100644 --- a/javascript/0219-contains-duplicate-ii.js +++ b/javascript/0219-contains-duplicate-ii.js @@ -8,18 +8,18 @@ * @param {number} k * @return {boolean} */ -var containsNearbyDuplicate = function(nums, k) { +var containsNearbyDuplicate = function (nums, k) { const window = new Set(); let L = 0; for (let R = 0; R < nums.length; R++) { if (!window.has(nums[R])) { window.add(nums[R]); } else { - return true + return true; } if (R - L + 1 > k) { - window.delete(nums[L]) + window.delete(nums[L]); L++; } } diff --git a/javascript/0225-implement-stack-using-queues.js b/javascript/0225-implement-stack-using-queues.js index b484845a2..20560b49e 100644 --- a/javascript/0225-implement-stack-using-queues.js +++ b/javascript/0225-implement-stack-using-queues.js @@ -1,27 +1,25 @@ -var MyStack = function() { +var MyStack = function () { this.q = []; }; -MyStack.prototype.push = function(x) { +MyStack.prototype.push = function (x) { this.q.push(x); }; -MyStack.prototype.pop = function() { +MyStack.prototype.pop = function () { let size = this.q.length; - for(let i = 0; i < size - 1; i++) - this.push(this.q.shift()); + for (let i = 0; i < size - 1; i++) this.push(this.q.shift()); return this.q.shift(); }; -MyStack.prototype.top = function() { +MyStack.prototype.top = function () { let size = this.q.length; - for(let i = 0; i < size - 1; i++) - this.push(this.q.shift()); + for (let i = 0; i < size - 1; i++) this.push(this.q.shift()); let res = this.q.shift(); this.push(res); return res; }; -MyStack.prototype.empty = function() { - return this.q.length == 0 +MyStack.prototype.empty = function () { + return this.q.length == 0; }; diff --git a/javascript/0226-invert-binary-tree.js b/javascript/0226-invert-binary-tree.js index 55438b15e..d8f79f843 100644 --- a/javascript/0226-invert-binary-tree.js +++ b/javascript/0226-invert-binary-tree.js @@ -9,7 +9,7 @@ var invertTree = (root) => { if (isBaseCase) return root; return dfs(root); -} +}; const dfs = (root) => { const left = invertTree(root.left); @@ -19,7 +19,7 @@ const dfs = (root) => { root.right = left; return root; -} +}; /** * https://leetcode.com/problems/invert-binary-tree/ @@ -27,18 +27,18 @@ const dfs = (root) => { * @param {TreeNode} root * @return {TreeNode} */ -var invertTree = (root,) => { +var invertTree = (root) => { const isBaseCase = root === null; if (isBaseCase) return root; - bfs([ root ]); + bfs([root]); return root; -} +}; const bfs = (queue) => { while (queue.length) { - for (let i = (queue.length - 1); 0 <= i; i--) { + for (let i = queue.length - 1; 0 <= i; i--) { const node = queue.shift(); const left = node.right; const right = node.left; @@ -50,5 +50,4 @@ const bfs = (queue) => { if (node.right) queue.push(node.right); } } -} - +}; diff --git a/javascript/0230-kth-smallest-element-in-a-bst.js b/javascript/0230-kth-smallest-element-in-a-bst.js index 3cb704080..a40149147 100644 --- a/javascript/0230-kth-smallest-element-in-a-bst.js +++ b/javascript/0230-kth-smallest-element-in-a-bst.js @@ -1,49 +1,49 @@ -/** - * https://leetcode.com/problems/kth-smallest-element-in-a-bst/ - * Time O(N + K) | Space O(H) - * @param {TreeNode} root - * @param {number} k - * @return {number} - */ - var kthSmallest = function(root, k, inOrder = []) { - if (!root) return inOrder - - return dfs(root, k, inOrder); -}; - -const dfs = (root, k, inOrder) => { - if (root.left) kthSmallest(root.left, k, inOrder); - - inOrder.push(root.val); - - if (root.right) kthSmallest(root.right, k, inOrder); - - return inOrder[(k - 1)]; -} - -/** - * https://leetcode.com/problems/kth-smallest-element-in-a-bst/ - * Time O(N + K) | Space O(H) - * @param {TreeNode} root - * @param {number} k - * @return {number} - */ - var kthSmallest = function(root, k, stack = []) { - while (k--) { - root = moveLeft(root, stack); - - const isSmallest = k === 0; - if (isSmallest) return root.val; - - root = root.right; - } -} - -const moveLeft = (root, stack) => { - while (root !== null) { - stack.push(root); - root = root.left; - } - - return stack.pop(); -} +/** + * https://leetcode.com/problems/kth-smallest-element-in-a-bst/ + * Time O(N + K) | Space O(H) + * @param {TreeNode} root + * @param {number} k + * @return {number} + */ +var kthSmallest = function (root, k, inOrder = []) { + if (!root) return inOrder; + + return dfs(root, k, inOrder); +}; + +const dfs = (root, k, inOrder) => { + if (root.left) kthSmallest(root.left, k, inOrder); + + inOrder.push(root.val); + + if (root.right) kthSmallest(root.right, k, inOrder); + + return inOrder[k - 1]; +}; + +/** + * https://leetcode.com/problems/kth-smallest-element-in-a-bst/ + * Time O(N + K) | Space O(H) + * @param {TreeNode} root + * @param {number} k + * @return {number} + */ +var kthSmallest = function (root, k, stack = []) { + while (k--) { + root = moveLeft(root, stack); + + const isSmallest = k === 0; + if (isSmallest) return root.val; + + root = root.right; + } +}; + +const moveLeft = (root, stack) => { + while (root !== null) { + stack.push(root); + root = root.left; + } + + return stack.pop(); +}; diff --git a/javascript/0232-implement-queue-using-stacks.js b/javascript/0232-implement-queue-using-stacks.js index c728e2daa..d34669fb9 100644 --- a/javascript/0232-implement-queue-using-stacks.js +++ b/javascript/0232-implement-queue-using-stacks.js @@ -1,25 +1,25 @@ // https://leetcode.com/problems/implement-queue-using-stacks/ -var MyQueue = function() { +var MyQueue = function () { this.stack1 = []; - this.stack2 = []; + this.stack2 = []; }; -/** +/** * @param {number} x * @return {void} */ -MyQueue.prototype.push = function(x) { +MyQueue.prototype.push = function (x) { this.stack1.push(x); }; /** * @return {number} */ -MyQueue.prototype.pop = function() { +MyQueue.prototype.pop = function () { this.swappingStacks(); - - if(!this.stack2.length){ + + if (!this.stack2.length) { return null; } return this.stack2.pop(); @@ -28,26 +28,26 @@ MyQueue.prototype.pop = function() { /** * @return {number} */ -MyQueue.prototype.peek = function() { +MyQueue.prototype.peek = function () { this.swappingStacks(); - return this.stack2.length == 0 ? null : this.stack2[this.stack2.length-1] + return this.stack2.length == 0 ? null : this.stack2[this.stack2.length - 1]; }; /** * @return {boolean} */ -MyQueue.prototype.empty = function() { +MyQueue.prototype.empty = function () { return this.stack1.length === 0 && this.stack2.length === 0; }; -MyQueue.prototype.swappingStacks = function() { +MyQueue.prototype.swappingStacks = function () { if (this.stack1.length) { this.stack2 = [...this.stack1.reverse(), ...this.stack2]; this.stack1 = []; } -} +}; -/** +/** * Your MyQueue object will be instantiated and called as such: * var obj = new MyQueue() * obj.push(x) diff --git a/javascript/0235-lowest-common-ancestor-of-a-binary-search-tree.js b/javascript/0235-lowest-common-ancestor-of-a-binary-search-tree.js index ee8396413..37a3a0606 100644 --- a/javascript/0235-lowest-common-ancestor-of-a-binary-search-tree.js +++ b/javascript/0235-lowest-common-ancestor-of-a-binary-search-tree.js @@ -6,11 +6,11 @@ * @param {TreeNode} q * @return {TreeNode} */ - var lowestCommonAncestor = function(root, p, q) { - const isGreater = (p.val < root.val) && (q.val < root.val); +var lowestCommonAncestor = function (root, p, q) { + const isGreater = p.val < root.val && q.val < root.val; if (isGreater) return lowestCommonAncestor(root.left, p, q); - const isLess = (root.val < p.val) && (root.val < q.val); + const isLess = root.val < p.val && root.val < q.val; if (isLess) return lowestCommonAncestor(root.right, p, q); return root; @@ -24,15 +24,15 @@ * @param {TreeNode} q * @return {TreeNode} */ - var lowestCommonAncestor = function(root, p, q) { +var lowestCommonAncestor = function (root, p, q) { while (root !== null) { - const isGreater = (root.val < p.val) && (root.val < q.val) + const isGreater = root.val < p.val && root.val < q.val; if (isGreater) { root = root.right; continue; } - const isLess = (p.val < root.val) && (q.val < root.val);; + const isLess = p.val < root.val && q.val < root.val; if (isLess) { root = root.left; continue; diff --git a/javascript/0238-product-of-array-except-self.js b/javascript/0238-product-of-array-except-self.js index a3ef93d0b..e2edb0a54 100644 --- a/javascript/0238-product-of-array-except-self.js +++ b/javascript/0238-product-of-array-except-self.js @@ -5,11 +5,11 @@ * @param {number[]} nums * @return {number[]} */ - function productExceptSelf(nums) { +function productExceptSelf(nums) { const result = []; let prefix = 1; let postfix = 1; - + for (let i = 0; i < nums.length; i++) { result[i] = prefix; prefix *= nums[i]; @@ -18,6 +18,6 @@ postfix *= nums[i + 1]; result[i] *= postfix; } - + return result; -}; \ No newline at end of file +} diff --git a/javascript/0242-valid-anagram.js b/javascript/0242-valid-anagram.js index 9fc874482..c58292a48 100644 --- a/javascript/0242-valid-anagram.js +++ b/javascript/0242-valid-anagram.js @@ -13,10 +13,13 @@ var isAnagram = (s, t) => { return reorder(s) === reorder(t); /* Time O(N * logN) | Space O(N) */ }; -const reorder = (str) => str - .split('') /* Time O(N) | Space O(N) */ - .sort((a, b) => a.localeCompare(b))/* Time O(N * log(N)) | Space O(1 || log(N)) */ - .join(''); /* Time O(N) | Space O(N) */ +const reorder = (str) => + str + .split('') /* Time O(N) | Space O(N) */ + .sort((a, b) => + a.localeCompare(b), + ) /* Time O(N * log(N)) | Space O(1 || log(N)) */ + .join(''); /* Time O(N) | Space O(N) */ /** * Hash Map - Frequency Counter @@ -30,35 +33,38 @@ var isAnagram = (s, t, map = new Map()) => { const isEqual = s.length === t.length; if (!isEqual) return false; - addFrequency(s, map); /* Time O(N) | Space O(1) */ + addFrequency(s, map); /* Time O(N) | Space O(1) */ subtractFrequency(t, map); /* Time O(N) | Space O(1) */ - return checkFrequency(map);/* Time O(N) */ + return checkFrequency(map); /* Time O(N) */ }; const addFrequency = (str, map) => { - for (const char of str) {/* Time O(N) */ + for (const char of str) { + /* Time O(N) */ const count = (map.get(char) || 0) + 1; - map.set(char, count); /* Space O(1) */ + map.set(char, count); /* Space O(1) */ } -} +}; const subtractFrequency = (str, map) => { - for (const char of str) {/* Time O(N) */ + for (const char of str) { + /* Time O(N) */ if (!map.has(char)) continue; const count = map.get(char) - 1; - map.set(char, count); /* Space O(1) */ + map.set(char, count); /* Space O(1) */ } }; const checkFrequency = (map) => { - for (const [ char, count ] of map) {/* Time O(N) */ + for (const [char, count] of map) { + /* Time O(N) */ const isEmpty = count === 0; if (!isEmpty) return false; } return true; -} +}; diff --git a/javascript/0252-meeting-rooms.js b/javascript/0252-meeting-rooms.js index bdd933a51..caa80a0dd 100644 --- a/javascript/0252-meeting-rooms.js +++ b/javascript/0252-meeting-rooms.js @@ -6,7 +6,7 @@ */ var canAttendMeetings = function (intervals) { intervals.sort(([aStart, aEnd], [bStart, bEnd]) => - aStart !== bStart ? aStart - bStart : aEnd - bEnd + aStart !== bStart ? aStart - bStart : aEnd - bEnd, ); return canAttend(intervals); diff --git a/javascript/0261-graph-valid-tree.js b/javascript/0261-graph-valid-tree.js index 0f88af14a..e376ef6ca 100644 --- a/javascript/0261-graph-valid-tree.js +++ b/javascript/0261-graph-valid-tree.js @@ -5,32 +5,32 @@ * @param {number[][]} edges * @return {boolean} */ -var validTree = function(n, edges, root = 0) { - const isEqual = edges.length === (n - 1) +var validTree = function (n, edges, root = 0) { + const isEqual = edges.length === n - 1; if (!isEqual) return false; - const { graph, visited } = buildGraph(n, edges) + const { graph, visited } = buildGraph(n, edges); dfs(root, graph, visited); return visited.size === n; -} +}; var initGraph = (n) => ({ graph: new Array(n).fill().map(() => []), - visited: new Set() -}) + visited: new Set(), +}); var buildGraph = (n, edges) => { - const { graph, visited } = initGraph(n) + const { graph, visited } = initGraph(n); - for (const [ src, dst ] of edges) { + for (const [src, dst] of edges) { graph[src].push(dst); graph[dst].push(src); } - return { graph, visited } -} + return { graph, visited }; +}; const dfs = (node, graph, visited) => { if (visited.has(node)) return; @@ -39,7 +39,7 @@ const dfs = (node, graph, visited) => { for (const neighbor of graph[node]) { dfs(neighbor, graph, visited); } -} +}; /** * https://leetcode.com/problems/graph-valid-tree/ @@ -48,28 +48,28 @@ const dfs = (node, graph, visited) => { * @param {number[][]} edges * @return {boolean} */ -var validTree = function(n, edges) { - const isEqual = edges.length === (n - 1) +var validTree = function (n, edges) { + const isEqual = edges.length === n - 1; if (!isEqual) return false; - const { graph, visited, queue } = buildGraph(n, edges) + const { graph, visited, queue } = buildGraph(n, edges); - bfs(graph, visited, queue) + bfs(graph, visited, queue); return visited.size === n; -} +}; var initGraph = (n) => ({ graph: new Array(n).fill().map(() => []), visited: new Set(), queue: new Queue(), - root: 0 -}) + root: 0, +}); var buildGraph = (n, edges) => { - const { graph, visited, queue, root } = initGraph(n) + const { graph, visited, queue, root } = initGraph(n); - for (const [ src, dst ] of edges) { + for (const [src, dst] of edges) { graph[src].push(dst); graph[dst].push(src); } @@ -77,16 +77,16 @@ var buildGraph = (n, edges) => { queue.enqueue(root); visited.add(root); - return { graph, visited, queue } -} + return { graph, visited, queue }; +}; const bfs = (graph, visited, queue) => { while (!queue.isEmpty()) { - for (let i = (queue.size() - 1); 0 <= i; i--) { - checkNeighbor(graph, visited, queue) + for (let i = queue.size() - 1; 0 <= i; i--) { + checkNeighbor(graph, visited, queue); } } -} +}; const checkNeighbor = (graph, visited, queue) => { const node = queue.dequeue(); @@ -97,7 +97,7 @@ const checkNeighbor = (graph, visited, queue) => { queue.enqueue(neighbor); } -} +}; /** * https://leetcode.com/problems/graph-valid-tree/ @@ -106,31 +106,31 @@ const checkNeighbor = (graph, visited, queue) => { * @param {number[][]} edges * @return {boolean} */ -var validTree = function(n, edges) { - const union = new Array(n).fill(-1) +var validTree = function (n, edges) { + const union = new Array(n).fill(-1); - for (const [ src, dst ] of edges) { - const [ x, y ] = [ find(union, src), find(union, dst) ] + for (const [src, dst] of edges) { + const [x, y] = [find(union, src), find(union, dst)]; - const hasCycle = x === y - if (hasCycle) return false + const hasCycle = x === y; + if (hasCycle) return false; - compress(union, x, y) + compress(union, x, y); } - const isValid = edges.length === (n - 1) - return isValid + const isValid = edges.length === n - 1; + return isValid; }; -const compress = (union, i, head) => union[i] = head +const compress = (union, i, head) => (union[i] = head); const find = (union, i, num = union[i]) => { - const isEmpty = num === -1 - if (isEmpty) return i + const isEmpty = num === -1; + if (isEmpty) return i; - const head = find(union, num) + const head = find(union, num); - compress(union, i, head) + compress(union, i, head); - return union[i] -} + return union[i]; +}; diff --git a/javascript/0263-ugly-number.js b/javascript/0263-ugly-number.js index 3f5997772..ef3b5c75d 100644 --- a/javascript/0263-ugly-number.js +++ b/javascript/0263-ugly-number.js @@ -1,9 +1,6 @@ -var isUgly = function(n) { - if(n <= 0) - return false; - - for(const p of [2, 3, 5]) - while(n % p == 0) - n = n / p; +var isUgly = function (n) { + if (n <= 0) return false; + + for (const p of [2, 3, 5]) while (n % p == 0) n = n / p; return n == 1; }; diff --git a/javascript/0268-missing-number.js b/javascript/0268-missing-number.js index 5d6e60928..5cb91cf8e 100644 --- a/javascript/0268-missing-number.js +++ b/javascript/0268-missing-number.js @@ -6,7 +6,7 @@ */ var missingNumber = function (nums, missingNumber = nums.length) { for (let i = 0; i < nums.length; i++) { - const xor = (i ^ nums[i]); + const xor = i ^ nums[i]; missingNumber ^= xor; } diff --git a/javascript/0269-alien-dictionary.js b/javascript/0269-alien-dictionary.js index 6638e7c78..8ba2efc61 100644 --- a/javascript/0269-alien-dictionary.js +++ b/javascript/0269-alien-dictionary.js @@ -4,7 +4,7 @@ * @param {string[]} words * @return {string} */ - var alienOrder = function(words) { +var alienOrder = function (words) { const { graph, frequencyMap, queue, buffer } = buildGraph(words); if (!canBuildGraph(words, graph, frequencyMap)) return ''; @@ -12,17 +12,15 @@ queueSources(queue, frequencyMap); bfs(queue, frequencyMap, graph, buffer); - return (frequencyMap.size <= buffer.length) - ? buffer.join('') - : ''; -} + return frequencyMap.size <= buffer.length ? buffer.join('') : ''; +}; var initGraph = () => ({ graph: new Map(), frequencyMap: new Map(), queue: new Queue(), buffer: [], -}) +}); var buildGraph = (words) => { const { graph, frequencyMap, queue, buffer } = initGraph(); @@ -38,19 +36,19 @@ var buildGraph = (words) => { }; var canBuildGraph = (words, graph, frequencyMap) => { - for (let index = 0; (index < words.length - 1); index++) { - const [ word1, word2 ] = [ words[index], words[(index + 1)] ]; - const minLength = Math.min(word1.length, word2.length) + for (let index = 0; index < words.length - 1; index++) { + const [word1, word2] = [words[index], words[index + 1]]; + const minLength = Math.min(word1.length, word2.length); - const isWord1Longer = (word2.length < word1.length); + const isWord1Longer = word2.length < word1.length; const isPrefix = isWord1Longer && word1.startsWith(word2); if (isPrefix) return false; - for (let j = 0; (j < minLength); j++) { - const [ char1, char2 ] = [ word1[j], word2[j] ]; + for (let j = 0; j < minLength; j++) { + const [char1, char2] = [word1[j], word2[j]]; - const isEqual = (char1 === char2); + const isEqual = char1 === char2; if (isEqual) continue; graph.get(char1).push(char2); @@ -65,8 +63,8 @@ var canBuildGraph = (words, graph, frequencyMap) => { const bfs = (queue, frequencyMap, graph, buffer) => { while (!queue.isEmpty()) { - for (let level = (queue.size() - 1); (0 <= level); level--) { - checkNeighbors(queue, frequencyMap, graph, buffer) + for (let level = queue.size() - 1; 0 <= level; level--) { + checkNeighbors(queue, frequencyMap, graph, buffer); } } }; @@ -77,25 +75,25 @@ var checkNeighbors = (queue, frequencyMap, graph, buffer) => { buffer.push(char); for (const next of graph.get(char)) { - const value = (frequencyMap.get(next) - 1); + const value = frequencyMap.get(next) - 1; frequencyMap.set(next, value); - const isEmpty = (frequencyMap.get(next) === 0); + const isEmpty = frequencyMap.get(next) === 0; if (!isEmpty) continue; queue.enqueue(next); } -} +}; const queueSources = (queue, frequencyMap) => { - for (const [ key, value ] of frequencyMap) { - const isEmpty = (frequencyMap.get(key) === 0); + for (const [key, value] of frequencyMap) { + const isEmpty = frequencyMap.get(key) === 0; if (!isEmpty) continue; queue.enqueue(key); } -} +}; /** * DFS @@ -103,23 +101,23 @@ const queueSources = (queue, frequencyMap) => { * @param {string[]} words * @return {string} */ - var alienOrder = function(words) { +var alienOrder = function (words) { const { graph, seen, buffer } = buildGraph(words); if (!canBuildGraph(words, graph)) return ''; - for (const [ char ] of graph) { + for (const [char] of graph) { if (!dfs(char, graph, seen, buffer)) return ''; } - return buffer.reverse().join('') -} + return buffer.reverse().join(''); +}; var initGraph = () => ({ graph: new Map(), seen: new Map(), buffer: [], -}) +}); var buildGraph = (words) => { const { graph, seen, buffer } = initGraph(); @@ -134,23 +132,23 @@ var buildGraph = (words) => { }; var canBuildGraph = (words, graph) => { - for (let index = 0; (index < words.length - 1); index++) { - const [ word1, word2 ] = [ words[index], words[(index + 1)] ]; - const minLength = Math.min(word1.length, word2.length) + for (let index = 0; index < words.length - 1; index++) { + const [word1, word2] = [words[index], words[index + 1]]; + const minLength = Math.min(word1.length, word2.length); - const isWord1Longer = (word2.length < word1.length); + const isWord1Longer = word2.length < word1.length; const isPrefix = isWord1Longer && word1.startsWith(word2); if (isPrefix) return false; - for (let j = 0; (j < minLength); j++) { - const [ char1, char2 ] = [ word1[j], word2[j] ]; + for (let j = 0; j < minLength; j++) { + const [char1, char2] = [word1[j], word2[j]]; - const isEqual = (char1 === char2); + const isEqual = char1 === char2; if (isEqual) continue; graph.get(char1).push(char2); - + break; } } @@ -166,14 +164,14 @@ const dfs = (char, graph, seen, buffer) => { buffer.push(char); return true; -} +}; const backTrack = (char, graph, seen, buffer) => { seen.set(char, false); - for (const neighbor of graph.get(char)) { - if (!dfs(neighbor, graph, seen, buffer)) return false; - } + for (const neighbor of graph.get(char)) { + if (!dfs(neighbor, graph, seen, buffer)) return false; + } seen.set(char, true); return true; -} \ No newline at end of file +}; diff --git a/javascript/0271-encode-and-decode-strings.js b/javascript/0271-encode-and-decode-strings.js index 2b16eea97..2b59bcd85 100644 --- a/javascript/0271-encode-and-decode-strings.js +++ b/javascript/0271-encode-and-decode-strings.js @@ -7,9 +7,11 @@ */ var encode = (strs) => { return strs - .map((str) => `${str.length}#${str}`)/* Time O(N) | Ignore Auxillary Space O(N) */ - .join(''); /* Time O(N) | Ignore Auxillary Space O(N) */ -} + .map( + (str) => `${str.length}#${str}`, + ) /* Time O(N) | Ignore Auxillary Space O(N) */ + .join(''); /* Time O(N) | Ignore Auxillary Space O(N) */ +}; /** * String - Delimiter @@ -19,27 +21,36 @@ var encode = (strs) => { * @return {string[]} */ var decode = (str, index = 0, decodedWords = []) => { - while (index < str.length) {/* Time O(N) */ - const { nextIndex, word } = delimitWord(str, index);/* Time O(K) | Ignore Auxillary Space Space (K) */ + while (index < str.length) { + /* Time O(N) */ + const { nextIndex, word } = delimitWord( + str, + index, + ); /* Time O(K) | Ignore Auxillary Space Space (K) */ - decodedWords.push(word); /* | Ignore Auxillary Space O(N * K ) */ + decodedWords.push( + word, + ); /* | Ignore Auxillary Space O(N * K ) */ index = nextIndex; } return decodedWords; -} +}; const delimitWord = (str, index) => { - const delimiter = str.indexOf('#', index); /* Time O(K) */ - const length = Number(str.slice(index, delimiter)); /* Time O(K) */ - const [ start, end ] = [ (delimiter + 1), ((delimiter + length) + 1) ]; - const word = str.slice(start, end); /* Time O(K) | Ignore Auxillary Space O(K) */ + const delimiter = str.indexOf('#', index); /* Time O(K) */ + const length = Number(str.slice(index, delimiter)); /* Time O(K) */ + const [start, end] = [delimiter + 1, delimiter + length + 1]; + const word = str.slice( + start, + end, + ); /* Time O(K) | Ignore Auxillary Space O(K) */ return { - nextIndex: end, - word + nextIndex: end, + word, }; -} +}; /** * Non-ASCII Delimiter - Ignore Auxiliary Space @@ -49,7 +60,9 @@ const delimitWord = (str, index) => { * @return {string} */ var encode = (strs, nonASCIICode = String.fromCharCode(257)) => { - return strs.join(nonASCIICode);/* Time O(N) | Ignore Auxillary Space O(N) */ + return strs.join( + nonASCIICode, + ); /* Time O(N) | Ignore Auxillary Space O(N) */ }; /** @@ -60,7 +73,9 @@ var encode = (strs, nonASCIICode = String.fromCharCode(257)) => { * @return {string} */ var decode = (strs, nonASCIICode = String.fromCharCode(257)) => { - return strs.split(nonASCIICode);/* Time O(N) | Ignore Auxillary Space O(N) */ + return strs.split( + nonASCIICode, + ); /* Time O(N) | Ignore Auxillary Space O(N) */ }; /** @@ -71,20 +86,18 @@ var decode = (strs, nonASCIICode = String.fromCharCode(257)) => { * @return {string} */ var encode = (strs, sb = []) => { - for (const str of strs) {/* Time O(N) */ - const code = getCode(str);/* Time O(1) */ + for (const str of strs) { + /* Time O(N) */ + const code = getCode(str); /* Time O(1) */ const encoding = `${code}${str}`; - sb.push(encoding); + sb.push(encoding); } return sb.join(''); /* Time O(N) | Ignore Auxillary Space O(N) */ -} +}; -const getCode = (str) => str - .length - .toString(2) - .padStart(8,'0'); +const getCode = (str) => str.length.toString(2).padStart(8, '0'); /** * Chunk Transfer Encoding @@ -94,16 +107,24 @@ const getCode = (str) => str * @return {string[]} */ var decode = (str, output = []) => { - for (let left = 0, right = (left + 8),length = 0; + for ( + let left = 0, right = left + 8, length = 0; left < str.length; - left = (right + length), right = (left + 8) - ) { /* Time O(N) */ - const countString = str.slice(left, right); /* | Ignore Auxillary Space O(K) */ + left = right + length, right = left + 8 + ) { + /* Time O(N) */ + const countString = str.slice( + left, + right, + ); /* | Ignore Auxillary Space O(K) */ length = parseInt(countString, 2); - const decoding = str.slice(right, (right + length)); /* Time O(K) | Ignore Auxillary Space O(N * K) */ - output.push(decoding); /* | Ignore Auxillary Space O(N * K) */ + const decoding = str.slice( + right, + right + length, + ); /* Time O(K) | Ignore Auxillary Space O(N * K) */ + output.push(decoding); /* | Ignore Auxillary Space O(N * K) */ } return output; -} +}; diff --git a/javascript/0273-integer-to-english-words.js b/javascript/0273-integer-to-english-words.js index f86df2ae0..4065977c2 100644 --- a/javascript/0273-integer-to-english-words.js +++ b/javascript/0273-integer-to-english-words.js @@ -6,45 +6,75 @@ */ var convertToWords = function (num) { - var belowTwenty = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]; - var belowHundred = ["", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]; - var thousands = ["" , "Thousand", "Million", "Billion"] + var belowTwenty = [ + '', + 'One', + 'Two', + 'Three', + 'Four', + 'Five', + 'Six', + 'Seven', + 'Eight', + 'Nine', + 'Ten', + 'Eleven', + 'Twelve', + 'Thirteen', + 'Fourteen', + 'Fifteen', + 'Sixteen', + 'Seventeen', + 'Eighteen', + 'Nineteen', + ]; + var belowHundred = [ + '', + 'Ten', + 'Twenty', + 'Thirty', + 'Forty', + 'Fifty', + 'Sixty', + 'Seventy', + 'Eighty', + 'Ninety', + ]; + var thousands = ['', 'Thousand', 'Million', 'Billion']; var pointer = 0; - result = ""; + result = ''; while (num > 0) { - var words = ""; + var words = ''; reminder = num % 1000; num = Math.floor(num / 1000); if (reminder > 0) { if (reminder >= 100) { - words += belowTwenty[Math.floor(reminder / 100)] + " Hundred "; + words += belowTwenty[Math.floor(reminder / 100)] + ' Hundred '; reminder %= 100; } if (reminder >= 20) { - words += belowHundred[Math.floor(reminder / 10)] + " "; + words += belowHundred[Math.floor(reminder / 10)] + ' '; reminder %= 10; } if (reminder > 0) { - words += belowTwenty[Math.floor(reminder)] + " "; + words += belowTwenty[Math.floor(reminder)] + ' '; } - - result = words + thousands[pointer] + " " + result; + + result = words + thousands[pointer] + ' ' + result; } pointer += 1; } return result.trim(); -} +}; var numberToWords = function (num) { if (num == 0) { - return "Zero"; - } - else { + return 'Zero'; + } else { return convertToWords(num); } - -}; \ No newline at end of file +}; diff --git a/javascript/0283-move-zeroes.js b/javascript/0283-move-zeroes.js index dff8f4e2e..5b6fddf4f 100644 --- a/javascript/0283-move-zeroes.js +++ b/javascript/0283-move-zeroes.js @@ -5,14 +5,13 @@ * @param {number[]} nums * @return {void} Do not return anything, modify nums in-place instead. */ -var moveZeroes = function(nums) { - +var moveZeroes = function (nums) { const arr = new Array(nums.length).fill(0); let [left, right] = [0, 0]; while (right < nums.length) { - const isZero = (nums[right] === 0); + const isZero = nums[right] === 0; if (!isZero) { arr[left] = nums[right]; left++; @@ -32,10 +31,10 @@ var moveZeroes = function(nums) { * @return {void} Do not return anything, modify nums in-place instead. */ var moveZeroes = (nums) => { - let [ left, right ] = [ 0, 0 ]; + let [left, right] = [0, 0]; while (right < nums.length) { - const canSwap = (nums[right] !== 0) + const canSwap = nums[right] !== 0; if (canSwap) { [nums[left], nums[right]] = [nums[right], nums[left]]; left++; diff --git a/javascript/0286-walls-and-gates.js b/javascript/0286-walls-and-gates.js index cb5324d13..11d4e9fc0 100644 --- a/javascript/0286-walls-and-gates.js +++ b/javascript/0286-walls-and-gates.js @@ -4,8 +4,8 @@ * @param {number[][]} rooms * @return {void} Do not return anything, modify rooms in-place instead. */ -var wallsAndGates = function(rooms) { - const [ rows, cols ] = [ rooms.length, rooms[0].length ]; +var wallsAndGates = function (rooms) { + const [rows, cols] = [rooms.length, rooms[0].length]; for (let row = 0; row < rows; row++) { for (let col = 0; col < cols; col++) { @@ -15,24 +15,34 @@ var wallsAndGates = function(rooms) { dfs(rooms, row, col); } } -} +}; const dfs = (rooms, row, col) => { - const [ rows, cols ] = [ rooms.length, rooms[0].length ]; + const [rows, cols] = [rooms.length, rooms[0].length]; - for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) { - const isPreviousDistanceGreater = rooms[_row][_col] <= (rooms[row][col] + 1); + for (const [_row, _col] of getNeighbors(row, rows, col, cols)) { + const isPreviousDistanceGreater = + rooms[_row][_col] <= rooms[row][col] + 1; if (isPreviousDistanceGreater) continue; - rooms[_row][_col] = (rooms[row][col] + 1); + rooms[_row][_col] = rooms[row][col] + 1; dfs(rooms, _row, _col); } -} +}; -var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ],[ 0, -1 ], [ 1, 0 ], [ -1, 0 ] ] - .map(([ _row, _col ]) => [ (row + _row), (col + _col) ]) - .filter(([ _row, _col ]) => (0 <= _row) && (0 <= _col) && (_row < rows) && (_col < cols)); +var getNeighbors = (row, rows, col, cols) => + [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ] + .map(([_row, _col]) => [row + _row, col + _col]) + .filter( + ([_row, _col]) => + 0 <= _row && 0 <= _col && _row < rows && _col < cols, + ); /** * https://leetcode.com/problems/walls-and-gates/ @@ -40,48 +50,57 @@ var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ],[ 0, -1 ], [ 1, 0 ], [ - * @param {number[][]} rooms * @return {void} Do not return anything, modify rooms in-place instead. */ -var wallsAndGates = function(rooms) { +var wallsAndGates = function (rooms) { const queue = searchGrid(rooms); bfs(rooms, queue); }; const searchGrid = (rooms, queue = new Queue([])) => { - const [ rows, cols ] = [ rooms.length, rooms[0].length ]; + const [rows, cols] = [rooms.length, rooms[0].length]; for (let row = 0; row < rows; row++) { for (let col = 0; col < cols; col++) { const isGate = rooms[row][col] === 0; if (!isGate) continue; - queue.enqueue([ row, col ]); + queue.enqueue([row, col]); } } return queue; -} +}; const bfs = (rooms, queue) => { while (!queue.isEmpty()) { - for (let i = (queue.size() - 1); 0 <= i; i--) { + for (let i = queue.size() - 1; 0 <= i; i--) { checkNeighbors(rooms, queue); } } -} +}; const checkNeighbors = (rooms, queue) => { - const [ rows, cols ] = [ rooms.length, rooms[0].length ]; - const [ row, col ] = queue.dequeue(); + const [rows, cols] = [rooms.length, rooms[0].length]; + const [row, col] = queue.dequeue(); - for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) { + for (const [_row, _col] of getNeighbors(row, rows, col, cols)) { const isINF = rooms[_row][_col] === 2147483647; /* (2 ** 31) - 1 */ if (!isINF) continue; - rooms[_row][_col] = (rooms[row][col] + 1); - queue.enqueue([ _row, _col ]); + rooms[_row][_col] = rooms[row][col] + 1; + queue.enqueue([_row, _col]); } -} +}; -var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ],[ 0, -1 ], [ 1, 0 ], [ -1, 0 ] ] - .map(([ _row, _col ]) => [ (row + _row), (col + _col) ]) - .filter(([ _row, _col ]) => (0 <= _row) && (0 <= _col) && (_row < rows) && (_col < cols)); +var getNeighbors = (row, rows, col, cols) => + [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ] + .map(([_row, _col]) => [row + _row, col + _col]) + .filter( + ([_row, _col]) => + 0 <= _row && 0 <= _col && _row < rows && _col < cols, + ); diff --git a/javascript/0287-find-the-duplicate-number.js b/javascript/0287-find-the-duplicate-number.js index e3578386b..5cd8812cb 100644 --- a/javascript/0287-find-the-duplicate-number.js +++ b/javascript/0287-find-the-duplicate-number.js @@ -1,257 +1,277 @@ -/** - * https://leetcode.com/problems/find-the-duplicate-number/ - * Time O(N * log(N)) | Space O(1) - * @param {number[]} nums - * @return {number} - */ -var findDuplicate = function(nums) { - nums.sort((a, b) => a - b);/* Time O(N * log(N)) | HeapSort Space O(1) | QuickSort Space O(log(N)) */ - - for (let i = 1; i < nums.length; i++) {/* Time O(N) */ - const isPrevDuplicate = nums[i - 1] === nums[i] - if (isPrevDuplicate) return nums[i]; - } - - return -1; -} - -/** - * https://leetcode.com/problems/find-the-duplicate-number/ - * Time O(N * log(N)) | Space O(1) - * @param {number[]} nums - * @return {number} - */ -var findDuplicate = function(nums) { - let [ left, right, duplicate ] = [ 1, (nums.length - 1), -1 ]; - - while (left <= right) {/* Time O(log(N)) */ - const mid = (left + right) >> 1; - const count = getCount(mid, nums);/* Time O(N) */ - - const isMidGreater = count <= mid - if (isMidGreater) left = mid + 1; - - const isMidLess = mid < count - if (isMidLess) { - duplicate = mid; - right = mid - 1; - } - } - - return duplicate; -} - -const getCount = (mid, nums, count = 0) => { - for (const num of nums) {/* Time O(N) */ - const isMidGreater = num <= mid - if (isMidGreater) count++; - } - - return count; -} - -/** - * https://leetcode.com/problems/find-the-duplicate-number/ - * Time O(N * log(N)) | Space O(1) - * @param {number[]} nums - * @return {number} - */ -var findDuplicate = function(nums, duplicate = 0) { - const mostSignificantBit = calcMaxBit(nums); /* Time O(N) */ - - for (let bit = 0; bit < mostSignificantBit; bit++) {/* Time O(log(N)) */ - const [ baseCount, numsCount, mask ] = count(nums, bit);/* Time O(N) */ - - const isMoreFrequentlySet = baseCount < numsCount - if (isMoreFrequentlySet) duplicate |= mask; - } - - return duplicate; -} - -const calcMaxBit = (nums, bits = 0) => { - let max = Math.max(0, ...nums);/* Time O(N) */ - - while (max) {/* Time O(log(MAX)) */ - max >>= 1; - bits++; - } - - return bits; -} - -const count = (nums, bit) => { - let [ baseCount, numsCount, mask ] = [ 0, 0, (1 << bit) ]; - - for (let i = 0; i < nums.length; i++) {/* Time O(N) */ - const isBaseBitSet = 0 < (i & mask); - if (isBaseBitSet) baseCount++; - - const isNumBitSet = 0 < (nums[i] & mask); - if (isNumBitSet) numsCount++; - } - - return [ baseCount, numsCount, mask ]; -} - -/** - * https://leetcode.com/problems/find-the-duplicate-number/ - * Time O(N) | Space O(N) - * @param {number[]} nums - * @return {number} - */ -var findDuplicate = function(nums, curr = 0) { - const isBaseCase = curr === nums[curr] - if (isBaseCase) return curr; - - const next = nums[curr]; - - nums[curr] = curr; - - return findDuplicate(nums, next);/* Time O(N) | Space O(N) */ -} - -/** - * https://leetcode.com/problems/find-the-duplicate-number/ - * Time O(N) | Space O(N) - * @param {number[]} nums - * @return {number} - */ - var findDuplicate = function(nums, seen = new Set()) { - for (const num of nums) {/* Time O(N) */ - if (seen.has(num)) return num; - - seen.add(num); /* Space O(N) */ - } - - return -1; -} - -/** - * https://leetcode.com/problems/find-the-duplicate-number/ - * Time O(N) | Space O(1) - * @param {number[]} nums - * @return {number} - */ -var findDuplicate = function(nums) { - cyclicSort(nums); /* Time O(N) */ - - return search(nums); /* Time O(N) */ -} - -const cyclicSort = (nums, index = 0) => { - const swap = (arr, a, b) => [arr[a], arr[b]] = [arr[b], arr[a]]; - - while (index < nums.length) { /* Time O(N) */ - const [ num, arrayIndex, arrayNum ] = [ nums[index], (nums[index] - 1), nums[(nums[index] - 1)] ]; - - const canSwap = !isSame(num, arrayNum); - if (canSwap) { - swap(nums, index, arrayIndex); - - continue; - } - - index++; - } -} -const isSame = (a, b) => a === b; - -const search = (nums) => { - for (let index = 0; index < nums.length; index++) {/* Time O(N) */ - const [ num, arrayIndex ] = [ nums[index], (index + 1) ]; - - if (!isSame(num, arrayIndex)) return num; - } - - return nums.length; -} - -/** - * https://leetcode.com/problems/find-the-duplicate-number/ - * Time O(N) | Space O(1) - * @param {number[]} nums - * @return {number} - */ -var findDuplicate = function(nums) { - const duplicate = negativeMarking(nums);/* Time O(N) */ - - restoreToPositiveNumbers(nums); /* Time O(N) */ - - return duplicate; -} - -const negativeMarking = (nums) => { - for (let i = 0; i < nums.length; i++) {/* Time O(N) */ - const curr = Math.abs(nums[i]); - - const isNegative = nums[curr] < 0; - if (isNegative) return curr; - - nums[curr] *= -1; - } - - return -1 -} - -const restoreToPositiveNumbers = (nums) => { - for (let i = 0; i < nums.length; i++) {/* Time O(N) */ - nums[i] = Math.abs(nums[i]); - } -} - -/** - * https://leetcode.com/problems/find-the-duplicate-number/ - * Time O(N) | Space O(1) - * @param {number[]} nums - * @return {number} - */ - var findDuplicate = function(nums, start = 0) { - const swap = (arr, a, b) => [arr[a], arr[b]] = [arr[b], arr[a]]; - - const isSame = () => nums[start] === nums[nums[start]]; - while (!isSame()) {/* Time O(N) */ - swap(nums, start, nums[start]); - } - - return nums[start]; -} - -/** - * https://leetcode.com/problems/find-the-duplicate-number/ - * Time O(N) | Space O(1) - * @param {number[]} nums - * @return {number} - */ - var findDuplicate = function(nums) { - if (!nums.length) return -1 - - let [ slow, fast ] = moveFast(nums); /* Time O(N) */ - [ slow, fast ] = moveSlow(nums, slow, fast);/* Time O(N) */ - - return slow; -}; - -const moveFast = (nums, start = 0) => { - let [ slow, fast ] = [ nums[start], nums[nums[start]] ]; - - const isSame = () => slow === fast; - while (!isSame()) { /* Time O(N) */ - slow = nums[slow]; - fast = nums[nums[fast]]; - } - - fast = start; - - return [ slow, fast ]; -} - -const moveSlow = (nums, slow, fast) => { - const isSame = () => slow === fast; - while (!isSame()) { /* Time O(N) */ - slow = nums[slow]; - fast = nums[fast]; - } - - return [ slow, fast ]; -} \ No newline at end of file +/** + * https://leetcode.com/problems/find-the-duplicate-number/ + * Time O(N * log(N)) | Space O(1) + * @param {number[]} nums + * @return {number} + */ +var findDuplicate = function (nums) { + nums.sort( + (a, b) => a - b, + ); /* Time O(N * log(N)) | HeapSort Space O(1) | QuickSort Space O(log(N)) */ + + for (let i = 1; i < nums.length; i++) { + /* Time O(N) */ + const isPrevDuplicate = nums[i - 1] === nums[i]; + if (isPrevDuplicate) return nums[i]; + } + + return -1; +}; + +/** + * https://leetcode.com/problems/find-the-duplicate-number/ + * Time O(N * log(N)) | Space O(1) + * @param {number[]} nums + * @return {number} + */ +var findDuplicate = function (nums) { + let [left, right, duplicate] = [1, nums.length - 1, -1]; + + while (left <= right) { + /* Time O(log(N)) */ + const mid = (left + right) >> 1; + const count = getCount(mid, nums); /* Time O(N) */ + + const isMidGreater = count <= mid; + if (isMidGreater) left = mid + 1; + + const isMidLess = mid < count; + if (isMidLess) { + duplicate = mid; + right = mid - 1; + } + } + + return duplicate; +}; + +const getCount = (mid, nums, count = 0) => { + for (const num of nums) { + /* Time O(N) */ + const isMidGreater = num <= mid; + if (isMidGreater) count++; + } + + return count; +}; + +/** + * https://leetcode.com/problems/find-the-duplicate-number/ + * Time O(N * log(N)) | Space O(1) + * @param {number[]} nums + * @return {number} + */ +var findDuplicate = function (nums, duplicate = 0) { + const mostSignificantBit = calcMaxBit(nums); /* Time O(N) */ + + for (let bit = 0; bit < mostSignificantBit; bit++) { + /* Time O(log(N)) */ + const [baseCount, numsCount, mask] = count(nums, bit); /* Time O(N) */ + + const isMoreFrequentlySet = baseCount < numsCount; + if (isMoreFrequentlySet) duplicate |= mask; + } + + return duplicate; +}; + +const calcMaxBit = (nums, bits = 0) => { + let max = Math.max(0, ...nums); /* Time O(N) */ + + while (max) { + /* Time O(log(MAX)) */ + max >>= 1; + bits++; + } + + return bits; +}; + +const count = (nums, bit) => { + let [baseCount, numsCount, mask] = [0, 0, 1 << bit]; + + for (let i = 0; i < nums.length; i++) { + /* Time O(N) */ + const isBaseBitSet = 0 < (i & mask); + if (isBaseBitSet) baseCount++; + + const isNumBitSet = 0 < (nums[i] & mask); + if (isNumBitSet) numsCount++; + } + + return [baseCount, numsCount, mask]; +}; + +/** + * https://leetcode.com/problems/find-the-duplicate-number/ + * Time O(N) | Space O(N) + * @param {number[]} nums + * @return {number} + */ +var findDuplicate = function (nums, curr = 0) { + const isBaseCase = curr === nums[curr]; + if (isBaseCase) return curr; + + const next = nums[curr]; + + nums[curr] = curr; + + return findDuplicate(nums, next); /* Time O(N) | Space O(N) */ +}; + +/** + * https://leetcode.com/problems/find-the-duplicate-number/ + * Time O(N) | Space O(N) + * @param {number[]} nums + * @return {number} + */ +var findDuplicate = function (nums, seen = new Set()) { + for (const num of nums) { + /* Time O(N) */ + if (seen.has(num)) return num; + + seen.add(num); /* Space O(N) */ + } + + return -1; +}; + +/** + * https://leetcode.com/problems/find-the-duplicate-number/ + * Time O(N) | Space O(1) + * @param {number[]} nums + * @return {number} + */ +var findDuplicate = function (nums) { + cyclicSort(nums); /* Time O(N) */ + + return search(nums); /* Time O(N) */ +}; + +const cyclicSort = (nums, index = 0) => { + const swap = (arr, a, b) => ([arr[a], arr[b]] = [arr[b], arr[a]]); + + while (index < nums.length) { + /* Time O(N) */ + const [num, arrayIndex, arrayNum] = [ + nums[index], + nums[index] - 1, + nums[nums[index] - 1], + ]; + + const canSwap = !isSame(num, arrayNum); + if (canSwap) { + swap(nums, index, arrayIndex); + + continue; + } + + index++; + } +}; +const isSame = (a, b) => a === b; + +const search = (nums) => { + for (let index = 0; index < nums.length; index++) { + /* Time O(N) */ + const [num, arrayIndex] = [nums[index], index + 1]; + + if (!isSame(num, arrayIndex)) return num; + } + + return nums.length; +}; + +/** + * https://leetcode.com/problems/find-the-duplicate-number/ + * Time O(N) | Space O(1) + * @param {number[]} nums + * @return {number} + */ +var findDuplicate = function (nums) { + const duplicate = negativeMarking(nums); /* Time O(N) */ + + restoreToPositiveNumbers(nums); /* Time O(N) */ + + return duplicate; +}; + +const negativeMarking = (nums) => { + for (let i = 0; i < nums.length; i++) { + /* Time O(N) */ + const curr = Math.abs(nums[i]); + + const isNegative = nums[curr] < 0; + if (isNegative) return curr; + + nums[curr] *= -1; + } + + return -1; +}; + +const restoreToPositiveNumbers = (nums) => { + for (let i = 0; i < nums.length; i++) { + /* Time O(N) */ + nums[i] = Math.abs(nums[i]); + } +}; + +/** + * https://leetcode.com/problems/find-the-duplicate-number/ + * Time O(N) | Space O(1) + * @param {number[]} nums + * @return {number} + */ +var findDuplicate = function (nums, start = 0) { + const swap = (arr, a, b) => ([arr[a], arr[b]] = [arr[b], arr[a]]); + + const isSame = () => nums[start] === nums[nums[start]]; + while (!isSame()) { + /* Time O(N) */ + swap(nums, start, nums[start]); + } + + return nums[start]; +}; + +/** + * https://leetcode.com/problems/find-the-duplicate-number/ + * Time O(N) | Space O(1) + * @param {number[]} nums + * @return {number} + */ +var findDuplicate = function (nums) { + if (!nums.length) return -1; + + let [slow, fast] = moveFast(nums); /* Time O(N) */ + [slow, fast] = moveSlow(nums, slow, fast); /* Time O(N) */ + + return slow; +}; + +const moveFast = (nums, start = 0) => { + let [slow, fast] = [nums[start], nums[nums[start]]]; + + const isSame = () => slow === fast; + while (!isSame()) { + /* Time O(N) */ + slow = nums[slow]; + fast = nums[nums[fast]]; + } + + fast = start; + + return [slow, fast]; +}; + +const moveSlow = (nums, slow, fast) => { + const isSame = () => slow === fast; + while (!isSame()) { + /* Time O(N) */ + slow = nums[slow]; + fast = nums[fast]; + } + + return [slow, fast]; +}; diff --git a/javascript/0290-word-pattern.js b/javascript/0290-word-pattern.js index 94787dd98..ae399d1be 100644 --- a/javascript/0290-word-pattern.js +++ b/javascript/0290-word-pattern.js @@ -2,26 +2,27 @@ // time coplexity O(n) // space complexity O(n) -var wordPattern = function(pattern, s) { - -s = s.split(' '); +var wordPattern = function (pattern, s) { + s = s.split(' '); -if(s.length !== pattern.length) return false; + if (s.length !== pattern.length) return false; -wordToChar = new Map(); -charToWord = new Map(); - -for(let i = 0; i < pattern.length; i++) { - wordToChar.set(s[i], pattern[i]); - charToWord.set(pattern[i], s[i]); -}; + wordToChar = new Map(); + charToWord = new Map(); + for (let i = 0; i < pattern.length; i++) { + wordToChar.set(s[i], pattern[i]); + charToWord.set(pattern[i], s[i]); + } -for(let i = 0; i < pattern.length; i++) { - if(charToWord.get(pattern[i]) !== s[i] || pattern[i] !== wordToChar.get(s[i])) { - return false; + for (let i = 0; i < pattern.length; i++) { + if ( + charToWord.get(pattern[i]) !== s[i] || + pattern[i] !== wordToChar.get(s[i]) + ) { + return false; + } } -} -return true; + return true; }; diff --git a/javascript/0295-find-median-from-data-stream.js b/javascript/0295-find-median-from-data-stream.js index 492039ff9..d0d6993d8 100644 --- a/javascript/0295-find-median-from-data-stream.js +++ b/javascript/0295-find-median-from-data-stream.js @@ -1,4 +1,4 @@ -/** +/** * https://leetcode.com/problems/find-median-from-data-stream/ * Your MedianFinder object will be instantiated and called as such: * var obj = new MedianFinder() @@ -6,51 +6,47 @@ * var param_2 = obj.findMedian() */ class MedianFinder { - constructor () { - this.maxHeap = new MaxPriorityQueue() - this.minHeap = new MinPriorityQueue() + constructor() { + this.maxHeap = new MaxPriorityQueue(); + this.minHeap = new MinPriorityQueue(); } /* Time O(log(N)) | Space (N) */ - insertNum (num) { - this.addNum(num) + insertNum(num) { + this.addNum(num); } - addNum (num, heap = this.getHeap(num)) { - heap.enqueue(num) - this.rebalance() + addNum(num, heap = this.getHeap(num)) { + heap.enqueue(num); + this.rebalance(); } - getHeap (num, { maxHeap, minHeap } = this) { - const isFirst = maxHeap.isEmpty() + getHeap(num, { maxHeap, minHeap } = this) { + const isFirst = maxHeap.isEmpty(); const isGreater = num <= this.top(maxHeap); - const isMaxHeap = (isFirst || isGreater); - return (isMaxHeap) - ? maxHeap - : minHeap + const isMaxHeap = isFirst || isGreater; + return isMaxHeap ? maxHeap : minHeap; } - rebalance ({ maxHeap, minHeap } = this) { - const canShiftMax = (minHeap.size() + 1) < maxHeap.size() - if (canShiftMax) return minHeap.enqueue(maxHeap.dequeue().element) + rebalance({ maxHeap, minHeap } = this) { + const canShiftMax = minHeap.size() + 1 < maxHeap.size(); + if (canShiftMax) return minHeap.enqueue(maxHeap.dequeue().element); - const canShiftMin = maxHeap.size() < minHeap.size() - if (canShiftMin) return maxHeap.enqueue(minHeap.dequeue().element) + const canShiftMin = maxHeap.size() < minHeap.size(); + if (canShiftMin) return maxHeap.enqueue(minHeap.dequeue().element); } /* Time O(1) | Space (1) */ - findMedian ({ maxHeap, minHeap } = this) { - const isEven = maxHeap.size() === minHeap.size() - return (isEven) - ? this.average(maxHeap, minHeap) - : this.top(maxHeap) + findMedian({ maxHeap, minHeap } = this) { + const isEven = maxHeap.size() === minHeap.size(); + return isEven ? this.average(maxHeap, minHeap) : this.top(maxHeap); } - average (maxHeap, minHeap) { - return (this.top(maxHeap) + this.top(minHeap)) / 2 + average(maxHeap, minHeap) { + return (this.top(maxHeap) + this.top(minHeap)) / 2; } - top (heap) { - return heap.front()?.element || 0 + top(heap) { + return heap.front()?.element || 0; } } diff --git a/javascript/0297-serialize-and-deserialize-binary-tree.js b/javascript/0297-serialize-and-deserialize-binary-tree.js index 96c3341de..22b7e792c 100644 --- a/javascript/0297-serialize-and-deserialize-binary-tree.js +++ b/javascript/0297-serialize-and-deserialize-binary-tree.js @@ -1,85 +1,85 @@ -/** - * Encodes a tree to a single string. - * https://leetcode.com/problems/serialize-and-deserialize-binary-tree/solution/ - * Time O(N) | Space O(H) - * @param {TreeNode} root - * @return {string} - */ - var serialize = function(root, result = []) { - serial(root, result); - - return result; -}; - -const serial = (root, result) => { - const isBase = root === null; - if (isBase) return result.push(null); - - dfsSerialize(root, result); -} - -const dfsSerialize = (node, result) => { - result.push(node.val); - serial(node.left, result); - serial(node.right, result); -}; - -/** - * Encodes a tree to a single string. - * https://leetcode.com/problems/serialize-and-deserialize-binary-tree/solution/ - * Time O(N) | Space O(H) - * @param {TreeNode} root - * @return {string} - */ -var serialize = function(root) { - const isBaseCase = root === null; - if (isBaseCase) return [ null ]; - - return dfsSerializeIterative([ root ]); -}; - -const dfsSerializeIterative = (stack, result = []) => { - while (stack.length) { - const curr = stack.pop(); - - const isNull = curr === null; - if (isNull) { - result.push(null); - continue; - } - - result.push(curr.val); - stack.push(curr.right); - stack.push(curr.left); - } - - return result; -} - -/** -* Decodes your encoded data to tree. -* https://leetcode.com/problems/serialize-and-deserialize-binary-tree/solution/ -* Time O(N) | Space O(H) -* @param {string} data -* @return {TreeNode} -*/ -var deserialize = function(data) { - const isBaseCase = !data.length; - if (isBaseCase) return null; - - const val = data.shift(); - - const isNull = val === null; - if (isNull) return null; - - return dfsDeserialize(val, data) -}; - -const dfsDeserialize = (val, data) => { - const node = new TreeNode(val); - - node.left = deserialize(data); - node.right = deserialize(data); - - return node; -} +/** + * Encodes a tree to a single string. + * https://leetcode.com/problems/serialize-and-deserialize-binary-tree/solution/ + * Time O(N) | Space O(H) + * @param {TreeNode} root + * @return {string} + */ +var serialize = function (root, result = []) { + serial(root, result); + + return result; +}; + +const serial = (root, result) => { + const isBase = root === null; + if (isBase) return result.push(null); + + dfsSerialize(root, result); +}; + +const dfsSerialize = (node, result) => { + result.push(node.val); + serial(node.left, result); + serial(node.right, result); +}; + +/** + * Encodes a tree to a single string. + * https://leetcode.com/problems/serialize-and-deserialize-binary-tree/solution/ + * Time O(N) | Space O(H) + * @param {TreeNode} root + * @return {string} + */ +var serialize = function (root) { + const isBaseCase = root === null; + if (isBaseCase) return [null]; + + return dfsSerializeIterative([root]); +}; + +const dfsSerializeIterative = (stack, result = []) => { + while (stack.length) { + const curr = stack.pop(); + + const isNull = curr === null; + if (isNull) { + result.push(null); + continue; + } + + result.push(curr.val); + stack.push(curr.right); + stack.push(curr.left); + } + + return result; +}; + +/** + * Decodes your encoded data to tree. + * https://leetcode.com/problems/serialize-and-deserialize-binary-tree/solution/ + * Time O(N) | Space O(H) + * @param {string} data + * @return {TreeNode} + */ +var deserialize = function (data) { + const isBaseCase = !data.length; + if (isBaseCase) return null; + + const val = data.shift(); + + const isNull = val === null; + if (isNull) return null; + + return dfsDeserialize(val, data); +}; + +const dfsDeserialize = (val, data) => { + const node = new TreeNode(val); + + node.left = deserialize(data); + node.right = deserialize(data); + + return node; +}; diff --git a/javascript/0300-longest-increasing-subsequence.js b/javascript/0300-longest-increasing-subsequence.js index ad4720dd5..9884edb72 100644 --- a/javascript/0300-longest-increasing-subsequence.js +++ b/javascript/0300-longest-increasing-subsequence.js @@ -7,26 +7,28 @@ * @return {number} */ var lengthOfLIS = (nums) => { - const tabu = initTabu(nums);/* | Space O(N) */ + const tabu = initTabu(nums); /* | Space O(N) */ - linearSearch(nums, tabu); /* Time O(N * N) | Space O(N)*/ + linearSearch(nums, tabu); /* Time O(N * N) | Space O(N)*/ - return Math.max(...tabu); /* Time O(N) */ + return Math.max(...tabu); /* Time O(N) */ }; const initTabu = (nums) => new Array(nums.length).fill(1); var linearSearch = (nums, tabu) => { - for (let right = 1; (right < nums.length); right++) {/* Time O(N) */ - for (let left = 0; (left < right); left++) { /* Time O(N) */ + for (let right = 1; right < nums.length; right++) { + /* Time O(N) */ + for (let left = 0; left < right; left++) { + /* Time O(N) */ const canUpdate = nums[left] < nums[right]; if (!canUpdate) continue; - const [ _left, _right ] = [ (tabu[left] + 1), tabu[right] ]; - tabu[right] = Math.max(_right, _left); /* Space O(N) */ + const [_left, _right] = [tabu[left] + 1, tabu[right]]; + tabu[right] = Math.max(_right, _left); /* Space O(N) */ } } -} +}; /** * Array - Subsequence @@ -36,33 +38,36 @@ var linearSearch = (nums, tabu) => { * @return {number} */ var lengthOfLIS = (nums) => { - const subsequence = linearSort(nums);/* Time O(N * N) | Space O(N) */ + const subsequence = linearSort(nums); /* Time O(N * N) | Space O(N) */ return subsequence.length; -} +}; var linearSort = (nums, subsequence = []) => { - for (const num of nums) {/* Time O(N) */ + for (const num of nums) { + /* Time O(N) */ const max = subsequence[subsequence.length - 1]; const canAdd = max < num; - if (canAdd) { subsequence.push(num); continue; }/* Space O(N) */ + if (canAdd) { + subsequence.push(num); + continue; + } /* Space O(N) */ - const index = getMax(subsequence, num); /* Time O(N) */ + const index = getMax(subsequence, num); /* Time O(N) */ subsequence[index] = num; } return subsequence; -} - +}; const getMax = (subsequence, num, index = 0) => { const isLess = () => subsequence[index] < num; - while (isLess()) index++;/* Time O(N) */ + while (isLess()) index++; /* Time O(N) */ return index; -} +}; /** * Array - Subsequence @@ -72,42 +77,47 @@ const getMax = (subsequence, num, index = 0) => { * @return {number} */ var lengthOfLIS = (nums) => { - const subsequence = logarithmicSort(nums);/* Time O(N * log(N) */ + const subsequence = logarithmicSort(nums); /* Time O(N * log(N) */ return subsequence.length; -} +}; var logarithmicSort = (nums, subsequence = []) => { - for (const num of nums) {/* Time O(N) */ - const max = subsequence[(subsequence.length - 1)]; + for (const num of nums) { + /* Time O(N) */ + const max = subsequence[subsequence.length - 1]; - const canAdd = (max < num); - if (canAdd) { subsequence.push(num); continue; }/* Space O(N) */ + const canAdd = max < num; + if (canAdd) { + subsequence.push(num); + continue; + } /* Space O(N) */ - const index = binarySearch(num, subsequence); /* Time O(log(N)) */ + const index = binarySearch(num, subsequence); /* Time O(log(N)) */ subsequence[index] = num; } return subsequence; -} +}; const binarySearch = (num, subsequence) => { - let [ left, right ] = [ 0, (subsequence.length - 1) ]; + let [left, right] = [0, subsequence.length - 1]; - while (left < right) {/* Time O(log(N)) */ - const mid = ((left + right) >> 1); + while (left < right) { + /* Time O(log(N)) */ + const mid = (left + right) >> 1; const guess = subsequence[mid]; - const isNumTarget = (num === guess); + const isNumTarget = num === guess; if (isNumTarget) return mid; - const isNumGreater = (guess < num); - if (isNumGreater) left = (mid + 1); + const isNumGreater = guess < num; + if (isNumGreater) left = mid + 1; - const isNumLess = (num < guess); + const isNumLess = num < guess; if (isNumLess) right = mid; } return left; -} \ No newline at end of file +}; diff --git a/javascript/0303-range-sum-query-immutable.js b/javascript/0303-range-sum-query-immutable.js index a09d46b69..c69118fcb 100644 --- a/javascript/0303-range-sum-query-immutable.js +++ b/javascript/0303-range-sum-query-immutable.js @@ -7,9 +7,9 @@ class NumArray { this.arr = nums; } - /** + /** * Time O(n) | Space O(1) - * @param {number} left + * @param {number} left * @param {number} right * @return {number} */ @@ -22,7 +22,7 @@ class NumArray { } } -/** +/** * Your NumArray object will be instantiated and called as such: * var obj = new NumArray(nums) * var param_1 = obj.sumRange(left,right) diff --git a/javascript/0304-range-sum-query-2d-immutable.js b/javascript/0304-range-sum-query-2d-immutable.js index 2319ae5af..2b71097fb 100644 --- a/javascript/0304-range-sum-query-2d-immutable.js +++ b/javascript/0304-range-sum-query-2d-immutable.js @@ -4,32 +4,32 @@ * @param {number[][]} matrix */ class NumMatrix { - constructor(matrix) { - this.matrix = matrix; - } + constructor(matrix) { + this.matrix = matrix; + } - /** - * - * m = row2 - row1; n = col2 - col1 - * Time O(m*n) | Space O(1) - * @param {number} row1 - * @param {number} col1 - * @param {number} row2 - * @param {number} col2 - * @return {number} - */ - sumRegion(row1, col1, row2, col2) { - let sum = 0; - for (let i = row1; i < row2 + 1; i++) { - for (let j = col1; j < col2 + 1; j++) { - sum += this.matrix[i][j]; - } + /** + * + * m = row2 - row1; n = col2 - col1 + * Time O(m*n) | Space O(1) + * @param {number} row1 + * @param {number} col1 + * @param {number} row2 + * @param {number} col2 + * @return {number} + */ + sumRegion(row1, col1, row2, col2) { + let sum = 0; + for (let i = row1; i < row2 + 1; i++) { + for (let j = col1; j < col2 + 1; j++) { + sum += this.matrix[i][j]; + } + } + return sum; } - return sum; - } } -/** +/** * Your NumMatrix object will be instantiated and called as such: * var obj = new NumMatrix(matrix) * var param_1 = obj.sumRegion(row1,col1,row2,col2) diff --git a/javascript/0309-best-time-to-buy-and-sell-stock-with-cooldown.js b/javascript/0309-best-time-to-buy-and-sell-stock-with-cooldown.js index ad34f2512..8bb721e88 100644 --- a/javascript/0309-best-time-to-buy-and-sell-stock-with-cooldown.js +++ b/javascript/0309-best-time-to-buy-and-sell-stock-with-cooldown.js @@ -5,25 +5,26 @@ * @param {number[]} prices * @return {number} */ - var maxProfit = (prices) => { - let [ sold, held, reset ] = [ (-Infinity), (-Infinity), 0 ]; +var maxProfit = (prices) => { + let [sold, held, reset] = [-Infinity, -Infinity, 0]; - [ sold, reset ] = search(prices, sold, held, reset);/* Time O(N) */ + [sold, reset] = search(prices, sold, held, reset); /* Time O(N) */ return Math.max(sold, reset); -} +}; var search = (prices, sold, held, reset) => { - for (const price of prices) {/* Time O(N) */ + for (const price of prices) { + /* Time O(N) */ const preSold = sold; - sold = (held + price); - held = Math.max(held, (reset - price)); + sold = held + price; + held = Math.max(held, reset - price); reset = Math.max(reset, preSold); } - return [ sold, reset ]; -} + return [sold, reset]; +}; /** * DP - Bottom Up @@ -34,30 +35,32 @@ var search = (prices, sold, held, reset) => { * @return {number} */ var maxProfit = (prices) => { - const tabu = initTabu(prices);/* Space O(N) */ + const tabu = initTabu(prices); /* Space O(N) */ - search(prices, tabu);/* Time O(N * N) */ + search(prices, tabu); /* Time O(N * N) */ return tabu[0]; -} +}; var initTabu = (prices) => new Array(prices.length + 2).fill(0); var search = (prices, tabu) => { - for (let i = (prices.length - 1); (0 <= i); i--) {/* Time O(N) */ - const prev = buyAndSell(prices, i, tabu); /* Time O(N) */ + for (let i = prices.length - 1; 0 <= i; i--) { + /* Time O(N) */ + const prev = buyAndSell(prices, i, tabu); /* Time O(N) */ const next = tabu[i + 1]; - tabu[i] = Math.max(prev, next); /* Space O(N) */ + tabu[i] = Math.max(prev, next); /* Space O(N) */ } -} +}; const buyAndSell = (prices, i, tabu, max = 0) => { - for (let sell = (i + 1); (sell < prices.length); sell++) {/* Time O(N) */ - const profit = ((prices[sell] - prices[i]) + tabu[(sell + 2)]); + for (let sell = i + 1; sell < prices.length; sell++) { + /* Time O(N) */ + const profit = prices[sell] - prices[i] + tabu[sell + 2]; max = Math.max(max, profit); } return max; -} \ No newline at end of file +}; diff --git a/javascript/0312-burst-balloons.js b/javascript/0312-burst-balloons.js index 7dd519e09..3b875f91c 100644 --- a/javascript/0312-burst-balloons.js +++ b/javascript/0312-burst-balloons.js @@ -6,38 +6,64 @@ * @param {number[]} nums * @return {number} */ - var maxCoins = (nums) => { - const _nums = [ 1, ...nums, 1 ];/* Time O(N) | Space O(N) */ +var maxCoins = (nums) => { + const _nums = [1, ...nums, 1]; /* Time O(N) | Space O(N) */ - return search(_nums); /* Time O(N * N * N) | Space O((N * N) + HEIGHT) */ -} + return search(_nums); /* Time O(N * N * N) | Space O((N * N) + HEIGHT) */ +}; -var search = (nums, left = 1 , right = (nums.length - 2), memo = initMemo(nums)) => { - const isBaseCase = (right - left < 0); +var search = ( + nums, + left = 1, + right = nums.length - 2, + memo = initMemo(nums), +) => { + const isBaseCase = right - left < 0; if (isBaseCase) return 0; - const hasSeen = (memo[left][right] !== -1); + const hasSeen = memo[left][right] !== -1; if (hasSeen) return memo[left][right]; - return dfs(nums, left, right, memo);/* Time O(N * N * N) | Space O((N * N) + HEIGHT) */ -} + return dfs( + nums, + left, + right, + memo, + ); /* Time O(N * N * N) | Space O((N * N) + HEIGHT) */ +}; -var initMemo = (nums) => new Array(nums.length).fill()/* Time O(N) | Space O(N) */ - .map(() => new Array(nums.length).fill(-1)); /* Time O(N) | Space O(N) */ +var initMemo = (nums) => + new Array(nums.length) + .fill() /* Time O(N) | Space O(N) */ + .map(() => + new Array(nums.length).fill(-1), + ); /* Time O(N) | Space O(N) */ var dfs = (nums, left, right, memo, result = 0) => { - for (let i = left; (i <= right); i++) {/* Time O(N) */ - const gain = ((nums[left - 1] * nums[i]) * nums[right + 1]); - const _left = search(nums, left, (i - 1), memo); /* Time O(N * N) | Space O(HEIGHT) */ - const _right = search(nums, (i + 1), right, memo);/* Time O(N * N) | Space O(HEIGHT) */ - const remaining = (_left + _right); + for (let i = left; i <= right; i++) { + /* Time O(N) */ + const gain = nums[left - 1] * nums[i] * nums[right + 1]; + const _left = search( + nums, + left, + i - 1, + memo, + ); /* Time O(N * N) | Space O(HEIGHT) */ + const _right = search( + nums, + i + 1, + right, + memo, + ); /* Time O(N * N) | Space O(HEIGHT) */ + const remaining = _left + _right; result = Math.max(result, remaining + gain); } - memo[left][right] = result; /* | Space O(N * N) */ + memo[left][right] = + result; /* | Space O(N * N) */ return result; -} +}; /** * DP - Bottom Up @@ -47,29 +73,36 @@ var dfs = (nums, left, right, memo, result = 0) => { * @param {number[]} nums * @return {number} */ - var maxCoins = (nums) => { - const tabu = initTabu(nums);/* Time O(N * N) | Space O(N * N) */ +var maxCoins = (nums) => { + const tabu = initTabu(nums); /* Time O(N * N) | Space O(N * N) */ - search(nums, tabu); /* Time O(N * N * N) | Space O(N * N) */ + search(nums, tabu); /* Time O(N * N * N) | Space O(N * N) */ - return tabu[1][(nums.length)]; -} + return tabu[1][nums.length]; +}; -var initTabu = (nums) => new Array(nums.length + 2).fill()/* Time O(N) | Space O(N) */ - .map(() => new Array(nums.length + 2).fill(0)) /* Time O(N) | Space O(N) */ +var initTabu = (nums) => + new Array(nums.length + 2) + .fill() /* Time O(N) | Space O(N) */ + .map(() => + new Array(nums.length + 2).fill(0), + ); /* Time O(N) | Space O(N) */ var search = (nums, tabu) => { - const _nums = [ 1, ...nums, 1 ]; /* Time O(N) | Space O(N) */ - - for (let left = nums.length; (1 <= left); left--) { /* Time O(N) */ - for (let right = left; (right <= nums.length); right++) {/* Time O(N) */ - for (let i = left; (i <= right); i++) { - const gain = ((_nums[left - 1] * _nums[i]) * _nums[right + 1]); - const remaining = (tabu[left][i - 1] + tabu[i + 1][right]); + const _nums = [1, ...nums, 1]; /* Time O(N) | Space O(N) */ - tabu[left][right] = /* | Space O(N * N) */ + for (let left = nums.length; 1 <= left; left--) { + /* Time O(N) */ + for (let right = left; right <= nums.length; right++) { + /* Time O(N) */ + for (let i = left; i <= right; i++) { + const gain = _nums[left - 1] * _nums[i] * _nums[right + 1]; + const remaining = tabu[left][i - 1] + tabu[i + 1][right]; + + tabu[left][right] = + /* | Space O(N * N) */ Math.max(remaining + gain, tabu[left][right]); } } } -} \ No newline at end of file +}; diff --git a/javascript/0322-coin-change.js b/javascript/0322-coin-change.js index 3e8d8a05a..2708e6a6a 100644 --- a/javascript/0322-coin-change.js +++ b/javascript/0322-coin-change.js @@ -6,38 +6,41 @@ * @param {number} amount * @return {number} */ - var coinChange = (coins, amount, coin = 0) => { +var coinChange = (coins, amount, coin = 0) => { const isBaseCase1 = amount === 0; if (isBaseCase1) return 0; - const isBaseCase2 = !((coin < coins.length) && (0 < amount)); + const isBaseCase2 = !(coin < coins.length && 0 < amount); if (isBaseCase2) return -1; - return dfs(coins, amount, coin);/* Time O(S^N) | Space O(N) */ -} + return dfs(coins, amount, coin); /* Time O(S^N) | Space O(N) */ +}; var dfs = (coins, amount, coin) => { - let [ max, minCost ] = [ (amount / coins[coin]), Infinity ]; + let [max, minCost] = [amount / coins[coin], Infinity]; - for (let num = 0; num <= max; num++) {/* Time O(N) */ - const caUpdate = ((num * coins[coin]) <= amount); + for (let num = 0; num <= max; num++) { + /* Time O(N) */ + const caUpdate = num * coins[coin] <= amount; if (!caUpdate) continue; - const product = (num * coins[coin]); + const product = num * coins[coin]; const difference = amount - product; - const min = coinChange(coins, difference, (coin + 1));/* Time O(S^N) | Space O(N) */ - const cost = (min + num); - - const isSentinel = (min === -1); + const min = coinChange( + coins, + difference, + coin + 1, + ); /* Time O(S^N) | Space O(N) */ + const cost = min + num; + + const isSentinel = min === -1; if (isSentinel) continue; minCost = Math.min(minCost, cost); } - return (minCost !== Infinity) - ? minCost - : -1; -} + return minCost !== Infinity ? minCost : -1; +}; /** * DP - Top Down @@ -48,37 +51,40 @@ var dfs = (coins, amount, coin) => { * @param {number} amount * @return {number} */ - var coinChange = (coins, amount, memo = initMemo(amount)) => { - const isBaseCase1 = (amount < 0); +var coinChange = (coins, amount, memo = initMemo(amount)) => { + const isBaseCase1 = amount < 0; if (isBaseCase1) return -1; - const isBaseCase2 = (amount < 1); + const isBaseCase2 = amount < 1; if (isBaseCase2) return 0; - const isBaseCase3 = (memo[amount - 1] !== 0); + const isBaseCase3 = memo[amount - 1] !== 0; if (isBaseCase3) return memo[amount - 1]; - return dfs(coins, amount, memo);/* Time O(N) | Space O(N) */ -} + return dfs(coins, amount, memo); /* Time O(N) | Space O(N) */ +}; const initMemo = (amount) => Array(amount).fill(0); var dfs = (coins, amount, memo, min = Infinity) => { - for (const coin of coins) { /* Time O(N) */ - const cost = coinChange(coins, (amount - coin), memo);/* Time O(N) | Space O(N) */ - - const canUpdate = ((0 <= cost) && (cost < min)); + for (const coin of coins) { + /* Time O(N) */ + const cost = coinChange( + coins, + amount - coin, + memo, + ); /* Time O(N) | Space O(N) */ + + const canUpdate = 0 <= cost && cost < min; if (!canUpdate) continue; - min = (cost + 1); + min = cost + 1; } - memo[amount - 1] = (min !== Infinity) - ? min - : -1; + memo[amount - 1] = min !== Infinity ? min : -1; return memo[amount - 1]; -} +}; /** * DP - Bottom Up @@ -92,27 +98,27 @@ var dfs = (coins, amount, memo, min = Infinity) => { var coinChange = (coins, amount) => { const tabu = initTabu(amount); - for (let _amount = 1; _amount <= amount; _amount++) {/* Time O(N) */ - for (let coin = 0; coin < coins.length; coin++) { /* Time O(N) */ - const canUpdate = (coins[coin] <= _amount); + for (let _amount = 1; _amount <= amount; _amount++) { + /* Time O(N) */ + for (let coin = 0; coin < coins.length; coin++) { + /* Time O(N) */ + const canUpdate = coins[coin] <= _amount; if (!canUpdate) continue; - const difference = (_amount - coins[coin]); - const min = (tabu[difference] + 1); + const difference = _amount - coins[coin]; + const min = tabu[difference] + 1; - tabu[_amount] = Math.min(tabu[_amount], min); /* Space O(N) */ + tabu[_amount] = Math.min(tabu[_amount], min); /* Space O(N) */ } } - return (tabu[amount] <= amount) - ? tabu[amount] - : -1; -} + return tabu[amount] <= amount ? tabu[amount] : -1; +}; const initTabu = (amount) => { - const tabu = Array((amount + 1)).fill((amount + 1)); + const tabu = Array(amount + 1).fill(amount + 1); tabu[0] = 0; return tabu; -} \ No newline at end of file +}; diff --git a/javascript/0323-number-of-connected-components-in-an-undirected-graph.js b/javascript/0323-number-of-connected-components-in-an-undirected-graph.js index d578f548f..f0dc6bbd0 100644 --- a/javascript/0323-number-of-connected-components-in-an-undirected-graph.js +++ b/javascript/0323-number-of-connected-components-in-an-undirected-graph.js @@ -21,15 +21,15 @@ const initGraph = (n) => ({ }); const buildGraph = (n, edges) => { - const { graph, visited } = initGraph(n) + const { graph, visited } = initGraph(n); - for (const [ src, dst ] of edges) { + for (const [src, dst] of edges) { graph[src].push(dst); graph[dst].push(src); } return { graph, visited }; -} +}; const hasPath = (graph, current, visited) => { if (visited[current]) return false; @@ -40,7 +40,7 @@ const hasPath = (graph, current, visited) => { } return true; -} +}; /** * https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/ @@ -49,63 +49,62 @@ const hasPath = (graph, current, visited) => { * @param {number[][]} edges * @return {number} */ - var countComponents = function(n, edges) { - return new UnionFind(n, edges) - .connectedComponents; +var countComponents = function (n, edges) { + return new UnionFind(n, edges).connectedComponents; }; class UnionFind { - constructor (n, edges) { - this.parent = new Array(n).fill().map((_, index) => index), - this.rank = new Array(n).fill(1) + constructor(n, edges) { + ((this.parent = new Array(n).fill().map((_, index) => index)), + (this.rank = new Array(n).fill(1))); this.connectedComponents = n; this.search(edges); } - search (edges) { - for (const [ src, dst ] of edges) { - this.union(src, dst) + search(edges) { + for (const [src, dst] of edges) { + this.union(src, dst); } } - find (head, tail = head, { parent } = this) { - const isEqual = () => head === parent[head] + find(head, tail = head, { parent } = this) { + const isEqual = () => head === parent[head]; while (!isEqual()) { head = parent[head]; } this.compress(tail, head); - return head + return head; } - compress (tail, head, { parent } = this) { + compress(tail, head, { parent } = this) { parent[tail] = head; } - - increaseRank (head, tail, { rank } = this) { + + increaseRank(head, tail, { rank } = this) { rank[head] += rank[tail]; } - union (src, dst, { rank } = this) { - const [ rootSrc, rootDst ] = [ this.find(src), this.find(dst) ] + union(src, dst, { rank } = this) { + const [rootSrc, rootDst] = [this.find(src), this.find(dst)]; - const hasCycle = rootSrc === rootDst - if (hasCycle) return + const hasCycle = rootSrc === rootDst; + if (hasCycle) return; this.connectedComponents--; - const isGreater = rank[rootSrc] < rank[rootDst] + const isGreater = rank[rootSrc] < rank[rootDst]; if (isGreater) { - this.increaseRank(rootDst, rootSrc) - this.compress(rootSrc, rootDst) + this.increaseRank(rootDst, rootSrc); + this.compress(rootSrc, rootDst); } - const isLess = rank[rootDst] <= rank[rootSrc] + const isLess = rank[rootDst] <= rank[rootSrc]; if (isLess) { - this.increaseRank(rootSrc, rootDst) - this.compress(rootDst, rootSrc) + this.increaseRank(rootSrc, rootDst); + this.compress(rootDst, rootSrc); } } } diff --git a/javascript/0329-longest-increasing-path-in-a-matrix.js b/javascript/0329-longest-increasing-path-in-a-matrix.js index f59d674ea..df04f6840 100644 --- a/javascript/0329-longest-increasing-path-in-a-matrix.js +++ b/javascript/0329-longest-increasing-path-in-a-matrix.js @@ -5,34 +5,58 @@ * @param {number[][]} matrix * @return {number} */ - var longestIncreasingPath = (matrix, maxPath = 0) => { - const [ rows, cols ] = [ matrix.length, matrix[0].length ]; - - for (let row = 0; (row < rows); row++) {/* Time O(N) */ - for (let col = 0; (col < cols); col++) {/* Time O(M) */ - const path = dfs(matrix, row, rows, col, cols);/* Time O(2^(N + M)) | Space O(HEIGHT) */ +var longestIncreasingPath = (matrix, maxPath = 0) => { + const [rows, cols] = [matrix.length, matrix[0].length]; + + for (let row = 0; row < rows; row++) { + /* Time O(N) */ + for (let col = 0; col < cols; col++) { + /* Time O(M) */ + const path = dfs( + matrix, + row, + rows, + col, + cols, + ); /* Time O(2^(N + M)) | Space O(HEIGHT) */ maxPath = Math.max(maxPath, path); } } return maxPath; -} +}; var dfs = (matrix, row, rows, col, cols, ans = 0) => { - for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) {/* Time O(4) */ - const path = dfs(matrix, _row, rows, _col, cols); /* Time O(2^(N + M)) | Space O(HEIGHT) */ + for (const [_row, _col] of getNeighbors(row, rows, col, cols)) { + /* Time O(4) */ + const path = dfs( + matrix, + _row, + rows, + _col, + cols, + ); /* Time O(2^(N + M)) | Space O(HEIGHT) */ ans = Math.max(ans, path); } ans += 1; return ans; -} +}; -var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ], [ 0, -1 ], [ 1, 0 ], [ -1, 0 ] ] - .map(([ _row, _col ]) => [ (row + _row), (col + _col) ]) - .filter(([ _row, _col ]) => (0 <= _row) && (_row < rows) && (0 <= _col) && (_col < cols)); +var getNeighbors = (row, rows, col, cols) => + [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ] + .map(([_row, _col]) => [row + _row, col + _col]) + .filter( + ([_row, _col]) => + 0 <= _row && _row < rows && 0 <= _col && _col < cols, + ); /** * DP - Top Down @@ -42,12 +66,15 @@ var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ], [ 0, -1 ], [ 1, 0 ], [ * @param {number[][]} matrix * @return {number} */ - var longestIncreasingPath = (matrix, maxPath = 0, memo = initMemo(matrix)) => { - const [ rows, cols ] = [ matrix.length, matrix[0].length ]; - - for (let row = 0; row < rows; row++) {/* Time O(N) */ - for (let col = 0; col < cols; col++) {/* Time O(M) */ - const path = /* Time O(N * M) | Space O((N * M) + HEIGHT) */ +var longestIncreasingPath = (matrix, maxPath = 0, memo = initMemo(matrix)) => { + const [rows, cols] = [matrix.length, matrix[0].length]; + + for (let row = 0; row < rows; row++) { + /* Time O(N) */ + for (let col = 0; col < cols; col++) { + /* Time O(M) */ + const path = + /* Time O(N * M) | Space O((N * M) + HEIGHT) */ search(matrix, row, rows, col, cols, memo); maxPath = Math.max(maxPath, path); @@ -57,35 +84,63 @@ var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ], [ 0, -1 ], [ 1, 0 ], [ return maxPath; }; -var initMemo = (matrix) => new Array(matrix.length).fill()/* Time O(N) | Space O(N)*/ - .map(() => new Array(matrix[0].length).fill(0)); /* Time O(M) | Space O(M)*/ +var initMemo = (matrix) => + new Array(matrix.length) + .fill() /* Time O(N) | Space O(N)*/ + .map(() => + new Array(matrix[0].length).fill(0), + ); /* Time O(M) | Space O(M)*/ const search = (matrix, row, rows, col, cols, memo) => { - const hasSeen = (memo[row][col] !== 0) + const hasSeen = memo[row][col] !== 0; if (hasSeen) return memo[row][col]; - return dfs(matrix, row, rows, col, cols, memo);/* Time O(N * M) | Space O((N * M) + HEIGHT) */ -} + return dfs( + matrix, + row, + rows, + col, + cols, + memo, + ); /* Time O(N * M) | Space O((N * M) + HEIGHT) */ +}; var dfs = (matrix, row, rows, col, cols, memo) => { - for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) {/* Time O(4) */ - const [ parent, node ] = [ matrix[row][col], matrix[_row][_col] ]; + for (const [_row, _col] of getNeighbors(row, rows, col, cols)) { + /* Time O(4) */ + const [parent, node] = [matrix[row][col], matrix[_row][_col]]; - const isLess = (node <= parent); + const isLess = node <= parent; if (isLess) continue; - const path = search(matrix, _row, rows, _col, cols, memo); /* Time O(N * M) | Space O(HEIGHT) */ + const path = search( + matrix, + _row, + rows, + _col, + cols, + memo, + ); /* Time O(N * M) | Space O(HEIGHT) */ memo[row][col] = Math.max(memo[row][col], path); } - memo[row][col] += 1; /* | Space O(N * M) */ + memo[row][col] += 1; /* | Space O(N * M) */ return memo[row][col]; -} +}; -var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ], [ 0, -1 ], [ 1, 0 ], [ -1, 0 ] ] - .map(([ _row, _col ]) => [ (row + _row), (col + _col) ]) - .filter(([ _row, _col ]) => (0 <= _row) && (_row < rows) && (0 <= _col) && (_col < cols)); +var getNeighbors = (row, rows, col, cols) => + [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ] + .map(([_row, _col]) => [row + _row, col + _col]) + .filter( + ([_row, _col]) => + 0 <= _row && _row < rows && 0 <= _col && _col < cols, + ); /** * Topological Sort @@ -98,79 +153,109 @@ var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ], [ 0, -1 ], [ 1, 0 ], [ * @return {number} */ var longestIncreasingPath = (matrix) => { - const { graph, indegree, sources } = /* Time O(N * M) | Space O(N * M) */ + const { graph, indegree, sources } = + /* Time O(N * M) | Space O(N * M) */ buildGraph(matrix); - findSources(graph, indegree, sources);/* Time O(N * M) | Space O(N * M) */ + findSources(graph, indegree, sources); /* Time O(N * M) | Space O(N * M) */ - return bfs(graph, indegree, sources); /* Time O((N * M) + WIDTH) | Space O((N * M) + WIDTH) */ -} + return bfs( + graph, + indegree, + sources, + ); /* Time O((N * M) + WIDTH) | Space O((N * M) + WIDTH) */ +}; const initGraph = (rows, cols) => ({ - graph: new Array((rows + 2)).fill() /* Time O(N) | Space O(N) */ - .map(() => new Array((cols + 2)).fill(0)),/* Time O(M) | Space O(M) */ - indegree: new Array((rows + 2)).fill() /* Time O(N) | Space O(N) */ - .map(() => new Array((cols + 2)).fill(0)),/* Time O(M) | Space O(M) */ - sources: new Queue() -}) + graph: new Array(rows + 2) + .fill() /* Time O(N) | Space O(N) */ + .map(() => new Array(cols + 2).fill(0)) /* Time O(M) | Space O(M) */, + indegree: new Array(rows + 2) + .fill() /* Time O(N) | Space O(N) */ + .map(() => new Array(cols + 2).fill(0)) /* Time O(M) | Space O(M) */, + sources: new Queue(), +}); var buildGraph = (matrix) => { - const [ rows, cols ] = [ matrix.length, matrix[0].length ]; - const { graph, indegree, sources } = /* Time O(N * M) | Space O(N * M) */ + const [rows, cols] = [matrix.length, matrix[0].length]; + const { graph, indegree, sources } = + /* Time O(N * M) | Space O(N * M) */ initGraph(rows, cols); - for (let row = 1; (row < (rows + 1)); row++) {/* Time O(N) */ - graph[row] = [ 0, ...matrix[row - 1], 0 ]; /* | Space O(N * M) */ + for (let row = 1; row < rows + 1; row++) { + /* Time O(N) */ + graph[row] = [ + 0, + ...matrix[row - 1], + 0, + ]; /* | Space O(N * M) */ } - for (let row = 1; (row <= rows); row++) { /* Time O(N) */ - for (let col = 1; (col <= cols); col++) { /* Time O(M) */ - for (const [ _row, _col ] of getNeighbors(row, col)) {/* Time O(4) */ - const isSink = (graph[row][col] < graph[_row][_col]); - if (isSink) indegree[row][col] += 1; /* | Space O(N * M) */ + for (let row = 1; row <= rows; row++) { + /* Time O(N) */ + for (let col = 1; col <= cols; col++) { + /* Time O(M) */ + for (const [_row, _col] of getNeighbors(row, col)) { + /* Time O(4) */ + const isSink = graph[row][col] < graph[_row][_col]; + if (isSink) + indegree[row][col] += 1; /* | Space O(N * M) */ } } } return { graph, indegree, sources }; -} +}; -var getNeighbors = (row, col) => [ [ 0, 1 ], [ 0, -1 ], [ 1, 0 ], [ -1, 0 ] ] - .map(([ _row, _col ]) => [ (row + _row), (col + _col) ]); +var getNeighbors = (row, col) => + [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ].map(([_row, _col]) => [row + _row, col + _col]); var findSources = (graph, indegree, sources) => { - const [ rows, cols ] = [ graph.length, graph[0].length ]; - - for (let row = 1; (row < (rows - 1)); ++row) {/* Time O(N) */ - for (let col = 1; (col < (cols - 1)); ++col) {/* Time O(M) */ - const isSource = (indegree[row][col] === 0); - if (isSource) sources.enqueue([ row, col ]); /* Space O(N * M) */ + const [rows, cols] = [graph.length, graph[0].length]; + + for (let row = 1; row < rows - 1; ++row) { + /* Time O(N) */ + for (let col = 1; col < cols - 1; ++col) { + /* Time O(M) */ + const isSource = indegree[row][col] === 0; + if (isSource) sources.enqueue([row, col]); /* Space O(N * M) */ } } -} +}; const bfs = (graph, indegree, sources, path = 0) => { - while (!sources.isEmpty()) { /* Time(N * M) */ - for (let level = (sources.size() - 1); 0 <= level; level--) {/* Time(WIDTH) */ - checkNeighbors(graph, indegree, sources) /* Space((N * M) + WIDTH) */ + while (!sources.isEmpty()) { + /* Time(N * M) */ + for (let level = sources.size() - 1; 0 <= level; level--) { + /* Time(WIDTH) */ + checkNeighbors( + graph, + indegree, + sources, + ); /* Space((N * M) + WIDTH) */ } path += 1; } return path; -} +}; const checkNeighbors = (graph, indegree, sources) => { - const [ row, col ] = sources.dequeue(); + const [row, col] = sources.dequeue(); - for (const [ _row, _col ] of getNeighbors(row, col)) { - const canDisconnect = (graph[_row][_col] < graph[row][col]); + for (const [_row, _col] of getNeighbors(row, col)) { + const canDisconnect = graph[_row][_col] < graph[row][col]; if (!canDisconnect) continue; - indegree[_row][_col] -= 1; /* Space O(N * M) */ + indegree[_row][_col] -= 1; /* Space O(N * M) */ - const isSource = (indegree[_row][_col] === 0); - if (isSource) sources.enqueue([ _row, _col ]);/* Space O(WIDTH) */ + const isSource = indegree[_row][_col] === 0; + if (isSource) sources.enqueue([_row, _col]); /* Space O(WIDTH) */ } -} \ No newline at end of file +}; diff --git a/javascript/0332-reconstruct-itinerary.js b/javascript/0332-reconstruct-itinerary.js index f198f3af6..1de40c8d7 100644 --- a/javascript/0332-reconstruct-itinerary.js +++ b/javascript/0332-reconstruct-itinerary.js @@ -12,12 +12,12 @@ var findItinerary = (tickets) => { }; const dfs = (tickets, graph, city = 'JFK', path = ['JFK']) => { - const isBaseCase = (path.length === (tickets.length + 1)); + const isBaseCase = path.length === tickets.length + 1; if (isBaseCase) return true; - const queue = (graph.get(city) || []); + const queue = graph.get(city) || []; - const isEmpty = (queue.length === 0); + const isEmpty = queue.length === 0; if (isEmpty) return false; for (const nextCity of queue.slice()) { @@ -33,14 +33,13 @@ const dfs = (tickets, graph, city = 'JFK', path = ['JFK']) => { return false; }; - const buildGraph = (tickets, graph = new Map()) => { - for (const [ src, dst ] of tickets) { - const edges = (graph.get(src) || []); + for (const [src, dst] of tickets) { + const edges = graph.get(src) || []; edges.push(dst); graph.set(src, edges); } return graph; -} +}; diff --git a/javascript/0337-house-robber-iii.js b/javascript/0337-house-robber-iii.js index 34f19eada..2f1a776f3 100644 --- a/javascript/0337-house-robber-iii.js +++ b/javascript/0337-house-robber-iii.js @@ -12,19 +12,19 @@ * @param {TreeNode} root * @return {number} */ -var rob = function(root) { - +var rob = function (root) { function dfs(root) { - if(!root) return [0, 0]; + if (!root) return [0, 0]; const leftSubTree = dfs(root.left); const rightSubTree = dfs(root.right); - const withoutRoot = Math.max(...leftSubTree) + Math.max(...rightSubTree); + const withoutRoot = + Math.max(...leftSubTree) + Math.max(...rightSubTree); const withRoot = root.val + leftSubTree[0] + rightSubTree[0]; - return [withoutRoot, withRoot]; + return [withoutRoot, withRoot]; } - return Math.max(...dfs(root)); + return Math.max(...dfs(root)); }; diff --git a/javascript/0338-counting-bits.js b/javascript/0338-counting-bits.js index 045d823a9..912c80059 100644 --- a/javascript/0338-counting-bits.js +++ b/javascript/0338-counting-bits.js @@ -4,10 +4,10 @@ * @param {number} n * @return {number[]} */ -var countBits = function (n, dp = [ 0 ]) { - for (let i = 1; i < (n + 1); i++) { - const [ mid, bit ] = [ (i >> 1), (i & 1) ] - const bits = (dp[mid] + bit) +var countBits = function (n, dp = [0]) { + for (let i = 1; i < n + 1; i++) { + const [mid, bit] = [i >> 1, i & 1]; + const bits = dp[mid] + bit; dp.push(bits); } diff --git a/javascript/0344-reverse-string.js b/javascript/0344-reverse-string.js index df84a10ed..1b6fd5ebb 100644 --- a/javascript/0344-reverse-string.js +++ b/javascript/0344-reverse-string.js @@ -2,14 +2,16 @@ * @param {character[]} s * @return {void} Do not return anything, modify s in-place instead. */ - var reverseString = function(s) { - let i = 0, j = s.length-1; - - while(i <= j) { - let leftval = s[i], rightval = s[j]; +var reverseString = function (s) { + let i = 0, + j = s.length - 1; + + while (i <= j) { + let leftval = s[i], + rightval = s[j]; s[i] = rightval; s[j] = leftval; - + i++; j--; } diff --git a/javascript/0347-top-k-frequent-elements.js b/javascript/0347-top-k-frequent-elements.js index 9813bb81b..e2137c4c4 100644 --- a/javascript/0347-top-k-frequent-elements.js +++ b/javascript/0347-top-k-frequent-elements.js @@ -6,19 +6,22 @@ * @param {number} k * @return {number[]} */ -var topKFrequent = function(nums, k) { - let frequency = {} - for( let i = 0; i < nums.length; i++){ - if(frequency.hasOwnProperty(nums[i])) frequency[nums[i]] += 1; +var topKFrequent = function (nums, k) { + let frequency = {}; + for (let i = 0; i < nums.length; i++) { + if (frequency.hasOwnProperty(nums[i])) frequency[nums[i]] += 1; else frequency[nums[i]] = 1; } - let result = Object.keys(frequency).map((key) => [Number(key), frequency[key]]); - let sortedResult = result.sort((a,b) => { - return b[1]-a[1] - }) - let output = [] - for ( let i = 0; i < k; i++){ - output.push(sortedResult[i][0]) + let result = Object.keys(frequency).map((key) => [ + Number(key), + frequency[key], + ]); + let sortedResult = result.sort((a, b) => { + return b[1] - a[1]; + }); + let output = []; + for (let i = 0; i < k; i++) { + output.push(sortedResult[i][0]); } return output; }; @@ -32,23 +35,22 @@ var topKFrequent = function(nums, k) { * @return {number[]} */ -var topKFrequent = function(nums, k) { +var topKFrequent = function (nums, k) { const mp = new Map(); const arr = new Array(nums.length + 1).fill(0); const ans = []; - nums.forEach(el => { + nums.forEach((el) => { const val = mp.get(el) || 0; mp.set(el, val + 1); }); - for ( let [key, value] of mp ) { + for (let [key, value] of mp) { const prev = arr[value] || []; prev.push(key); arr[value] = prev; } - arr.reverse(); for (let el of arr) { if (k < 1) break; diff --git a/javascript/0352-data-stream-as-disjoint-intervals.js b/javascript/0352-data-stream-as-disjoint-intervals.js index 3cd7f7717..088b5265c 100644 --- a/javascript/0352-data-stream-as-disjoint-intervals.js +++ b/javascript/0352-data-stream-as-disjoint-intervals.js @@ -1,31 +1,31 @@ class SummaryRanges { - constructor() { - this.numSet = new Set(); - } + constructor() { + this.numSet = new Set(); + } + + addNum(value) { + this.numSet.add(value); + } - addNum(value) { - this.numSet.add(value); - } + getIntervals() { + let nums = Array.from(this.numSet.keys()); + nums.sort((a, b) => a - b); - getIntervals() { - let nums = Array.from(this.numSet.keys()); - nums.sort((a, b) => a - b); + let res = []; - let res = []; + let i = 0; - let i = 0; + while (i < nums.length) { + let start = nums[i]; - while (i < nums.length) { - let start = nums[i]; + while (i + 1 < nums.length && nums[i] + 1 == nums[i + 1]) { + i++; + } - while (i + 1 < nums.length && nums[i] + 1 == nums[i + 1]) { - i++; - } + res.push([start, nums[i]]); + i++; + } - res.push([start, nums[i]]); - i++; + return res; } - - return res; - } } diff --git a/javascript/0355-design-twitter.js b/javascript/0355-design-twitter.js index d2fb3bad9..181d5f2e2 100644 --- a/javascript/0355-design-twitter.js +++ b/javascript/0355-design-twitter.js @@ -1,42 +1,43 @@ -/** - * https://leetcode.com/problems/design-twitter/ - * Your Twitter object will be instantiated and called as such: - * var obj = new Twitter() - * obj.postTweet(userId,tweetId) - * var param_2 = obj.getNewsFeed(userId) - * obj.follow(followerId,followeeId) - * obj.unfollow(followerId,followeeId) - */ - class Twitter { - constructor () { - this.tweets = []; - this.following = new Map(); - } - - postTweet (userId, tweetId, { tweets } = this) { - tweets.push({ authorId: userId, id: tweetId }); - } - - getNewsFeed (userId, newsIDs = [], { tweets, following } = this) { - for (let i = (tweets.length - 1); ((0 <= i) && (newsIDs.length < 10)); i--) { - const tweet = tweets[i]; - - const isAuthor = tweet.authorId === userId - const isFollowing = following?.get(userId)?.has(tweet.authorId); - const canAddTweet = isAuthor || isFollowing - if (canAddTweet) newsIDs.push(tweet.id); - } - - return newsIDs; - } - - follow (followerId, followeeId, { following } = this) { - if (!following.has(followerId)) following.set(followerId, new Set()); - - following.get(followerId).add(followeeId); - } - - unfollow (followerId, followeeId, { following } = this) { - if (following.has(followerId)) following.get(followerId).delete(followeeId); - } -} +/** + * https://leetcode.com/problems/design-twitter/ + * Your Twitter object will be instantiated and called as such: + * var obj = new Twitter() + * obj.postTweet(userId,tweetId) + * var param_2 = obj.getNewsFeed(userId) + * obj.follow(followerId,followeeId) + * obj.unfollow(followerId,followeeId) + */ +class Twitter { + constructor() { + this.tweets = []; + this.following = new Map(); + } + + postTweet(userId, tweetId, { tweets } = this) { + tweets.push({ authorId: userId, id: tweetId }); + } + + getNewsFeed(userId, newsIDs = [], { tweets, following } = this) { + for (let i = tweets.length - 1; 0 <= i && newsIDs.length < 10; i--) { + const tweet = tweets[i]; + + const isAuthor = tweet.authorId === userId; + const isFollowing = following?.get(userId)?.has(tweet.authorId); + const canAddTweet = isAuthor || isFollowing; + if (canAddTweet) newsIDs.push(tweet.id); + } + + return newsIDs; + } + + follow(followerId, followeeId, { following } = this) { + if (!following.has(followerId)) following.set(followerId, new Set()); + + following.get(followerId).add(followeeId); + } + + unfollow(followerId, followeeId, { following } = this) { + if (following.has(followerId)) + following.get(followerId).delete(followeeId); + } +} diff --git a/javascript/0367-valid-perfect-square.js b/javascript/0367-valid-perfect-square.js index a46a49c12..c15951b30 100644 --- a/javascript/0367-valid-perfect-square.js +++ b/javascript/0367-valid-perfect-square.js @@ -2,16 +2,17 @@ * @param {number} num * @return {boolean} */ - var isPerfectSquare = function(num) { - let left = 1, right = num; - - while(left <= right) { +var isPerfectSquare = function (num) { + let left = 1, + right = num; + + while (left <= right) { let mid = Math.floor((left + right) / 2); - - if(mid*mid === num) return true; - else if(mid*mid > num) right = mid -1; + + if (mid * mid === num) return true; + else if (mid * mid > num) right = mid - 1; else left = mid + 1; } - + return false; }; diff --git a/javascript/0371-sum-of-two-integers.js b/javascript/0371-sum-of-two-integers.js index 1fb652a62..582241546 100644 --- a/javascript/0371-sum-of-two-integers.js +++ b/javascript/0371-sum-of-two-integers.js @@ -5,13 +5,13 @@ * @param {number} b * @return {number} */ - var getSum = function(a, b) { +var getSum = function (a, b) { while (b !== 0) { - const [ xor, carry ] = [ (a ^ b), ((a & b) << 1) ]; + const [xor, carry] = [a ^ b, (a & b) << 1]; a = xor; b = carry; } - - return a -}; \ No newline at end of file + + return a; +}; diff --git a/javascript/0374-guess-number-higher-or-lower.js b/javascript/0374-guess-number-higher-or-lower.js index 416b61b5e..f3042911b 100644 --- a/javascript/0374-guess-number-higher-or-lower.js +++ b/javascript/0374-guess-number-higher-or-lower.js @@ -1,15 +1,12 @@ -var guessNumber = function(n) { +var guessNumber = function (n) { let low = 1; let high = n; - - while(true) { - let mid = low + Math.floor((high - low)/2); + + while (true) { + let mid = low + Math.floor((high - low) / 2); let myGuess = guess(mid); - if(myGuess == 1) - low = mid + 1; - else if(myGuess == -1) - high = mid - 1; - else - return mid; + if (myGuess == 1) low = mid + 1; + else if (myGuess == -1) high = mid - 1; + else return mid; } }; diff --git a/javascript/0392-is-subsequence.js b/javascript/0392-is-subsequence.js index 6f8fee951..ae40a1739 100644 --- a/javascript/0392-is-subsequence.js +++ b/javascript/0392-is-subsequence.js @@ -4,19 +4,18 @@ * @param {string} t * @return {boolean} */ -var isSubsequence = function(s, t) { - - if(!s.length || (s === t)) return true; - if(s.length > t.length) return false; - +var isSubsequence = function (s, t) { + if (!s.length || s === t) return true; + if (s.length > t.length) return false; + let j = 0; - - for(let i = 0; i < t.length && j < s.length; i++) { - if(s[j] === t[i]) { + + for (let i = 0; i < t.length && j < s.length; i++) { + if (s[j] === t[i]) { j++; } } - + return j === s.length; }; @@ -26,13 +25,13 @@ var isSubsequence = function(s, t) { * @param {string} t * @return {boolean} */ -var isSubsequence = function(s, t) { +var isSubsequence = function (s, t) { for (let char of s) { let indexChar = t.indexOf(char); if (indexChar === -1) { return false; } - t = t.slice(indexChar+1); + t = t.slice(indexChar + 1); } - return true + return true; }; diff --git a/javascript/0410-split-array-largest-sum.js b/javascript/0410-split-array-largest-sum.js index 32a30f03a..7d99ba5a8 100644 --- a/javascript/0410-split-array-largest-sum.js +++ b/javascript/0410-split-array-largest-sum.js @@ -1,20 +1,19 @@ /** * https://leetcode.com/problems/split-array-largest-sum/ - * + * * Binary Search * Time O(log(s)*n) (s = difference between the least and max possible value) | Space O(1) * @param {number[]} nums * @param {number} k * @return {number} */ -var splitArray = function(nums, k) { - +var splitArray = function (nums, k) { let left = Math.max(...nums); let right = nums.reduce((acc, num) => acc + num, 0); let result = right; - while(left <= right) { + while (left <= right) { const mid = (left + right) >> 1; - if(canSplit(mid)) { + if (canSplit(mid)) { result = mid; right = mid - 1; } else { @@ -26,9 +25,9 @@ var splitArray = function(nums, k) { let splitCount = 0; let currSum = 0; - for(let i = 0; i < nums.length; i++) { + for (let i = 0; i < nums.length; i++) { currSum += nums[i]; - if(currSum > largest) { + if (currSum > largest) { currSum = nums[i]; splitCount++; } diff --git a/javascript/0416-partition-equal-subset-sum.js b/javascript/0416-partition-equal-subset-sum.js index 0206b8c31..ec0dbc06e 100644 --- a/javascript/0416-partition-equal-subset-sum.js +++ b/javascript/0416-partition-equal-subset-sum.js @@ -5,38 +5,38 @@ * @param {number[]} nums * @return {boolean} */ - var canPartition = (nums) => { - const sum = getSum(nums);/* Time O(N) */ - const subSetSum = (sum / 2); +var canPartition = (nums) => { + const sum = getSum(nums); /* Time O(N) */ + const subSetSum = sum / 2; - const isEven = ((sum % 2) === 0); + const isEven = sum % 2 === 0; if (!isEven) return false; - const index = (nums.length - 1); + const index = nums.length - 1; return dfs(nums, index, subSetSum); -} +}; var getSum = (nums, sum = 0) => { - for (const num of nums) (sum += num);/* Time O(N) */ + for (const num of nums) sum += num; /* Time O(N) */ return sum; -} +}; var dfs = (nums, index, subSetSum) => { const isBaseCase1 = subSetSum === 0; if (isBaseCase1) return true; - const isBaseCase2 = (index === 0) || (subSetSum < 0); + const isBaseCase2 = index === 0 || subSetSum < 0; if (isBaseCase2) return false; - const difference = (subSetSum - nums[(index - 1)]); + const difference = subSetSum - nums[index - 1]; - const left = dfs(nums, (index - 1), difference); - const right = dfs(nums, (index - 1), subSetSum); + const left = dfs(nums, index - 1, difference); + const right = dfs(nums, index - 1, subSetSum); - return (left || right); -} + return left || right; +}; /** * DP - Top Down @@ -46,43 +46,50 @@ var dfs = (nums, index, subSetSum) => { * @param {number[]} nums * @return {boolean} */ - var canPartition = (nums) => { +var canPartition = (nums) => { const isEmpty = nums.length === 0; if (isEmpty) return false; - const sum = getSum(nums); /* Time O(N) */ + const sum = getSum(nums); /* Time O(N) */ - const isEven = ((sum % 2) === 0); + const isEven = sum % 2 === 0; if (!isEven) return false; - const subSetSum = (sum >> 1); - const memo = initMemo(nums, subSetSum); /* | Space O(N * M) */ - const index = (nums.length - 1); + const subSetSum = sum >> 1; + const memo = initMemo(nums, subSetSum); /* | Space O(N * M) */ + const index = nums.length - 1; - return dfs(nums, index, subSetSum, memo);/* Time O(N * M) | Space O(N * M) */ -} + return dfs( + nums, + index, + subSetSum, + memo, + ); /* Time O(N * M) | Space O(N * M) */ +}; -var initMemo = (nums, subSetSum) => new Array((nums.length + 1)).fill()/* Space O(N) */ - .map(() => new Array((subSetSum + 1)).fill(null)); /* Space O(M) */ +var initMemo = (nums, subSetSum) => + new Array(nums.length + 1) + .fill() /* Space O(N) */ + .map(() => new Array(subSetSum + 1).fill(null)); /* Space O(M) */ var dfs = (nums, index, subSetSum, memo) => { - const isBaseCase1 = (subSetSum === 0); + const isBaseCase1 = subSetSum === 0; if (isBaseCase1) return true; - const isBaseCase2 = ((index === 0) || (subSetSum < 0)); + const isBaseCase2 = index === 0 || subSetSum < 0; if (isBaseCase2) return false; - const hasSeen = (memo[index][subSetSum] !== null); + const hasSeen = memo[index][subSetSum] !== null; if (hasSeen) return memo[index][subSetSum]; - const difference = (subSetSum - nums[(index - 1)]); + const difference = subSetSum - nums[index - 1]; - const left = dfs(nums, (index - 1), difference, memo); - const right = dfs(nums, (index - 1), subSetSum, memo); + const left = dfs(nums, index - 1, difference, memo); + const right = dfs(nums, index - 1, subSetSum, memo); - memo[index][subSetSum] = (left || right); + memo[index][subSetSum] = left || right; return memo[index][subSetSum]; -} +}; /** * DP - Bottom Up @@ -96,52 +103,62 @@ var canPartition = (nums) => { const isEmpty = nums.length === 0; if (isEmpty) return false; - const sum = getSum(nums); /* Time O(N) */ + const sum = getSum(nums); /* Time O(N) */ - const isEven = ((sum % 2) === 0); + const isEven = sum % 2 === 0; if (!isEven) return false; - const subSetSum = (sum >> 1); - const tabu = initTabu(nums, subSetSum);/* | Space O(N * M) */ + const subSetSum = sum >> 1; + const tabu = initTabu(nums, subSetSum); /* | Space O(N * M) */ search(nums, subSetSum, tabu); return tabu[nums.length][subSetSum]; -} +}; var getSum = (nums, sum = 0) => { - for (const num of nums) { sum += num };/* Time O(N) */ + for (const num of nums) { + sum += num; + } /* Time O(N) */ return sum; -} +}; var initTabu = (nums, subSetSum) => { - const tabu = new Array((nums.length + 1)).fill()/* Space O(N) */ - .map(() => new Array((subSetSum + 1)).fill(false));/* Space O(M) */ + const tabu = new Array(nums.length + 1) + .fill() /* Space O(N) */ + .map(() => new Array(subSetSum + 1).fill(false)); /* Space O(M) */ - tabu[0][0] = true; /* Space O(N * M) */ + tabu[0][0] = true; /* Space O(N * M) */ return tabu; -} +}; var search = (nums, subSetSum, tabu) => { - for (let numIndex = 1; (numIndex <= nums.length); numIndex++) {/* Time O(N) */ - update(nums, numIndex, subSetSum, tabu); /* Time O(N) | Space O(N * M) */ + for (let numIndex = 1; numIndex <= nums.length; numIndex++) { + /* Time O(N) */ + update( + nums, + numIndex, + subSetSum, + tabu, + ); /* Time O(N) | Space O(N * M) */ } -} +}; var update = (nums, numIndex, subSetSum, tabu) => { - const num = (numIndex - 1); + const num = numIndex - 1; const prevNum = nums[num]; - for (let subSet = 0; subSet <= subSetSum; subSet++) {/* Time O(M) */ - const isNumGreater = (subSet < prevNum); + for (let subSet = 0; subSet <= subSetSum; subSet++) { + /* Time O(M) */ + const isNumGreater = subSet < prevNum; - tabu[numIndex][subSet] = isNumGreater /* Space O(N * M) */ - ? (tabu[num][subSet]) - : ((tabu[num][subSet]) || (tabu[num][subSet - prevNum])); + tabu[numIndex][subSet] = isNumGreater /* Space O(N * M) */ + ? tabu[num][subSet] + : tabu[num][subSet] || tabu[num][subSet - prevNum]; } -} +}; /** * DP - Bottom Up @@ -155,43 +172,47 @@ var canPartition = (nums) => { const isEmpty = nums.length === 0; if (isEmpty) return false; - const sum = getSum(nums); /* Time O(N) */ + const sum = getSum(nums); /* Time O(N) */ - const isEven = ((sum % 2) === 0); + const isEven = sum % 2 === 0; if (!isEven) return false; - const subSetSum = (sum >> 1); - const tabu = initTabu(subSetSum);/* | Space O(M) */ + const subSetSum = sum >> 1; + const tabu = initTabu(subSetSum); /* | Space O(M) */ - search(nums, subSetSum, tabu); /* Time O(N * M) | Space O(M) */ + search(nums, subSetSum, tabu); /* Time O(N * M) | Space O(M) */ return tabu[subSetSum]; }; var getSum = (nums, sum = 0) => { - for (const num of nums) { sum += num };/* Time O(N) */ + for (const num of nums) { + sum += num; + } /* Time O(N) */ return sum; -} +}; var initTabu = (subSetSum) => { - const tabu = new Array((subSetSum + 1)).fill(false);/* Space O(M) */ + const tabu = new Array(subSetSum + 1).fill(false); /* Space O(M) */ - tabu[0] = true; /* Space O(M) */ + tabu[0] = true; /* Space O(M) */ return tabu; -} +}; var search = (nums, subSetSum, tabu) => { - for (const num of nums) {/* Time O(N) */ - update(num, subSetSum, tabu);/* Time O(M) | Space O(M) */ + for (const num of nums) { + /* Time O(N) */ + update(num, subSetSum, tabu); /* Time O(M) | Space O(M) */ } -} +}; var update = (num, subSetSum, tabu) => { - for (let subSet = subSetSum; (num <= subSet); subSet--) {/* Time O(M) */ - const difference = (subSet - num); + for (let subSet = subSetSum; num <= subSet; subSet--) { + /* Time O(M) */ + const difference = subSet - num; - tabu[subSet] |= tabu[difference]; /* Space O(M) */ + tabu[subSet] |= tabu[difference]; /* Space O(M) */ } -} +}; diff --git a/javascript/0417-pacific-atlantic-water-flow.js b/javascript/0417-pacific-atlantic-water-flow.js index 39f5c685b..cd13feba8 100644 --- a/javascript/0417-pacific-atlantic-water-flow.js +++ b/javascript/0417-pacific-atlantic-water-flow.js @@ -4,75 +4,138 @@ * @param {number[][]} heights * @return {number[][]} */ -var pacificAtlantic = function(heights) { - const [ pacificReachable, atlanticReachable ] = search(heights); /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ - - return searchGrid(heights, pacificReachable, atlanticReachable);/* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ +var pacificAtlantic = function (heights) { + const [pacificReachable, atlanticReachable] = + search(heights); /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ + + return searchGrid( + heights, + pacificReachable, + atlanticReachable, + ); /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ }; var search = (heights) => { - const [ rows, cols ] = [ heights.length, heights[0].length ]; - const [ pacificReachable, atlanticReachable ] = [ getMatrix(rows, cols), getMatrix(rows, cols) ];/* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ + const [rows, cols] = [heights.length, heights[0].length]; + const [pacificReachable, atlanticReachable] = [ + getMatrix(rows, cols), + getMatrix(rows, cols), + ]; /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ searchRows(heights, rows, cols, pacificReachable, atlanticReachable); searchCols(heights, rows, cols, pacificReachable, atlanticReachable); - return [ pacificReachable, atlanticReachable ]; -} + return [pacificReachable, atlanticReachable]; +}; -var getMatrix = (rows, cols) => new Array(rows).fill()/* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ - .map(() => new Array(cols).fill(false)); +var getMatrix = (rows, cols) => + new Array(rows) + .fill() /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ + .map(() => new Array(cols).fill(false)); var searchRows = (heights, rows, cols, pacificReachable, atlanticReachable) => { - for (let row = 0; row < rows; row++) {/* Time O(ROWS) */ - const [ pacificStart, atlanticStart ] = [ 0, (cols - 1) ]; - - dfs(row, pacificStart, rows, cols, pacificReachable, heights); /* Space O(ROWS * COLS) */ - dfs(row, atlanticStart, rows, cols, atlanticReachable, heights); /* Space O(ROWS * COLS) */ + for (let row = 0; row < rows; row++) { + /* Time O(ROWS) */ + const [pacificStart, atlanticStart] = [0, cols - 1]; + + dfs( + row, + pacificStart, + rows, + cols, + pacificReachable, + heights, + ); /* Space O(ROWS * COLS) */ + dfs( + row, + atlanticStart, + rows, + cols, + atlanticReachable, + heights, + ); /* Space O(ROWS * COLS) */ } -} +}; var searchCols = (heights, rows, cols, pacificReachable, atlanticReachable) => { - for (let col = 0; col < cols; col++) {/* Time O(COLS) */ - const [ pacificStart, atlanticStart ] = [ 0, (rows - 1) ]; - - dfs(pacificStart, col, rows, cols, pacificReachable, heights); /* Space O(ROWS * COLS) */ - dfs(atlanticStart, col, rows, cols, atlanticReachable, heights); /* Space O(ROWS * COLS) */ + for (let col = 0; col < cols; col++) { + /* Time O(COLS) */ + const [pacificStart, atlanticStart] = [0, rows - 1]; + + dfs( + pacificStart, + col, + rows, + cols, + pacificReachable, + heights, + ); /* Space O(ROWS * COLS) */ + dfs( + atlanticStart, + col, + rows, + cols, + atlanticReachable, + heights, + ); /* Space O(ROWS * COLS) */ } -} +}; const dfs = (row, col, rows, cols, isReachable, heights) => { isReachable[row][col] = true; - for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) { + for (const [_row, _col] of getNeighbors(row, rows, col, cols)) { if (isReachable[_row][_col]) continue; const isLower = heights[_row][_col] < heights[row][col]; if (isLower) continue; - - dfs(_row, _col, rows, cols, isReachable, heights); /* Space O(ROWS * COLS) */ + dfs( + _row, + _col, + rows, + cols, + isReachable, + heights, + ); /* Space O(ROWS * COLS) */ } -} - -var searchGrid = (heights, pacificReachable, atlanticReachable, intersection = []) => { - const [ rows, cols ] = [ heights.length, heights[0].length ]; +}; - for (let row = 0; row < rows; row++) {/* Time O(ROWS) */ - for (let col = 0; col < cols; col++) {/* Time O(COLS) */ - const isReachable = pacificReachable[row][col] && atlanticReachable[row][col] - if (!isReachable) continue +var searchGrid = ( + heights, + pacificReachable, + atlanticReachable, + intersection = [], +) => { + const [rows, cols] = [heights.length, heights[0].length]; + + for (let row = 0; row < rows; row++) { + /* Time O(ROWS) */ + for (let col = 0; col < cols; col++) { + /* Time O(COLS) */ + const isReachable = + pacificReachable[row][col] && atlanticReachable[row][col]; + if (!isReachable) continue; - intersection.push([ row, col ]); /* Space O(ROWS * COLS) */ + intersection.push([row, col]); /* Space O(ROWS * COLS) */ } } return intersection; -} +}; -var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ], [ 0, -1 ], [ 1, 0 ], [ -1, 0 ] ] - .map(([ _row, _col ]) => [ (row + _row), (col + _col)]) - .filter(([ _row, _col ]) => (0 <= _row) && (_row < rows) && (0 <= _col) && (_col < cols)) +var getNeighbors = (row, rows, col, cols) => + [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ] + .map(([_row, _col]) => [row + _row, col + _col]) + .filter( + ([_row, _col]) => + 0 <= _row && _row < rows && 0 <= _col && _col < cols, + ); /** * https://leetcode.com/problems/pacific-atlantic-water-flow/ @@ -80,84 +143,121 @@ var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ], [ 0, -1 ], [ 1, 0 ], [ * @param {number[][]} heights * @return {number[][]} */ - var pacificAtlantic = function(heights) { - const [ pacificQueue, atlanticQueue ] = search(heights); /* Time O(ROWS + COLS) | Space O(ROWS + COLS) */ - const [ pacificReachable, atlanticReachable ] = [ bfs(heights, pacificQueue), bfs(heights, atlanticQueue) ];/* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ - - return getIntersection(heights, pacificReachable, atlanticReachable); /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ -} +var pacificAtlantic = function (heights) { + const [pacificQueue, atlanticQueue] = + search(heights); /* Time O(ROWS + COLS) | Space O(ROWS + COLS) */ + const [pacificReachable, atlanticReachable] = [ + bfs(heights, pacificQueue), + bfs(heights, atlanticQueue), + ]; /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ + + return getIntersection( + heights, + pacificReachable, + atlanticReachable, + ); /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ +}; -var search = (heights, pacificQueue = new Queue([]), atlanticQueue = new Queue([])) => { +var search = ( + heights, + pacificQueue = new Queue([]), + atlanticQueue = new Queue([]), +) => { searchRows(heights, pacificQueue, atlanticQueue); searchCols(heights, pacificQueue, atlanticQueue); - return [ pacificQueue, atlanticQueue ] -} + return [pacificQueue, atlanticQueue]; +}; var searchRows = (heights, pacificQueue, atlanticQueue) => { - const [ rows, cols ] = [ heights.length, heights[0].length ]; + const [rows, cols] = [heights.length, heights[0].length]; - for (let row = 0; row < rows; row++) {/* Time O(ROWS) */ - pacificQueue.enqueue([ row, 0 ]); /* Space O(ROWS) */ - atlanticQueue.enqueue([ row, (cols - 1) ]);/* Space O(ROWS) */ + for (let row = 0; row < rows; row++) { + /* Time O(ROWS) */ + pacificQueue.enqueue([row, 0]); /* Space O(ROWS) */ + atlanticQueue.enqueue([row, cols - 1]); /* Space O(ROWS) */ } -} +}; var searchCols = (heights, pacificQueue, atlanticQueue) => { - const [ rows, cols ] = [ heights.length, heights[0].length ]; + const [rows, cols] = [heights.length, heights[0].length]; - for (let col = 0; col < cols; col++) {/* Time O(COLS) */ - pacificQueue.enqueue([ 0, col ]); /* Space O(COLS) */ - atlanticQueue.enqueue([ (rows - 1), col ]);/* Space O(COLS) */ + for (let col = 0; col < cols; col++) { + /* Time O(COLS) */ + pacificQueue.enqueue([0, col]); /* Space O(COLS) */ + atlanticQueue.enqueue([rows - 1, col]); /* Space O(COLS) */ } -} +}; const bfs = (heights, queue) => { - const [ rows, cols ] = [ heights.length, heights[0].length ]; - const isReachable = getMatrix(rows, cols); /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ + const [rows, cols] = [heights.length, heights[0].length]; + const isReachable = getMatrix( + rows, + cols, + ); /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ while (!queue.isEmpty()) { - for (let i = (queue.size() - 1); 0 <= i; i--) {/* | Space O(WIDTH) */ - const [ row, col ] = queue.dequeue(); + for (let i = queue.size() - 1; 0 <= i; i--) { + /* | Space O(WIDTH) */ + const [row, col] = queue.dequeue(); checkNeighbor(heights, row, rows, col, cols, isReachable, queue); } } return isReachable; -} +}; -var getMatrix = (rows, cols) => new Array(rows).fill()/* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ - .map(() => new Array(cols).fill(false)); +var getMatrix = (rows, cols) => + new Array(rows) + .fill() /* Time O(ROWS * COLS) | Space O(ROWS * COLS) */ + .map(() => new Array(cols).fill(false)); var checkNeighbor = (heights, row, rows, col, cols, isReachable, queue) => { isReachable[row][col] = true; - for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) { + for (const [_row, _col] of getNeighbors(row, rows, col, cols)) { if (isReachable[_row][_col]) continue; const isLower = heights[_row][_col] < heights[row][col]; if (isLower) continue; - queue.enqueue([ _row, _col ]); + queue.enqueue([_row, _col]); } -} - -var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ], [ 0, -1 ], [ 1, 0 ], [ -1, 0 ] ] - .map(([ _row, _col ]) => [ (row + _row), (col + _col)]) - .filter(([ _row, _col ]) => (0 <= _row) && (_row < rows) && (0 <= _col) && (_col < cols)) - -const getIntersection = (heights, pacificReachable, atlanticReachable, intersection = []) => { - const [ rows, cols ] = [ heights.length, heights[0].length ]; +}; - for (let row = 0; row < rows; row++) {/* Time O(ROWS) */ - for (let col = 0; col < cols; col++) {/* Time O(COLS) */ - const isReachable = pacificReachable[row][col] && atlanticReachable[row][col]; +var getNeighbors = (row, rows, col, cols) => + [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ] + .map(([_row, _col]) => [row + _row, col + _col]) + .filter( + ([_row, _col]) => + 0 <= _row && _row < rows && 0 <= _col && _col < cols, + ); + +const getIntersection = ( + heights, + pacificReachable, + atlanticReachable, + intersection = [], +) => { + const [rows, cols] = [heights.length, heights[0].length]; + + for (let row = 0; row < rows; row++) { + /* Time O(ROWS) */ + for (let col = 0; col < cols; col++) { + /* Time O(COLS) */ + const isReachable = + pacificReachable[row][col] && atlanticReachable[row][col]; if (!isReachable) continue; - intersection.push([ row, col ]); /* Space O(ROWS * COLS) */ + intersection.push([row, col]); /* Space O(ROWS * COLS) */ } } return intersection; -} \ No newline at end of file +}; diff --git a/javascript/0424-longest-repeating-character-replacement.js b/javascript/0424-longest-repeating-character-replacement.js index c886fb30e..aa597b992 100644 --- a/javascript/0424-longest-repeating-character-replacement.js +++ b/javascript/0424-longest-repeating-character-replacement.js @@ -5,21 +5,21 @@ * @param {number} k * @return {number} */ -var characterReplacement = function(s, k) { +var characterReplacement = function (s, k) { let res = 0; let count = new Map(); let l = 0; for (let r = 0; r < s.length; r++) { - let len = r - l + 1 - count.set(s[r], 1 + (count.get(s[r]) || 0)) + let len = r - l + 1; + count.set(s[r], 1 + (count.get(s[r]) || 0)); - if ((len - Math.max(...count.values())) > k) { - count.set(s[l], count.get(s[l]) - 1) + if (len - Math.max(...count.values()) > k) { + count.set(s[l], count.get(s[l]) - 1); l++; } len = r - l + 1; - res = Math.max(res, len) + res = Math.max(res, len); } return res; diff --git a/javascript/0435-non-overlapping-intervals.js b/javascript/0435-non-overlapping-intervals.js index 21331dfd2..34b9eaef6 100644 --- a/javascript/0435-non-overlapping-intervals.js +++ b/javascript/0435-non-overlapping-intervals.js @@ -6,7 +6,7 @@ */ var eraseOverlapIntervals = function (intervals) { intervals.sort(([aStart, aEnd], [bStart, bEnd]) => - aEnd !== bEnd ? aEnd - bEnd : aStart - bStart + aEnd !== bEnd ? aEnd - bEnd : aStart - bStart, ); return getGaps(intervals); diff --git a/javascript/0441-arranging-coins.js b/javascript/0441-arranging-coins.js index 67875334a..82187a10a 100644 --- a/javascript/0441-arranging-coins.js +++ b/javascript/0441-arranging-coins.js @@ -5,12 +5,11 @@ * @param {number} n * @return {number} */ -var arrangeCoins = function(n) { - +var arrangeCoins = function (n) { let steps = 1; let canBuild = 0; - while(n >= steps) { + while (n >= steps) { n = n - steps; canBuild++; steps++; @@ -25,39 +24,37 @@ var arrangeCoins = function(n) { * @param {number} n * @return {number} */ -var arrangeCoins = function(n) { - +var arrangeCoins = function (n) { let left = 1; let right = n; let result = 0; - - while(left <= right) { - - const mid = Math.floor((right+left)/2); - const total = (1 + mid) * (mid/2); - if(n < total) { - right = mid -1; + + while (left <= right) { + const mid = Math.floor((right + left) / 2); + const total = (1 + mid) * (mid / 2); + if (n < total) { + right = mid - 1; } else { - left = mid+1; + left = mid + 1; result = Math.max(result, mid); } } - + return result; - }; - -/** - * Math +}; + +/** + * Math * Time O(1) | Space O(1) * @param {number} n * @return {number} */ -var arrangeCoins = function(n) { - let discriminant = 1 + 8 * n; - let sqrtDiscriminant = Math.sqrt(discriminant); +var arrangeCoins = function (n) { + let discriminant = 1 + 8 * n; + let sqrtDiscriminant = Math.sqrt(discriminant); - let result1 = Math.floor((-1 + sqrtDiscriminant) / 2); - let result2 = Math.floor((-1 - sqrtDiscriminant) / 2); + let result1 = Math.floor((-1 + sqrtDiscriminant) / 2); + let result2 = Math.floor((-1 - sqrtDiscriminant) / 2); - return Math.max(result1, result2); + return Math.max(result1, result2); }; diff --git a/javascript/0448-find-all-numbers-disappeared-in-an-array.js b/javascript/0448-find-all-numbers-disappeared-in-an-array.js index 83739d63c..0a9a3c9dd 100644 --- a/javascript/0448-find-all-numbers-disappeared-in-an-array.js +++ b/javascript/0448-find-all-numbers-disappeared-in-an-array.js @@ -1,16 +1,15 @@ // problem link https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array // time complexity O(n) -var findDisappearedNumbers = function(nums) { - +var findDisappearedNumbers = function (nums) { const numberSet = new Set(); - for(let i = 1; i < nums.length + 1; i++) { + for (let i = 1; i < nums.length + 1; i++) { numberSet.add(i); } nums.forEach((element) => { - if(numberSet.has(element)) { + if (numberSet.has(element)) { numberSet.delete(element); } }); @@ -22,21 +21,21 @@ var findDisappearedNumbers = function(nums) { //time complexity O(n) , space complexity O(1) -var findDisappearedNumbers = function(nums) { - for(let i = 0; i < nums.length; i++) { - let curr = Math.abs(nums[i]) - let idx = curr - 1 - if(nums[idx] > 0) { - nums[idx] = nums[idx] * (-1) +var findDisappearedNumbers = function (nums) { + for (let i = 0; i < nums.length; i++) { + let curr = Math.abs(nums[i]); + let idx = curr - 1; + if (nums[idx] > 0) { + nums[idx] = nums[idx] * -1; } } - let res = [] - for(let i = 0; i < nums.length; i++) { - if(nums[i] > 0) { - res.push(i + 1) + let res = []; + for (let i = 0; i < nums.length; i++) { + if (nums[i] > 0) { + res.push(i + 1); } } - return res + return res; }; // For each value in the array mark its presence by making the number negative at that place in array diff --git a/javascript/0450-delete-node-in-a-bst.js b/javascript/0450-delete-node-in-a-bst.js index 8e2d7bb85..1d0a487c0 100644 --- a/javascript/0450-delete-node-in-a-bst.js +++ b/javascript/0450-delete-node-in-a-bst.js @@ -14,7 +14,7 @@ * @param {number} key * @return {TreeNode} */ -var deleteNode = function(root, key) { +var deleteNode = function (root, key) { if (!root) return root; if (key === root.val) { @@ -32,7 +32,7 @@ var deleteNode = function(root, key) { root.right = deleteNode(root.right, root.val); return root; - } + } if (key < root.val) { root.left = deleteNode(root.left, key); return root; diff --git a/javascript/0460-lfu-cache.js b/javascript/0460-lfu-cache.js index 9219ce187..ab0817c10 100644 --- a/javascript/0460-lfu-cache.js +++ b/javascript/0460-lfu-cache.js @@ -1,121 +1,124 @@ // https://leetcode.com/problems/lfu-cache/ class ListNode { - constructor(val, next, prev) { - this.val = (val===undefined ? 0 : val) - this.next = (next===undefined ? null : next) - this.prev = (next===undefined ? null : prev) - } + constructor(val, next, prev) { + this.val = val === undefined ? 0 : val; + this.next = next === undefined ? null : next; + this.prev = next === undefined ? null : prev; + } } class LinkedList { - constructor() { - this.map = new Map() - this.Right = new ListNode(null) - this.Left = new ListNode(null, this.Right) - this.Right.prev = this.Left - } + constructor() { + this.map = new Map(); + this.Right = new ListNode(null); + this.Left = new ListNode(null, this.Right); + this.Right.prev = this.Left; + } - len() { - return this.map.size - } + len() { + return this.map.size; + } - pop(val) { - if (this.map.has(val)) { - let node = this.map.get(val) + pop(val) { + if (this.map.has(val)) { + let node = this.map.get(val); - // save - let prevNode = node.prev - // delete - prevNode.next = node.next - prevNode.next.prev = prevNode - this.map.delete(val) + // save + let prevNode = node.prev; + // delete + prevNode.next = node.next; + prevNode.next.prev = prevNode; + this.map.delete(val); + } } - } - popleft() { - let data = this.Left.next.val - this.Left.next = this.Left.next.next - this.Left.next.prev = this.Left - this.map.delete(data) - return data - } + popleft() { + let data = this.Left.next.val; + this.Left.next = this.Left.next.next; + this.Left.next.prev = this.Left; + this.map.delete(data); + return data; + } - pushRight(val) { - let newNode = new ListNode(val, this.Right) - newNode.prev = this.Right.prev - newNode.prev.next = newNode - this.Right.prev = newNode - this.map.set(val, newNode) - } + pushRight(val) { + let newNode = new ListNode(val, this.Right); + newNode.prev = this.Right.prev; + newNode.prev.next = newNode; + this.Right.prev = newNode; + this.map.set(val, newNode); + } - update(val) { - this.pop(val) - this.pushRight(val) - } + update(val) { + this.pop(val); + this.pushRight(val); + } } /** * @param {number} capacity */ -var LFUCache = function(capacity) { - this.capacity = capacity - this.valueMap = new Map() - this.countMap = new Map() - this.lftCount = 1 - this.lists = [] - this.counter = (key) => { - let count = this.countMap.get(key) || 0 - if (this.lists[count]) { - this.lists[count].pop(key) - } - if (!this.lists[count + 1]) { - this.lists[count + 1] = new LinkedList() - } - this.lists[count + 1].pushRight(key) - this.countMap.set(key, count + 1) - // console.log(this.lftCount == count, count, this.lists[count].len()) - if (this.lftCount == count && this.lists[count] && this.lists[count].len() === 0) { - this.lftCount++ - } - } +var LFUCache = function (capacity) { + this.capacity = capacity; + this.valueMap = new Map(); + this.countMap = new Map(); + this.lftCount = 1; + this.lists = []; + this.counter = (key) => { + let count = this.countMap.get(key) || 0; + if (this.lists[count]) { + this.lists[count].pop(key); + } + if (!this.lists[count + 1]) { + this.lists[count + 1] = new LinkedList(); + } + this.lists[count + 1].pushRight(key); + this.countMap.set(key, count + 1); + // console.log(this.lftCount == count, count, this.lists[count].len()) + if ( + this.lftCount == count && + this.lists[count] && + this.lists[count].len() === 0 + ) { + this.lftCount++; + } + }; }; -/** +/** * @param {number} key * @return {number} */ -LFUCache.prototype.get = function(key) { - if (!this.valueMap.has(key)) { - return -1 - } - - this.counter(key) - return this.valueMap.get(key) +LFUCache.prototype.get = function (key) { + if (!this.valueMap.has(key)) { + return -1; + } + + this.counter(key); + return this.valueMap.get(key); }; -/** - * @param {number} key +/** + * @param {number} key * @param {number} value * @return {void} */ -LFUCache.prototype.put = function(key, value) { - - if (!this.valueMap.has(key) && this.valueMap.size == this.capacity) { - // we need to evict - // console.log(this.lists[this.lftCount]) - let evictedKey = this.lists[this.lftCount].popleft() - this.valueMap.delete(evictedKey) - this.countMap.delete(evictedKey) - } +LFUCache.prototype.put = function (key, value) { + if (!this.valueMap.has(key) && this.valueMap.size == this.capacity) { + // we need to evict + // console.log(this.lists[this.lftCount]) + let evictedKey = this.lists[this.lftCount].popleft(); + this.valueMap.delete(evictedKey); + this.countMap.delete(evictedKey); + } - this.valueMap.set(key, value) - this.counter(key) - this.lftCount = Math.min(this.countMap.get(key), this.lftCount) + this.valueMap.set(key, value); + this.counter(key); + this.lftCount = Math.min(this.countMap.get(key), this.lftCount); }; -/** +/** * Your LFUCache object will be instantiated and called as such: * var obj = new LFUCache(capacity) * var param_1 = obj.get(key) * obj.put(key,value) - */ \ No newline at end of file + */ diff --git a/javascript/0463-island-perimeter.js b/javascript/0463-island-perimeter.js index 55ddb839e..85d85fd98 100644 --- a/javascript/0463-island-perimeter.js +++ b/javascript/0463-island-perimeter.js @@ -1,13 +1,18 @@ -var islandPerimeter = function(grid) { +var islandPerimeter = function (grid) { const visit = new Set(); - - const dfs = function(i, j) { - if(i >= grid.length || j >= grid[0].length || i < 0 || j < 0 || grid[i][j] == 0) + + const dfs = function (i, j) { + if ( + i >= grid.length || + j >= grid[0].length || + i < 0 || + j < 0 || + grid[i][j] == 0 + ) return 1; - let flatCoord = i*grid[0].length + j; - if(visit.has(flatCoord)) - return 0; - + let flatCoord = i * grid[0].length + j; + if (visit.has(flatCoord)) return 0; + visit.add(flatCoord); let perim = dfs(i, j + 1); perim += dfs(i + 1, j); @@ -15,9 +20,8 @@ var islandPerimeter = function(grid) { perim += dfs(i - 1, j); return perim; }; - - for(let i = 0; i < grid.length; i++) - for(let j = 0; j < grid[0].length; j++) - if(grid[i][j]) - return dfs(i, j); + + for (let i = 0; i < grid.length; i++) + for (let j = 0; j < grid[0].length; j++) + if (grid[i][j]) return dfs(i, j); }; diff --git a/javascript/0494-target-sum.js b/javascript/0494-target-sum.js index 7df390be9..cccde095b 100644 --- a/javascript/0494-target-sum.js +++ b/javascript/0494-target-sum.js @@ -6,24 +6,34 @@ * @param {number} target * @return {number} */ - var findTargetSumWays = (nums, target, index = 0, sum = 0) => { - const isBaseCase = (index === nums.length); +var findTargetSumWays = (nums, target, index = 0, sum = 0) => { + const isBaseCase = index === nums.length; if (isBaseCase) { - const isTarget = (sum === target); + const isTarget = sum === target; if (isTarget) return 1; return 0; } - return dfs(nums, target, index, sum);/* Time O(2^N) | Space O(HEIGHT) */ -} + return dfs(nums, target, index, sum); /* Time O(2^N) | Space O(HEIGHT) */ +}; var dfs = (nums, target, index, sum) => { - const left = findTargetSumWays(nums, target, (index + 1), (sum + nums[index])); /* Time O(2^N) | Space O(HEIGHT) */ - const right = findTargetSumWays(nums, target, (index + 1), (sum - nums[index]));/* Time O(2^N) | Space O(HEIGHT) */ - - return (left + right); -} + const left = findTargetSumWays( + nums, + target, + index + 1, + sum + nums[index], + ); /* Time O(2^N) | Space O(HEIGHT) */ + const right = findTargetSumWays( + nums, + target, + index + 1, + sum - nums[index], + ); /* Time O(2^N) | Space O(HEIGHT) */ + + return left + right; +}; /** * DP - Top Down @@ -35,36 +45,73 @@ var dfs = (nums, target, index, sum) => { * @return {number} */ var findTargetSumWays = (nums, target) => { - const total = nums.reduce((sum, num) => (sum + num), 0);/* Time O(N) */ - - return calculate(nums, target, total); /* Time O(N * M) | Space O((N * M) + HEIGHT) */ -} + const total = nums.reduce((sum, num) => sum + num, 0); /* Time O(N) */ -var initMemo = (nums, total) => new Array(nums.length).fill()/* Time O(N) | Space O(N) */ - .map(() => new Array(((total + 1) << 1)).fill(null)); /* Time O(M) | Space O(M) */ + return calculate( + nums, + target, + total, + ); /* Time O(N * M) | Space O((N * M) + HEIGHT) */ +}; -const calculate = (nums, target, total, index = 0, sum = 0, memo = initMemo(nums, total)) => { - const isBaseCase = (index === nums.length); +var initMemo = (nums, total) => + new Array(nums.length) + .fill() /* Time O(N) | Space O(N) */ + .map(() => + new Array((total + 1) << 1).fill(null), + ); /* Time O(M) | Space O(M) */ + +const calculate = ( + nums, + target, + total, + index = 0, + sum = 0, + memo = initMemo(nums, total), +) => { + const isBaseCase = index === nums.length; if (isBaseCase) { - const isTarget = (sum === target); + const isTarget = sum === target; if (isTarget) return 1; return 0; } - const hasSeen = (memo[index][(sum + total)] != null); - if (hasSeen) return memo[index][(sum + total)]; - - return dfs(nums, target, total, index, sum, memo);/* Time O(N * M) | Space O((N * M) + HEIGHT) */ -} + const hasSeen = memo[index][sum + total] != null; + if (hasSeen) return memo[index][sum + total]; + + return dfs( + nums, + target, + total, + index, + sum, + memo, + ); /* Time O(N * M) | Space O((N * M) + HEIGHT) */ +}; var dfs = (nums, target, total, index, sum, memo) => { - const left = calculate(nums, target, total, (index + 1), (sum + nums[index]), memo); /* Time O(N * M) | Space O(HEIGHT) */ - const right = calculate(nums, target, total, (index + 1), (sum - nums[index]), memo);/* Time O(N * M) | Space O(HEIGHT) */ - - memo[index][(sum + total)] = (left + right); /* | Space O(N * M) */ - return memo[index][(sum + total)]; -} + const left = calculate( + nums, + target, + total, + index + 1, + sum + nums[index], + memo, + ); /* Time O(N * M) | Space O(HEIGHT) */ + const right = calculate( + nums, + target, + total, + index + 1, + sum - nums[index], + memo, + ); /* Time O(N * M) | Space O(HEIGHT) */ + + memo[index][sum + total] = + left + right; /* | Space O(N * M) */ + return memo[index][sum + total]; +}; /** * DP - Bottom Up @@ -76,42 +123,47 @@ var dfs = (nums, target, total, index, sum, memo) => { * @return {number} */ var findTargetSumWays = (nums, target) => { - const total = nums.reduce((sum, num) => (sum + num), 0);/* Time O(N) */ - const tabu = initTabu(nums, total); /* Time O(N * M) | Space O(N * M) */ + const total = nums.reduce((sum, num) => sum + num, 0); /* Time O(N) */ + const tabu = initTabu(nums, total); /* Time O(N * M) | Space O(N * M) */ - search(nums, total, tabu); /* Time O(N * M) | Space O(N * M) */ + search(nums, total, tabu); /* Time O(N * M) | Space O(N * M) */ - return (Math.abs(target) <= total) - ? tabu[(nums.length - 1)][(target + total)] + return Math.abs(target) <= total + ? tabu[nums.length - 1][target + total] : 0; }; var initTabu = (nums, total) => { - const tabu = new Array(nums.length).fill() /* Time O(N) | Space O(N) */ - .map(() => new Array(((total + 1) << 1)).fill(0));/* Time O(M) | Space O(M) */ - const [ left, right ] = [ (total + nums[0]), (total - nums[0]) ]; + const tabu = new Array(nums.length) + .fill() /* Time O(N) | Space O(N) */ + .map(() => + new Array((total + 1) << 1).fill(0), + ); /* Time O(M) | Space O(M) */ + const [left, right] = [total + nums[0], total - nums[0]]; - tabu[0][left] = 1; /* | Space O(N * M) */ - tabu[0][right] += 1; /* | Space O(N * M) */ + tabu[0][left] = 1; /* | Space O(N * M) */ + tabu[0][right] += 1; /* | Space O(N * M) */ return tabu; -} +}; var search = (nums, total, tabu) => { - for (let i = 1; (i < nums.length); i++) {/* Time O(N) */ - for (let sum = (-total); (sum <= total); sum++) {/* Time O(M) */ - const isInvalid = (tabu[(i - 1)][(sum + total)] <= 0); + for (let i = 1; i < nums.length; i++) { + /* Time O(N) */ + for (let sum = -total; sum <= total; sum++) { + /* Time O(M) */ + const isInvalid = tabu[i - 1][sum + total] <= 0; if (isInvalid) continue; - const dpSum = tabu[(i - 1)][sum + total]; - const left = ((sum + nums[i]) + total); - const right = ((sum - nums[i]) + total); + const dpSum = tabu[i - 1][sum + total]; + const left = sum + nums[i] + total; + const right = sum - nums[i] + total; - tabu[i][left] += dpSum; /* Space O(N * M) */ - tabu[i][right] += dpSum; /* Space O(N * M) */ + tabu[i][left] += dpSum; /* Space O(N * M) */ + tabu[i][right] += dpSum; /* Space O(N * M) */ } } -} +}; /** * DP - Top Down @@ -123,51 +175,52 @@ var search = (nums, total, tabu) => { * @return {number} */ var findTargetSumWays = (nums, target) => { - const total = nums.reduce((sum, num) => (sum + num), 0);/* Time O(N) */ - let tabu = getTabu(nums, total); /* Time O(M) | Space O(M) */ + const total = nums.reduce((sum, num) => sum + num, 0); /* Time O(N) */ + let tabu = getTabu(nums, total); /* Time O(M) | Space O(M) */ - tabu = search(nums, total, tabu); /* Time O(N * M) | Space O(M) */ + tabu = search(nums, total, tabu); /* Time O(N * M) | Space O(M) */ - return (Math.abs(target) <= total) - ? tabu[(target + total)] - : 0 -} + return Math.abs(target) <= total ? tabu[target + total] : 0; +}; -var initTabu = (total) => new Array((total + 1) << 1).fill(0);/* Time O(M) | Space O(M) */ +var initTabu = (total) => + new Array((total + 1) << 1).fill(0); /* Time O(M) | Space O(M) */ var getTabu = (nums, total) => { - const tabu = initTabu(total);/* Time O(M) | Space O(M) */ - const [ left, right ] = [ (total + nums[0]), (total - nums[0]) ]; + const tabu = initTabu(total); /* Time O(M) | Space O(M) */ + const [left, right] = [total + nums[0], total - nums[0]]; - tabu[left] = 1; /* | Space O(M) */ - tabu[right] += 1; /* | Space O(M) */ + tabu[left] = 1; /* | Space O(M) */ + tabu[right] += 1; /* | Space O(M) */ return tabu; -} +}; var search = (nums, total, tabu) => { - for (let i = 1; (i < nums.length); i++) { /* Time O(N) */ + for (let i = 1; i < nums.length; i++) { + /* Time O(N) */ const num = nums[i]; - const temp = initTabu(total); /* Time O(M) | Space O(M) */ + const temp = initTabu(total); /* Time O(M) | Space O(M) */ - tabu = update(num, total, tabu, temp); /* Time O(M) | Space O(M) */ + tabu = update(num, total, tabu, temp); /* Time O(M) | Space O(M) */ } return tabu; -} +}; var update = (num, total, tabu, temp) => { - for (let sum = (-total); (sum <= total); sum++) {/* Time O(M) */ - const isInvalid = (tabu[sum + total] <= 0); + for (let sum = -total; sum <= total; sum++) { + /* Time O(M) */ + const isInvalid = tabu[sum + total] <= 0; if (isInvalid) continue; const dpSum = tabu[sum + total]; - const left = ((sum + num) + total); - const right = ((sum - num) + total); + const left = sum + num + total; + const right = sum - num + total; - temp[left] += dpSum; /* Space O(M) */ - temp[right] += dpSum; /* Space O(M) */ + temp[left] += dpSum; /* Space O(M) */ + temp[right] += dpSum; /* Space O(M) */ } return temp; -} \ No newline at end of file +}; diff --git a/javascript/0496-next-greater-element-i.js b/javascript/0496-next-greater-element-i.js index 7e973b6f8..036889d83 100644 --- a/javascript/0496-next-greater-element-i.js +++ b/javascript/0496-next-greater-element-i.js @@ -8,20 +8,20 @@ */ var nextGreaterElement = function (nums1, nums2) { - const subsetMap = new Map(nums1.map((val, i) => [val, i])); - const res = new Array(nums1.length).fill(-1); + const subsetMap = new Map(nums1.map((val, i) => [val, i])); + const res = new Array(nums1.length).fill(-1); - let stack = []; + let stack = []; - for (let num of nums2) { - while (stack.length && num > stack.at(-1)) { - const val = stack.pop(); - const idx = subsetMap.get(val); - res[idx] = num; - } + for (let num of nums2) { + while (stack.length && num > stack.at(-1)) { + const val = stack.pop(); + const idx = subsetMap.get(val); + res[idx] = num; + } - if (subsetMap.has(num)) stack.push(num); - } + if (subsetMap.has(num)) stack.push(num); + } - return res; + return res; }; diff --git a/javascript/0502-ipo.js b/javascript/0502-ipo.js index ce1bec72d..bcb1651c9 100644 --- a/javascript/0502-ipo.js +++ b/javascript/0502-ipo.js @@ -1,5 +1,5 @@ /** - * MaxPriorityQueue | Sorting + * MaxPriorityQueue | Sorting * Time O(n*log(n)) | Space O(n) * https://leetcode.com/problems/ipo/description/ * @param {number} k @@ -8,44 +8,41 @@ * @param {number[]} capital * @return {number} */ -var findMaximizedCapital = function(k, w, profits, capital) { - - const maxQueue = new MaxPriorityQueue({ - compare: (a, b) => { - return b[0] - a[0]; +var findMaximizedCapital = function (k, w, profits, capital) { + const maxQueue = new MaxPriorityQueue({ + compare: (a, b) => { + return b[0] - a[0]; + }, + }); + + const minQueue = new MinPriorityQueue({ + compare: (a, b) => { + return a[0] - b[0]; + }, + }); + + const pc = profits.map((profit, idx) => { + return [profit, capital[idx]]; + }); + + for (let i = 0; i < pc.length; i++) { + minQueue.enqueue([pc[i][1], pc[i][0]]); } - }); - const minQueue = new MinPriorityQueue({ - compare: (a, b) => { - return a[0] - b[0]; - } - }); - - const pc = profits.map((profit, idx) => { - return [profit, capital[idx]]; - }); + let cc = w; + while (k && (!maxQueue.isEmpty() || !minQueue.isEmpty())) { + // add all the project that we can take to maxQ + while (!minQueue.isEmpty() && cc >= minQueue.front()[0]) { + const curr = minQueue.dequeue(); + maxQueue.enqueue([curr[1], curr[0]]); + } - for (let i = 0; i < pc.length; i++) { - minQueue.enqueue([pc[i][1], pc[i][0]]); - } + if (!maxQueue.isEmpty()) { + cc += maxQueue.dequeue()[0]; + } - let cc = w; - while (k && (!maxQueue.isEmpty() || !minQueue.isEmpty())) { - - // add all the project that we can take to maxQ - while (!minQueue.isEmpty() && cc >= minQueue.front()[0]) { - const curr = minQueue.dequeue(); - maxQueue.enqueue([curr[1], curr[0]]); + k--; } - if (!maxQueue.isEmpty()) { - cc += maxQueue.dequeue()[0]; - } - - k--; - } - - return cc; + return cc; }; - diff --git a/javascript/0513-find-bottom-left-tree-value.js b/javascript/0513-find-bottom-left-tree-value.js index ec69d129c..55c01c295 100644 --- a/javascript/0513-find-bottom-left-tree-value.js +++ b/javascript/0513-find-bottom-left-tree-value.js @@ -13,23 +13,22 @@ * @param {TreeNode} root * @return {number} */ -var findBottomLeftValue = function(root) { - +var findBottomLeftValue = function (root) { let leftVal = 0; let deepestLevel = -Infinity; - const dfs = (node, level) => { - if(!node.left && !node.right) { - if(level > deepestLevel) { + const dfs = (node, level) => { + if (!node.left && !node.right) { + if (level > deepestLevel) { leftVal = node.val; deepestLevel = level; - } + } return; } - node.left && dfs(node.left, level + 1); + node.left && dfs(node.left, level + 1); node.right && dfs(node.right, level + 1); - } + }; dfs(root, 0); return leftVal; diff --git a/javascript/0515-find-largest-value-in-each-tree-row.js b/javascript/0515-find-largest-value-in-each-tree-row.js index 36ba63755..bf5360fc9 100644 --- a/javascript/0515-find-largest-value-in-each-tree-row.js +++ b/javascript/0515-find-largest-value-in-each-tree-row.js @@ -8,13 +8,12 @@ */ /** * BFS | Level order traversal - * Time O(n) | Space O(n) + * Time O(n) | Space O(n) * https://leetcode.com/problems/find-largest-value-in-each-tree-row/ * @param {TreeNode} root * @return {number[]} */ -var largestValues = function(root) { - +var largestValues = function (root) { if (!root) return []; const result = []; @@ -34,7 +33,7 @@ var largestValues = function(root) { } result.push(max); } - } + }; bfs(root); return result; diff --git a/javascript/0518-coin-change-ii.js b/javascript/0518-coin-change-ii.js index 3945176da..a30e9ee78 100644 --- a/javascript/0518-coin-change-ii.js +++ b/javascript/0518-coin-change-ii.js @@ -5,25 +5,30 @@ * @param {number[]} coins * @return {number} */ - var change = (amount, coins, n = (coins.length)) => { - const isBaseCase1 = (amount === 0); +var change = (amount, coins, n = coins.length) => { + const isBaseCase1 = amount === 0; if (isBaseCase1) return 1; - const isBaseCase2 = (n === 0); + const isBaseCase2 = n === 0; if (isBaseCase2) return 0; - return dfs(amount, coins, n);/* Time O(2^N) | Space O(N) */ -} + return dfs(amount, coins, n); /* Time O(2^N) | Space O(N) */ +}; var dfs = (amount, coins, n) => { - const isLess = (amount < coins[(n - 1)]); - if (isLess) return change(amount, coins, (n - 1)); /* Time O(2^N) | Space O(N) */ - - const left = change((amount - coins[(n - 1)]), coins, n);/* Time O(2^N) | Space O(N) */ - const right = change(amount, coins, (n - 1)); /* Time O(2^N) | Space O(N) */ - - return (left + right); -} + const isLess = amount < coins[n - 1]; + if (isLess) + return change(amount, coins, n - 1); /* Time O(2^N) | Space O(N) */ + + const left = change( + amount - coins[n - 1], + coins, + n, + ); /* Time O(2^N) | Space O(N) */ + const right = change(amount, coins, n - 1); /* Time O(2^N) | Space O(N) */ + + return left + right; +}; /** * DP - Top Down @@ -34,35 +39,63 @@ var dfs = (amount, coins, n) => { * @param {number[]} coins * @return {number} */ -var change = (amount, coins, n = (coins.length), memo = initMemo(coins, amount)) => { - const isBaseCase1 = (n === 0); +var change = ( + amount, + coins, + n = coins.length, + memo = initMemo(coins, amount), +) => { + const isBaseCase1 = n === 0; if (isBaseCase1) return 0; - const isBaseCase2 = (amount === 0); + const isBaseCase2 = amount === 0; if (isBaseCase2) return 1; - const hasSeen = (memo[n][amount] !== null); + const hasSeen = memo[n][amount] !== null; if (hasSeen) return memo[n][amount]; - return dfs(amount, coins, n, memo);/* Time O(N * AMOUNT) | Space O((N * AMOUNT) + HEIGHT) */ -} + return dfs( + amount, + coins, + n, + memo, + ); /* Time O(N * AMOUNT) | Space O((N * AMOUNT) + HEIGHT) */ +}; -var initMemo = (coins, amount) => new Array(coins.length + 2).fill() - .map(() => new Array(amount + 2).fill(null)); +var initMemo = (coins, amount) => + new Array(coins.length + 2) + .fill() + .map(() => new Array(amount + 2).fill(null)); var dfs = (amount, coins, n, memo) => { - const isLess = (amount < coins[(n - 1)]); + const isLess = amount < coins[n - 1]; if (isLess) { - memo[n][amount] = change(amount, coins, (n - 1), memo); /* Time O(N * AMOUNT) | Space O(HEIGHT) */ + memo[n][amount] = change( + amount, + coins, + n - 1, + memo, + ); /* Time O(N * AMOUNT) | Space O(HEIGHT) */ return memo[n][amount]; } - const left = change((amount - coins[(n - 1)]), coins, n, memo);/* Time O(N * AMOUNT) | Space O(HEIGHT) */ - const right = change(amount, coins, (n - 1), memo); /* Time O(N * AMOUNT) | Space O(HEIGHT) */ - - memo[n][amount] = (left + right); /* | Space O(N * AMOUNT) */ + const left = change( + amount - coins[n - 1], + coins, + n, + memo, + ); /* Time O(N * AMOUNT) | Space O(HEIGHT) */ + const right = change( + amount, + coins, + n - 1, + memo, + ); /* Time O(N * AMOUNT) | Space O(HEIGHT) */ + + memo[n][amount] = + left + right; /* | Space O(N * AMOUNT) */ return memo[n][amount]; -} +}; /** * DP - Bottom Up @@ -70,38 +103,46 @@ var dfs = (amount, coins, n, memo) => { * Time O(N * AMOUNT) | Space O(N * AMOUNT) * https://leetcode.com/problems/coin-change-ii/ */ - var change = (amount, coins) => { - const tabu = initTabu(amount, coins);/* Time O(N * AMOUNT) | Space O(N * AMOUNT) */ +var change = (amount, coins) => { + const tabu = initTabu( + amount, + coins, + ); /* Time O(N * AMOUNT) | Space O(N * AMOUNT) */ - search(amount, coins, tabu); /* Time O(N * AMOUNT) | Space O(N * AMOUNT) */ + search(amount, coins, tabu); /* Time O(N * AMOUNT) | Space O(N * AMOUNT) */ return tabu[coins.length][amount]; -} +}; var initTabu = (amount, coins) => { - const tabu = new Array((coins.length + 1)).fill()/* Time O(N) | Space O(N) */ - .map(() => new Array((amount + 1)).fill(0)); /* Time O(AMOUNT) | Space O(AMOUNT) */ + const tabu = new Array(coins.length + 1) + .fill() /* Time O(N) | Space O(N) */ + .map(() => + new Array(amount + 1).fill(0), + ); /* Time O(AMOUNT) | Space O(AMOUNT) */ - tabu[0][0] = 1; /* | Space O(N * AMOUNT) */ + tabu[0][0] = 1; /* | Space O(N * AMOUNT) */ return tabu; -} +}; var search = (amount, coins, tabu) => { - for (let coin = 1; coin <= coins.length; coin++) { /* Time O(N)*/ - tabu[coin][0] = 1; /* Space O(N * AMOUNT) */ + for (let coin = 1; coin <= coins.length; coin++) { + /* Time O(N)*/ + tabu[coin][0] = 1; /* Space O(N * AMOUNT) */ - for (let _amount = 1; _amount <= amount; _amount++) {/* Time O(AMOUNT) */ + for (let _amount = 1; _amount <= amount; _amount++) { + /* Time O(AMOUNT) */ tabu[coin][_amount] = tabu[coin - 1][_amount]; - const canUpdate = (0 <= (_amount - coins[(coin - 1)])); + const canUpdate = 0 <= _amount - coins[coin - 1]; if (!canUpdate) continue; - const val = tabu[coin][(_amount - coins[(coin - 1)])]; - tabu[coin][_amount] += val /* Space O(N * AMOUNT) */ + const val = tabu[coin][_amount - coins[coin - 1]]; + tabu[coin][_amount] += val; /* Space O(N * AMOUNT) */ } } -} +}; /** * DP - Bottom Up @@ -121,20 +162,20 @@ var change = (amount, coins) => { }; var initTabu = (amount) => { - var tabu = new Array((amount + 1)).fill(0); + var tabu = new Array(amount + 1).fill(0); tabu[0] = 1; return tabu; -} +}; var search = (amount, coins, tabu) => { for (const coin of coins) { - for (let _amount = 0; (_amount < (amount + 1)); _amount++) { - const canUpdate = (coin <= _amount); + for (let _amount = 0; _amount < amount + 1; _amount++) { + const canUpdate = coin <= _amount; if (!canUpdate) continue; - tabu[_amount] += tabu[(_amount - coin)]; + tabu[_amount] += tabu[_amount - coin]; } } -} +}; diff --git a/javascript/0523-continuous-subarray-sum.js b/javascript/0523-continuous-subarray-sum.js index 107151223..39f078fe4 100644 --- a/javascript/0523-continuous-subarray-sum.js +++ b/javascript/0523-continuous-subarray-sum.js @@ -6,19 +6,19 @@ * @param {number} k * @return {boolean} */ -var checkSubarraySum = function(arr, k) { +var checkSubarraySum = function (arr, k) { let sum = 0; - const remainderMap = new Map([ [0, -1] ]); - - for(let i = 0; i < arr.length; i++) { + const remainderMap = new Map([[0, -1]]); + + for (let i = 0; i < arr.length; i++) { sum += arr[i]; - if(remainderMap.has(sum%k) && i - remainderMap.get(sum%k) > 1) { + if (remainderMap.has(sum % k) && i - remainderMap.get(sum % k) > 1) { return true; - } - if(!remainderMap.has(sum%k)) { - remainderMap.set(sum%k,i); - } + } + if (!remainderMap.has(sum % k)) { + remainderMap.set(sum % k, i); + } } - + return false; - }; +}; diff --git a/javascript/0535-encode-and-decode-tinyurl.js b/javascript/0535-encode-and-decode-tinyurl.js index e08802891..ee166968f 100644 --- a/javascript/0535-encode-and-decode-tinyurl.js +++ b/javascript/0535-encode-and-decode-tinyurl.js @@ -5,16 +5,16 @@ const encodeMap = new Map(); const decodeMap = new Map(); const base = 'http://tinyurl.com/'; -var encode = function(longUrl) { - let shortUrl = '' - if(!encodeMap.has(longUrl)) { - shortUrl = base + encodeMap.size + 1 - encodeMap.set(longUrl, shortUrl); - decodeMap.set(shortUrl, longUrl); - } - return shortUrl || encodeMap.get(longUrl); +var encode = function (longUrl) { + let shortUrl = ''; + if (!encodeMap.has(longUrl)) { + shortUrl = base + encodeMap.size + 1; + encodeMap.set(longUrl, shortUrl); + decodeMap.set(shortUrl, longUrl); + } + return shortUrl || encodeMap.get(longUrl); }; -var decode = function(shortUrl) { +var decode = function (shortUrl) { return decodeMap.get(shortUrl); }; diff --git a/javascript/0538-convert-bst-to-greater-tree.js b/javascript/0538-convert-bst-to-greater-tree.js index e74e2e528..60eb1167d 100644 --- a/javascript/0538-convert-bst-to-greater-tree.js +++ b/javascript/0538-convert-bst-to-greater-tree.js @@ -7,21 +7,20 @@ * } */ /** - * Tree | reverse pre-order-traversal + * Tree | reverse pre-order-traversal * Time O(n) | Space O(n) * @param {TreeNode} root * @return {TreeNode} */ -var convertBST = function(root) { - - const dfs = (node, max) => { - if(!node) return max; +var convertBST = function (root) { + const dfs = (node, max) => { + if (!node) return max; const result = dfs(node.right, max); node.val = result + node.val; const result1 = dfs(node.left, node.val); return result1; - } + }; dfs(root, 0); return root; diff --git a/javascript/0543-diameter-of-binary-tree.js b/javascript/0543-diameter-of-binary-tree.js index 092d52b01..2e3c6859b 100644 --- a/javascript/0543-diameter-of-binary-tree.js +++ b/javascript/0543-diameter-of-binary-tree.js @@ -4,7 +4,7 @@ * @param {TreeNode} root * @return {number} */ -var diameterOfBinaryTree = function(root, max = [0]) { +var diameterOfBinaryTree = function (root, max = [0]) { diameterOfTree(root, max); return max[0]; @@ -15,7 +15,7 @@ const diameterOfTree = (root, max) => { if (isBaseCase) return 0; return dfs(root, max); -} +}; const dfs = (root, max) => { const left = diameterOfTree(root.left, max); @@ -27,4 +27,4 @@ const dfs = (root, max) => { const height = Math.max(left, right); return height + 1; -} \ No newline at end of file +}; diff --git a/javascript/0554-brick-wall.js b/javascript/0554-brick-wall.js index 8e2276252..8d0a495b2 100644 --- a/javascript/0554-brick-wall.js +++ b/javascript/0554-brick-wall.js @@ -2,29 +2,30 @@ // time coplexity O(n^2) or the number of bricks we have in our input. // space complexity: whatever the length of the rows happend to be. -var leastBricks = function(wall) { - - const myHash = new Map(); +var leastBricks = function (wall) { + const myHash = new Map(); - const width = wall[0].reduce((pre, brick) => { - return brick + pre; - }, 0); + const width = wall[0].reduce((pre, brick) => { + return brick + pre; + }, 0); - for(let i = 0; i < wall.length; i++) { - let currentWidth = 0; - for(let j = 0; j < wall[i].length; j++) { - currentWidth += wall[i][j]; - myHash.has(currentWidth) ? myHash.set(currentWidth,myHash.get(currentWidth)+1) : myHash.set(currentWidth, 1); - } - } + for (let i = 0; i < wall.length; i++) { + let currentWidth = 0; + for (let j = 0; j < wall[i].length; j++) { + currentWidth += wall[i][j]; + myHash.has(currentWidth) + ? myHash.set(currentWidth, myHash.get(currentWidth) + 1) + : myHash.set(currentWidth, 1); + } + } -// deleteing total width as this will be the rightmost gap which will always give us false positive. -myHash.delete(width); + // deleteing total width as this will be the rightmost gap which will always give us false positive. + myHash.delete(width); -maxGap = 0; - for([key, value] of myHash) { - maxGap = Math.max(maxGap, value); - } + maxGap = 0; + for ([key, value] of myHash) { + maxGap = Math.max(maxGap, value); + } - return wall.length - maxGap; + return wall.length - maxGap; }; diff --git a/javascript/0572-subtree-of-another-tree.js b/javascript/0572-subtree-of-another-tree.js index 3bb99eb13..1461279be 100644 --- a/javascript/0572-subtree-of-another-tree.js +++ b/javascript/0572-subtree-of-another-tree.js @@ -5,93 +5,93 @@ * @return {boolean} */ var isSubtree = function (root, subRoot) { - if (!root) return false + if (!root) return false; - if (isSame(root, subRoot)) return true + if (isSame(root, subRoot)) return true; - const hasLeftTree = isSubtree(root.left, subRoot) - const hasRightTree = isSubtree(root.right, subRoot) + const hasLeftTree = isSubtree(root.left, subRoot); + const hasRightTree = isSubtree(root.right, subRoot); - return hasLeftTree || hasRightTree + return hasLeftTree || hasRightTree; }; const isSame = (root, subRoot) => { - const hasReachedEnd = !(root && subRoot) - if (hasReachedEnd) return root === subRoot + const hasReachedEnd = !(root && subRoot); + if (hasReachedEnd) return root === subRoot; const isMismatch = root.val !== subRoot.val; - if (isMismatch) return false + if (isMismatch) return false; - const isLeftSame = isSame(root.left, subRoot.left) - const isRightSame = isSame(root.right, subRoot.right) + const isLeftSame = isSame(root.left, subRoot.left); + const isRightSame = isSame(root.right, subRoot.right); - return isLeftSame && isRightSame -} + return isLeftSame && isRightSame; +}; const hash = (val) => - require('crypto').createHash('md5').update(val).digest('hex') + require('crypto').createHash('md5').update(val).digest('hex'); const merkle = (root) => { - if (!root) return '#' + if (!root) return '#'; - const { left, val, right } = root + const { left, val, right } = root; - const leftMerkle = merkle(left) - const rightMerkle = merkle(right) + const leftMerkle = merkle(left); + const rightMerkle = merkle(right); - const merkleVal = [leftMerkle, val, rightMerkle].join('') - const merkleHash = hash(merkleVal) + const merkleVal = [leftMerkle, val, rightMerkle].join(''); + const merkleHash = hash(merkleVal); - root.merkle = merkleHash + root.merkle = merkleHash; - return root.merkle -} + return root.merkle; +}; const search = (root, subRoot) => { - if (!root) return false + if (!root) return false; - const hasSamePath = root.merkle === subRoot.merkle - if (hasSamePath) return true + const hasSamePath = root.merkle === subRoot.merkle; + if (hasSamePath) return true; - const left = search(root.left, subRoot) - const right = search(root.right, subRoot) + const left = search(root.left, subRoot); + const right = search(root.right, subRoot); - return left || right -} + return left || right; +}; var isSubtree = function (root, subRoot) { - [root, subRoot].forEach(merkle) + [root, subRoot].forEach(merkle); - return search(root, subRoot) -} + return search(root, subRoot); +}; const hashify = (root, hash, postOrderKey) => { - if (!root) return '#' + if (!root) return '#'; - const left = hashify(root.left, hash, postOrderKey) - const right = hashify(root.right, hash, postOrderKey) + const left = hashify(root.left, hash, postOrderKey); + const right = hashify(root.right, hash, postOrderKey); - const key = [left, root.val, right].join('') + const key = [left, root.val, right].join(''); if (!hash.has(key)) { - hash.set(key, postOrderKey[0]) - postOrderKey[0]++ + hash.set(key, postOrderKey[0]); + postOrderKey[0]++; } - return hash.get(key) -} + return hash.get(key); +}; var isSubtree = function (root, subRoot, hash = new Map(), postOrderKey = [0]) { - hashify(root, hash, postOrderKey) + hashify(root, hash, postOrderKey); const hashKey = [ hashify(subRoot.left, hash, postOrderKey), subRoot.val, hashify(subRoot.right, hash, postOrderKey), - ].join('') + ].join(''); - return hash.has(hashKey) -} + return hash.has(hashKey); +}; /** * Definition for a binary tree node. @@ -109,30 +109,30 @@ var isSubtree = function (root, subRoot, hash = new Map(), postOrderKey = [0]) { */ var isSubtree = function (root, subRoot) { if (!subRoot) { - return true + return true; } else if (!root) { - return false + return false; } else if (isSameTree(root, subRoot)) { - return true + return true; } - const leftResult = isSubtree(root.left, subRoot) - const rightResult = isSubtree(root.right, subRoot) + const leftResult = isSubtree(root.left, subRoot); + const rightResult = isSubtree(root.right, subRoot); - return leftResult || rightResult -} + return leftResult || rightResult; +}; function isSameTree(root, subRoot) { if (!root && !subRoot) { - return true + return true; } else if (!root || !subRoot) { - return false + return false; } else if (root.val !== subRoot.val) { - return false + return false; } - const leftRes = isSameTree(root.left, subRoot.left) - const rightRes = isSameTree(root.right, subRoot.right) + const leftRes = isSameTree(root.left, subRoot.left); + const rightRes = isSameTree(root.right, subRoot.right); - return leftRes && rightRes + return leftRes && rightRes; } diff --git a/javascript/0605-can-place-flowers.js b/javascript/0605-can-place-flowers.js index e37490755..651dfb42e 100644 --- a/javascript/0605-can-place-flowers.js +++ b/javascript/0605-can-place-flowers.js @@ -8,16 +8,16 @@ */ var canPlaceFlowers = function (fb, n) { - if (n === 0) return true; + if (n === 0) return true; - for (let i = 0; i < fb.length; i++) { - if (fb[i] === 0) { - fb[i - 1] !== 1 && fb[i + 1] !== 1 && n-- && i++; - } else { - i++; - } - if (n === 0) return true; - } + for (let i = 0; i < fb.length; i++) { + if (fb[i] === 0) { + fb[i - 1] !== 1 && fb[i + 1] !== 1 && n-- && i++; + } else { + i++; + } + if (n === 0) return true; + } - return false; + return false; }; diff --git a/javascript/0606-construct-string-from-binary-tree.js b/javascript/0606-construct-string-from-binary-tree.js index ebee0cfd0..7978f80b3 100644 --- a/javascript/0606-construct-string-from-binary-tree.js +++ b/javascript/0606-construct-string-from-binary-tree.js @@ -1,5 +1,5 @@ /** - * InOrder Traversal + * InOrder Traversal * Time O(n) | Space O(n) * https://leetcode.com/problems/construct-string-from-binary-tree/ * Definition for a binary tree node. @@ -13,8 +13,8 @@ * @param {TreeNode} root * @return {string} */ -var tree2str = function(root) { - return dfs(root, []).join(""); +var tree2str = function (root) { + return dfs(root, []).join(''); }; const dfs = (node, strArr) => { @@ -22,14 +22,14 @@ const dfs = (node, strArr) => { strArr.push(node.val); - if (node.right || node.left) strArr.push("("); + if (node.right || node.left) strArr.push('('); dfs(node.left, strArr); - if (node.right || node.left) strArr.push(")"); + if (node.right || node.left) strArr.push(')'); // right tree - if (node.right) strArr.push("("); + if (node.right) strArr.push('('); dfs(node.right, strArr); - if (node.right) strArr.push(")"); + if (node.right) strArr.push(')'); return strArr; -} +}; diff --git a/javascript/0617-merge-two-binary-trees.js b/javascript/0617-merge-two-binary-trees.js index fc400d116..76d3709b0 100644 --- a/javascript/0617-merge-two-binary-trees.js +++ b/javascript/0617-merge-two-binary-trees.js @@ -2,19 +2,25 @@ * @param {TreeNode} root1 * @param {TreeNode} root2 * @return {TreeNode} - * Time complexity = O(n+m) + * Time complexity = O(n+m) */ - var mergeTrees = function(root1, root2) { +var mergeTrees = function (root1, root2) { // Base case to return null as result of having both root1, root2 null - if(!root1 && !root2) { + if (!root1 && !root2) { return null; } const val1 = root1 ? root1.val : 0; const val2 = root2 ? root2.val : 0; - - const root = new TreeNode(val1+val2); - root.left = mergeTrees(root1 ? root1.left : null, root2 ? root2.left: null); - root.right = mergeTrees(root1 ? root1.right : null , root2 ? root2.right: null); + + const root = new TreeNode(val1 + val2); + root.left = mergeTrees( + root1 ? root1.left : null, + root2 ? root2.left : null, + ); + root.right = mergeTrees( + root1 ? root1.right : null, + root2 ? root2.right : null, + ); return root; -}; \ No newline at end of file +}; diff --git a/javascript/0621-task-scheduler.js b/javascript/0621-task-scheduler.js index 4957acf26..f86ed2a6c 100644 --- a/javascript/0621-task-scheduler.js +++ b/javascript/0621-task-scheduler.js @@ -1,107 +1,121 @@ -/** - * https://leetcode.com/problems/task-scheduler/ - * Time O(N * log(N)) | Space O(N) - * @param {character[]} tasks - * @param {number} n - * @return {number} - */ -var leastInterval = function(tasks, n) { - const frequencyMap = getFrequencyMap(tasks) - const maxHeap = getMaxHeap(frequencyMap) - - return getMinimumCpuIntervals(maxHeap, n) -} - -var getFrequencyMap = (tasks, frequencyMap = new Array(26).fill(0)) => { - for (const task of tasks) { - const index = task.charCodeAt(0) - 'A'.charCodeAt(0); - - frequencyMap[index]++; - } - - return frequencyMap; -} - -const getMaxHeap = (frequencyMap, maxHeap = new MaxPriorityQueue()) => { - for (const frequency of frequencyMap) { - const hasFrequency = 0 < frequency; - if (hasFrequency) maxHeap.enqueue(frequency) - } - - return maxHeap -} - -const getMinimumCpuIntervals = (maxHeap, n, cpuIntervals = [ 0 ]) => { - while (!maxHeap.isEmpty()) { - const { iterations, coolingPeriodQueue } = execute(n, maxHeap, cpuIntervals) - - reQueueCoolingPeriod(coolingPeriodQueue, maxHeap) - - if (!maxHeap.isEmpty()) cpuIntervals[0] += iterations - } - - return cpuIntervals[0] -} - -const execute = (n, maxHeap, cpuIntervals, iterations = (n + 1), coolingPeriodQueue = new Queue()) => { - while ((0 < iterations) && !maxHeap.isEmpty()) { - const frequency = maxHeap.dequeue().element; - - const hasFrequency = 0 < (frequency - 1); - if (hasFrequency) coolingPeriodQueue.enqueue(frequency - 1); - - cpuIntervals[0]++; - iterations--; - } - - return { iterations, coolingPeriodQueue }; -} - -const reQueueCoolingPeriod = (coolingPeriodQueue, maxHeap) => { - while (!coolingPeriodQueue.isEmpty()) { - maxHeap.enqueue(coolingPeriodQueue.dequeue()) - } -} - -/** - * https://leetcode.com/problems/task-scheduler/ - * Time O(N) | Space O(1) - * @param {character[]} tasks - * @param {number} n - * @return {number} - */ - var leastInterval = function(tasks, n) { - const frequencyMap = getFrequencyMap(tasks); - const maxFrequency = getMaxFrequency(frequencyMap); - const mostFrequentTask = getMostFrequentTask(frequencyMap, maxFrequency); - const interval = ((maxFrequency - 1) * (n + 1)) + mostFrequentTask; - - return Math.max(tasks.length, interval); -} - -var getFrequencyMap = (tasks, frequencyMap = new Array(26).fill(0)) => { - for (const task of tasks) { - const index = task.charCodeAt(0) - 'A'.charCodeAt(0); - - frequencyMap[index]++; - } - - return frequencyMap; -} - -const getMaxFrequency = (frequencyMap, maxFrequency = 0) => { - for (const frequency of frequencyMap) { - maxFrequency = Math.max(maxFrequency, frequency); - } - - return maxFrequency; -} - -const getMostFrequentTask = (frequencyMap, maxFrequency, mostFrequentTask = 0) => { - for (const frequency of frequencyMap) { - const isSame = frequency === maxFrequency; - if (isSame) mostFrequentTask++; - } - - return mostFrequentTask; -} +/** + * https://leetcode.com/problems/task-scheduler/ + * Time O(N * log(N)) | Space O(N) + * @param {character[]} tasks + * @param {number} n + * @return {number} + */ +var leastInterval = function (tasks, n) { + const frequencyMap = getFrequencyMap(tasks); + const maxHeap = getMaxHeap(frequencyMap); + + return getMinimumCpuIntervals(maxHeap, n); +}; + +var getFrequencyMap = (tasks, frequencyMap = new Array(26).fill(0)) => { + for (const task of tasks) { + const index = task.charCodeAt(0) - 'A'.charCodeAt(0); + + frequencyMap[index]++; + } + + return frequencyMap; +}; + +const getMaxHeap = (frequencyMap, maxHeap = new MaxPriorityQueue()) => { + for (const frequency of frequencyMap) { + const hasFrequency = 0 < frequency; + if (hasFrequency) maxHeap.enqueue(frequency); + } + + return maxHeap; +}; + +const getMinimumCpuIntervals = (maxHeap, n, cpuIntervals = [0]) => { + while (!maxHeap.isEmpty()) { + const { iterations, coolingPeriodQueue } = execute( + n, + maxHeap, + cpuIntervals, + ); + + reQueueCoolingPeriod(coolingPeriodQueue, maxHeap); + + if (!maxHeap.isEmpty()) cpuIntervals[0] += iterations; + } + + return cpuIntervals[0]; +}; + +const execute = ( + n, + maxHeap, + cpuIntervals, + iterations = n + 1, + coolingPeriodQueue = new Queue(), +) => { + while (0 < iterations && !maxHeap.isEmpty()) { + const frequency = maxHeap.dequeue().element; + + const hasFrequency = 0 < frequency - 1; + if (hasFrequency) coolingPeriodQueue.enqueue(frequency - 1); + + cpuIntervals[0]++; + iterations--; + } + + return { iterations, coolingPeriodQueue }; +}; + +const reQueueCoolingPeriod = (coolingPeriodQueue, maxHeap) => { + while (!coolingPeriodQueue.isEmpty()) { + maxHeap.enqueue(coolingPeriodQueue.dequeue()); + } +}; + +/** + * https://leetcode.com/problems/task-scheduler/ + * Time O(N) | Space O(1) + * @param {character[]} tasks + * @param {number} n + * @return {number} + */ +var leastInterval = function (tasks, n) { + const frequencyMap = getFrequencyMap(tasks); + const maxFrequency = getMaxFrequency(frequencyMap); + const mostFrequentTask = getMostFrequentTask(frequencyMap, maxFrequency); + const interval = (maxFrequency - 1) * (n + 1) + mostFrequentTask; + + return Math.max(tasks.length, interval); +}; + +var getFrequencyMap = (tasks, frequencyMap = new Array(26).fill(0)) => { + for (const task of tasks) { + const index = task.charCodeAt(0) - 'A'.charCodeAt(0); + + frequencyMap[index]++; + } + + return frequencyMap; +}; + +const getMaxFrequency = (frequencyMap, maxFrequency = 0) => { + for (const frequency of frequencyMap) { + maxFrequency = Math.max(maxFrequency, frequency); + } + + return maxFrequency; +}; + +const getMostFrequentTask = ( + frequencyMap, + maxFrequency, + mostFrequentTask = 0, +) => { + for (const frequency of frequencyMap) { + const isSame = frequency === maxFrequency; + if (isSame) mostFrequentTask++; + } + + return mostFrequentTask; +}; diff --git a/javascript/0647-palindromic-substrings.js b/javascript/0647-palindromic-substrings.js index 87a3b220c..7c279454c 100644 --- a/javascript/0647-palindromic-substrings.js +++ b/javascript/0647-palindromic-substrings.js @@ -6,25 +6,29 @@ * @return {number} */ var countSubstrings = (s, count = 0) => { - for (let left = 0; (left < s.length); left++) { /* Time O(N) */ - for (let right = left; (right < s.length); right++) {/* Time O(N) */ - count += Number(isPalindrome(s, left, right)); /* Time O(N) */ + for (let left = 0; left < s.length; left++) { + /* Time O(N) */ + for (let right = left; right < s.length; right++) { + /* Time O(N) */ + count += Number(isPalindrome(s, left, right)); /* Time O(N) */ } } return count; -} +}; const isPalindrome = (s, left, right) => { - while (left < right) {/* Time O(N) */ - const isEqual = (s[left] === s[right]); + while (left < right) { + /* Time O(N) */ + const isEqual = s[left] === s[right]; if (!isEqual) return false; - left++; right--; + left++; + right--; } return true; -} +}; /** * DP - Bottom Up @@ -36,63 +40,70 @@ const isPalindrome = (s, left, right) => { * @return {number} */ var countSubstrings = (s, count = 0) => { - const tabu = initTabu(s); /* Time O(N * N) | Space O(N * N) */ + const tabu = initTabu(s); /* Time O(N * N) | Space O(N * N) */ - count += singleLetters(s, tabu);/* Time O(N) | Space O(N * N) */ - count += doubleLetters(s, tabu);/* Time O(N) | Space O(N * N) */ + count += singleLetters(s, tabu); /* Time O(N) | Space O(N * N) */ + count += doubleLetters(s, tabu); /* Time O(N) | Space O(N * N) */ count += multiLetters(s, tabu); /* Time O(N * N) | Space O(N * N) */ return count; }; -const initTabu = (s) => new Array(s.length).fill()/* Space O(N) */ - .map(() => new Array(s.length).fill(false)); /* Space O(N) */ +const initTabu = (s) => + new Array(s.length) + .fill() /* Space O(N) */ + .map(() => new Array(s.length).fill(false)); /* Space O(N) */ const singleLetters = (s, tabu, count = 0) => { - for (let index = 0; (index < s.length); index++) {/* Time O(N) */ - tabu[index][index] = true; /* Space O(N * N) */ + for (let index = 0; index < s.length; index++) { + /* Time O(N) */ + tabu[index][index] = true; /* Space O(N * N) */ count += Number(tabu[index][index]); } return count; -} +}; const doubleLetters = (s, tabu, count = 0) => { - for (let curr = 0; curr < (s.length - 1); curr++) {/* Time O(N) */ - const next = (curr + 1); - const isEqual = (s[curr] === s[next]); + for (let curr = 0; curr < s.length - 1; curr++) { + /* Time O(N) */ + const next = curr + 1; + const isEqual = s[curr] === s[next]; - tabu[curr][next] = isEqual; /* Space O(N * N) */ + tabu[curr][next] = isEqual; /* Space O(N * N) */ count += Number(tabu[curr][next]); } return count; -} +}; const multiLetters = (s, tabu, count = 0) => { - for (let window = 3; (window <= s.length); window++) {/* Time O(N) */ - count += slideWindow(s, tabu, window); /* Time O(N) | Space O(N * N) */ + for (let window = 3; window <= s.length; window++) { + /* Time O(N) */ + count += slideWindow(s, tabu, window); /* Time O(N) | Space O(N * N) */ } return count; -} +}; const slideWindow = (s, tabu, window, count = 0) => { - let [ left, right ] = [ 0, (window - 1) ]; + let [left, right] = [0, window - 1]; - while (right < s.length) {/* Time O(N) */ - const isTrue = tabu[(left + 1)][(right - 1)]; - const isEqual = (s[left] === s[right]); + while (right < s.length) { + /* Time O(N) */ + const isTrue = tabu[left + 1][right - 1]; + const isEqual = s[left] === s[right]; - tabu[left][right] = (isTrue && isEqual);/* Space O(N * N) */ + tabu[left][right] = isTrue && isEqual; /* Space O(N * N) */ count += Number(tabu[left][right]); - left++; right++; + left++; + right++; } return count; -} +}; /** * 2 Pointer - Expand Around Center @@ -102,27 +113,30 @@ const slideWindow = (s, tabu, window, count = 0) => { * @return {number} */ var countSubstrings = (s, count = 0) => { - for (let i = 0; (i < s.length); i++) {/* Time O(N) */ - const [ odd, even ] = [ i, (i + 1) ]; + for (let i = 0; i < s.length; i++) { + /* Time O(N) */ + const [odd, even] = [i, i + 1]; /* odd-length: single character center */ count += isPalindromeFromCenter(s, i, odd); /* Time O(N) */ /* even-length: consecutive characters center */ - count += isPalindromeFromCenter(s, i, even);/* Time O(N) */ + count += isPalindromeFromCenter(s, i, even); /* Time O(N) */ } return count; -} +}; const isPalindromeFromCenter = (s, left, right, count = 0) => { - const isInBounds = () => ((0 <= left) && (right < s.length)); - while (isInBounds()) {/* Time O(N) */ - const isEqual = (s[left] === s[right]); + const isInBounds = () => 0 <= left && right < s.length; + while (isInBounds()) { + /* Time O(N) */ + const isEqual = s[left] === s[right]; if (!isEqual) break; count++; - left--; right++; + left--; + right++; } return count; -} \ No newline at end of file +}; diff --git a/javascript/0652-find-duplicate-subtrees.js b/javascript/0652-find-duplicate-subtrees.js index cb0dc0597..bb964366c 100644 --- a/javascript/0652-find-duplicate-subtrees.js +++ b/javascript/0652-find-duplicate-subtrees.js @@ -7,45 +7,44 @@ * } */ /** - * Hashing + * Hashing * Time O(n^2) | Space O(n^2) * https://leetcode.com/problems/find-duplicate-subtrees/ * @param {TreeNode} root * @return {TreeNode[]} */ -var findDuplicateSubtrees = function(root) { - +var findDuplicateSubtrees = function (root) { const stringHash = {}; const makePreOrderStr = (node, str) => { - if(!node) return str + "-" + "null"; - - const str1 = makePreOrderStr(node.left, str + "-" + node.val); + if (!node) return str + '-' + 'null'; + + const str1 = makePreOrderStr(node.left, str + '-' + node.val); const str2 = makePreOrderStr(node.right, str1); return str2; - } + }; const duplicates = []; const dfs = (node) => { - if(!node) return; - const str = makePreOrderStr(node, ""); + if (!node) return; + const str = makePreOrderStr(node, ''); - if(!stringHash[str]) { + if (!stringHash[str]) { stringHash[str] = []; } - + stringHash[str].push(node); dfs(node.left); dfs(node.right); - } + }; dfs(root); - + for (let key in stringHash) { - if(stringHash[key].length > 1) duplicates.push(stringHash[key][0]); + if (stringHash[key].length > 1) duplicates.push(stringHash[key][0]); } return duplicates; diff --git a/javascript/0669-trim-a-binary-search-tree.js b/javascript/0669-trim-a-binary-search-tree.js index ef6973c19..e8bc7567b 100644 --- a/javascript/0669-trim-a-binary-search-tree.js +++ b/javascript/0669-trim-a-binary-search-tree.js @@ -1,33 +1,32 @@ -/** - * Definition for a binary tree node. - * function TreeNode(val, left, right) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - */ -/** - * @param {TreeNode} root - * @param {number} low - * @param {number} high - * @return {TreeNode} - */ -var trimBST = function (root, low, high) { - - if (!root) { - return null; - } - - if (root.val < low) { - return trimBST(root.right, low, high); - } - - if (root.val > high) { - return trimBST(root.left, low, high); - } - - root.left = trimBST(root.left, low, high); - root.right = trimBST(root.right, low, high); - - return root; -}; \ No newline at end of file +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {number} low + * @param {number} high + * @return {TreeNode} + */ +var trimBST = function (root, low, high) { + if (!root) { + return null; + } + + if (root.val < low) { + return trimBST(root.right, low, high); + } + + if (root.val > high) { + return trimBST(root.left, low, high); + } + + root.left = trimBST(root.left, low, high); + root.right = trimBST(root.right, low, high); + + return root; +}; diff --git a/javascript/0678-valid-parenthesis-string.js b/javascript/0678-valid-parenthesis-string.js index c7cb6a3b0..f569c4ea7 100644 --- a/javascript/0678-valid-parenthesis-string.js +++ b/javascript/0678-valid-parenthesis-string.js @@ -36,77 +36,83 @@ var checkValidString = function (s) { * @param {string} s * @return {boolean} */ - var checkValidString = function(s) { +var checkValidString = function (s) { const isBaseCase = s.length === 0; if (isBaseCase) return true; - const dp = new Array(s.length).fill() + const dp = new Array(s.length) + .fill() .map(() => new Array(s.length).fill(false)); - for (let i = 0; i < s.length; i++) {/* Time O(N) */ + for (let i = 0; i < s.length; i++) { + /* Time O(N) */ if (isStar(s[i])) dp[i][i] = true; - - const isInBound = i < (s.length - 1) - const isOpenedOrStar = isOpened(s[i]) || isStar(s[i]) - const isClosedOrStar = isClosed(s[i + 1]) || isStar(s[i + 1]) - - const isValid = isInBound && isOpenedOrStar && isClosedOrStar - if (isValid) dp[i][i + 1] = true;/* Space O(N^2) */ + + const isInBound = i < s.length - 1; + const isOpenedOrStar = isOpened(s[i]) || isStar(s[i]); + const isClosedOrStar = isClosed(s[i + 1]) || isStar(s[i + 1]); + + const isValid = isInBound && isOpenedOrStar && isClosedOrStar; + if (isValid) dp[i][i + 1] = true; /* Space O(N^2) */ } - for (let size = 2; size < s.length; size++) {/* Time O() */ - for (let i = 0; i + size < s.length; i++) {/* Time O(N) */ - const isStarOrDP = isStar(s[i]) && isDP(dp, (i + 1), (i + size)) - if (isStarOrDP) { dp[i][i + size] = true; continue; } - - const isOpenedOrStar = isOpened(s[i]) || isStar(s[i]) + for (let size = 2; size < s.length; size++) { + /* Time O() */ + for (let i = 0; i + size < s.length; i++) { + /* Time O(N) */ + const isStarOrDP = isStar(s[i]) && isDP(dp, i + 1, i + size); + if (isStarOrDP) { + dp[i][i + size] = true; + continue; + } + + const isOpenedOrStar = isOpened(s[i]) || isStar(s[i]); if (isOpenedOrStar) check(dp, size, i); /* Time O(N) */ } } - + return dp[0][s.length - 1]; -} +}; -const check = (dp, size, i) => { - for (let k = (i + 1); k <= (i + size); k++) {/* Time O(N) */ - const isClosedOrStar = isClosed(s[k]) || isStar(s[k]) - const isKOrDP = isKEqual(k, i, 1) || isDP(dp, (i + 1), (k - 1)) - const isKOrDPSize = isKEqual(k, i, size) || isDP(dp, (k + 1), (i + size)) +const check = (dp, size, i) => { + for (let k = i + 1; k <= i + size; k++) { + /* Time O(N) */ + const isClosedOrStar = isClosed(s[k]) || isStar(s[k]); + const isKOrDP = isKEqual(k, i, 1) || isDP(dp, i + 1, k - 1); + const isKOrDPSize = isKEqual(k, i, size) || isDP(dp, k + 1, i + size); - const isValid = isClosedOrStar && isKOrDP && isKOrDPSize - if (isValid) dp[i][i + size] = true;/* Space O(N^2) */ + const isValid = isClosedOrStar && isKOrDP && isKOrDPSize; + if (isValid) dp[i][i + size] = true; /* Space O(N^2) */ } -} - -var isStar = (char) => char === '*' -var isOpened = (char) => char === '(' -var isClosed = (char) => char === ')' -const isKEqual = (k, i, size) => k === (i + size) -const isDP = (dp, i, k) => dp[i][k] +}; +var isStar = (char) => char === '*'; +var isOpened = (char) => char === '('; +var isClosed = (char) => char === ')'; +const isKEqual = (k, i, size) => k === i + size; +const isDP = (dp, i, k) => dp[i][k]; /** * Time O(N) | Space O(1) * @param {string} s * @return {boolean} */ -var checkValidString = function(s) { - let [ left, right ] = [ 0, 0 ]; +var checkValidString = function (s) { + let [left, right] = [0, 0]; - for (const char of s) {/* Time O(N) */ - left += isOpened(char) ? 1 : -1; - right += !isClosed(char) ? 1 : -1; - - const isNegative = right < 0; - if (isNegative) break; + for (const char of s) { + /* Time O(N) */ + left += isOpened(char) ? 1 : -1; + right += !isClosed(char) ? 1 : -1; - left = Math.max(left, 0); - } - - return left === 0; -} + const isNegative = right < 0; + if (isNegative) break; -var isOpened = (char) => char === '(' -var isClosed = (char) => char === ')' + left = Math.max(left, 0); + } + return left === 0; +}; +var isOpened = (char) => char === '('; +var isClosed = (char) => char === ')'; diff --git a/javascript/0682-baseball-game.js b/javascript/0682-baseball-game.js index 7df3428fb..9a93ac183 100644 --- a/javascript/0682-baseball-game.js +++ b/javascript/0682-baseball-game.js @@ -2,21 +2,21 @@ * @param {string[]} operations * @return {number} */ -var calPoints = function(operations) { +var calPoints = function (operations) { let runningSum = 0; const stack = []; - for(const o of operations) { - if(o === 'C') { + for (const o of operations) { + if (o === 'C') { runningSum -= stack.pop(); continue; } - if(o === 'D') { + if (o === 'D') { const val = stack[stack.length - 1] * 2; stack.push(val); runningSum += val; continue; } - if(o === '+') { + if (o === '+') { const val = stack[stack.length - 1] + stack[stack.length - 2]; stack.push(val); runningSum += val; diff --git a/javascript/0684-redundant-connection.js b/javascript/0684-redundant-connection.js index 61771b9b0..4c0ab4c7b 100644 --- a/javascript/0684-redundant-connection.js +++ b/javascript/0684-redundant-connection.js @@ -5,26 +5,27 @@ * @return {number[]} */ var findRedundantConnection = function (edges) { - const graph = new Array((1000 + 1)).fill().map(() => []); + const graph = new Array(1000 + 1).fill().map(() => []); - for (const [ src, dst ] of edges) { - const hasNodes = (src in graph) && (dst in graph) - if (hasNodes && hasRedundantConnection(graph, src, dst)) return [ src, dst ]; + for (const [src, dst] of edges) { + const hasNodes = src in graph && dst in graph; + if (hasNodes && hasRedundantConnection(graph, src, dst)) + return [src, dst]; graph[src].push(dst); graph[dst].push(src); } -} +}; const hasRedundantConnection = (graph, source, target, seen = new Set()) => { - if (seen.has(source)) return false + if (seen.has(source)) return false; seen.add(source); - const isEqual = source === target + const isEqual = source === target; if (isEqual) return true; return dfs(graph, source, target, seen); -} +}; const dfs = (graph, source, target, seen) => { for (const neighbor of graph[source]) { @@ -32,7 +33,7 @@ const dfs = (graph, source, target, seen) => { } return false; -} +}; /** * https://leetcode.com/problems/redundant-connection/ @@ -41,27 +42,28 @@ const dfs = (graph, source, target, seen) => { * @return {number[]} */ var findRedundantConnection = function (edges) { - return new UnionFind(edges) - .redundantConnection; + return new UnionFind(edges).redundantConnection; }; class UnionFind { - constructor (edges) { - this.parent = new Array(edges.length + 1).fill().map((_, index) => index); + constructor(edges) { + this.parent = new Array(edges.length + 1) + .fill() + .map((_, index) => index); this.rank = new Array(edges.length + 1).fill(1); - this.redundantConnection = [ -1, -1 ]; + this.redundantConnection = [-1, -1]; this.search(edges); } - search (edges) { - for (let [ src, dst ] of edges) { + search(edges) { + for (let [src, dst] of edges) { const hasConnection = this.union(src, dst); - if (!hasConnection) return (this.redundantConnection = [ src, dst ]); + if (!hasConnection) return (this.redundantConnection = [src, dst]); } } - find (node, { parent } = this) { + find(node, { parent } = this) { let head = parent[node]; const isEqual = () => head === parent[head]; @@ -75,30 +77,30 @@ class UnionFind { return head; } - compress (tail, head, { parent } = this) { + compress(tail, head, { parent } = this) { parent[tail] = head; } - - increaseRank (head, tail, { rank } = this) { + + increaseRank(head, tail, { rank } = this) { rank[head] += rank[tail]; } - union (src, dst, { rank } = this) { - const [ rootSrc, rootDst ] = [ this.find(src), this.find(dst) ]; + union(src, dst, { rank } = this) { + const [rootSrc, rootDst] = [this.find(src), this.find(dst)]; const hasCycle = rootSrc === rootDst; if (hasCycle) return false; const isSrcGreater = rank[rootDst] < rank[rootSrc]; if (isSrcGreater) { - this.increaseRank(rootDst, rootSrc) - this.compress(rootSrc, rootDst) + this.increaseRank(rootDst, rootSrc); + this.compress(rootSrc, rootDst); } const isDstGreater = rank[rootSrc] <= rank[rootDst]; if (isDstGreater) { - this.increaseRank(rootSrc, rootDst) - this.compress(rootDst, rootSrc) + this.increaseRank(rootSrc, rootDst); + this.compress(rootDst, rootSrc); } return true; diff --git a/javascript/0695-max-area-of-island.js b/javascript/0695-max-area-of-island.js index 56d3aab38..feb7f10cf 100644 --- a/javascript/0695-max-area-of-island.js +++ b/javascript/0695-max-area-of-island.js @@ -4,13 +4,22 @@ * @param {number[][]} grid * @return {number} */ - var maxAreaOfIsland = function(grid, maxArea = 0) { - const [ rows, cols ] = [ grid.length, grid[0].length ]; +var maxAreaOfIsland = function (grid, maxArea = 0) { + const [rows, cols] = [grid.length, grid[0].length]; const seen = new Array(rows).fill().map(() => new Array(cols)); - for (let row = 0; row < rows; row++) {/* Time O(ROWS) */ - for (let col = 0; col < cols; col++) {/* Time O(COLS) */ - const area = getArea(grid, row, rows, col, cols, seen);/* Space O(ROWS * COLS) */ + for (let row = 0; row < rows; row++) { + /* Time O(ROWS) */ + for (let col = 0; col < cols; col++) { + /* Time O(COLS) */ + const area = getArea( + grid, + row, + rows, + col, + cols, + seen, + ); /* Space O(ROWS * COLS) */ maxArea = Math.max(maxArea, area); } @@ -24,65 +33,81 @@ var getArea = (grid, row, rows, col, cols, seen) => { if (isBaseCase) return 0; if (seen[row][col]) return 0; - seen[row][col] = true; /* Space O(ROWS * COLS) */ + seen[row][col] = true; /* Space O(ROWS * COLS) */ - return dfs(grid, row, rows, col, cols, seen) + 1; /* Space O(ROWS * COLS) */ -} + return dfs(grid, row, rows, col, cols, seen) + 1; /* Space O(ROWS * COLS) */ +}; const dfs = (grid, row, rows, col, cols, seen, area = 0) => { - for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) { + for (const [_row, _col] of getNeighbors(row, rows, col, cols)) { area += getArea(grid, _row, rows, _col, cols, seen); } - return area -} + return area; +}; -var getNeighbors = (row, rows, col, cols) => [[ 0, 1 ], [ 0, -1 ], [ 1, 0 ], [ -1, 0 ]] - .map(([ _row, _col]) => [ (row + _row), (col + _col) ]) - .filter(([ _row, _col ]) => (0 <= _row) && (_row < rows) && (0 <= _col) && (_col < cols)) +var getNeighbors = (row, rows, col, cols) => + [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ] + .map(([_row, _col]) => [row + _row, col + _col]) + .filter( + ([_row, _col]) => + 0 <= _row && _row < rows && 0 <= _col && _col < cols, + ); - /** +/** * https://leetcode.com/problems/number-of-islands/ * Time O(ROWS * COLS) | Space O(ROWS * COLS) * @param {character[][]} grid * @return {number} */ var maxAreaOfIsland = (grid, maxArea = 0) => { - const [ rows, cols ] = [ grid.length, grid[0].length ] + const [rows, cols] = [grid.length, grid[0].length]; const seen = new Array(rows).fill().map(() => new Array(cols)); - for (let row = 0; row < rows; row++) {/* Time O(ROWS) */ - for (let col = 0; col < cols; col++) {/* Time O(COLS) */ - const isBaseCase = grid[row][col] === 0 + for (let row = 0; row < rows; row++) { + /* Time O(ROWS) */ + for (let col = 0; col < cols; col++) { + /* Time O(COLS) */ + const isBaseCase = grid[row][col] === 0; if (isBaseCase) continue; if (seen[row][col]) continue; - seen[row][col] = true; /* Space O(ROWS * COLS) */ + seen[row][col] = true; /* Space O(ROWS * COLS) */ - const area = getArea(new Queue([[ row, col ]]), grid, seen);/* Space O(ROWS * COLS) */ + const area = getArea( + new Queue([[row, col]]), + grid, + seen, + ); /* Space O(ROWS * COLS) */ maxArea = Math.max(maxArea, area); } } - return maxArea -} + return maxArea; +}; var getArea = (queue, grid, seen, area = 0) => { - const [ rows, cols ] = [ grid.length, grid[0].length ]; + const [rows, cols] = [grid.length, grid[0].length]; while (!queue.isEmpty()) { - for (let i = (queue.size() - 1); 0 <= i; i--) {/* Time O(WIDTH) */ - const [ row, col ] = queue.dequeue(); + for (let i = queue.size() - 1; 0 <= i; i--) { + /* Time O(WIDTH) */ + const [row, col] = queue.dequeue(); - for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) { + for (const [_row, _col] of getNeighbors(row, rows, col, cols)) { const isBaseCase = grid[_row][_col] === 0; if (isBaseCase) continue; if (seen[_row][_col]) continue; - seen[_row][_col] = true; /* Space O(ROWS * COLS) */ - - queue.enqueue([ _row, _col ]); /* Space O(HEIGHT) */ + seen[_row][_col] = true; /* Space O(ROWS * COLS) */ + + queue.enqueue([_row, _col]); /* Space O(HEIGHT) */ } area++; @@ -90,8 +115,17 @@ var getArea = (queue, grid, seen, area = 0) => { } return area; -} +}; -var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ], [ 0, -1 ], [ 1, 0 ], [ -1, 0 ] ] - .map(([ _row, _col]) => [ (row + _row), (col + _col) ]) - .filter(([ _row, _col ]) => (0 <= _row) && (_row < rows) && (0 <= _col) && (_col < cols)) \ No newline at end of file +var getNeighbors = (row, rows, col, cols) => + [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ] + .map(([_row, _col]) => [row + _row, col + _col]) + .filter( + ([_row, _col]) => + 0 <= _row && _row < rows && 0 <= _col && _col < cols, + ); diff --git a/javascript/0701-insert-into-a-binary-search-tree.js b/javascript/0701-insert-into-a-binary-search-tree.js index 0ab181e89..f10454079 100644 --- a/javascript/0701-insert-into-a-binary-search-tree.js +++ b/javascript/0701-insert-into-a-binary-search-tree.js @@ -13,7 +13,7 @@ * @param {number} val * @return {TreeNode} */ -var insertIntoBST = function(root, val) { +var insertIntoBST = function (root, val) { return dfs(root, val); }; @@ -27,4 +27,4 @@ const dfs = (root, val) => { } root.left = dfs(root.left, val); return root; -} +}; diff --git a/javascript/0703-kth-largest-element-in-a-stream.js b/javascript/0703-kth-largest-element-in-a-stream.js index 2a500dcce..bf6d59a32 100644 --- a/javascript/0703-kth-largest-element-in-a-stream.js +++ b/javascript/0703-kth-largest-element-in-a-stream.js @@ -1,21 +1,21 @@ -/** +/** * https://leetcode.com/problems/kth-largest-element-in-a-stream/ * Time O(N * (K * log(K))) | Space O(K) * Your KthLargest object will be instantiated and called as such: * var obj = new KthLargest(k, nums) * var param_1 = obj.add(val) */ - class KthLargest { +class KthLargest { /** * @param {number} k * @param {number[]} nums * @constructor */ constructor(k, nums) { - this.k = k + this.k = k; this.minHeap = new MinPriorityQueue(); - nums.forEach((num) => this.add(num)) + nums.forEach((num) => this.add(num)); } /** @@ -26,21 +26,20 @@ const isUnderCapacity = minHeap.size() < this.k; if (isUnderCapacity) { minHeap.enqueue(val); - + return this.top(); } const isLarger = this.top() < val; if (isLarger) { - minHeap.dequeue() + minHeap.dequeue(); minHeap.enqueue(val); } - + return this.top(); } - top ({ minHeap } = this) { - return minHeap.front()?.element || 0 + top({ minHeap } = this) { + return minHeap.front()?.element || 0; } } - diff --git a/javascript/0705-design-hashset.js b/javascript/0705-design-hashset.js index 275b5d59f..43f6e42d1 100644 --- a/javascript/0705-design-hashset.js +++ b/javascript/0705-design-hashset.js @@ -4,7 +4,7 @@ class MyHashSet { this.set = []; } - /** + /** * Time O(1) | Space O(1) * @param {number} key * @return {void} @@ -13,7 +13,7 @@ class MyHashSet { this.set[key] = key; } - /** + /** * Time O(1) | Space O(1) * @param {number} key * @return {void} @@ -22,7 +22,7 @@ class MyHashSet { this.set[key] = undefined; } - /** + /** * Time O(1) | Space O(1) * @param {number} key * @return {boolean} @@ -32,7 +32,7 @@ class MyHashSet { } } -/** +/** * Your MyHashSet object will be instantiated and called as such: * var obj = new MyHashSet() * obj.add(key) diff --git a/javascript/0739-daily-temperatures.js b/javascript/0739-daily-temperatures.js index f89955b56..3134da9d5 100644 --- a/javascript/0739-daily-temperatures.js +++ b/javascript/0739-daily-temperatures.js @@ -4,18 +4,18 @@ * @param {number[]} temperatures * @return {number[]} */ -var dailyTemperatures = function(temp) { - let res = new Array(temp.length).fill(0) - let stack = [] +var dailyTemperatures = function (temp) { + let res = new Array(temp.length).fill(0); + let stack = []; - for (let i = 0; i < temp.length; i++){ - while (stack.length && temp[i] > temp[stack[stack.length - 1]]){ - let idx = stack.pop() - res[idx] = i - idx + for (let i = 0; i < temp.length; i++) { + while (stack.length && temp[i] > temp[stack[stack.length - 1]]) { + let idx = stack.pop(); + res[idx] = i - idx; } - stack.push(i) + stack.push(i); } - return res + return res; }; /** @@ -24,18 +24,20 @@ var dailyTemperatures = function(temp) { * @param {number[]} temperatures * @return {number[]} */ -var dailyTemperatures = function(temperatures, stack = []) { +var dailyTemperatures = function (temperatures, stack = []) { const days = Array(temperatures.length).fill(0); - for (let day = 0; day < temperatures.length; day++) {/* Time O(N + N) */ - while (canShrink(stack, temperatures, day)) { /* Time O(N + N) */ + for (let day = 0; day < temperatures.length; day++) { + /* Time O(N + N) */ + while (canShrink(stack, temperatures, day)) { + /* Time O(N + N) */ const prevColdDay = stack.pop(); - const daysToWait = (day - prevColdDay); + const daysToWait = day - prevColdDay; - days[prevColdDay] = daysToWait; /* Ignore Space O(N) */ + days[prevColdDay] = daysToWait; /* Ignore Space O(N) */ } - stack.push(day); /* Space O(N) */ + stack.push(day); /* Space O(N) */ } return days; @@ -43,11 +45,14 @@ var dailyTemperatures = function(temperatures, stack = []) { const canShrink = (stack, temperatures, day) => { const previousDay = stack[stack.length - 1]; - const [ prevTemperature, currTemperature ] = [ temperatures[previousDay], temperatures[day] ]; + const [prevTemperature, currTemperature] = [ + temperatures[previousDay], + temperatures[day], + ]; const isWarmer = prevTemperature < currTemperature; return stack.length && isWarmer; -} +}; /** * https://leetcode.com/problems/daily-temperatures @@ -55,27 +60,33 @@ const canShrink = (stack, temperatures, day) => { * @param {number[]} temperatures * @return {number[]} */ -var dailyTemperatures = function(temperatures, hottest = 0) { +var dailyTemperatures = function (temperatures, hottest = 0) { const days = new Array(temperatures.length).fill(0); - for (let day = (temperatures.length - 1); (0 <= day); day--) {/* Time O(N + N) */ + for (let day = temperatures.length - 1; 0 <= day; day--) { + /* Time O(N + N) */ const temperature = temperatures[day]; - const isHotter = hottest <= temperature + const isHotter = hottest <= temperature; if (isHotter) { hottest = temperature; - continue; /* Time O(N + N) */ + continue; /* Time O(N + N) */ } - search(temperatures, day, temperature, days); /* Time O(N + N) | Ignore Space O(N) */ + search( + temperatures, + day, + temperature, + days, + ); /* Time O(N + N) | Ignore Space O(N) */ } return days; -} +}; const search = (temperatures, day, temperature, days, dayCount = 1) => { const isHotter = () => temperatures[day + dayCount] <= temperature; - while (isHotter()) dayCount += days[day + dayCount]; /* Time O(N + N) */ + while (isHotter()) dayCount += days[day + dayCount]; /* Time O(N + N) */ - days[day] = dayCount; /* Ignore Space O(N) */ -} + days[day] = dayCount; /* Ignore Space O(N) */ +}; diff --git a/javascript/0743-network-delay-time.js b/javascript/0743-network-delay-time.js index 90be1ea0d..2c8bc6c6e 100644 --- a/javascript/0743-network-delay-time.js +++ b/javascript/0743-network-delay-time.js @@ -8,7 +8,7 @@ * @param {number} k * @return {number} */ - var networkDelayTime = (times, n, k) => { +var networkDelayTime = (times, n, k) => { const { graph, maxTime, queue } = buildGraph(times, n, k); bfs(queue, graph, maxTime, k); @@ -17,51 +17,51 @@ }; var initGraph = (n, k) => ({ - graph: Array.from({ length: n + 1}).fill().map(() => []), - maxTime: Array.from({ length: n + 1}).fill(Infinity), - queue: new Queue([[ k, 0 ]]) -}) + graph: Array.from({ length: n + 1 }) + .fill() + .map(() => []), + maxTime: Array.from({ length: n + 1 }).fill(Infinity), + queue: new Queue([[k, 0]]), +}); var buildGraph = (times, n, k) => { const { graph, maxTime, queue } = initGraph(n, k); - for (const [ src, dst, weight ] of times ) { - graph[src].push([ dst, weight ]); - }; + for (const [src, dst, weight] of times) { + graph[src].push([dst, weight]); + } maxTime[0] = 0; return { graph, maxTime, queue }; -} +}; var bfs = (queue, graph, maxTime) => { while (!queue.isEmpty()) { - for (let level = (queue.size() -1); (0 <= level); level-- ) { + for (let level = queue.size() - 1; 0 <= level; level--) { checkNeighbors(queue, graph, maxTime); } } -} +}; var checkNeighbors = (queue, graph, maxTime) => { - const [ node, time ] = queue.dequeue(); + const [node, time] = queue.dequeue(); - const canUpdate = (time < maxTime[node]); + const canUpdate = time < maxTime[node]; if (!canUpdate) return; maxTime[node] = time; - for (const [ dst, weight ] of graph[node]) { - queue.enqueue([ dst, (weight + time) ]); + for (const [dst, weight] of graph[node]) { + queue.enqueue([dst, weight + time]); } -} +}; var checkAns = (maxTime) => { const max = Math.max(...maxTime); - return (max < Infinity) - ? max - : (-1); -} + return max < Infinity ? max : -1; +}; /** * https://leetcode.com/problems/network-delay-time/ @@ -70,36 +70,36 @@ var checkAns = (maxTime) => { * @param {number} k * @return {number} */ - var networkDelayTime = (times, n, k) => { - const { graph, seen, minHeap } = buildGraph(times, n, k) +var networkDelayTime = (times, n, k) => { + const { graph, seen, minHeap } = buildGraph(times, n, k); const maxTime = getTime(graph, seen, minHeap); - return (seen.size === n) - ? maxTime - : -1; + return seen.size === n ? maxTime : -1; }; var initGraph = (n, k) => ({ - graph: Array.from({ length: n + 1}).fill().map(() => []), + graph: Array.from({ length: n + 1 }) + .fill() + .map(() => []), seen: new Set(), - minHeap: new MinPriorityQueue() -}) + minHeap: new MinPriorityQueue(), +}); var buildGraph = (times, n, k) => { const { graph, seen, minHeap } = initGraph(n, k); - for (const [ src, dst, weight ] of times ) { - graph[src].push([ dst, weight ]); - }; + for (const [src, dst, weight] of times) { + graph[src].push([dst, weight]); + } minHeap.enqueue([k, 0], 0); return { graph, seen, minHeap }; -} +}; const getTime = (graph, seen, minHeap, maxTime = 0) => { while (!minHeap.isEmpty()) { - const [ node, cost ] = minHeap.dequeue().element; + const [node, cost] = minHeap.dequeue().element; if (seen.has(node)) continue; seen.add(node); @@ -109,15 +109,15 @@ const getTime = (graph, seen, minHeap, maxTime = 0) => { } return maxTime; -} +}; var checkNeighbors = (graph, src, srcCost, seen, minHeap) => { - for (const [ dst, dstCost ] of graph[src]) { + for (const [dst, dstCost] of graph[src]) { if (seen.has(dst)) continue; - const cost = (dstCost + srcCost) - const node = [ dst, cost]; + const cost = dstCost + srcCost; + const node = [dst, cost]; minHeap.enqueue(node, cost); } -} \ No newline at end of file +}; diff --git a/javascript/0746-min-cost-climbing-stairs.js b/javascript/0746-min-cost-climbing-stairs.js index 5e67b88a3..a49acdeb3 100644 --- a/javascript/0746-min-cost-climbing-stairs.js +++ b/javascript/0746-min-cost-climbing-stairs.js @@ -10,16 +10,20 @@ var minCostClimbingStairs = (cost, i = cost.length, memo = new Map()) => { const isBaseCase = i <= 1; if (isBaseCase) return 0; - if (memo.has(i)) return memo.get(i);; + if (memo.has(i)) return memo.get(i); - const [ prev, prevPrev ] = [ (i - 1), (i - 2) ]; - const downOne = minCostClimbingStairs(cost, prev, memo) + cost[prev]; /* Time O(N) | Space O(N) */ - const downTwo = minCostClimbingStairs(cost, prevPrev, memo) + cost[prevPrev];/* Time O(N) | Space O(N) */ + const [prev, prevPrev] = [i - 1, i - 2]; + const downOne = + minCostClimbingStairs(cost, prev, memo) + + cost[prev]; /* Time O(N) | Space O(N) */ + const downTwo = + minCostClimbingStairs(cost, prevPrev, memo) + + cost[prevPrev]; /* Time O(N) | Space O(N) */ memo.set(i, Math.min(downOne, downTwo)); return memo.get(i); -} +}; /** * DP - Bottom Up @@ -29,11 +33,11 @@ var minCostClimbingStairs = (cost, i = cost.length, memo = new Map()) => { * @param {number[]} cost * @return {number} */ - var minCostClimbingStairs = (cost) => { +var minCostClimbingStairs = (cost) => { const tabu = new Array(cost.length + 1).fill(0); for (let i = 2; i < tabu.length; i++) { - const [ prev, prevPrev ] = [ (i - 1), (i - 2) ]; + const [prev, prevPrev] = [i - 1, i - 2]; const downOne = tabu[prev] + cost[prev]; const downTwo = tabu[prevPrev] + cost[prevPrev]; @@ -41,7 +45,7 @@ var minCostClimbingStairs = (cost, i = cost.length, memo = new Map()) => { } return tabu[tabu.length - 1]; -} +}; /** * DP - Bottom Up @@ -51,12 +55,13 @@ var minCostClimbingStairs = (cost, i = cost.length, memo = new Map()) => { * @return {number} */ var minCostClimbingStairs = (cost) => { - let [ downOne, downTwo ] = [ 0, 0 ]; + let [downOne, downTwo] = [0, 0]; - for (let i = 2; i < cost.length + 1; i++) {/* Time O(N) */ + for (let i = 2; i < cost.length + 1; i++) { + /* Time O(N) */ const temp = downOne; - const [ _prev, _prevPrev ] = [ (i - 1), (i - 2) ]; + const [_prev, _prevPrev] = [i - 1, i - 2]; const prev = downOne + cost[_prev]; const prevPrev = downTwo + cost[_prevPrev]; @@ -65,4 +70,4 @@ var minCostClimbingStairs = (cost) => { } return downOne; -} \ No newline at end of file +}; diff --git a/javascript/0752-open-the-lock.js b/javascript/0752-open-the-lock.js index 524470ff5..2b97a4f1a 100644 --- a/javascript/0752-open-the-lock.js +++ b/javascript/0752-open-the-lock.js @@ -3,18 +3,17 @@ * @param {string} target * @return {number} */ -var openLock = function(deadends, target) { - +var openLock = function (deadends, target) { // General approach: // Start at the end, mark that spot to be 0 away from target // Find all the valid neighbors through bfs, mark those as 1 // Find all _their_ valid neighbors, mark those as ++ etc // Until we find 0000. Whatever we mark that as is the number. BFS will guarantee it's the shortest path - + let q = [target]; // our BFS Queue - let mem = {}; // to keep track what we already have visited - mem[target] = 0; // starting distance of the end - + let mem = {}; // to keep track what we already have visited + mem[target] = 0; // starting distance of the end + // Helper function that given a position, will generate all the numbers we // can create in 1 move; let getNextPositions = function (pos) { @@ -23,7 +22,7 @@ var openLock = function(deadends, target) { let arr = pos.split(''); let positions = []; let i, j; - + for (j = 0; j < 2; j++) { let next = ''; // for each number in the position @@ -38,27 +37,27 @@ var openLock = function(deadends, target) { } } return positions; - } - + }; + while (q.length) { // dequeue a position to check out let pos = q.shift(); - + // if it's 0000 we're done. BFS guarantees it's the shortest possible if (pos === '0000') { return mem[pos]; } else { let next = getNextPositions(pos); - next.forEach(function(n) { + next.forEach(function (n) { // if we haven't seen n before, and it's not a dead end, if (mem[n] === undefined && !deadends.includes(n)) { - // mark the distance and enqueue to check out next - mem[n] = mem[pos] + 1; - q.push(n); + // mark the distance and enqueue to check out next + mem[n] = mem[pos] + 1; + q.push(n); } - }) - } + }); + } } // if we end up here, we couldn't find it return -1; -}; \ No newline at end of file +}; diff --git a/javascript/0763-partition-labels.js b/javascript/0763-partition-labels.js index b46b17d5c..5ce5b274b 100644 --- a/javascript/0763-partition-labels.js +++ b/javascript/0763-partition-labels.js @@ -31,39 +31,41 @@ var partitionLabels = function (s) { * @param {string} S * @return {number[]} */ - var partitionLabels = function(S) { +var partitionLabels = function (S) { const lastSeen = getLast(S); return getAns(S, lastSeen); }; const getLast = (S, lastSeen = []) => { - for (const index in S) {/* Time O(N) */ + for (const index in S) { + /* Time O(N) */ const code = getCode(S[Number(index)]); - - lastSeen[code] = Number(index);/* Space O(1) */ + + lastSeen[code] = Number(index); /* Space O(1) */ } return lastSeen; }; -const getCode = (char ) => char.charCodeAt(0) - 'a'.charCodeAt(0); +const getCode = (char) => char.charCodeAt(0) - 'a'.charCodeAt(0); const getAns = (S, lastSeen, left = 0, right = 0, labels = []) => { - for (const index in S) {/* Time O(N) */ + for (const index in S) { + /* Time O(N) */ const code = getCode(S[Number(index)]); const lastSeenAt = lastSeen[code]; - + right = Math.max(right, lastSeenAt); - + const isEqual = Number(index) === right; if (!isEqual) continue; - - const placement = (Number(index) - left) + 1; - + + const placement = Number(index) - left + 1; + labels.push(placement); - left = Number(index) + 1; - }; - + left = Number(index) + 1; + } + return labels; -} +}; diff --git a/javascript/0767-reorganize-string.js b/javascript/0767-reorganize-string.js index c4798c81d..91293418b 100644 --- a/javascript/0767-reorganize-string.js +++ b/javascript/0767-reorganize-string.js @@ -5,38 +5,35 @@ * @param {string} s * @return {string} */ -var reorganizeString = function(s) { - +var reorganizeString = function (s) { const maxQ = new MaxPriorityQueue({ compare: (a, b) => { - return b[0] - a[0]; - } + return b[0] - a[0]; + }, }); const freq = {}; for (let i = 0; i < s.length; i++) { const char = s[i]; - freq[char] = (freq[char] && freq[char] + 1 || 1); + freq[char] = (freq[char] && freq[char] + 1) || 1; } for (const key in freq) { const val = freq[key]; maxQ.enqueue([val, key]); } - let orgStr = ""; + let orgStr = ''; while (!maxQ.isEmpty()) { - const [occurance, char] = maxQ.dequeue(); if (orgStr[orgStr.length - 1] === char) { + if (maxQ.isEmpty()) return ''; - if (maxQ.isEmpty()) return ""; - - const [occurance1, char1] = maxQ.dequeue(); + const [occurance1, char1] = maxQ.dequeue(); orgStr += char1; if (occurance1 - 1) { maxQ.enqueue([occurance1 - 1, char1]); - } + } maxQ.enqueue([occurance, char]); } else { orgStr += char; diff --git a/javascript/0778-swim-in-rising-water.js b/javascript/0778-swim-in-rising-water.js index 1611766e6..c65cfbdcd 100644 --- a/javascript/0778-swim-in-rising-water.js +++ b/javascript/0778-swim-in-rising-water.js @@ -3,45 +3,53 @@ * @param {number[][]} grid * @return {number} */ - var swimInWater = (grid) => { +var swimInWater = (grid) => { const seen = new Set(); const minHeap = getHeap(grid); return getTime(grid, seen, minHeap); }; - const getHeap = (grid, minHeap = new MinPriorityQueue()) => { - minHeap.enqueue([ 0, 0 ], grid[0][0]); + minHeap.enqueue([0, 0], grid[0][0]); - return minHeap; -} + return minHeap; +}; var getTime = (grid, seen, minHeap, maxTime = 0) => { - const [ rows, cols ] = [ (grid.length - 1), (grid[0].length - 1) ]; + const [rows, cols] = [grid.length - 1, grid[0].length - 1]; while (!minHeap.isEmpty()) { const { element, priority: cost } = minHeap.dequeue(); - const [ row, col ] = element; + const [row, col] = element; seen.add(grid[row][col]); maxTime = Math.max(maxTime, cost); - const isEnd = (row === rows) && (col === cols); + const isEnd = row === rows && col === cols; if (isEnd) return maxTime; checkNeighbors(grid, row, rows, col, cols, seen, minHeap); } -} +}; var checkNeighbors = (grid, row, rows, col, cols, seen, minHeap) => { - for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) { + for (const [_row, _col] of getNeighbors(row, rows, col, cols)) { if (seen.has(grid[_row][_col])) continue; - minHeap.enqueue([ _row, _col ], grid[_row][_col]); + minHeap.enqueue([_row, _col], grid[_row][_col]); } -} +}; -const getNeighbors = (row, rows, col, cols) => [ [1, 0], [-1, 0], [0, 1], [0, -1] ] - .map(([ _row, _col ]) => [ (row + _row), (col + _col) ]) - .filter(([ _row, _col ]) => ((0 <= _row) && (_row <= rows) && (0 <= _col) && (_col <= cols))) +const getNeighbors = (row, rows, col, cols) => + [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + ] + .map(([_row, _col]) => [row + _row, col + _col]) + .filter( + ([_row, _col]) => + 0 <= _row && _row <= rows && 0 <= _col && _col <= cols, + ); diff --git a/javascript/0783-minimum-distance-between-bst-nodes.js b/javascript/0783-minimum-distance-between-bst-nodes.js index 87704f1c5..4e9fca04f 100644 --- a/javascript/0783-minimum-distance-between-bst-nodes.js +++ b/javascript/0783-minimum-distance-between-bst-nodes.js @@ -13,10 +13,10 @@ * @param {TreeNode} root * @return {number} */ -var minDiffInBST = function(root) { +var minDiffInBST = function (root) { // levelOrderTraversal const sortedArr = dfs(root, []); - + let min = Infinity; for (let i = 1; i < sortedArr.length; i++) { min = Math.min(min, sortedArr[i] - sortedArr[i - 1]); @@ -28,8 +28,8 @@ const dfs = (node, sortedArr) => { if (!node) return; dfs(node.left, sortedArr); - sortedArr.push(node.val) + sortedArr.push(node.val); dfs(node.right, sortedArr); return sortedArr; -} +}; diff --git a/javascript/0787-cheapest-flights-within-k-stops.js b/javascript/0787-cheapest-flights-within-k-stops.js index 79562829f..e63fc62ca 100644 --- a/javascript/0787-cheapest-flights-within-k-stops.js +++ b/javascript/0787-cheapest-flights-within-k-stops.js @@ -6,7 +6,7 @@ * @param {number} k * @return {number} */ - var findCheapestPrice = function (n, flights, src, dst, K) { +var findCheapestPrice = function (n, flights, src, dst, K) { const { graph, seen, minHeap } = buildGraph(n, flights, src, dst, K); return search(graph, src, dst, seen, minHeap); @@ -16,49 +16,49 @@ var initGraph = (n) => ({ graph: new Array(n).fill().map(() => []), seen: new Map(), minHeap: new MinPriorityQueue(), -}) +}); var buildGraph = (n, flights, src, dst, K) => { const { graph, seen, minHeap } = initGraph(n); - for (const [ src, dst, cost ] of flights) { - graph[src].push([ dst, cost ]); + for (const [src, dst, cost] of flights) { + graph[src].push([dst, cost]); } const priority = 0; - const node = [ priority, src, (K + 1) ]; + const node = [priority, src, K + 1]; minHeap.enqueue(node, priority); return { graph, seen, minHeap }; -} +}; const search = (graph, src, dst, seen, minHeap) => { while (!minHeap.isEmpty()) { - const [ cost, city, stops ] = minHeap.dequeue().element; + const [cost, city, stops] = minHeap.dequeue().element; seen.set(city, stops); - const isTarget = (city === dst); + const isTarget = city === dst; if (isTarget) return cost; - const canSkip = (stops <= 0); + const canSkip = stops <= 0; if (canSkip) continue; checkNeighbors(graph, cost, city, stops, seen, minHeap); } return -1; -} +}; var checkNeighbors = (graph, cost, city, stops, seen, minHeap) => { - for (let [ nextCity, nextCost ] of graph[city]) { - const hasSeen = (seen.has(nextCity) && ((stops - 1) <= seen.get(nextCity))); + for (let [nextCity, nextCost] of graph[city]) { + const hasSeen = seen.has(nextCity) && stops - 1 <= seen.get(nextCity); if (hasSeen) continue; - const priority = (cost + nextCost) - const node = [ priority, nextCity, (stops - 1)]; + const priority = cost + nextCost; + const node = [priority, nextCity, stops - 1]; minHeap.enqueue(node, priority); } -} \ No newline at end of file +}; diff --git a/javascript/0837-new-21-game.js b/javascript/0837-new-21-game.js index 375d086a4..52279bf67 100644 --- a/javascript/0837-new-21-game.js +++ b/javascript/0837-new-21-game.js @@ -5,30 +5,30 @@ * @param {number} maxPts * @return {number} */ -var new21Game = function(n, k, maxPts) { - if (k == 0) { - return 1 - } +var new21Game = function (n, k, maxPts) { + if (k == 0) { + return 1; + } - let windowSum = 0 - for (let i = k; i < k + maxPts; i++) { - if (i <= n) { - windowSum += 1 + let windowSum = 0; + for (let i = k; i < k + maxPts; i++) { + if (i <= n) { + windowSum += 1; + } } - } - let dp = {} - for (let i = k - 1; i >= 0; i--) { - dp[i] = windowSum / maxPts + let dp = {}; + for (let i = k - 1; i >= 0; i--) { + dp[i] = windowSum / maxPts; - let remove = 0 - if (i + maxPts <= n) { - remove = dp[i + maxPts] || 1 - } + let remove = 0; + if (i + maxPts <= n) { + remove = dp[i + maxPts] || 1; + } - windowSum += dp[i] - windowSum -= remove - } + windowSum += dp[i]; + windowSum -= remove; + } - return dp[0] -}; \ No newline at end of file + return dp[0]; +}; diff --git a/javascript/0846-hand-of-straights.js b/javascript/0846-hand-of-straights.js index 9b7b4da05..e08caa280 100644 --- a/javascript/0846-hand-of-straights.js +++ b/javascript/0846-hand-of-straights.js @@ -5,46 +5,53 @@ * @param {number} groupSize * @return {boolean} */ - var isNStraightHand = function (hand, groupSize, count = new Map()) { - const map = getFrequencyMap(hand);/* Time O(N) | Space O(N) */ - const sortUniqHand = getUniqueHand(hand);/* Time O(N * Log(N)) | Space O(N) */ +var isNStraightHand = function (hand, groupSize, count = new Map()) { + const map = getFrequencyMap(hand); /* Time O(N) | Space O(N) */ + const sortUniqHand = + getUniqueHand(hand); /* Time O(N * Log(N)) | Space O(N) */ - return search(groupSize, map, sortUniqHand);/* Time O(N * K) */ + return search(groupSize, map, sortUniqHand); /* Time O(N * K) */ }; const getFrequencyMap = (hand, map = new Map()) => { - for (const _hand of hand) {/* Time O(N) */ + for (const _hand of hand) { + /* Time O(N) */ const val = (map.get(_hand) || 0) + 1; - map.set(_hand, val);/* Space O(N) */ + map.set(_hand, val); /* Space O(N) */ } - + return map; -} +}; -const getUniqueHand = (hand) => [ ...new Set(hand) ]/* Time O(N) | Space O(N) */ - .sort((a, b) => b - a);/* Time O(N * Log(N)) | Space HeapSort O(1) | Space QuickSort O(log(N)) */ +const getUniqueHand = (hand) => + [...new Set(hand)] /* Time O(N) | Space O(N) */ + .sort( + (a, b) => b - a, + ); /* Time O(N * Log(N)) | Space HeapSort O(1) | Space QuickSort O(log(N)) */ const search = (groupSize, map, sortUniqHand) => { - while (sortUniqHand.length) {/* Time O(N) */ + while (sortUniqHand.length) { + /* Time O(N) */ const smallest = sortUniqHand[sortUniqHand.length - 1]; - - for (let i = smallest; i < smallest + groupSize; i++) {/* Time O(K) */ + + for (let i = smallest; i < smallest + groupSize; i++) { + /* Time O(K) */ if (!map.has(i)) return false; const val = map.get(i) - 1; - + map.set(i, val); - + let isEqual = map.get(i) === 0; if (!isEqual) continue; - + isEqual = i === sortUniqHand[sortUniqHand.length - 1]; if (!isEqual) return false; sortUniqHand.pop(); } } - + return true; -} \ No newline at end of file +}; diff --git a/javascript/0853-car-fleet.js b/javascript/0853-car-fleet.js index 5d1df6710..e186bdb5f 100644 --- a/javascript/0853-car-fleet.js +++ b/javascript/0853-car-fleet.js @@ -1,63 +1,89 @@ -/** - * https://leetcode.com/problems/car-fleet - * Time O(N * log(N)) | Space O(N) - * @param {number} target - * @param {number[]} position - * @param {number[]} speed - * @return {number} - */ -var carFleet = function(target, position, speed) { - const coordinates = getCoordinates(target, position, speed); /* Time O(N * log(N)) | Space O(N) */ - - return searchAscending(coordinates); /* Time O(N) | Space O(N) */ -}; - -var getCoordinates = (target, position, speed) => position - .map((_position, index) => [ _position, speed[index] ]) /* Time O(N) | Space O(N) */ - .sort(([ aPosition ], [ bPosition ]) => aPosition - bPosition) /* Time O(N * log(N)) | HeapSort Space 0(1) | QuickSort Space O(log(N)) */ - .map(([ _position, _speed ]) => (target - _position) / _speed); /* Time O(N) | Space O(N) */ - -var searchAscending = (coordinates, stack = []) => { - for (const coordinate of coordinates) { /* Time O(N + N) */ - shrink(coordinate, stack); /* Time O(N + N) */ - stack.push(coordinate); /* Space O(N) */ - } - - return stack.length; -} - -const shrink = (coordinate, stack) => { - const isPreviousLess = () => stack[stack.length - 1] <= coordinate; - while (stack.length && isPreviousLess()) stack.pop(); /* Time O(N + N) */ -} - -/** - * https://leetcode.com/problems/car-fleet - * Time O(N * log(N)) | Space O(N) - * @param {number} target - * @param {number[]} position - * @param {number[]} speed - * @return {number} - */ - var carFleet = function(target, position, speed) { - const coordinates = getCoordinates(target, position, speed); /* Time O(N * log(N)) | Space O(N) */ - - return searchDescending(coordinates); /* Time O(N) */ -}; - -var getCoordinates = (target, position, speed) => position - .map((_position, index) => [ _position, speed[index] ]) /* Time O(N) | Space O(N) */ - .sort(([ aPosition ], [ bPosition ]) => bPosition - aPosition) /* Time O(N * log(N)) | HeapSort Space 0(1) | QuickSort Space O(log(N)) */ - .map(([ _position, _speed ]) => (target - _position) / _speed);/* Time O(N) | Space O(N) */ - -var searchDescending = (coordinates, previous = 0, fleets = 0) => { - for (const coordinate of coordinates) { /* Time O(N) */ - const isPreviousLess = previous < coordinate - if (!isPreviousLess) continue - - previous = coordinate - fleets++ - } - - return fleets; -} \ No newline at end of file +/** + * https://leetcode.com/problems/car-fleet + * Time O(N * log(N)) | Space O(N) + * @param {number} target + * @param {number[]} position + * @param {number[]} speed + * @return {number} + */ +var carFleet = function (target, position, speed) { + const coordinates = getCoordinates( + target, + position, + speed, + ); /* Time O(N * log(N)) | Space O(N) */ + + return searchAscending(coordinates); /* Time O(N) | Space O(N) */ +}; + +var getCoordinates = (target, position, speed) => + position + .map((_position, index) => [ + _position, + speed[index], + ]) /* Time O(N) | Space O(N) */ + .sort( + ([aPosition], [bPosition]) => aPosition - bPosition, + ) /* Time O(N * log(N)) | HeapSort Space 0(1) | QuickSort Space O(log(N)) */ + .map( + ([_position, _speed]) => (target - _position) / _speed, + ); /* Time O(N) | Space O(N) */ + +var searchAscending = (coordinates, stack = []) => { + for (const coordinate of coordinates) { + /* Time O(N + N) */ + shrink(coordinate, stack); /* Time O(N + N) */ + stack.push(coordinate); /* Space O(N) */ + } + + return stack.length; +}; + +const shrink = (coordinate, stack) => { + const isPreviousLess = () => stack[stack.length - 1] <= coordinate; + while (stack.length && isPreviousLess()) stack.pop(); /* Time O(N + N) */ +}; + +/** + * https://leetcode.com/problems/car-fleet + * Time O(N * log(N)) | Space O(N) + * @param {number} target + * @param {number[]} position + * @param {number[]} speed + * @return {number} + */ +var carFleet = function (target, position, speed) { + const coordinates = getCoordinates( + target, + position, + speed, + ); /* Time O(N * log(N)) | Space O(N) */ + + return searchDescending(coordinates); /* Time O(N) */ +}; + +var getCoordinates = (target, position, speed) => + position + .map((_position, index) => [ + _position, + speed[index], + ]) /* Time O(N) | Space O(N) */ + .sort( + ([aPosition], [bPosition]) => bPosition - aPosition, + ) /* Time O(N * log(N)) | HeapSort Space 0(1) | QuickSort Space O(log(N)) */ + .map( + ([_position, _speed]) => (target - _position) / _speed, + ); /* Time O(N) | Space O(N) */ + +var searchDescending = (coordinates, previous = 0, fleets = 0) => { + for (const coordinate of coordinates) { + /* Time O(N) */ + const isPreviousLess = previous < coordinate; + if (!isPreviousLess) continue; + + previous = coordinate; + fleets++; + } + + return fleets; +}; diff --git a/javascript/0861-score-after-flipping-matrix.js b/javascript/0861-score-after-flipping-matrix.js index f2d9e9e40..d6c549091 100644 --- a/javascript/0861-score-after-flipping-matrix.js +++ b/javascript/0861-score-after-flipping-matrix.js @@ -5,13 +5,11 @@ * @param {number[][]} grid * @return {number} */ -var matrixScore = function(grid) { - +var matrixScore = function (grid) { const ROW = grid[0].length; const COL = grid.length; const countZeros = (col) => { - let start = 0; let count = 0; while (start < COL) { @@ -20,7 +18,7 @@ var matrixScore = function(grid) { } return count; - } + }; const flip = (i, isRow) => { let start = 0; @@ -40,12 +38,12 @@ var matrixScore = function(grid) { } return; } - } + }; for (let i = 0; i < COL; i++) { if (!grid[i][0]) flip(i, true); - for (let j = (grid[i][0] && 1); j < ROW; j++) { + for (let j = grid[i][0] && 1; j < ROW; j++) { const numberOfZeros = countZeros(j); if (numberOfZeros > COL - numberOfZeros) { flip(j, false); @@ -55,7 +53,7 @@ var matrixScore = function(grid) { let total = 0; for (let i = 0; i < COL; i++) { - total += parseInt(grid[i].join(""), 2); + total += parseInt(grid[i].join(''), 2); } return total; diff --git a/javascript/0872-leaf-similar-trees.js b/javascript/0872-leaf-similar-trees.js index b600b3351..5e5a93e88 100644 --- a/javascript/0872-leaf-similar-trees.js +++ b/javascript/0872-leaf-similar-trees.js @@ -14,8 +14,7 @@ * @param {TreeNode} root2 * @return {boolean} */ -var leafSimilar = function(root1, root2) { - +var leafSimilar = function (root1, root2) { const dfs = (node, arr) => { if (!node.left && !node.right) { arr.push(node.val); @@ -25,7 +24,7 @@ var leafSimilar = function(root1, root2) { if (node.right) dfs(node.right, arr); return arr; - } + }; const arr1 = dfs(root1, []); const arr2 = dfs(root2, []); diff --git a/javascript/0894-all-possible-full-binary-trees.js b/javascript/0894-all-possible-full-binary-trees.js index 76b52ae33..750c60e7a 100644 --- a/javascript/0894-all-possible-full-binary-trees.js +++ b/javascript/0894-all-possible-full-binary-trees.js @@ -13,25 +13,23 @@ * @param {number} n * @return {TreeNode[]} */ -var allPossibleFBT = function(n) { - +var allPossibleFBT = function (n) { // even number of nodes can't make a full binary tree. - if(!(n % 2)) return []; + if (!(n % 2)) return []; const dfs = (n) => { - if(n === 1) return [new TreeNode(0)]; + if (n === 1) return [new TreeNode(0)]; const allPossibleTrees = []; - for(let i = 1; i < n; i += 2) { - + for (let i = 1; i < n; i += 2) { const leftNumOfNodes = i; const rightNumOfNodes = n - i - 1; const leftTrees = dfs(leftNumOfNodes); const rightTrees = dfs(rightNumOfNodes); - for(let i = 0; i < leftTrees.length; i++) { - for(let j = 0; j < rightTrees.length; j++) { + for (let i = 0; i < leftTrees.length; i++) { + for (let j = 0; j < rightTrees.length; j++) { const root = new TreeNode(0, leftTrees[i], rightTrees[j]); allPossibleTrees.push(root); } @@ -39,7 +37,7 @@ var allPossibleFBT = function(n) { } return allPossibleTrees; - } + }; return dfs(n); }; diff --git a/javascript/0901-online-stock-span.js b/javascript/0901-online-stock-span.js index 7b23c590d..ef446b34f 100644 --- a/javascript/0901-online-stock-span.js +++ b/javascript/0901-online-stock-span.js @@ -1,36 +1,36 @@ //https://leetcode.com/problems/online-stock-span/ class StockSpanner { constructor() { - this.stack = []; + this.stack = []; } - + // Time O(1) | Space O(1) isEmpty() { - return this.stack.length === 0; + return this.stack.length === 0; } - + // Time O(1) | Space O(1) peek() { - return this.isEmpty() ? null : this.stack[this.stack.length - 1]; + return this.isEmpty() ? null : this.stack[this.stack.length - 1]; } - + // Time O(1) | Space O(1) push(val) { - return this.stack.push(val); + return this.stack.push(val); } - + // Time O(1) | Space O(1) pop() { - return this.stack.pop(); + return this.stack.pop(); } - + // Time O(n) | Space O(1) next(price) { - let currunt = 1; - while (this.peek() && this.peek()[0] <= price) { - currunt += this.pop()[1]; - } - this.push([price, currunt]); - return this.peek()[1]; + let currunt = 1; + while (this.peek() && this.peek()[0] <= price) { + currunt += this.pop()[1]; + } + this.push([price, currunt]); + return this.peek()[1]; } - } +} diff --git a/javascript/0909-snakes-and-ladders.js b/javascript/0909-snakes-and-ladders.js index b00e525cf..d1386c404 100644 --- a/javascript/0909-snakes-and-ladders.js +++ b/javascript/0909-snakes-and-ladders.js @@ -2,29 +2,29 @@ * @param {number[][]} board * @return {number} */ -var snakesAndLadders = function(board) { +var snakesAndLadders = function (board) { let n = board.length; let set = new Set(); let getPos = (pos) => { - let row = Math.floor((pos - 1) / n) - let col = (pos - 1) % n + let row = Math.floor((pos - 1) / n); + let col = (pos - 1) % n; col = row % 2 == 1 ? n - 1 - col : col; row = n - 1 - row; - return [row, col] - } - let q = [[1, 0]] - while (q.length > 0){ + return [row, col]; + }; + let q = [[1, 0]]; + while (q.length > 0) { [pos, moves] = q.shift(); - for (let i = 1; i < 7; i++){ + for (let i = 1; i < 7; i++) { let newPos = i + pos; let [r, c] = getPos(newPos); - if (board[r][c] != -1 ) newPos = board[r][c] + if (board[r][c] != -1) newPos = board[r][c]; if (newPos == n * n) return moves + 1; if (!set.has(newPos)) { - set.add(newPos) - q.push([newPos, moves + 1]) + set.add(newPos); + q.push([newPos, moves + 1]); } } } - return -1 + return -1; }; diff --git a/javascript/0912-sort-an-array.js b/javascript/0912-sort-an-array.js index 2a9fc4274..399a27881 100644 --- a/javascript/0912-sort-an-array.js +++ b/javascript/0912-sort-an-array.js @@ -5,30 +5,29 @@ * @param {number[]} nums * @return {number[]} */ -const sortArray = function(nums) { - return mergeSort(0, nums.length - 1, nums); -}; +const sortArray = function (nums) { + return mergeSort(0, nums.length - 1, nums); +}; const mergeSort = (left, right, nums) => { + if (left === right) return nums; - if(left === right) return nums; - - const mid = Math.floor((left+right)/2); + const mid = Math.floor((left + right) / 2); mergeSort(left, mid, nums); - mergeSort(mid+1, right, nums); + mergeSort(mid + 1, right, nums); return merge(left, right, mid, nums); -} +}; const merge = (left, right, mid, nums) => { - const arr1 = nums.slice(left, mid+1); - const arr2 = nums.slice(mid+1, right + 1); - - let p1 = 0; + const arr1 = nums.slice(left, mid + 1); + const arr2 = nums.slice(mid + 1, right + 1); + + let p1 = 0; let p2 = 0; let gp = left; - while(p1 < arr1.length && p2 < arr2.length) { - if(arr1[p1] < arr2[p2]) { + while (p1 < arr1.length && p2 < arr2.length) { + if (arr1[p1] < arr2[p2]) { nums[gp] = arr1[p1]; p1++; } else { @@ -38,16 +37,16 @@ const merge = (left, right, mid, nums) => { gp++; } - while(p1 < arr1.length) { + while (p1 < arr1.length) { nums[gp] = arr1[p1]; p1++; gp++; } - while(p2 < arr2.length) { + while (p2 < arr2.length) { nums[gp] = arr2[p2]; p2++; gp++; } return nums; -} +}; diff --git a/javascript/0929-unique-email-addresses.js b/javascript/0929-unique-email-addresses.js index bd9b09a09..3c21d81be 100644 --- a/javascript/0929-unique-email-addresses.js +++ b/javascript/0929-unique-email-addresses.js @@ -7,14 +7,12 @@ * @return {number} */ var numUniqueEmails = function (emails) { - const valid = emails.map(email => { - const [local, domain] = email.split("@"); - return ( - local.split("+").shift().split(".").join("") + "@" + domain - ); - }); + const valid = emails.map((email) => { + const [local, domain] = email.split('@'); + return local.split('+').shift().split('.').join('') + '@' + domain; + }); - return new Set(valid).size; + return new Set(valid).size; }; /** @@ -26,25 +24,25 @@ var numUniqueEmails = function (emails) { * @return {number} */ var numUniqueEmails = function (emails) { - const uniqEmails = new Set(); + const uniqEmails = new Set(); - for (let email of emails) { - let cleanEmail = ""; - for (let i = 0; i < email.length; i++) { - if (email[i] === "@") { - cleanEmail += email.slice(i); - break; - } else if (email[i] === "+") { - while (email[i] !== "@") i++; - cleanEmail += email.slice(i); - break; - } else if (email[i] !== ".") { - cleanEmail += email[i]; - } - } + for (let email of emails) { + let cleanEmail = ''; + for (let i = 0; i < email.length; i++) { + if (email[i] === '@') { + cleanEmail += email.slice(i); + break; + } else if (email[i] === '+') { + while (email[i] !== '@') i++; + cleanEmail += email.slice(i); + break; + } else if (email[i] !== '.') { + cleanEmail += email[i]; + } + } - uniqEmails.add(cleanEmail); - } + uniqEmails.add(cleanEmail); + } - return uniqEmails.size; + return uniqEmails.size; }; diff --git a/javascript/0934-shortest-bridge.js b/javascript/0934-shortest-bridge.js index f2452d428..df3440eaf 100644 --- a/javascript/0934-shortest-bridge.js +++ b/javascript/0934-shortest-bridge.js @@ -1,70 +1,81 @@ -const DIRECTIONS = [[-1, 0], [1, 0], [0, -1], [0, 1]]; +const DIRECTIONS = [ + [-1, 0], + [1, 0], + [0, -1], + [0, 1], +]; const shortestBridge = (grid) => { - const rows = grid.length; - const cols = grid[0].length; + const rows = grid.length; + const cols = grid[0].length; - let queue = []; + let queue = []; - const exploreIslandDFS = (row, col) => { - if (row < 0 || row >= rows || col < 0 || col >= cols || grid[row][col] !== 1) { - return false; - } + const exploreIslandDFS = (row, col) => { + if ( + row < 0 || + row >= rows || + col < 0 || + col >= cols || + grid[row][col] !== 1 + ) { + return false; + } + + queue.push([row, col]); + grid[row][col] = 2; - queue.push([row, col]); - grid[row][col] = 2; + exploreIslandDFS(row - 1, col); + exploreIslandDFS(row + 1, col); + exploreIslandDFS(row, col - 1); + exploreIslandDFS(row, col + 1); - exploreIslandDFS(row - 1, col); - exploreIslandDFS(row + 1, col); - exploreIslandDFS(row, col - 1); - exploreIslandDFS(row, col + 1); + return true; + }; - return true; - }; + const buildBridgeBFS = () => { + let distance = -1; + let currentQueue = []; - const buildBridgeBFS = () => { - let distance = -1; - let currentQueue = []; + while (queue.length) { + currentQueue = queue; + queue = []; - while (queue.length) { - currentQueue = queue; - queue = []; + for (let [row, col] of currentQueue) { + for (let [dx, dy] of DIRECTIONS) { + const nextRow = row + dx; + const nextCol = col + dy; - for (let [row, col] of currentQueue) { - for (let [dx, dy] of DIRECTIONS) { - const nextRow = row + dx; - const nextCol = col + dy; + if ( + nextRow >= 0 && + nextRow < rows && + nextCol >= 0 && + nextCol < cols && + grid[nextRow][nextCol] !== 2 + ) { + if (grid[nextRow][nextCol] === 1) { + return distance + 1; + } - if ( - nextRow >= 0 && - nextRow < rows && - nextCol >= 0 && - nextCol < cols && - grid[nextRow][nextCol] !== 2 - ) { - if (grid[nextRow][nextCol] === 1) { - return distance + 1; + queue.push([nextRow, nextCol]); + grid[nextRow][nextCol] = 2; + } + } } - queue.push([nextRow, nextCol]); - grid[nextRow][nextCol] = 2; - } + distance++; } - } - distance++; - } + return -1; + }; - return -1; - }; - - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - if (exploreIslandDFS(i, j)) { - return buildBridgeBFS(); - } + for (let i = 0; i < rows; i++) { + for (let j = 0; j < cols; j++) { + if (exploreIslandDFS(i, j)) { + return buildBridgeBFS(); + } + } } - } - return -1; -}; \ No newline at end of file + return -1; +}; diff --git a/javascript/0937-k-closest-points-to-origin.js b/javascript/0937-k-closest-points-to-origin.js index 03d1b738e..abe2b8350 100644 --- a/javascript/0937-k-closest-points-to-origin.js +++ b/javascript/0937-k-closest-points-to-origin.js @@ -5,8 +5,8 @@ * @param {number} k * @return {number[][]} */ - var kClosest = function(points, K) { - const distance = ([x, y]) => (x * x) + (y * y); +var kClosest = function (points, K) { + const distance = ([x, y]) => x * x + y * y; points.sort((a, b) => distance(a) - distance(b)); @@ -20,38 +20,42 @@ * @param {number} k * @return {number[][]} */ -var kClosest = function(points, K) { - const [ left, right ] = [ 0, (points.length - 1) ]; +var kClosest = function (points, K) { + const [left, right] = [0, points.length - 1]; quickSelect(points, K, left, right); - return points.slice(0, K) + return points.slice(0, K); }; const quickSelect = (points, target, left, right) => { const mid = getMid(points, left, right); - const isTarget = mid === (target - 1); + const isTarget = mid === target - 1; if (isTarget) return; - - const isTargetGreater = mid < (target - 1); - if (isTargetGreater) quickSelect(points, target, (mid + 1), right); - - const isTargetLess = (target - 1) < mid; - if (isTargetLess) quickSelect(points, target, left, (mid - 1)); -} -const swap = (points, left, right) => [ points[left], points[right] ] = [ points[right], points[left] ]; + const isTargetGreater = mid < target - 1; + if (isTargetGreater) quickSelect(points, target, mid + 1, right); + + const isTargetLess = target - 1 < mid; + if (isTargetLess) quickSelect(points, target, left, mid - 1); +}; + +const swap = (points, left, right) => + ([points[left], points[right]] = [points[right], points[left]]); -const squareRoot = ([ x, y ]) => ((x * x) + (y * y)); +const squareRoot = ([x, y]) => x * x + y * y; const getMid = (points, left, right) => { let mid = left; while (left < right) { - const [ leftDistance, rightDistance ] = [ squareRoot(points[left]), squareRoot(points[right]) ]; + const [leftDistance, rightDistance] = [ + squareRoot(points[left]), + squareRoot(points[right]), + ]; - const canSwapMid = leftDistance <= rightDistance + const canSwapMid = leftDistance <= rightDistance; if (canSwapMid) { swap(points, left, mid); mid++; @@ -63,7 +67,7 @@ const getMid = (points, left, right) => { swap(points, mid, right); return mid; -} +}; /** * https://leetcode.com/problems/k-closest-points-to-origin/ @@ -72,8 +76,10 @@ const getMid = (points, left, right) => { * @param {number} k * @return {number[][]} */ -var kClosest = function(points, k) { - const maxHeap = new MaxPriorityQueue({ priority: (point) => distance(point) }) +var kClosest = function (points, k) { + const maxHeap = new MaxPriorityQueue({ + priority: (point) => distance(point), + }); for (const point of points) { const isUnderCapacity = maxHeap.size() < k; @@ -89,9 +95,7 @@ var kClosest = function(points, k) { } } - return maxHeap - .toArray() - .map(({ element }) => element); -} + return maxHeap.toArray().map(({ element }) => element); +}; -const distance = ([ x, y ]) => (x * x) + (y * y); \ No newline at end of file +const distance = ([x, y]) => x * x + y * y; diff --git a/javascript/0938-range-sum-of-bst.js b/javascript/0938-range-sum-of-bst.js index 7fa56e034..c8e7ae8ba 100644 --- a/javascript/0938-range-sum-of-bst.js +++ b/javascript/0938-range-sum-of-bst.js @@ -10,14 +10,13 @@ * DFS | Recursion * Time O(n) | Space O(n) * https://leetcode.com/problems/range-sum-of-bst - * + * * @param {TreeNode} root * @param {number} low * @param {number} high * @return {number} */ -var rangeSumBST = function(root, low, high) { - +var rangeSumBST = function (root, low, high) { let total = 0; const dfs = (node) => { @@ -25,7 +24,7 @@ var rangeSumBST = function(root, low, high) { if (node.val >= low && node.val <= high) total += node.val; dfs(node.left); dfs(node.right); - } + }; dfs(root); return total; }; diff --git a/javascript/0951-flip-equivalent-binary-trees.js b/javascript/0951-flip-equivalent-binary-trees.js index d9f061112..b75b28754 100644 --- a/javascript/0951-flip-equivalent-binary-trees.js +++ b/javascript/0951-flip-equivalent-binary-trees.js @@ -14,13 +14,12 @@ * @param {TreeNode} root2 * @return {boolean} */ -var flipEquiv = function(root1, root2) { - +var flipEquiv = function (root1, root2) { const dfs = (node1, node2) => { if (!node1 && !node2) return true; if (!node1) return false; if (!node2) return false; - + if (node1.val !== node2.val) return false; if ((node1.left && node1.left.val) !== (node2.left && node2.left.val)) { @@ -28,7 +27,7 @@ var flipEquiv = function(root1, root2) { } return dfs(node1.left, node2.left) && dfs(node1.right, node2.right); - } + }; return dfs(root1, root2); }; diff --git a/javascript/0953-verifying-an-alien-dictionary.js b/javascript/0953-verifying-an-alien-dictionary.js index 511086dc1..c93c87dc0 100644 --- a/javascript/0953-verifying-an-alien-dictionary.js +++ b/javascript/0953-verifying-an-alien-dictionary.js @@ -1,24 +1,23 @@ -var isAlienSorted = function(words, order) { +var isAlienSorted = function (words, order) { // first differing char // if word A is prefix of word B, word B must be AFTER word A - orderInd = new Map(); { + orderInd = new Map(); + { let ind = 0; - for(const c of order) - orderInd.set(c, ind++); + for (const c of order) orderInd.set(c, ind++); } - - for(let i = 0; i < words.length - 1; i++) { - let w1 = words[i], w2 = words[i + 1]; - - for(let j = 0; j < w1.length; j++) { - if(j == w2.length) - return false; - - if(w1.charAt(j) != w2.charAt(j)) - if(orderInd.get(w2.charAt(j)) < orderInd.get(w1.charAt(j))) + + for (let i = 0; i < words.length - 1; i++) { + let w1 = words[i], + w2 = words[i + 1]; + + for (let j = 0; j < w1.length; j++) { + if (j == w2.length) return false; + + if (w1.charAt(j) != w2.charAt(j)) + if (orderInd.get(w2.charAt(j)) < orderInd.get(w1.charAt(j))) return false; - else - break; + else break; } } return true; diff --git a/javascript/0958-check-completeness-of-a-binary-tree.js b/javascript/0958-check-completeness-of-a-binary-tree.js index 51b8b68e3..e3e4191df 100644 --- a/javascript/0958-check-completeness-of-a-binary-tree.js +++ b/javascript/0958-check-completeness-of-a-binary-tree.js @@ -13,16 +13,15 @@ * @param {TreeNode} root * @return {boolean} */ -var isCompleteTree = function(root) { - +var isCompleteTree = function (root) { // get the depth of the tree // bfs until n-1 level of depth const getDepth = (node) => { if (!node) return 0; return 1 + Math.max(getDepth(node.left), getDepth(node.right)); - } - + }; + const depth = getDepth(root) - 1; const q = new Queue(); @@ -38,14 +37,13 @@ var isCompleteTree = function(root) { } return true; - } + }; let i = 0; while (i < depth) { - let size = q.size(); - if (size !== 2**i) return false; + if (size !== 2 ** i) return false; while (size) { const node = q.dequeue(); @@ -56,7 +54,6 @@ var isCompleteTree = function(root) { q.enqueue(node.left); q.enqueue(node.right); } else { - if (!node.left) { q.enqueue(null); } else { @@ -68,14 +65,13 @@ var isCompleteTree = function(root) { } else { q.enqueue(node.right); } - } - + size--; } i++; } - + return checkLastLevel(q.toArray()); }; diff --git a/javascript/0978-longest-turbulent-subarray.js b/javascript/0978-longest-turbulent-subarray.js index ff06ee4ca..422468015 100644 --- a/javascript/0978-longest-turbulent-subarray.js +++ b/javascript/0978-longest-turbulent-subarray.js @@ -5,10 +5,8 @@ * @param {number[]} arr * @return {number} */ -var maxTurbulenceSize = function(arr) { - +var maxTurbulenceSize = function (arr) { const higherAndLower = (start) => { - let i = start; let shouldBeLow = true; @@ -21,12 +19,9 @@ var maxTurbulenceSize = function(arr) { } return i; - - } + }; const lowerAndHigher = (start) => { - - let i = start; let shouldBeHigh = true; @@ -39,15 +34,13 @@ var maxTurbulenceSize = function(arr) { } return i; - } - + }; let left = 0; let right = 1; let max = 1; while (right < arr.length) { - if (arr[left] > arr[right]) { right = higherAndLower(left); max = Math.max(right - left + 1, max); @@ -68,7 +61,6 @@ var maxTurbulenceSize = function(arr) { left++; right++; } - } return max; diff --git a/javascript/0988-smallest-string-starting-from-leaf.js b/javascript/0988-smallest-string-starting-from-leaf.js index 4d2c57a0e..7eb0ace35 100644 --- a/javascript/0988-smallest-string-starting-from-leaf.js +++ b/javascript/0988-smallest-string-starting-from-leaf.js @@ -13,25 +13,22 @@ * @param {TreeNode} root * @return {string} */ -var smallestFromLeaf = function(root) { - - let biggestStr = new Array(8500).fill("z"); - biggestStr = biggestStr.join(""); +var smallestFromLeaf = function (root) { + let biggestStr = new Array(8500).fill('z'); + biggestStr = biggestStr.join(''); let smallest = biggestStr; const dfs = (node, str) => { - - const char = String.fromCharCode(node.val+97); + const char = String.fromCharCode(node.val + 97); if (!node.left && !node.right) { str.push(char); - const str1 = str.slice(0).reverse().join(""); + const str1 = str.slice(0).reverse().join(''); if (str1 < smallest) { smallest = str1; } str.pop(); return; - } if (node.left) { @@ -44,10 +41,10 @@ var smallestFromLeaf = function(root) { str.push(char); dfs(node.right, str); str.pop(); - } - } + } + }; - dfs(root,[]); + dfs(root, []); return smallest; }; diff --git a/javascript/0994-rotting-oranges.js b/javascript/0994-rotting-oranges.js index abeea84e9..40d110b25 100644 --- a/javascript/0994-rotting-oranges.js +++ b/javascript/0994-rotting-oranges.js @@ -4,37 +4,38 @@ * @param {number[][]} grid * @return {number} */ -var orangesRotting = function(grid) { - const { queue, orangeCount } = searchGrid(grid); /* Time O(ROWS * COLS) */ +var orangesRotting = function (grid) { + const { queue, orangeCount } = searchGrid(grid); /* Time O(ROWS * COLS) */ const { rottenCount, minutes } = bfs(grid, queue); const isEqual = orangeCount === rottenCount; - return isEqual - ? minutes - : -1; + return isEqual ? minutes : -1; }; const searchGrid = (grid, orangeCount = 0, queue = new Queue([])) => { - const [ rows, cols ] = [ grid.length, grid[0].length ]; + const [rows, cols] = [grid.length, grid[0].length]; - for (let row = 0; row < rows; row++){/* Time O(ROWS) */ - for (let col = 0; col < cols; col++) {/* Time O(COLS) */ + for (let row = 0; row < rows; row++) { + /* Time O(ROWS) */ + for (let col = 0; col < cols; col++) { + /* Time O(COLS) */ const isEmpty = grid[row][col] === 0; if (!isEmpty) orangeCount++; const isRotten = grid[row][col] === 2; - if (isRotten) queue.enqueue([ row, col ]);/* Space O(ROWS * COLS) */ + if (isRotten) queue.enqueue([row, col]); /* Space O(ROWS * COLS) */ } } - return { queue, orangeCount } -} + return { queue, orangeCount }; +}; const bfs = (grid, queue, rottenCount = 0, minutes = 0) => { while (!queue.isEmpty()) { rottenCount += queue.size(); - for (let i = (queue.size() - 1); 0 <= i; i--) {/* Time O(WIDTH) */ + for (let i = queue.size() - 1; 0 <= i; i--) { + /* Time O(WIDTH) */ expireFresh(grid, queue); } @@ -42,24 +43,33 @@ const bfs = (grid, queue, rottenCount = 0, minutes = 0) => { } return { rottenCount, minutes }; -} +}; var expireFresh = (grid, queue) => { - const [ rows, cols ] = [ grid.length, grid[0].length ]; - const [ row, col ] = queue.dequeue(); + const [rows, cols] = [grid.length, grid[0].length]; + const [row, col] = queue.dequeue(); - for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) { + for (const [_row, _col] of getNeighbors(row, rows, col, cols)) { const isFresh = grid[_row][_col] === 1; if (!isFresh) continue; grid[_row][_col] = 2; - queue.enqueue([ _row, _col ]);/* Space O(ROWS * COLS) */ + queue.enqueue([_row, _col]); /* Space O(ROWS * COLS) */ } -} +}; -var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ],[ 0, -1 ], [ 1, 0 ], [ -1, 0 ] ] - .map(([ _row, _col ]) => [ (row + _row), (col + _col) ]) - .filter(([ _row, _col ]) => (0 <= _row) && (_row < rows) && (0 <= _col) && (_col < cols)); +var getNeighbors = (row, rows, col, cols) => + [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ] + .map(([_row, _col]) => [row + _row, col + _col]) + .filter( + ([_row, _col]) => + 0 <= _row && _row < rows && 0 <= _col && _col < cols, + ); /** * https://leetcode.com/problems/rotting-oranges/ @@ -67,46 +77,57 @@ var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ],[ 0, -1 ], [ 1, 0 ], [ - * @param {number[][]} grid * @return {number} */ -var orangesRotting = function(grid, minutes = 2) { - while (expireFresh(grid, minutes)) minutes++;/* Time O((ROWS * COLS)^2) */ +var orangesRotting = function (grid, minutes = 2) { + while (expireFresh(grid, minutes)) minutes++; /* Time O((ROWS * COLS)^2) */ - return !hasFresh(grid) /* Time O(ROWS * COLS) */ - ? (minutes - 2) - : -1; -} + return !hasFresh(grid) /* Time O(ROWS * COLS) */ ? minutes - 2 : -1; +}; var expireFresh = (grid, minutes, toBeContinued = false) => { - const [ rows, cols ] = [ grid.length, grid[0].length ]; + const [rows, cols] = [grid.length, grid[0].length]; - for (let row = 0; row < rows; row++) {/* Time O(ROWS) */ - for (let col = 0; col < cols; col++) {/* Time O(COLS) */ + for (let row = 0; row < rows; row++) { + /* Time O(ROWS) */ + for (let col = 0; col < cols; col++) { + /* Time O(COLS) */ const isEqual = grid[row][col] === minutes; if (!isEqual) continue; - for (const [ _row, _col ] of getNeighbors(row, rows, col, cols)) { + for (const [_row, _col] of getNeighbors(row, rows, col, cols)) { const isFresh = grid[_row][_col] === 1; if (!isFresh) continue; - grid[_row][_col] = (minutes + 1); + grid[_row][_col] = minutes + 1; toBeContinued = true; } } } return toBeContinued; -} +}; -var getNeighbors = (row, rows, col, cols) => [ [ 0, 1 ],[ 0, -1 ], [ 1, 0 ], [ -1, 0 ] ] - .map(([ _row, _col ]) => [ (row + _row), (col + _col) ]) - .filter(([ _row, _col ]) => (0 <= _row) && (_row < rows) && (0 <= _col) && (_col < cols)); +var getNeighbors = (row, rows, col, cols) => + [ + [0, 1], + [0, -1], + [1, 0], + [-1, 0], + ] + .map(([_row, _col]) => [row + _row, col + _col]) + .filter( + ([_row, _col]) => + 0 <= _row && _row < rows && 0 <= _col && _col < cols, + ); const hasFresh = (grid) => { - for (const row of grid) {/* Time O(ROWS) */ - for (const cell of row) {/* Time O(COLS) */ + for (const row of grid) { + /* Time O(ROWS) */ + for (const cell of row) { + /* Time O(COLS) */ const isFresh = cell === 1; if (isFresh) return true; } } return false; -} \ No newline at end of file +}; diff --git a/javascript/1046-last-stone-weight.js b/javascript/1046-last-stone-weight.js index d19a8999e..380580d93 100644 --- a/javascript/1046-last-stone-weight.js +++ b/javascript/1046-last-stone-weight.js @@ -5,29 +5,27 @@ * @return {number} */ var lastStoneWeight = function (stones) { - const maxHeap = getMaxHeap(stones) + const maxHeap = getMaxHeap(stones); - shrink(maxHeap) + shrink(maxHeap); - return !maxHeap.isEmpty() - ? maxHeap.front().element - : 0 + return !maxHeap.isEmpty() ? maxHeap.front().element : 0; }; const getMaxHeap = (stones, maxHeap = new MaxPriorityQueue()) => { for (const stone of stones) { - maxHeap.enqueue(stone) + maxHeap.enqueue(stone); } - return maxHeap -} + return maxHeap; +}; const shrink = (maxHeap) => { while (1 < maxHeap.size()) { - const [ x, y ] = [ maxHeap.dequeue().element, maxHeap.dequeue().element ] + const [x, y] = [maxHeap.dequeue().element, maxHeap.dequeue().element]; const difference = x - y; - const isPositive = 0 < difference + const isPositive = 0 < difference; if (isPositive) maxHeap.enqueue(difference); } -} \ No newline at end of file +}; diff --git a/javascript/1071-greatest-common-divisor-of-strings.js b/javascript/1071-greatest-common-divisor-of-strings.js index afc7af93c..e9d9b8fb4 100644 --- a/javascript/1071-greatest-common-divisor-of-strings.js +++ b/javascript/1071-greatest-common-divisor-of-strings.js @@ -4,25 +4,26 @@ * @return {string} */ var gcdOfStrings = function (str1, str2) { - let [len1, len2] = [str1.length, str2.length]; + let [len1, len2] = [str1.length, str2.length]; - function isDivisor(l) { - if (len1 % l || len2 % l) { - return false; - } + function isDivisor(l) { + if (len1 % l || len2 % l) { + return false; + } - let [f1, f2] = [Math.floor(len1 / l), Math.floor(len2 / l)]; + let [f1, f2] = [Math.floor(len1 / l), Math.floor(len2 / l)]; - return ( - str1.slice(0, l).repeat(f1) == str1 && str1.slice(0, l).repeat(f2) == str2 - ); - } + return ( + str1.slice(0, l).repeat(f1) == str1 && + str1.slice(0, l).repeat(f2) == str2 + ); + } - for (let l = Math.min(len1, len2); l > 0; l--) { - if (isDivisor(l)) { - return str1.slice(0, l); + for (let l = Math.min(len1, len2); l > 0; l--) { + if (isDivisor(l)) { + return str1.slice(0, l); + } } - } - return ""; + return ''; }; diff --git a/javascript/1094-car-pooling.js b/javascript/1094-car-pooling.js index da6dfc6fe..cbb123682 100644 --- a/javascript/1094-car-pooling.js +++ b/javascript/1094-car-pooling.js @@ -6,12 +6,11 @@ * @param {number} capacity * @return {boolean} */ -var carPooling = function(trips, capacity) { - +var carPooling = function (trips, capacity) { const minQ = new MinPriorityQueue({ compare: (e1, e2) => { return e1[0] - e2[0]; - } + }, }); trips.sort((a, b) => a[1] - b[1]); @@ -19,7 +18,7 @@ var carPooling = function(trips, capacity) { for (let i = 0; i < trips.length; i++) { while (!minQ.isEmpty() && minQ.front()[0] <= trips[i][1]) { capacity += minQ.dequeue()[1]; - }; + } capacity -= trips[i][0]; if (capacity < 0) return false; diff --git a/javascript/1143-longest-common-subsequence.js b/javascript/1143-longest-common-subsequence.js index 66ce896f3..32d661c4c 100644 --- a/javascript/1143-longest-common-subsequence.js +++ b/javascript/1143-longest-common-subsequence.js @@ -7,32 +7,55 @@ * @param {string} text2 * @return {number} */ - var longestCommonSubsequence = (text1, text2, p1 = 0, p2 = 0, memo = initMemo(text1, text2)) => { - const isBaseCase = ((p1 === text1.length) || (p2 === text2.length)); +var longestCommonSubsequence = ( + text1, + text2, + p1 = 0, + p2 = 0, + memo = initMemo(text1, text2), +) => { + const isBaseCase = p1 === text1.length || p2 === text2.length; if (isBaseCase) return 0; - const hasSeen = (memo[p1][p2] !== null); + const hasSeen = memo[p1][p2] !== null; if (hasSeen) return memo[p1][p2]; - return dfs(text1, text2, p1, p2, memo);/* Time O((N * M) * M)) | Space O((N * M) + HEIGHT) */ -} + return dfs( + text1, + text2, + p1, + p2, + memo, + ); /* Time O((N * M) * M)) | Space O((N * M) + HEIGHT) */ +}; -var initMemo = (text1, text2) => new Array((text1.length + 1)).fill()/* Time O(N) | Space O(N) */ - .map(() => new Array((text2.length + 1)).fill(null)); /* Time O(M) | Space O(M) */ +var initMemo = (text1, text2) => + new Array(text1.length + 1) + .fill() /* Time O(N) | Space O(N) */ + .map(() => + new Array(text2.length + 1).fill(null), + ); /* Time O(M) | Space O(M) */ var dfs = (text1, text2, p1, p2, memo) => { - const left = longestCommonSubsequence(text1, text2, (p1 + 1), p2, memo); /* Time O(N * M) | Space O(HEIGHT) */ + const left = longestCommonSubsequence( + text1, + text2, + p1 + 1, + p2, + memo, + ); /* Time O(N * M) | Space O(HEIGHT) */ - const index = text2.indexOf(text1[p1], p2); /* Time O(M) */ - const isPrefix = (index !== -1); + const index = text2.indexOf(text1[p1], p2); /* Time O(M) */ + const isPrefix = index !== -1; const right = isPrefix - ? (longestCommonSubsequence(text1, text2, (p1 + 1), (index + 1), memo) + 1)/* Time O(N * M) | Space O(HEIGHT) */ + ? longestCommonSubsequence(text1, text2, p1 + 1, index + 1, memo) + + 1 /* Time O(N * M) | Space O(HEIGHT) */ : 0; - memo[p1][p2] = Math.max(left, right); /* | Space O(N * M) */ + memo[p1][p2] = Math.max(left, right); /* | Space O(N * M) */ return memo[p1][p2]; -} +}; /** * DP - Top Down @@ -43,32 +66,52 @@ var dfs = (text1, text2, p1, p2, memo) => { * @param {string} text2 * @return {number} */ -var longestCommonSubsequence = (text1, text2, p1 = 0, p2 = 0, memo = initMemo(text1, text2)) => { - const isBaseCase = ((p1 === text1.length) || (p2 === text2.length)); +var longestCommonSubsequence = ( + text1, + text2, + p1 = 0, + p2 = 0, + memo = initMemo(text1, text2), +) => { + const isBaseCase = p1 === text1.length || p2 === text2.length; if (isBaseCase) return 0; - const hasSeen = (memo[p1][p2] !== null); + const hasSeen = memo[p1][p2] !== null; if (hasSeen) return memo[p1][p2]; - return dfs(text1, text2, p1, p2, memo);/* Time O(N * M) | Space O((N * M) + HEIGHT) */ -} + return dfs( + text1, + text2, + p1, + p2, + memo, + ); /* Time O(N * M) | Space O((N * M) + HEIGHT) */ +}; -var initMemo = (text1, text2) => new Array((text1.length + 1)).fill()/* Time O(N) | Space O(N) */ - .map(() => new Array((text2.length + 1)).fill(null)); /* Time O(M) | Space O(M) */ +var initMemo = (text1, text2) => + new Array(text1.length + 1) + .fill() /* Time O(N) | Space O(N) */ + .map(() => + new Array(text2.length + 1).fill(null), + ); /* Time O(M) | Space O(M) */ var dfs = (text1, text2, p1, p2, memo) => { - const left = (longestCommonSubsequence(text1, text2, (p1 + 1), (p2 + 1), memo) + 1);/* Time O(N * M) | Space O(HEIGHT) */ - const right = /* Time O(N * M) | Space O(HEIGHT) */ - Math.max(longestCommonSubsequence(text1, text2, p1, (p2 + 1), memo), longestCommonSubsequence(text1, text2, (p1 + 1), p2, memo)); - - const isEqual = (text1[p1] == text2[p2]); - const count = isEqual - ? left - : right - - memo[p1][p2] = count; /* | Space O(N * M) */ + const left = + longestCommonSubsequence(text1, text2, p1 + 1, p2 + 1, memo) + + 1; /* Time O(N * M) | Space O(HEIGHT) */ + const right = + /* Time O(N * M) | Space O(HEIGHT) */ + Math.max( + longestCommonSubsequence(text1, text2, p1, p2 + 1, memo), + longestCommonSubsequence(text1, text2, p1 + 1, p2, memo), + ); + + const isEqual = text1[p1] == text2[p2]; + const count = isEqual ? left : right; + + memo[p1][p2] = count; /* | Space O(N * M) */ return memo[p1][p2]; -} +}; /** * DP - Bottom Up @@ -80,28 +123,34 @@ var dfs = (text1, text2, p1, p2, memo) => { * @return {number} */ var longestCommonSubsequence = (text1, text2) => { - const tabu = initTabu(text1, text2);/* Time O(N * M) | Space O(N * M) */ + const tabu = initTabu(text1, text2); /* Time O(N * M) | Space O(N * M) */ - search(text1, text2, tabu); /* Time O(N * M) | Space O(N * M) */ + search(text1, text2, tabu); /* Time O(N * M) | Space O(N * M) */ return tabu[0][0]; }; -var initTabu = (text1, text2) => - new Array((text1.length + 1)).fill() /* Time O(N) | Space O(N) */ - .map(() => new Array((text2.length + 1)).fill(0));/* Time O(M) | Space O(M) */ +var initTabu = (text1, text2) => + new Array(text1.length + 1) + .fill() /* Time O(N) | Space O(N) */ + .map(() => + new Array(text2.length + 1).fill(0), + ); /* Time O(M) | Space O(M) */ var search = (text1, text2, tabu) => { - const [ n, m ] = [ text1.length, text2.length ]; - - for (let x = (n - 1); (0 <= x); x--) {/* Time O(N) */ - for (let y = (m - 1); (0 <= y); y--) {/* Time O(M) */ - tabu[x][y] = (text1[x] === text2[y]) /* Space O(N * M) */ - ? (tabu[x + 1][y + 1] + 1) - : Math.max(tabu[x + 1][y], tabu[x][y + 1]); + const [n, m] = [text1.length, text2.length]; + + for (let x = n - 1; 0 <= x; x--) { + /* Time O(N) */ + for (let y = m - 1; 0 <= y; y--) { + /* Time O(M) */ + tabu[x][y] = + text1[x] === text2[y] /* Space O(N * M) */ + ? tabu[x + 1][y + 1] + 1 + : Math.max(tabu[x + 1][y], tabu[x][y + 1]); } } -} +}; /** * DP - Bottom Up @@ -113,32 +162,34 @@ var search = (text1, text2, tabu) => { * @return {number} */ var longestCommonSubsequence = (text1, text2) => { - const canSwap = (text2.length < text1.length); - if (canSwap) [ text1, text2 ] = [ text2, text1 ]; + const canSwap = text2.length < text1.length; + if (canSwap) [text1, text2] = [text2, text1]; - let tabu = initTabu(text1); /* Time O(M) | Space O(M) */ + let tabu = initTabu(text1); /* Time O(M) | Space O(M) */ - tabu = search(text1, text2, tabu);/* Time O(N * M) | Space O(M) */ + tabu = search(text1, text2, tabu); /* Time O(N * M) | Space O(M) */ return tabu[0]; }; -var initTabu = (text1) => new Array((text1.length + 1)).fill(0) +var initTabu = (text1) => new Array(text1.length + 1).fill(0); var search = (text1, text2, tabu) => { - for (let col = (text2.length - 1); (0 <= col); col--) {/* Time O(N) */ - const temp = initTabu(text1); /* Space O(M) */ + for (let col = text2.length - 1; 0 <= col; col--) { + /* Time O(N) */ + const temp = initTabu(text1); /* Space O(M) */ - for (let row = (text1.length - 1); (0 <= row); row--) {/* Time O(M) */ - const isEqual = (text1[row] == text2[col]); + for (let row = text1.length - 1; 0 <= row; row--) { + /* Time O(M) */ + const isEqual = text1[row] == text2[col]; - temp[row] = isEqual /* Space O(M) */ - ? (tabu[(row + 1)] + 1) - : Math.max(tabu[row], temp[(row + 1)]); + temp[row] = isEqual /* Space O(M) */ + ? tabu[row + 1] + 1 + : Math.max(tabu[row], temp[row + 1]); } - tabu = temp; /* Space O(M) */ + tabu = temp; /* Space O(M) */ } return tabu; -} +}; diff --git a/javascript/1189-maximum-number-of-balloons.js b/javascript/1189-maximum-number-of-balloons.js index 9985f763c..22f094b34 100644 --- a/javascript/1189-maximum-number-of-balloons.js +++ b/javascript/1189-maximum-number-of-balloons.js @@ -2,24 +2,24 @@ // time complexity O(n) // space complexity O(n) -var maxNumberOfBalloons = function(text) { - - const balloonCach = {}; +var maxNumberOfBalloons = function (text) { + const balloonCach = {}; const ballonSet = new Set(text.split('')); - + for (const char of text) { - if (!ballonSet.has(char)) continue; + if (!ballonSet.has(char)) continue; - const count = ((balloonCach[char] ?? 0) + 1) + const count = (balloonCach[char] ?? 0) + 1; balloonCach[char] = count; } - let min = Math.min(balloonCach['b'], - balloonCach['a'], - balloonCach['n'], - Math.floor(balloonCach['l']/2), - Math.floor(balloonCach['o']/2)); - + let min = Math.min( + balloonCach['b'], + balloonCach['a'], + balloonCach['n'], + Math.floor(balloonCach['l'] / 2), + Math.floor(balloonCach['o'] / 2), + ); + return min ? min : 0; }; - diff --git a/javascript/1260-shift-2d-grid.js b/javascript/1260-shift-2d-grid.js index 8491c15ea..1866f41b4 100644 --- a/javascript/1260-shift-2d-grid.js +++ b/javascript/1260-shift-2d-grid.js @@ -1,16 +1,14 @@ -var shiftGrid = function(grid, k) { - const M = grid.length, N = grid[0].length; - - let posToVal = (r, c) => - r * N + c; - let valToPos = (v) => - [Math.floor(v / N), v % N]; - +var shiftGrid = function (grid, k) { + const M = grid.length, + N = grid[0].length; + + let posToVal = (r, c) => r * N + c; + let valToPos = (v) => [Math.floor(v / N), v % N]; + res = []; - for(let i = 0; i < M; i++) - res.push([]); - for(let r = 0; r < M; r++) - for(let c = 0; c < N; c++) { + for (let i = 0; i < M; i++) res.push([]); + for (let r = 0; r < M; r++) + for (let c = 0; c < N; c++) { let newVal = (posToVal(r, c) + k) % (M * N); let newRC = valToPos(newVal); res[newRC[0]][newRC[1]] = grid[r][c]; diff --git a/javascript/1268-search-suggestions-system.js b/javascript/1268-search-suggestions-system.js index 513b3844d..56ad706f8 100644 --- a/javascript/1268-search-suggestions-system.js +++ b/javascript/1268-search-suggestions-system.js @@ -1,22 +1,21 @@ /** * Binary Search - * + * * Time O(n*log(n) + m*n) | Space O(m) * https://leetcode.com/problems/search-suggestions-system/description/ * @param {string[]} products * @param {string} searchWord * @return {string[][]} */ -var suggestedProducts = function(products, searchWord) { - +var suggestedProducts = function (products, searchWord) { products.sort((product1, product2) => { - if(product1 < product2) { + if (product1 < product2) { return -1; } - if(product2 < product1) { + if (product2 < product1) { return 1; } - if(product1 === product2) { + if (product1 === product2) { return 0; } }); @@ -24,20 +23,26 @@ var suggestedProducts = function(products, searchWord) { const result = []; let left = 0; let right = products.length - 1; - for(let i = 0; i < searchWord.length; i++) { + for (let i = 0; i < searchWord.length; i++) { let char = searchWord[i]; - - while(left <= right && (products[left].length - 1 < i || products[left][i] !== char)) { + + while ( + left <= right && + (products[left].length - 1 < i || products[left][i] !== char) + ) { left++; } - while(left <= right && (products[right].length - 1 < i || products[right][i] !== char)) { + while ( + left <= right && + (products[right].length - 1 < i || products[right][i] !== char) + ) { right--; } const subResult = []; const len = Math.min(right - left + 1, 3); - for(let j = 0; j < len; j++) { - subResult.push(products[left+j]); + for (let j = 0; j < len; j++) { + subResult.push(products[left + j]); } result.push(subResult); } @@ -53,34 +58,33 @@ var suggestedProducts = function(products, searchWord) { * @param {string} searchWord * @return {string[][]} */ -var suggestedProducts1 = (products, searchWord) => new Trie() - .buildTrie(products) - .searchWord(searchWord); +var suggestedProducts1 = (products, searchWord) => + new Trie().buildTrie(products).searchWord(searchWord); class Node { - constructor () { + constructor() { this.children = new Map(); this.isWord = false; } -}; +} class Trie { - constructor () { + constructor() { this.root = new Node(); } - buildTrie (products) { + buildTrie(products) { for (const word of products) { this.insert(word); } return this; } - - insert (word, { root: node } = this) { + + insert(word, { root: node } = this) { for (const char of word.split('')) { - const child = (node.children.get(char) ?? new Node()); - + const child = node.children.get(char) ?? new Node(); + node.children.set(char, child); node = child; @@ -88,38 +92,38 @@ class Trie { node.isWord = true; } - - searchWord (searchWord, buffer = [], suggestions = []) { + + searchWord(searchWord, buffer = [], suggestions = []) { for (const char of searchWord.split('')) { const prefix = this.getPrefix(buffer, char); const words = this.getSuggestions(prefix); suggestions.push(words); } - + return suggestions; } - getPrefix (buffer, char) { + getPrefix(buffer, char) { buffer.push(char); return buffer.join(''); } - - getSuggestions (prefix, words = []) { + + getSuggestions(prefix, words = []) { const node = this.getPrefixNode(prefix); - const isInvalidPrefix = (node === null); - if (isInvalidPrefix) return words - + const isInvalidPrefix = node === null; + if (isInvalidPrefix) return words; + return this.search(node, prefix, words); } - getPrefixNode (prefix, { root: node } = this) { + getPrefixNode(prefix, { root: node } = this) { for (const char of prefix.split('')) { - const child = (node.children.get(char) ?? null); + const child = node.children.get(char) ?? null; - const isLeafNode = (child === null); + const isLeafNode = child === null; if (isLeafNode) return null; node = child; @@ -128,8 +132,8 @@ class Trie { return node; } - search (node, word, words) { - const isBaseCase = (words.length === 3); + search(node, word, words) { + const isBaseCase = words.length === 3; if (isBaseCase) return words; if (node.isWord) words.push(word); @@ -137,21 +141,22 @@ class Trie { return this.dfs(node, word, words); } - dfs (node, word, words) { + dfs(node, word, words) { for (const char of this.getChars()) { - const child = (node.children.get(char) ?? null); + const child = node.children.get(char) ?? null; - const isLeafNode = (child === null); + const isLeafNode = child === null; if (isLeafNode) continue; - - this.search(child, (word + char), words); + + this.search(child, word + char, words); } return words; } - getChars () { - return new Array(26).fill() - .map((_, index) => String.fromCharCode((index + 97))); + getChars() { + return new Array(26) + .fill() + .map((_, index) => String.fromCharCode(index + 97)); } -}; +} diff --git a/javascript/1290-convert-binary-number-in-a-linked-list-to-integer.js b/javascript/1290-convert-binary-number-in-a-linked-list-to-integer.js index a3a377217..24ec6a03b 100644 --- a/javascript/1290-convert-binary-number-in-a-linked-list-to-integer.js +++ b/javascript/1290-convert-binary-number-in-a-linked-list-to-integer.js @@ -11,10 +11,11 @@ */ var getDecimalValue = function (head) { let value = 0; // initialize value to zero - while (head) { // while loop will run till head becomes null + while (head) { + // while loop will run till head becomes null value = (value << 1) | head.val; // used left shift operator (<<) and bitwise OR (|) operator returns a number from binary head = head.next; // next value of head } return value; // return the value -}; \ No newline at end of file +}; diff --git a/javascript/1299-replace-elements-with-greatest-element-on-right-side.js b/javascript/1299-replace-elements-with-greatest-element-on-right-side.js index f2283a7e4..7d282c268 100644 --- a/javascript/1299-replace-elements-with-greatest-element-on-right-side.js +++ b/javascript/1299-replace-elements-with-greatest-element-on-right-side.js @@ -5,15 +5,16 @@ * @param {number[]} arr * @return {number[]} */ -var replaceElements = (arr, max = -1, ans = [ -1 ]) => { - arr = arr.reverse(); /* Time O(N) */ - - for (let i = 0; (i < (arr.length - 1)); i++) {/* Time O(N) */ +var replaceElements = (arr, max = -1, ans = [-1]) => { + arr = arr.reverse(); /* Time O(N) */ + + for (let i = 0; i < arr.length - 1; i++) { + /* Time O(N) */ max = Math.max(max, arr[i]); - ans[(i + 1)] = max; /* Space O(N) */ + ans[i + 1] = max; /* Space O(N) */ } - - return ans.reverse(); /* Time O(N) */ + + return ans.reverse(); /* Time O(N) */ }; /** @@ -23,21 +24,21 @@ var replaceElements = (arr, max = -1, ans = [ -1 ]) => { * @param {number[]} arr * @return {number[]} */ -var replaceElements = (arr, max = -1) => { - for (let i = (arr.length - 1); (0 <= i); i--) {/* Time O(N) */ - const num = arr[i]; +var replaceElements = (arr, max = -1) => { + for (let i = arr.length - 1; 0 <= i; i--) { + /* Time O(N) */ + const num = arr[i]; - arr[i] = max; - max = Math.max(max, num); - } + arr[i] = max; + max = Math.max(max, num); + } - return arr; + return arr; }; -// This is brute force with O(n^2). Just for reference's sake. +// This is brute force with O(n^2). Just for reference's sake. // submission link: https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/submissions/844439163/ -var replaceElementsBrute = function(arr) { - - for(let i = 0; i < arr.length; i++) { +var replaceElementsBrute = function (arr) { + for (let i = 0; i < arr.length; i++) { arr[i] = biggestElement(i, arr); } @@ -46,9 +47,8 @@ var replaceElementsBrute = function(arr) { }; function biggestElement(index, arr) { - let biggest = 0; - for(let i = index + 1; i < arr.length; i++) { + for (let i = index + 1; i < arr.length; i++) { biggest = Math.max(biggest, arr[i]); } diff --git a/javascript/1323-maximum-69-number.js b/javascript/1323-maximum-69-number.js index 11dc25fe5..b1d2e1699 100644 --- a/javascript/1323-maximum-69-number.js +++ b/javascript/1323-maximum-69-number.js @@ -7,10 +7,12 @@ var maximum69Number = function (num) { let numArr = num.toString().split(''); // initialize numArr as array of num - for (let i = 0; i < numArr.length; i++) { // loop through the every element of array numArr + for (let i = 0; i < numArr.length; i++) { + // loop through the every element of array numArr - if (numArr[i] == 6) { // if current element of numArr is 6 - let arr = [...numArr] // copy numArr into arr + if (numArr[i] == 6) { + // if current element of numArr is 6 + let arr = [...numArr]; // copy numArr into arr arr.splice(i, 1, 9); // make current element arr to 9 maxArr.push(arr.join('')); // convert arr to string and push into maxArr and break the loop break; @@ -18,4 +20,4 @@ var maximum69Number = function (num) { } return Math.max(...maxArr); // return max value from maxArr -}; \ No newline at end of file +}; diff --git a/javascript/1325-delete-leaves-with-a-given-value.js b/javascript/1325-delete-leaves-with-a-given-value.js index 5b0ea13c7..1e1cd2c45 100644 --- a/javascript/1325-delete-leaves-with-a-given-value.js +++ b/javascript/1325-delete-leaves-with-a-given-value.js @@ -14,8 +14,7 @@ * @param {number} target * @return {TreeNode} */ -var removeLeafNodes = function(root, target) { - +var removeLeafNodes = function (root, target) { const dfs = (node) => { if (!node) return null; node.left = dfs(node.left); @@ -24,7 +23,7 @@ var removeLeafNodes = function(root, target) { if (node.val === target) return null; } return node; - } + }; return dfs(root); }; diff --git a/javascript/1342-number-of-steps-to-reduce-a-number-to-zero.js b/javascript/1342-number-of-steps-to-reduce-a-number-to-zero.js index c1ae9000f..848984709 100644 --- a/javascript/1342-number-of-steps-to-reduce-a-number-to-zero.js +++ b/javascript/1342-number-of-steps-to-reduce-a-number-to-zero.js @@ -5,17 +5,21 @@ var numberOfSteps = function (num) { let count = 0; // initialize count to zero let ans = num; // initialize ans to num - while (ans >= 0) { // loop the ans if anwer is greater than or equal to zero - if (ans === 0) { // if ans is zero then break while loop + while (ans >= 0) { + // loop the ans if anwer is greater than or equal to zero + if (ans === 0) { + // if ans is zero then break while loop break; } - if (ans % 2 === 0) { // if ans is even then divide it by 2 and increment count + if (ans % 2 === 0) { + // if ans is even then divide it by 2 and increment count ans /= 2; count++; - } else { // if ans is odd then decrement ans by -1 and increment count + } else { + // if ans is odd then decrement ans by -1 and increment count ans -= 1; count++; } } return count; // return the count -}; \ No newline at end of file +}; diff --git a/javascript/1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.js b/javascript/1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.js index 721595879..9278b7b71 100644 --- a/javascript/1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.js +++ b/javascript/1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold.js @@ -5,18 +5,17 @@ * @return {number} */ var numOfSubarrays = function (arr, k, threshold) { - if (arr.length < k) return 0; - let count = 0; - let sum = 0; - let L = 0; - for (let R = 0; R < arr.length; R++) { - sum += arr[R]; - if (R - L + 1 === k) { - if (sum / k >= threshold) - count += 1; - sum -= arr[L]; - L += 1; + if (arr.length < k) return 0; + let count = 0; + let sum = 0; + let L = 0; + for (let R = 0; R < arr.length; R++) { + sum += arr[R]; + if (R - L + 1 === k) { + if (sum / k >= threshold) count += 1; + sum -= arr[L]; + L += 1; + } } - } - return count; + return count; }; diff --git a/javascript/1361-validate-binary-tree-nodes.js b/javascript/1361-validate-binary-tree-nodes.js index 4a613fd39..71962efe5 100644 --- a/javascript/1361-validate-binary-tree-nodes.js +++ b/javascript/1361-validate-binary-tree-nodes.js @@ -2,41 +2,38 @@ * DFS * Time O(n) | Space O(n) * https://leetcode.com/problems/validate-binary-tree-nodes/ - * + * * @param {number} n * @param {number[]} leftChild * @param {number[]} rightChild * @return {boolean} */ -var validateBinaryTreeNodes = function(n, leftChild, rightChild) { - +var validateBinaryTreeNodes = function (n, leftChild, rightChild) { const visited = new Set(); const findRoot = () => { - - const childrenSet = new Set(); - for (let i = 0; i < n; i++) { - childrenSet.add(i); - } - - for (let i = 0; i < n; i++) { - childrenSet.delete(leftChild[i]); - childrenSet.delete(rightChild[i]); - } + const childrenSet = new Set(); + for (let i = 0; i < n; i++) { + childrenSet.add(i); + } - return [...childrenSet][0]; - } + for (let i = 0; i < n; i++) { + childrenSet.delete(leftChild[i]); + childrenSet.delete(rightChild[i]); + } - const dfs = (i) => { + return [...childrenSet][0]; + }; - if (i === -1) return true; - if (visited.has(i)) return false; + const dfs = (i) => { + if (i === -1) return true; + if (visited.has(i)) return false; - const left = leftChild[i]; - const right = rightChild[i]; - visited.add(i); - return dfs(left) && dfs(right); - } + const left = leftChild[i]; + const right = rightChild[i]; + visited.add(i); + return dfs(left) && dfs(right); + }; const root = findRoot(); return dfs(root) && visited.size === n; diff --git a/javascript/1376-time-needed-to-inform-all-employees.js b/javascript/1376-time-needed-to-inform-all-employees.js index aec42b207..5e4d6e3f9 100644 --- a/javascript/1376-time-needed-to-inform-all-employees.js +++ b/javascript/1376-time-needed-to-inform-all-employees.js @@ -1,5 +1,5 @@ /** - * DFS | Tree + * DFS | Tree * Time O(n) | Space O(n) * https://leetcode.com/problems/time-needed-to-inform-all-employees/ * @param {number} n @@ -8,11 +8,9 @@ * @param {number[]} informTime * @return {number} */ -var numOfMinutes = function(n, headID, manager, informTime) { - +var numOfMinutes = function (n, headID, manager, informTime) { const tree = {}; for (let i = 0; i < manager.length; i++) { - if (manager[i] === -1) continue; const senior = manager[i]; @@ -25,7 +23,6 @@ var numOfMinutes = function(n, headID, manager, informTime) { tree[senior].push(junior); } - let time = 0; const dfs = (node, totalTime) => { if (tree[node] === undefined) { @@ -35,11 +32,11 @@ var numOfMinutes = function(n, headID, manager, informTime) { const subordinates = tree[node]; - for (let i = 0; i < subordinates.length; i++) { + for (let i = 0; i < subordinates.length; i++) { const subordinate = subordinates[i]; dfs(subordinate, totalTime + informTime[node]); } - } + }; dfs(headID, 0); diff --git a/javascript/1383-maximum-performance-of-a-team.js b/javascript/1383-maximum-performance-of-a-team.js index 0e10a8263..364b5a2a3 100644 --- a/javascript/1383-maximum-performance-of-a-team.js +++ b/javascript/1383-maximum-performance-of-a-team.js @@ -8,13 +8,13 @@ * @param {number} k * @return {number}` */ -var maxPerformance = function(n, speed, efficiency, k) { - const mod = 10**9 + 7; +var maxPerformance = function (n, speed, efficiency, k) { + const mod = 10 ** 9 + 7; const minSpeedHeap = new MinPriorityQueue({ compare: (a, b) => { return a - b; - } + }, }); efficiency = efficiency.map((eff, idx) => { @@ -22,7 +22,7 @@ var maxPerformance = function(n, speed, efficiency, k) { }); efficiency.sort((a, b) => b[0] - a[0]); - + let speedSoFar = 0; let max = 0; @@ -36,7 +36,7 @@ var maxPerformance = function(n, speed, efficiency, k) { speedSoFar += efficiency[i][1]; const minEfficiency = efficiency[i][0]; - max = Math.max(max, (speedSoFar * minEfficiency)); + max = Math.max(max, speedSoFar * minEfficiency); minSpeedHeap.enqueue(efficiency[i][1]); } diff --git a/javascript/1396-design-underground-system.js b/javascript/1396-design-underground-system.js index 849731125..71435676f 100644 --- a/javascript/1396-design-underground-system.js +++ b/javascript/1396-design-underground-system.js @@ -1,54 +1,55 @@ // https://leetcode.com/problems/design-underground-system/ class UndergroundSystem { - constructor() { - this.stationSystem = {}; - this.averageTime = {}; - } + constructor() { + this.stationSystem = {}; + this.averageTime = {}; + } - /** - * Time O(1) | Space O(1) - * Records the check-in time and station for a user. - * @param {number} id - User ID - * @param {string} stationName - Check-in station name - * @param {number} t - Check-in time - * @return {void} - */ - checkIn(id, stationName, t) { - this.stationSystem[id] = [stationName, '', t, '']; - } + /** + * Time O(1) | Space O(1) + * Records the check-in time and station for a user. + * @param {number} id - User ID + * @param {string} stationName - Check-in station name + * @param {number} t - Check-in time + * @return {void} + */ + checkIn(id, stationName, t) { + this.stationSystem[id] = [stationName, '', t, '']; + } - /** - * Time O(1) | Space O(1) - * Records the check-out time and station for a user, and calculates the average time. - * @param {number} id - User ID - * @param {string} stationName - Check-out station name - * @param {number} t - Check-out time - * @return {void} - */ - checkOut(id, stationName, t) { - const user = this.stationSystem[id]; - user[1] = stationName; - user[3] = t; - const stationHash = `${user[0]}-${user[1]}`; - if (this.averageTime[stationHash]) { - this.averageTime[stationHash][0] += 1; - this.averageTime[stationHash][1] += user[3] - user[2]; - } else { - this.averageTime[stationHash] = []; - this.averageTime[stationHash][0] = 1; - this.averageTime[stationHash][1] = user[3] - user[2]; + /** + * Time O(1) | Space O(1) + * Records the check-out time and station for a user, and calculates the average time. + * @param {number} id - User ID + * @param {string} stationName - Check-out station name + * @param {number} t - Check-out time + * @return {void} + */ + checkOut(id, stationName, t) { + const user = this.stationSystem[id]; + user[1] = stationName; + user[3] = t; + const stationHash = `${user[0]}-${user[1]}`; + if (this.averageTime[stationHash]) { + this.averageTime[stationHash][0] += 1; + this.averageTime[stationHash][1] += user[3] - user[2]; + } else { + this.averageTime[stationHash] = []; + this.averageTime[stationHash][0] = 1; + this.averageTime[stationHash][1] = user[3] - user[2]; + } } - } - /** - * Time O(1) | Space O(1) - * Returns the average time taken to travel between two stations. - * @param {string} startStation - Start station name - * @param {string} endStation - End station name - * @return {number} - Average time in hours - */ - getAverageTime(startStation, endStation) { - const [rounds, totalHours] = this.averageTime[`${startStation}-${endStation}`]; - return totalHours / rounds; - } + /** + * Time O(1) | Space O(1) + * Returns the average time taken to travel between two stations. + * @param {string} startStation - Start station name + * @param {string} endStation - End station name + * @return {number} - Average time in hours + */ + getAverageTime(startStation, endStation) { + const [rounds, totalHours] = + this.averageTime[`${startStation}-${endStation}`]; + return totalHours / rounds; + } } diff --git a/javascript/1405-longest-happy-string.js b/javascript/1405-longest-happy-string.js index eab01f090..fbd4a67bd 100644 --- a/javascript/1405-longest-happy-string.js +++ b/javascript/1405-longest-happy-string.js @@ -7,28 +7,27 @@ * @param {number} c * @return {string} */ -var longestDiverseString = function(a, b, c) { - +var longestDiverseString = function (a, b, c) { const maxQ = new MaxPriorityQueue({ - compare: (a,b) => { - return b[0]-a[0]; - } + compare: (a, b) => { + return b[0] - a[0]; + }, }); - a && maxQ.enqueue([a, "a"]); - b && maxQ.enqueue([b, "b"]); - c && maxQ.enqueue([c, "c"]); + a && maxQ.enqueue([a, 'a']); + b && maxQ.enqueue([b, 'b']); + c && maxQ.enqueue([c, 'c']); - let happyStr = ""; - - while(!maxQ.isEmpty()) { + let happyStr = ''; - let [count, char] = maxQ.dequeue(); + while (!maxQ.isEmpty()) { + let [count, char] = maxQ.dequeue(); - if(happyStr[happyStr.length - 1] === char && - happyStr[happyStr.length - 2] === char) { - - if(!maxQ.isEmpty()) { + if ( + happyStr[happyStr.length - 1] === char && + happyStr[happyStr.length - 2] === char + ) { + if (!maxQ.isEmpty()) { let [count1, char1] = maxQ.dequeue(); happyStr += char1; @@ -36,10 +35,9 @@ var longestDiverseString = function(a, b, c) { count1 && maxQ.enqueue([count1, char1]); maxQ.enqueue([count, char]); - } + } } else { - - if(count >= 2) { + if (count >= 2) { happyStr += char.repeat(2); count -= 2; } else { diff --git a/javascript/1423-maximum-points-you-can-obtain-from-cards.js b/javascript/1423-maximum-points-you-can-obtain-from-cards.js index 805c9a5b2..3186fc7f2 100644 --- a/javascript/1423-maximum-points-you-can-obtain-from-cards.js +++ b/javascript/1423-maximum-points-you-can-obtain-from-cards.js @@ -1,17 +1,18 @@ /** - * Greedy | Sliding Window | PrefixSum + * Greedy | Sliding Window | PrefixSum * Time O(n) | Space O(1) * https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/ * @param {number[]} cardPoints * @param {number} k * @return {number} */ -var maxScore = function(cardPoints, k) { - +var maxScore = function (cardPoints, k) { const total = cardPoints.reduce((acc, curr) => acc + curr, 0); - let currTotal = cardPoints.slice(0, cardPoints.length - k).reduce((acc, curr) => acc + curr, 0); + let currTotal = cardPoints + .slice(0, cardPoints.length - k) + .reduce((acc, curr) => acc + curr, 0); let max = total - currTotal; - + let left = 0; let right = cardPoints.length - k - 1; // -1 because the array is 0 indexed. diff --git a/javascript/1443-minimum-time-to-collect-all-apples-in-a-tree.js b/javascript/1443-minimum-time-to-collect-all-apples-in-a-tree.js index 1230778ef..7f1aaa36e 100644 --- a/javascript/1443-minimum-time-to-collect-all-apples-in-a-tree.js +++ b/javascript/1443-minimum-time-to-collect-all-apples-in-a-tree.js @@ -1,5 +1,5 @@ /** - * Graph | DFS + * Graph | DFS * Time O(n) | Space O(n) * https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/ * @param {number} n @@ -7,7 +7,7 @@ * @param {boolean[]} hasApple * @return {number} */ -var minTime = function(n, edges, hasApple) { +var minTime = function (n, edges, hasApple) { if (n === 1) return 0; const result = dfs(0, -1, makeGraph(edges), hasApple) - 2; return (result > 0 && result) || 0; @@ -18,17 +18,16 @@ const dfs = (curr, pre, graph, hasApple) => { for (const nextNode of graph[curr]) { if (nextNode === pre) continue; pathLen += dfs(nextNode, curr, graph, hasApple); - } + } if (pathLen > 0 || hasApple[curr]) return pathLen + 2; return 0; -} +}; const makeGraph = (edges) => { const graph = {}; for (let i = 0; i < edges.length; i++) { - const from = edges[i][0]; const to = edges[i][1]; @@ -38,11 +37,11 @@ const makeGraph = (edges) => { if (!graph[to]) { graph[to] = []; - }; + } graph[to].push(from); graph[from].push(to); } return graph; -} +}; diff --git a/javascript/1448-count-good-nodes-in-binary-tree.js b/javascript/1448-count-good-nodes-in-binary-tree.js index 21cfd6d56..d28996622 100644 --- a/javascript/1448-count-good-nodes-in-binary-tree.js +++ b/javascript/1448-count-good-nodes-in-binary-tree.js @@ -1,59 +1,59 @@ -/** - * https://leetcode.com/problems/count-good-nodes-in-binary-tree/ - * Time O(N) | Space O(H) - * @param {TreeNode} root - * @return {number} - */ - var goodNodes = function(root, max = -Infinity, total = [ 0 ]) { - count(root, max, total); - - return total[0] -}; - -const count = (root, max, total) => { - const isBaseCase = root === null; - if (isBaseCase) return 0; - - return dfs(root, max, total); -} - -const dfs = (root, max, total) => { - const isGood = max <= root.val - if (isGood) total[0]++; - - max = Math.max(max, root.val); - - count(root.left, max, total); - count(root.right, max, total); -} - -/** - * https://leetcode.com/problems/count-good-nodes-in-binary-tree/ - * Time O(N) | Space O(W) - * @param {TreeNode} root - * @return {number} - */ -var goodNodes = function(root, ) { - const isBaseCase = root === null; - if (isBaseCase) return 0 - - return bfs([[ root, -Infinity ]]); -} - -const bfs = (queue, total = 0) => { - while (queue.length) { - for (let i = (queue.length - 1); 0 <= i; i--) { - let [ root, max ] = queue.shift(); - - const isGood = max <= root.val; - if (isGood) total++; - - max = Math.max(max, root.val); - - if (root.right) queue.push([ root.right, max ]); - if (root.left) queue.push([ root.left, max ]); - } - } - - return total; -} +/** + * https://leetcode.com/problems/count-good-nodes-in-binary-tree/ + * Time O(N) | Space O(H) + * @param {TreeNode} root + * @return {number} + */ +var goodNodes = function (root, max = -Infinity, total = [0]) { + count(root, max, total); + + return total[0]; +}; + +const count = (root, max, total) => { + const isBaseCase = root === null; + if (isBaseCase) return 0; + + return dfs(root, max, total); +}; + +const dfs = (root, max, total) => { + const isGood = max <= root.val; + if (isGood) total[0]++; + + max = Math.max(max, root.val); + + count(root.left, max, total); + count(root.right, max, total); +}; + +/** + * https://leetcode.com/problems/count-good-nodes-in-binary-tree/ + * Time O(N) | Space O(W) + * @param {TreeNode} root + * @return {number} + */ +var goodNodes = function (root) { + const isBaseCase = root === null; + if (isBaseCase) return 0; + + return bfs([[root, -Infinity]]); +}; + +const bfs = (queue, total = 0) => { + while (queue.length) { + for (let i = queue.length - 1; 0 <= i; i--) { + let [root, max] = queue.shift(); + + const isGood = max <= root.val; + if (isGood) total++; + + max = Math.max(max, root.val); + + if (root.right) queue.push([root.right, max]); + if (root.left) queue.push([root.left, max]); + } + } + + return total; +}; diff --git a/javascript/1461-check-if-a-string-contains-all-binary-codes-of-size-k.js b/javascript/1461-check-if-a-string-contains-all-binary-codes-of-size-k.js index f95ef230c..2d10a0d5b 100644 --- a/javascript/1461-check-if-a-string-contains-all-binary-codes-of-size-k.js +++ b/javascript/1461-check-if-a-string-contains-all-binary-codes-of-size-k.js @@ -1,22 +1,20 @@ /** * https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/ - * + * * Hashing * Time O(n*k) | Space O(2^k) (it can't get any bigger than 2^k in the worst case) * @param {string} s * @param {number} k * @return {boolean} */ -var hasAllCodes = function(s, k) { - +var hasAllCodes = function (s, k) { const bitSet = new Set(); - for(let i = 0; i < s.length; i++) { - if(s.substring(i,i+k).length === k) { - bitSet.add(s.substring(i,i + k)); + for (let i = 0; i < s.length; i++) { + if (s.substring(i, i + k).length === k) { + bitSet.add(s.substring(i, i + k)); } } - return bitSet.size === 1< a[1] - b[1]); frequenciesArr.reverse(); - + while (k) { const lastEl = frequenciesArr[frequenciesArr.length - 1]; while (lastEl[1]) { diff --git a/javascript/1486-xor-operation-in-an-array.js b/javascript/1486-xor-operation-in-an-array.js index ea3342f3b..4e8eb63c7 100644 --- a/javascript/1486-xor-operation-in-an-array.js +++ b/javascript/1486-xor-operation-in-an-array.js @@ -1,14 +1,15 @@ -/** - * @param {number} n - * @param {number} start - * @return {number} - */ -var xorOperation = function(n, start) { - let nums = new Array(n).fill(0); // initialize a nums which is the length of n elements with 0 value of Array using Array() nad fill() - - for(let i=0; i a^b); // return the bitwise XOR of all elements of nums using reduce() -}; +/** + * @param {number} n + * @param {number} start + * @return {number} + */ +var xorOperation = function (n, start) { + let nums = new Array(n).fill(0); // initialize a nums which is the length of n elements with 0 value of Array using Array() nad fill() + + for (let i = 0; i < n; i++) { + // loop through the 0 to n + nums[i] = start + 2 * i; // current element of nums is equal to sum of start and twice the i + } + + return nums.reduce((a, b) => a ^ b); // return the bitwise XOR of all elements of nums using reduce() +}; diff --git a/javascript/1512-number-of-good-pairs.js b/javascript/1512-number-of-good-pairs.js index e0cb98100..c2aa6bb45 100644 --- a/javascript/1512-number-of-good-pairs.js +++ b/javascript/1512-number-of-good-pairs.js @@ -12,4 +12,4 @@ var numIdenticalPairs = function (nums) { } } return result; -}; \ No newline at end of file +}; diff --git a/javascript/1514-path-with-maximum-probability.js b/javascript/1514-path-with-maximum-probability.js index 900b39bb0..863dc980c 100644 --- a/javascript/1514-path-with-maximum-probability.js +++ b/javascript/1514-path-with-maximum-probability.js @@ -6,7 +6,7 @@ * @param {number} end * @return {number} */ -var maxProbability = function(n, edges, succProb, start, end) { +var maxProbability = function (n, edges, succProb, start, end) { const genAdjList = () => { /*** { @@ -16,35 +16,35 @@ var maxProbability = function(n, edges, succProb, start, end) { } ***/ let list = {}; - for(let i = 0; i < n; i++) { + for (let i = 0; i < n; i++) { list[i] = []; } - for(let i = 0; i < edges.length; i++) { + for (let i = 0; i < edges.length; i++) { const [v1, v2] = edges[i]; const p = succProb[i]; list[v1].push([v2, p]); list[v2].push([v1, p]); } - + return list; - } + }; const graph = genAdjList(); const queue = new MaxPriorityQueue(); const visited = new Set(); - + queue.enqueue([start, 1], 1); - - while(!queue.isEmpty()) { + + while (!queue.isEmpty()) { const [n1, p1] = queue.dequeue().element; - if(visited.has(n1)) continue; + if (visited.has(n1)) continue; visited.add(n1); - if(n1 === end) return p1; - - for(const [n2, p2] of graph[n1]) { - if(visited.has(n2)) continue; + if (n1 === end) return p1; + + for (const [n2, p2] of graph[n1]) { + if (visited.has(n2)) continue; const val = p1 * p2; queue.enqueue([n2, val], val); } } - if(visited.size !== n) return 0; + if (visited.size !== n) return 0; }; diff --git a/javascript/1572-matrix-diagonal-sum.js b/javascript/1572-matrix-diagonal-sum.js index e857c5601..60fbae98f 100644 --- a/javascript/1572-matrix-diagonal-sum.js +++ b/javascript/1572-matrix-diagonal-sum.js @@ -5,11 +5,13 @@ var diagonalSum = function (mat) { let sum = 0; // initialize sum to zero let n = mat.length - 1; // initialize n to mat length - 1 - for (let i = 0; i <= n; i++) { // loop through to 0 to n + for (let i = 0; i <= n; i++) { + // loop through to 0 to n sum += mat[i][i]; // add mat[i][i] to sum - if (i !== (n - i)) { // if i not equal to n - i then add mat[i][n - i] to sum + if (i !== n - i) { + // if i not equal to n - i then add mat[i][n - i] to sum sum += mat[i][n - i]; } } return sum; // return sum; -}; \ No newline at end of file +}; diff --git a/javascript/1584-min-cost-to-connect-all-points.js b/javascript/1584-min-cost-to-connect-all-points.js index b5d3a295a..bd2f3a4d3 100644 --- a/javascript/1584-min-cost-to-connect-all-points.js +++ b/javascript/1584-min-cost-to-connect-all-points.js @@ -5,7 +5,7 @@ * @return {number} */ const minCostConnectPoints = (points) => { - const isBaseCase = ((points.length === 0) || (1000 <= points.length)); + const isBaseCase = points.length === 0 || 1000 <= points.length; if (isBaseCase) return 0; const { graph, seen, minHeap } = buildGraph(points); @@ -16,38 +16,38 @@ const minCostConnectPoints = (points) => { const initGraph = (points) => ({ graph: new Array(points.length).fill().map(() => []), seen: new Array(points.length).fill(false), - minHeap: new MinPriorityQueue() -}) + minHeap: new MinPriorityQueue(), +}); const buildGraph = (points) => { const { graph, seen, minHeap } = initGraph(points); - for (let src = 0; src < (points.length - 1); src++) { - for (let dst = (src + 1); (dst < points.length); dst++) { + for (let src = 0; src < points.length - 1; src++) { + for (let dst = src + 1; dst < points.length; dst++) { const cost = getCost(points, src, dst); - graph[src].push([ dst, cost ]); - graph[dst].push([ src, cost ]); + graph[src].push([dst, cost]); + graph[dst].push([src, cost]); } } - const [ src, cost, priority ] = [ 0, 0, 0 ]; - const node = [ src, cost ]; + const [src, cost, priority] = [0, 0, 0]; + const node = [src, cost]; minHeap.enqueue(node, priority); return { graph, seen, minHeap }; -} +}; const getCost = (points, src, dst) => { - const [ [ x1, y1 ], [ x2, y2 ] ] = [ points[src], points[dst] ]; + const [[x1, y1], [x2, y2]] = [points[src], points[dst]]; - return (Math.abs(x1 - x2) + Math.abs(y1 - y2)); -} + return Math.abs(x1 - x2) + Math.abs(y1 - y2); +}; const search = (points, graph, seen, minHeap, nodeCount = 0, cost = 0) => { while (nodeCount < points.length) { - let [ src, srcCost ] = minHeap.dequeue().element; + let [src, srcCost] = minHeap.dequeue().element; if (seen[src]) continue; seen[src] = true; @@ -59,12 +59,12 @@ const search = (points, graph, seen, minHeap, nodeCount = 0, cost = 0) => { } return cost; -} +}; const checkNeighbors = (graph, src, seen, minHeap) => { - for (const [ dst, dstCost ] of graph[src]) { + for (const [dst, dstCost] of graph[src]) { if (seen[dst]) continue; - minHeap.enqueue([ dst, dstCost ], dstCost); + minHeap.enqueue([dst, dstCost], dstCost); } -} \ No newline at end of file +}; diff --git a/javascript/1588-sum-of-all-odd-length-subarrays.js b/javascript/1588-sum-of-all-odd-length-subarrays.js index 6c47dd70b..e06f21172 100644 --- a/javascript/1588-sum-of-all-odd-length-subarrays.js +++ b/javascript/1588-sum-of-all-odd-length-subarrays.js @@ -3,10 +3,11 @@ * @return {number} */ var sumOddLengthSubarrays = function (arr) { - let sum = 0, len = arr.length; + let sum = 0, + len = arr.length; for (let i = 0; i < arr.length; i++) { let total = i * (len - i) + (len - i); sum += Math.ceil(total / 2) * arr[i]; } return sum; -}; \ No newline at end of file +}; diff --git a/javascript/1603-design-parking-system.js b/javascript/1603-design-parking-system.js index 8a17d286f..0750e41b9 100644 --- a/javascript/1603-design-parking-system.js +++ b/javascript/1603-design-parking-system.js @@ -6,39 +6,39 @@ * @param {number} small */ class ParkingSystem { - constructor(big, medium, small) { - this.isBigRemaining = big; - this.isMediumRemaining = medium; - this.isSmallRemaining = small; - } - - /** - * Time O(1) | Space O(1) - * @param {number} carType - * @return {boolean} - */ - addCar(carType) { - const isBigCarAvailable = (carType === 1 && this.isBigRemaining > 0); - if(isBigCarAvailable) { - this.isBigRemaining -= 1; - return true; - } - const isMediumCarAvailable = (carType === 2 && this.isMediumRemaining > 0); - if(isMediumCarAvailable) { - this.isMediumRemaining -= 1; - return true; + constructor(big, medium, small) { + this.isBigRemaining = big; + this.isMediumRemaining = medium; + this.isSmallRemaining = small; } - const isSmallCarAvailable = (carType === 3 && this.isSmallRemaining > 0); - if(isSmallCarAvailable) { - this.isSmallRemaining -= 1; - return true; + + /** + * Time O(1) | Space O(1) + * @param {number} carType + * @return {boolean} + */ + addCar(carType) { + const isBigCarAvailable = carType === 1 && this.isBigRemaining > 0; + if (isBigCarAvailable) { + this.isBigRemaining -= 1; + return true; + } + const isMediumCarAvailable = + carType === 2 && this.isMediumRemaining > 0; + if (isMediumCarAvailable) { + this.isMediumRemaining -= 1; + return true; + } + const isSmallCarAvailable = carType === 3 && this.isSmallRemaining > 0; + if (isSmallCarAvailable) { + this.isSmallRemaining -= 1; + return true; + } + return false; } - return false; - } } - -/** +/** * Your ParkingSystem object will be instantiated and called as such: * var obj = new ParkingSystem(big, medium, small) * var param_1 = obj.addCar(carType) diff --git a/javascript/1609-even-odd-tree.js b/javascript/1609-even-odd-tree.js index 9acd11f83..0261de1a5 100644 --- a/javascript/1609-even-odd-tree.js +++ b/javascript/1609-even-odd-tree.js @@ -14,31 +14,32 @@ * @param {TreeNode} root * @return {boolean} */ -var isEvenOddTree = function(root) { - +var isEvenOddTree = function (root) { // helper function const isStricklyIncreasingAndOdd = (arr) => { - for (let i = 0; i < arr.length; i++) { const currElement = arr[i]; - const nextElement = (arr[i + 1] !== undefined && arr[i + 1]) || Infinity; - if (currElement >= nextElement || currElement % 2 === 0) return false; + const nextElement = + (arr[i + 1] !== undefined && arr[i + 1]) || Infinity; + if (currElement >= nextElement || currElement % 2 === 0) + return false; } return true; - } - + }; + // helper function const isStricklyDecreasingAndEven = (arr) => { - for (let i = 0; i < arr.length; i++) { const currElement = arr[i]; - const nextElement = (arr[i + 1] !== undefined && arr[i + 1]) || -Infinity; - if (currElement <= nextElement || currElement % 2 === 1) return false; + const nextElement = + (arr[i + 1] !== undefined && arr[i + 1]) || -Infinity; + if (currElement <= nextElement || currElement % 2 === 1) + return false; } return true; - } + }; const q = new Queue(); q.enqueue([root, 0]); @@ -50,7 +51,6 @@ var isEvenOddTree = function(root) { const level = q.front()[1]; for (let i = 0; i < size; i++) { - const element = q.dequeue(); const node = element[0]; levelArr.push(node.val); @@ -59,8 +59,10 @@ var isEvenOddTree = function(root) { node.right && q.enqueue([node.right, level + 1]); } - if (level % 2 === 0 && !isStricklyIncreasingAndOdd(levelArr)) return false; - if (level % 2 === 1 && !isStricklyDecreasingAndEven(levelArr)) return false; + if (level % 2 === 0 && !isStricklyIncreasingAndOdd(levelArr)) + return false; + if (level % 2 === 1 && !isStricklyDecreasingAndEven(levelArr)) + return false; } return true; diff --git a/javascript/1614-maximum-nesting-depth-of-the-parentheses.js b/javascript/1614-maximum-nesting-depth-of-the-parentheses.js index 126c5840b..b7ce34d5a 100644 --- a/javascript/1614-maximum-nesting-depth-of-the-parentheses.js +++ b/javascript/1614-maximum-nesting-depth-of-the-parentheses.js @@ -1,17 +1,17 @@ /** - * Stack + * Stack * Time O(n) | Space O(1) * https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses * @param {string} s * @return {number} */ -var maxDepth = function(s) { +var maxDepth = function (s) { let currDepth = 0; let maxDepth = 0; for (let i = 0; i < s.length; i++) { - if (s[i] === "(") currDepth++; + if (s[i] === '(') currDepth++; maxDepth = Math.max(currDepth, maxDepth); - if (s[i] === ")") currDepth--; + if (s[i] === ')') currDepth--; } return maxDepth; }; diff --git a/javascript/1642-furthest-building-you-can-reach.js b/javascript/1642-furthest-building-you-can-reach.js index c48314f9b..f95889cb3 100644 --- a/javascript/1642-furthest-building-you-can-reach.js +++ b/javascript/1642-furthest-building-you-can-reach.js @@ -1,5 +1,5 @@ /** - * MaxPriorityQueue + * MaxPriorityQueue * Time O(n*log(n)) | Space O(n) * https://leetcode.com/problems/furthest-building-you-can-reach/ * @param {number[]} heights @@ -7,12 +7,11 @@ * @param {number} ladders * @return {number} */ -var furthestBuilding = function(heights, bricks, ladders) { - +var furthestBuilding = function (heights, bricks, ladders) { const maxPriorityQueue = new MaxPriorityQueue({ compare: (a, b) => { return b - a; - } + }, }); let i = 0; diff --git a/javascript/1647-minimum-deletions-to-make-character-frequencies-unique.js b/javascript/1647-minimum-deletions-to-make-character-frequencies-unique.js index aa1b61f57..27506c03c 100644 --- a/javascript/1647-minimum-deletions-to-make-character-frequencies-unique.js +++ b/javascript/1647-minimum-deletions-to-make-character-frequencies-unique.js @@ -5,12 +5,11 @@ * @param {string} s * @return {number} */ -var minDeletions = function(s) { - +var minDeletions = function (s) { // hash frequency let i = 0; const charHash = new Map(); - while (i < s.length) { + while (i < s.length) { const frequency = charHash.get(s[i]) || 0; charHash.set(s[i], frequency + 1); i++; @@ -25,8 +24,8 @@ var minDeletions = function(s) { for (const [key, val] of frequencyHash) { let frequency = key; let frequencyOfFrequency = val; - while(frequencyOfFrequency > 1) { - while(frequencyHash.has(frequency)) { + while (frequencyOfFrequency > 1) { + while (frequencyHash.has(frequency)) { frequency -= 1; min += 1; } diff --git a/javascript/1688-count-of-matches-in-tournament.js b/javascript/1688-count-of-matches-in-tournament.js index d0104aeb6..ee233ebfa 100644 --- a/javascript/1688-count-of-matches-in-tournament.js +++ b/javascript/1688-count-of-matches-in-tournament.js @@ -5,15 +5,20 @@ var numberOfMatches = function (n) { let matches = 0; // initialize matches to zero let num = n; // initialize num equal to n - for (let i = 0; i < n; i++) { // loop through the number n - if (num == 1) { // if num is equal to 1 then break the for loop + for (let i = 0; i < n; i++) { + // loop through the number n + if (num == 1) { + // if num is equal to 1 then break the for loop break; - } else { // else - if (num % 2 == 0) { // if num is even + } else { + // else + if (num % 2 == 0) { + // if num is even let divide = num / 2; // divide num by 2 matches += divide; // add divide to matches num -= divide; // subtract divide to num - } else { // else + } else { + // else let divide = (num - 1) / 2; // subtract num by 1 and then divide it by 2 matches += divide; // add divide to matches num -= divide; // subtract divide to num @@ -21,4 +26,4 @@ var numberOfMatches = function (n) { } } return matches; // return number matches -}; \ No newline at end of file +}; diff --git a/javascript/1700-number-of-students-unable-to-eat-lunch.js b/javascript/1700-number-of-students-unable-to-eat-lunch.js index 3ef2bdf2d..54193ae71 100644 --- a/javascript/1700-number-of-students-unable-to-eat-lunch.js +++ b/javascript/1700-number-of-students-unable-to-eat-lunch.js @@ -6,20 +6,24 @@ var countStudents = function (students, sandwiches) { let movement = 0; // initialize movement to be zero - while (sandwiches.length > 0) { // while length of sandwiches is greater than zero - if (students[0] == sandwiches[0]) { // if first element of students and sandwiches both are same + while (sandwiches.length > 0) { + // while length of sandwiches is greater than zero + if (students[0] == sandwiches[0]) { + // if first element of students and sandwiches both are same students.shift(); // reomve first element of students using shift() sandwiches.shift(); // remove first element of sandwiches using shift() movement = 0; // make movement to be zero - } else { // else + } else { + // else let add = students.shift(); // initialize add to be first element of students students.push(add); // push add to array students movement++; // increment movement - if (movement == students.length) { // if movement is equal to length of students then break the loop + if (movement == students.length) { + // if movement is equal to length of students then break the loop break; } } } return students.length; // return length of array students -}; \ No newline at end of file +}; diff --git a/javascript/1834-single-threaded-cpu.js b/javascript/1834-single-threaded-cpu.js index 6d636203e..1544d8d32 100644 --- a/javascript/1834-single-threaded-cpu.js +++ b/javascript/1834-single-threaded-cpu.js @@ -2,28 +2,28 @@ * @param {number[][]} tasks * @return {number[]} */ -var getOrder = function(tasks) { - for(let i = 0; i < tasks.length; i++) tasks[i].push(i); +var getOrder = function (tasks) { + for (let i = 0; i < tasks.length; i++) tasks[i].push(i); tasks.sort((a, b) => a[0] - b[0]); const pq = new MinPriorityQueue({ compare: (e1, e2) => { - if(e1[1] === e2[1]) return e1[2] - e2[2]; + if (e1[1] === e2[1]) return e1[2] - e2[2]; return e1[1] - e2[1]; - } + }, }); const a = []; - let t = tasks[0][0], i = 0; - while(pq.size() || i < tasks.length){ - while(i < tasks.length && t >= tasks[i][0]){ + let t = tasks[0][0], + i = 0; + while (pq.size() || i < tasks.length) { + while (i < tasks.length && t >= tasks[i][0]) { pq.enqueue(tasks[i]); i++; } - if(pq.size()){ + if (pq.size()) { let e = pq.dequeue(); a.push(e[2]); t += e[1]; - } - else t = tasks[i][0]; + } else t = tasks[i][0]; } return a; -}; \ No newline at end of file +}; diff --git a/javascript/1845-seat-reservation-manager.js b/javascript/1845-seat-reservation-manager.js index 9fb1c1d3b..2f17d9f7f 100644 --- a/javascript/1845-seat-reservation-manager.js +++ b/javascript/1845-seat-reservation-manager.js @@ -1,14 +1,13 @@ - class SeatManager { /** - * MinHeap - * Time O(n*log(n)) | Space O(n) - * https://leetcode.com/problems/seat-reservation-manager/ - * @param {number} n - */ + * MinHeap + * Time O(n*log(n)) | Space O(n) + * https://leetcode.com/problems/seat-reservation-manager/ + * @param {number} n + */ constructor(n) { this.unreserved = new MinPriorityQueue({ - compare: (a, b) => a - b + compare: (a, b) => a - b, }); for (let i = 1; i < n + 1; i++) { @@ -25,7 +24,7 @@ class SeatManager { return minAvailableSeat; } - /** + /** * Time O(log(n)) | Space O(1) * @param {number} seatNumber * @return {void} diff --git a/javascript/1846-maximum-element-after-decreasing-and-rearranging.js b/javascript/1846-maximum-element-after-decreasing-and-rearranging.js index 0a9e4631c..9ee5c5a13 100644 --- a/javascript/1846-maximum-element-after-decreasing-and-rearranging.js +++ b/javascript/1846-maximum-element-after-decreasing-and-rearranging.js @@ -1,4 +1,3 @@ - /** * Sorting * Time O(n*log(n)) | Space O(n) @@ -6,14 +5,12 @@ * @param {number[]} arr * @return {number} */ -var maximumElementAfterDecrementingAndRearranging = function(arr) { - +var maximumElementAfterDecrementingAndRearranging = function (arr) { arr.sort((a, b) => a - b); let index = 1; arr[0] = 1; - + while (index < arr.length) { - const pre = arr[index - 1]; const curr = arr[index]; if (Math.abs(curr - pre) > 1 && pre + 1 < curr) { @@ -21,6 +18,6 @@ var maximumElementAfterDecrementingAndRearranging = function(arr) { } index++; } - + return Math.max(...arr); }; diff --git a/javascript/1851-minimum-interval-to-include-each-query.js b/javascript/1851-minimum-interval-to-include-each-query.js index f35523608..29263c7fa 100644 --- a/javascript/1851-minimum-interval-to-include-each-query.js +++ b/javascript/1851-minimum-interval-to-include-each-query.js @@ -3,28 +3,28 @@ * @param {number[]} queries * @return {number[]} */ -var minInterval = function(intervals, queries) { - intervals.sort((a, b) => a[0] - b[0]); - const queriesSorted = [ ...queries ].sort((a, b) => a - b); - const minHeap = new MinPriorityQueue(); - const output = {}; - let i = 0; +var minInterval = function (intervals, queries) { + intervals.sort((a, b) => a[0] - b[0]); + const queriesSorted = [...queries].sort((a, b) => a - b); + const minHeap = new MinPriorityQueue(); + const output = {}; + let i = 0; - for (const query of queriesSorted) { - while (i < intervals.length && intervals[i][0] <= query) { - const [ start, end ] = intervals[i]; - const length = end - start + 1; - // Use length as the priority in the heap. - minHeap.enqueue([ length, end ], length); - i++; - } + for (const query of queriesSorted) { + while (i < intervals.length && intervals[i][0] <= query) { + const [start, end] = intervals[i]; + const length = end - start + 1; + // Use length as the priority in the heap. + minHeap.enqueue([length, end], length); + i++; + } - while (!minHeap.isEmpty() && minHeap.front().element[1] < query) { - minHeap.dequeue(); - } + while (!minHeap.isEmpty() && minHeap.front().element[1] < query) { + minHeap.dequeue(); + } - output[query] = (!minHeap.isEmpty()) ? minHeap.front().element[0] : -1; - } + output[query] = !minHeap.isEmpty() ? minHeap.front().element[0] : -1; + } - return queries.map((query) => output[query]); + return queries.map((query) => output[query]); }; diff --git a/javascript/1863-sum-of-all-subset-xor-totals.js b/javascript/1863-sum-of-all-subset-xor-totals.js index cc2977bb5..91c6ab976 100644 --- a/javascript/1863-sum-of-all-subset-xor-totals.js +++ b/javascript/1863-sum-of-all-subset-xor-totals.js @@ -7,5 +7,5 @@ var subsetXORSum = function (nums) { for (let i = 0; i < nums.length; ++i) { bitOR |= nums[i]; } - return (bitOR * Math.pow(2, nums.length - 1)); -}; \ No newline at end of file + return bitOR * Math.pow(2, nums.length - 1); +}; diff --git a/javascript/1882-process-tasks-using-servers.js b/javascript/1882-process-tasks-using-servers.js index bf3ac6f2b..9ac6db271 100644 --- a/javascript/1882-process-tasks-using-servers.js +++ b/javascript/1882-process-tasks-using-servers.js @@ -6,20 +6,19 @@ * @param {number[]} tasks * @return {number[]} */ -var assignTasks = function(servers, tasks) { - +var assignTasks = function (servers, tasks) { const toBeCompleted = new MinPriorityQueue({ compare: (a, b) => { if (a[0] === b[0]) return a[1] - b[1]; return a[0] - b[0]; - } + }, }); const freeServers = new MinPriorityQueue({ compare: (a, b) => { if (a[0] === b[0]) return a[1] - b[1]; return a[0] - b[0]; - } + }, }); for (let i = 0; i < servers.length; i++) { @@ -34,13 +33,12 @@ var assignTasks = function(servers, tasks) { for (let i = 0; i < tasks.length; i++) { sec = Math.max(i, sec); - // if the we don't have server available then jump to the next imidiate + // if the we don't have server available then jump to the next imidiate // time when the server will be available. if (freeServers.isEmpty()) { sec = toBeCompleted.front()[0]; } - while (!toBeCompleted.isEmpty() && - toBeCompleted.front()[0] <= sec) { + while (!toBeCompleted.isEmpty() && toBeCompleted.front()[0] <= sec) { const [endTime, serverIdx] = toBeCompleted.dequeue(); const weight = servers[serverIdx]; freeServers.enqueue([weight, serverIdx]); @@ -49,7 +47,7 @@ var assignTasks = function(servers, tasks) { const [weight, serverIdx] = freeServers.dequeue(); const timeToBeTaken = tasks[i]; result.push(serverIdx); - toBeCompleted.enqueue([sec+timeToBeTaken, serverIdx]); + toBeCompleted.enqueue([sec + timeToBeTaken, serverIdx]); } return result; diff --git a/javascript/1898-maximum-number-of-removable-characters.js b/javascript/1898-maximum-number-of-removable-characters.js index 3ae59a871..aa6b3ccf4 100644 --- a/javascript/1898-maximum-number-of-removable-characters.js +++ b/javascript/1898-maximum-number-of-removable-characters.js @@ -1,6 +1,6 @@ /** * https://leetcode.com/problems/maximum-number-of-removable-characters/ - * + * * Brute force * Time O(removable.length * s.length) | Space O(n) * @param {string} s @@ -8,45 +8,44 @@ * @param {number[]} removable * @return {number} */ -var maximumRemovals1 = function(s, p, removable) { - let k = 0; - // removable.reverse(); - s = s.split(''); - p = p.split(''); +var maximumRemovals1 = function (s, p, removable) { + let k = 0; + // removable.reverse(); + s = s.split(''); + p = p.split(''); + + for (let i = 0; i < removable.length; i++) { + s[removable[i]] = -1; + if (isSubSet1(s, p)) { + k++; + continue; + } + return k; + } - for (let i = 0; i < removable.length; i++) { - s[removable[i]] = -1; - if (isSubSet1(s, p)) { - k++; - continue; - } return k; - } - - return k; }; // helper function. function isSubSet1(s, p) { - let i = 0; - let j = 0; - - while (i < s.length && j < p.length) { - if (s[i] === p[j]) { - i++; - j++; - } else { - i++; + let i = 0; + let j = 0; + + while (i < s.length && j < p.length) { + if (s[i] === p[j]) { + i++; + j++; + } else { + i++; + } } - } - return j === p.length; + return j === p.length; } - /** - * - * Binary Search + * + * Binary Search * n = length of string, k = length of removable * Time O(log(k)*n) | Space O(1) * @param {string} s @@ -54,42 +53,41 @@ function isSubSet1(s, p) { * @param {number[]} removable * @return {number} */ -var maximumRemovals = function(s, p, removable) { - - let left = 0; - let right = removable.length - 1; - let k = 0; - - while (left <= right) { - const mid = (left + right) >> 1; - const hash = new Set(removable.slice(0, mid + 1)); - - if (isSubSet(hash, s, p)) { - k = Math.max(k, mid + 1); - left = mid + 1; - continue; +var maximumRemovals = function (s, p, removable) { + let left = 0; + let right = removable.length - 1; + let k = 0; + + while (left <= right) { + const mid = (left + right) >> 1; + const hash = new Set(removable.slice(0, mid + 1)); + + if (isSubSet(hash, s, p)) { + k = Math.max(k, mid + 1); + left = mid + 1; + continue; + } + + right = mid - 1; } - right = mid - 1; - } - - return k; + return k; }; // helper function. function isSubSet(hash, s, p) { - let i = 0; - let j = 0; + let i = 0; + let j = 0; - while (i < s.length && j < p.length) { - if (s[i] === p[j] && !hash.has(i)) { - i++; - j++; - continue; - } + while (i < s.length && j < p.length) { + if (s[i] === p[j] && !hash.has(i)) { + i++; + j++; + continue; + } - i++; - } + i++; + } - return j === p.length; + return j === p.length; } diff --git a/javascript/1899-merge-triplets-to-form-target-triplet.js b/javascript/1899-merge-triplets-to-form-target-triplet.js index ba55f3ef8..acedf53ff 100644 --- a/javascript/1899-merge-triplets-to-form-target-triplet.js +++ b/javascript/1899-merge-triplets-to-form-target-triplet.js @@ -33,18 +33,19 @@ var mergeTriplets = function (triplets, target) { * @param {number[]} target * @return {boolean} */ - var mergeTriplets = function(triplets, target, res = new Array(3).fill(0)) { - for (const [ a, b, c ] of triplets) { /* Time O(N) */ - const [ _a, _b, _c ] = target; +var mergeTriplets = function (triplets, target, res = new Array(3).fill(0)) { + for (const [a, b, c] of triplets) { + /* Time O(N) */ + const [_a, _b, _c] = target; - const isTargetGreater = (a <= _a) && (b <= _b) && (c <= _c); + const isTargetGreater = a <= _a && b <= _b && c <= _c; if (!isTargetGreater) continue; - const [ __a, __b, __c ] = res; - res = [ Math.max(__a, a), Math.max(__b, b), Math.max(__c, c) ]; + const [__a, __b, __c] = res; + res = [Math.max(__a, a), Math.max(__b, b), Math.max(__c, c)]; } - - return res.every((val, i) => val === target[i])/* Time O(N) */ + + return res.every((val, i) => val === target[i]); /* Time O(N) */ }; /** @@ -54,17 +55,22 @@ var mergeTriplets = function (triplets, target) { * @param {number[]} target * @return {boolean} */ -var mergeTriplets = function(triplets, target, res = new Array(3).fill(false)) { - for (const [ a, b, c ] of triplets) {/* Time O(N) */ - const [ _a, _b, _c ] = target; - - const isTargetGreater = (a <= _a) && (b <= _b) && (c <= _c); +var mergeTriplets = function ( + triplets, + target, + res = new Array(3).fill(false), +) { + for (const [a, b, c] of triplets) { + /* Time O(N) */ + const [_a, _b, _c] = target; + + const isTargetGreater = a <= _a && b <= _b && c <= _c; if (!isTargetGreater) continue; - - res[0] |= (a === _a); - res[1] |= (b === _b); - res[2] |= (c === _c); + + res[0] |= a === _a; + res[1] |= b === _b; + res[2] |= c === _c; } - + return res[0] && res[1] && res[2]; -} +}; diff --git a/javascript/1905-count-sub-islands.js b/javascript/1905-count-sub-islands.js index 5cebc1269..ce2d2b188 100644 --- a/javascript/1905-count-sub-islands.js +++ b/javascript/1905-count-sub-islands.js @@ -1,35 +1,35 @@ -var countSubIslands = function(grid1, grid2) { - let ROWS = grid1.length, COLS = grid1[0].length; +var countSubIslands = function (grid1, grid2) { + let ROWS = grid1.length, + COLS = grid1[0].length; let visit = new Set(); - - const dfs = function(r, c) { - let flatCoord = r*COLS + c; + + const dfs = function (r, c) { + let flatCoord = r * COLS + c; if ( - r < 0 - || c < 0 - || r == ROWS - || c == COLS - || grid2[r][c] == 0 - || visit.has(flatCoord) + r < 0 || + c < 0 || + r == ROWS || + c == COLS || + grid2[r][c] == 0 || + visit.has(flatCoord) ) return true; - + visit.add(flatCoord); let res = true; - if(grid1[r][c] == 0) - res = false; - + if (grid1[r][c] == 0) res = false; + res = dfs(r - 1, c) && res; res = dfs(r + 1, c) && res; res = dfs(r, c - 1) && res; res = dfs(r, c + 1) && res; return res; }; - + let count = 0; - for(let r = 0; r < ROWS; r++) - for(let c = 0; c < COLS; c++) - if(grid2[r][c] && !visit.has(r*COLS + c) && dfs(r, c)) + for (let r = 0; r < ROWS; r++) + for (let c = 0; c < COLS; c++) + if (grid2[r][c] && !visit.has(r * COLS + c) && dfs(r, c)) count += 1; return count; }; diff --git a/javascript/1921-eliminate-maximum-number-of-monsters.js b/javascript/1921-eliminate-maximum-number-of-monsters.js index e0ca5a87d..e0bd3f3e6 100644 --- a/javascript/1921-eliminate-maximum-number-of-monsters.js +++ b/javascript/1921-eliminate-maximum-number-of-monsters.js @@ -5,8 +5,7 @@ * @param {number[]} speed * @return {number} */ -var eliminateMaximum = function(dist, speed) { - +var eliminateMaximum = function (dist, speed) { const time = dist.map((d, i) => { return d / speed[i]; }); diff --git a/javascript/1929-concatenation-of-array.js b/javascript/1929-concatenation-of-array.js index a7007d22f..deebc6820 100644 --- a/javascript/1929-concatenation-of-array.js +++ b/javascript/1929-concatenation-of-array.js @@ -5,9 +5,9 @@ * @return {number[]} */ var getConcatenation = function (nums) { - let res = []; - for (let i = 0; i < nums.length * 2; i++) { - res.push(nums[i % nums.length]); - } - return res; + let res = []; + for (let i = 0; i < nums.length * 2; i++) { + res.push(nums[i % nums.length]); + } + return res; }; diff --git a/javascript/1930-unique-length-3-palindromic-subsequences.js b/javascript/1930-unique-length-3-palindromic-subsequences.js index 817c69a2d..28f8e3e5e 100644 --- a/javascript/1930-unique-length-3-palindromic-subsequences.js +++ b/javascript/1930-unique-length-3-palindromic-subsequences.js @@ -5,8 +5,9 @@ var countPalindromicSubsequence = function (s) { let count = 0; let chars = new Set(s); - for(const char of chars){ - let first = s.indexOf(char),last = s.lastIndexOf(char); + for (const char of chars) { + let first = s.indexOf(char), + last = s.lastIndexOf(char); count += new Set(s.slice(first + 1, last)).size; } return count; diff --git a/javascript/1958-check-if-move-is-legal.js b/javascript/1958-check-if-move-is-legal.js index 78ce9ecf4..19f95a6f2 100644 --- a/javascript/1958-check-if-move-is-legal.js +++ b/javascript/1958-check-if-move-is-legal.js @@ -1,27 +1,35 @@ -var checkMove = function(board, rMove, cMove, color) { - const ROWS = board.length, COLS = board[0].length; - let direction = [[1, 0], [-1, 0], [0, 1], [0, -1], - [1, 1], [-1, -1], [1, -1], [-1, 1]]; +var checkMove = function (board, rMove, cMove, color) { + const ROWS = board.length, + COLS = board[0].length; + let direction = [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + [1, 1], + [-1, -1], + [1, -1], + [-1, 1], + ]; board[rMove][cMove] = color; - - let legal = function(row, col, color, direc) { - let dr = direc[0], dc = direc[1]; + + let legal = function (row, col, color, direc) { + let dr = direc[0], + dc = direc[1]; row = row + dr; col = col + dc; let length = 1; - - while(0 <= row && row < ROWS && 0 <= col && col < COLS) { + + while (0 <= row && row < ROWS && 0 <= col && col < COLS) { length += 1; - if(board[row][col] == '.') return false; - if(board[row][col] == color) - return length >= 3; + if (board[row][col] == '.') return false; + if (board[row][col] == color) return length >= 3; row = row + dr; col = col + dc; } return false; - } - - for(const d of direction) - if(legal(rMove, cMove, color, d)) return true; + }; + + for (const d of direction) if (legal(rMove, cMove, color, d)) return true; return false; }; diff --git a/javascript/1963-minimum-number-of-swaps-to-make-the-string-balanced.js b/javascript/1963-minimum-number-of-swaps-to-make-the-string-balanced.js index 3da70d70e..7e530e159 100644 --- a/javascript/1963-minimum-number-of-swaps-to-make-the-string-balanced.js +++ b/javascript/1963-minimum-number-of-swaps-to-make-the-string-balanced.js @@ -2,14 +2,13 @@ // time complexity O(n) // space complexity O(1) -var minSwaps = function(s) { - +var minSwaps = function (s) { let extraClosing = 0; let maxClosing = 0; - for(let i = 0; i < s.length; i++) { + for (let i = 0; i < s.length; i++) { s[i] === ']' ? extraClosing++ : extraClosing--; maxClosing = Math.max(maxClosing, extraClosing); } - return Math.ceil(maxClosing/2); + return Math.ceil(maxClosing / 2); }; diff --git a/javascript/1968-array-with-elements-not-equal-to-average-of-neighbors.js b/javascript/1968-array-with-elements-not-equal-to-average-of-neighbors.js index dc1975f4d..977e038f7 100644 --- a/javascript/1968-array-with-elements-not-equal-to-average-of-neighbors.js +++ b/javascript/1968-array-with-elements-not-equal-to-average-of-neighbors.js @@ -1,25 +1,25 @@ /** * Two Pointers * https://leetcode.com/problems/array-with-elements-not-equal-to-average-of-neighbors/ - * + * * Time O(n*log(n)) | Space O(n) * @param {number[]} nums * @return {number[]} */ - var rearrangeArray = function(nums) { - nums.sort((a,b) => a-b); - +var rearrangeArray = function (nums) { + nums.sort((a, b) => a - b); + let midPointer = Math.ceil(nums.length / 2); let beginingPointer = 1; - - while(midPointer < nums.length) { + + while (midPointer < nums.length) { swap(midPointer, beginingPointer, nums); midPointer++; - beginingPointer += 2 + beginingPointer += 2; } return nums; - }; - -var swap = function(i,j,nums) { +}; + +var swap = function (i, j, nums) { [nums[i], nums[j]] = [nums[j], nums[i]]; -} +}; diff --git a/javascript/1984-minimum-difference-between-highest-and-lowest-of-k-scores.js b/javascript/1984-minimum-difference-between-highest-and-lowest-of-k-scores.js index b50b93538..32df3884e 100644 --- a/javascript/1984-minimum-difference-between-highest-and-lowest-of-k-scores.js +++ b/javascript/1984-minimum-difference-between-highest-and-lowest-of-k-scores.js @@ -2,14 +2,13 @@ * Loglinear/N*log(N) * Time O(N*log(N)) | Space O(1) * https://leetcode.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores - * + * * @param {number[]} nums * @param {number} k * @return {number} */ -var minimumDifference = function(nums, k) { - - const isEdgeCase = (k === 1); +var minimumDifference = function (nums, k) { + const isEdgeCase = k === 1; if (isEdgeCase) return 0; nums = nums.sort((a, b) => { diff --git a/javascript/1985-find-the-kth-largest-integer-in-the-array.js b/javascript/1985-find-the-kth-largest-integer-in-the-array.js index e10ad39f5..3384a5284 100644 --- a/javascript/1985-find-the-kth-largest-integer-in-the-array.js +++ b/javascript/1985-find-the-kth-largest-integer-in-the-array.js @@ -6,8 +6,7 @@ * @param {number} k * @return {string} */ -var kthLargestNumber = function(nums, k) { - +var kthLargestNumber = function (nums, k) { // sort it string wise. nums.sort((a, b) => { if (a.length !== b.length) return b.length - a.length; diff --git a/javascript/1993-operations-on-tree.js b/javascript/1993-operations-on-tree.js index c32b4625c..ba11291a1 100644 --- a/javascript/1993-operations-on-tree.js +++ b/javascript/1993-operations-on-tree.js @@ -6,8 +6,8 @@ class LockingTree { this.parent = parent; this.childHash = {}; this.treeHash = {}; - for(let i = 0; i < parent.length; i++) { - if(this.childHash[parent[i]]) { + for (let i = 0; i < parent.length; i++) { + if (this.childHash[parent[i]]) { this.childHash[parent[i]].push(i); } else { this.childHash[parent[i]] = [i]; @@ -15,38 +15,38 @@ class LockingTree { } } - /** + /** * Time O(1) | Space O(1) - * @param {number} num + * @param {number} num * @param {number} user * @return {boolean} */ lock(num, user) { // it will just lock a node for a given user if it's not already locked THAT'S IT! - if(this.treeHash[num]) return false; + if (this.treeHash[num]) return false; this.treeHash[num] = user; return true; } - /** + /** * Time O(1) | Space O(1) - * @param {number} num + * @param {number} num * @param {number} user * @return {boolean} */ unlock(num, user) { - // only unlock the node if it's locked by the same user - if(this.treeHash[num] === user) { + // only unlock the node if it's locked by the same user + if (this.treeHash[num] === user) { delete this.treeHash[num]; return true; } return false; } - /** - * + /** + * * Time O(n) | Space O(n) - * @param {number} num + * @param {number} num * @param {number} user * @return {boolean} */ @@ -54,10 +54,10 @@ class LockingTree { // lock the node for a given user and unlock all of its descendants no matter who locked it. // 1. the given node should be unlocked // 2. the given node should have at least one locked node descendant by anyone - // 3. the given node shouldn't have any locked ancestors - if(this.treeHash[num]) return false; - if(!this.checkDescendants(num)) return false; - if(!this.checkAncestors(num)) return false; + // 3. the given node shouldn't have any locked ancestors + if (this.treeHash[num]) return false; + if (!this.checkDescendants(num)) return false; + if (!this.checkAncestors(num)) return false; // locking the given node this.treeHash[num] = user; @@ -73,10 +73,10 @@ class LockingTree { unlockDescendants(index) { const stack = []; stack.push(index); - while(stack.length) { + while (stack.length) { const node = stack.pop(); const children = this.childHash[node]; - for(let i = 0; i < (children && children.length); i++) { + for (let i = 0; i < (children && children.length); i++) { delete this.treeHash[children[i]]; stack.push(children[i]); } @@ -91,8 +91,8 @@ class LockingTree { */ checkAncestors(index) { let node = this.parent[index]; - while(node !== -1) { - if(this.treeHash[node]) return false; + while (node !== -1) { + if (this.treeHash[node]) return false; node = this.parent[node]; } return true; @@ -107,11 +107,11 @@ class LockingTree { checkDescendants(index) { const stack = []; stack.push(index); - while(stack.length) { + while (stack.length) { const node = stack.pop(); const children = this.childHash[node]; - for(let i = 0; i < (children && children.length); i++) { - if(this.treeHash[children[i]]) return true; + for (let i = 0; i < (children && children.length); i++) { + if (this.treeHash[children[i]]) return true; stack.push(children[i]); } } diff --git a/javascript/2001-number-of-pairs-of-interchangeable-rectangles.js b/javascript/2001-number-of-pairs-of-interchangeable-rectangles.js index 00b46d9a0..b76aeb3e8 100644 --- a/javascript/2001-number-of-pairs-of-interchangeable-rectangles.js +++ b/javascript/2001-number-of-pairs-of-interchangeable-rectangles.js @@ -6,11 +6,13 @@ * @return {number} */ var interchangeableRectangles = (rectangles) => { - let totalPair = 0; for (let i = 0; i < rectangles.length; i++) { for (let j = i + 1; j < rectangles.length; j++) { - if (rectangles[i][1] / rectangles[i][0] === rectangles[j][1] / rectangles[j][0]) { + if ( + rectangles[i][1] / rectangles[i][0] === + rectangles[j][1] / rectangles[j][0] + ) { totalPair++; } } @@ -18,13 +20,12 @@ var interchangeableRectangles = (rectangles) => { return totalPair; }; /** - * Linear + * Linear * Time O(N) | Space O(n) * @param {number[][]} rectangles * @return {number} */ var interchangeableRectangles = (rectangles) => { - const ratioFrequency = {}; for (let i = 0; i < rectangles.length; i++) { diff --git a/javascript/2002-maximum-product-of-the-length-of-two-palindromic-subsequences.js b/javascript/2002-maximum-product-of-the-length-of-two-palindromic-subsequences.js index a498c0528..a41d6b8c5 100644 --- a/javascript/2002-maximum-product-of-the-length-of-two-palindromic-subsequences.js +++ b/javascript/2002-maximum-product-of-the-length-of-two-palindromic-subsequences.js @@ -29,7 +29,7 @@ var maxProduct = function (s) { return Math.max( dp(m - lb), dp(m - fb), - dp(m - lb - fb) + (s[l] == s[f]) * 2 + dp(m - lb - fb) + (s[l] == s[f]) * 2, ); }); let ans = 0; diff --git a/javascript/2013-detect-squares.js b/javascript/2013-detect-squares.js index ed26ae11a..b31646728 100644 --- a/javascript/2013-detect-squares.js +++ b/javascript/2013-detect-squares.js @@ -3,50 +3,51 @@ * https://leetcode.com/problems/detect-squares */ class DetectSquares { - constructor () { - this.map = {}; /* Space O(N) */ - this.points = [];/* Space O(N) */ + constructor() { + this.map = {}; /* Space O(N) */ + this.points = []; /* Space O(N) */ } - - add (point, { map, points } = this) { - const [ x, y ] = point; + + add(point, { map, points } = this) { + const [x, y] = point; const key = this.getKey(x, y); - const value = ((map[key] || 0) + 1); + const value = (map[key] || 0) + 1; - map[key] = value; /* Space O(N) */ - points.push(point);/* Space O(N) */ + map[key] = value; /* Space O(N) */ + points.push(point); /* Space O(N) */ } - count (point, { points } = this, score = 0) { - const [ x1, y1 ] = point; + count(point, { points } = this, score = 0) { + const [x1, y1] = point; - for (const [ x2, y2 ] of points) {/* Time O(N) */ - const isSame = (Math.abs(x2 - x1) === Math.abs(y2 - y1)); - const isEqual = ((x1 === x2) || (y1 === y2)); - const canSkip = (!isSame || isEqual); + for (const [x2, y2] of points) { + /* Time O(N) */ + const isSame = Math.abs(x2 - x1) === Math.abs(y2 - y1); + const isEqual = x1 === x2 || y1 === y2; + const canSkip = !isSame || isEqual; if (canSkip) continue; score += this.getScore(x1, y1, x2, y2); } return score; - }; + } - getKey (x, y) { + getKey(x, y) { return `${x},${y}`; } - getScore (x1, y1, x2, y2, { map } = this) { - const [ aKey, bKey ] = [ this.getKey(x1, y2), this.getKey(x2, y1) ]; - const [ aScore, bScore ] = [ (map[aKey] || 0), (map[bKey] || 0) ]; - - return (aScore * bScore); + getScore(x1, y1, x2, y2, { map } = this) { + const [aKey, bKey] = [this.getKey(x1, y2), this.getKey(x2, y1)]; + const [aScore, bScore] = [map[aKey] || 0, map[bKey] || 0]; + + return aScore * bScore; } -}; +} -/** +/** * Your DetectSquares object will be instantiated and called as such: * var obj = new DetectSquares() * obj.add(point) * var param_2 = obj.count(point) - */ \ No newline at end of file + */ diff --git a/javascript/2017-grid-game.js b/javascript/2017-grid-game.js index 443af1762..04c8f39a9 100644 --- a/javascript/2017-grid-game.js +++ b/javascript/2017-grid-game.js @@ -1,5 +1,5 @@ /** - * Submission Details: + * Submission Details: * https://leetcode.com/problems/grid-game/ * Time O(n), Space O(1) * Runtime: 89ms (beats 79.31%) || 53.5mb (beats 89.66%) @@ -10,14 +10,14 @@ * @return {number} */ -var gridGame = function(grid) { - let one = grid[0].reduce((a,b)=>a+b) - grid[0][0]; +var gridGame = function (grid) { + let one = grid[0].reduce((a, b) => a + b) - grid[0][0]; let two = 0; let res = one; - for(let i = 1; i < grid[0].length; i++){ - one-=grid[0][i]; - two+=grid[1][i-1]; - res = Math.min(res, Math.max(one,two)); + for (let i = 1; i < grid[0].length; i++) { + one -= grid[0][i]; + two += grid[1][i - 1]; + res = Math.min(res, Math.max(one, two)); } return res; -}; \ No newline at end of file +}; diff --git a/javascript/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color.js b/javascript/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color.js index ae64637e6..98a121ece 100644 --- a/javascript/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color.js +++ b/javascript/2038-remove-colored-pieces-if-both-neighbors-are-the-same-color.js @@ -5,16 +5,19 @@ * @param {string} colors * @return {boolean} */ -var winnerOfGame = function(colors) { - +var winnerOfGame = function (colors) { let aScore = 0; let bScore = 0; - + const canRemove = (index) => { - if (colors[index] === colors[index - 1] && colors[index] === colors[index + 1]) return colors[index]; + if ( + colors[index] === colors[index - 1] && + colors[index] === colors[index + 1] + ) + return colors[index]; return false; - } - + }; + for (let i = 1; i < colors.length; i++) { if (canRemove(i) === 'A') aScore++; if (canRemove(i) === 'B') bScore++; diff --git a/javascript/2125-number-of-laser-beams-in-a-bank.js b/javascript/2125-number-of-laser-beams-in-a-bank.js index 3afac319a..335e84e5d 100644 --- a/javascript/2125-number-of-laser-beams-in-a-bank.js +++ b/javascript/2125-number-of-laser-beams-in-a-bank.js @@ -5,21 +5,20 @@ * @param {string[]} bank * @return {number} */ -var numberOfBeams = function(bank) { - +var numberOfBeams = function (bank) { let totalBeams = 0; let left = 0; let right = left + 1; const countBeam = (beam) => { - return beam.split("").filter((b) => b === "1").length; - } + return beam.split('').filter((b) => b === '1').length; + }; while (right < bank.length) { while (right < bank.length && !countBeam(bank[right])) { right++; - } + } if (right < bank.length) { totalBeams += countBeam(bank[left]) * countBeam(bank[right]); diff --git a/javascript/2130-maximum-twin-sum-of-a-linked-list.js b/javascript/2130-maximum-twin-sum-of-a-linked-list.js index 1b5d435ef..a387329a3 100644 --- a/javascript/2130-maximum-twin-sum-of-a-linked-list.js +++ b/javascript/2130-maximum-twin-sum-of-a-linked-list.js @@ -7,56 +7,56 @@ */ /** - * Linear Time + * Linear Time * Time O(n) | Space O(1) * @param {ListNode} head * @return {number} */ var pairSum = function (head) { - const mid = llLength(head) / 2; - const rightPointer = getRightPointer(head, mid); - const leftPointer = reverseLL(head, mid); - - return getMax(leftPointer, rightPointer); + const mid = llLength(head) / 2; + const rightPointer = getRightPointer(head, mid); + const leftPointer = reverseLL(head, mid); + + return getMax(leftPointer, rightPointer); }; var getMax = (leftPointer, rightPointer) => { let max = 0; while (leftPointer && rightPointer) { - max = Math.max(leftPointer.val + rightPointer.val, max); - leftPointer = leftPointer.next; - rightPointer = rightPointer.next; + max = Math.max(leftPointer.val + rightPointer.val, max); + leftPointer = leftPointer.next; + rightPointer = rightPointer.next; } return max; -} +}; var getRightPointer = (head, mid) => { let count = 0; let rightPointer = head; while (count < mid) { - rightPointer = rightPointer.next; - count++; + rightPointer = rightPointer.next; + count++; } return rightPointer; -} +}; var llLength = (head) => { - let count = 0; - while (head) { - head = head.next; - count++; - } - return count; + let count = 0; + while (head) { + head = head.next; + count++; + } + return count; }; var reverseLL = (head, len) => { - let count = 0; - let temp = null; - while (count < len) { - const next = head.next; - head.next = temp; - temp = head; - head = next; - count++; - } - return temp; + let count = 0; + let temp = null; + while (count < len) { + const next = head.next; + head.next = temp; + temp = head; + head = next; + count++; + } + return temp; }; diff --git a/javascript/2160-minimum-sum-of-four-digit-number-after-splitting-digits.js b/javascript/2160-minimum-sum-of-four-digit-number-after-splitting-digits.js index acbc88fd0..49524e5ee 100644 --- a/javascript/2160-minimum-sum-of-four-digit-number-after-splitting-digits.js +++ b/javascript/2160-minimum-sum-of-four-digit-number-after-splitting-digits.js @@ -3,6 +3,6 @@ * @return {number} */ var minimumSum = function (num) { - let str = String(num).split("").sort(); // intialize str and split the num using String(), split() and sort() - return parseInt(str[0] + str[2]) + parseInt(str[1] + str[3]); // return sum of 1st, 3rd and 2nd, 4th string digit and convert into num using parseInt -}; \ No newline at end of file + let str = String(num).split('').sort(); // intialize str and split the num using String(), split() and sort() + return parseInt(str[0] + str[2]) + parseInt(str[1] + str[3]); // return sum of 1st, 3rd and 2nd, 4th string digit and convert into num using parseInt +}; diff --git a/javascript/2235-add-two-integers.js b/javascript/2235-add-two-integers.js index 0ab61fe5a..9d871c93d 100644 --- a/javascript/2235-add-two-integers.js +++ b/javascript/2235-add-two-integers.js @@ -5,4 +5,4 @@ */ var sum = function (num1, num2) { return num1 + num2; // add num1 and num2 and return it -}; \ No newline at end of file +}; diff --git a/javascript/2306-naming-a-company.js b/javascript/2306-naming-a-company.js index 652daa7a2..991e792c5 100644 --- a/javascript/2306-naming-a-company.js +++ b/javascript/2306-naming-a-company.js @@ -2,7 +2,7 @@ * @param {string[]} ideas * @return {number} */ -var distinctNames = function(ideas) { +var distinctNames = function (ideas) { let sets = []; for (let i = 0; i < 26; i++) { sets[i] = new Set(); @@ -26,9 +26,9 @@ var distinctNames = function(ideas) { let res = 0; for (let i = 0; i < 26; i++) { for (let j = i + 1; j < 26; j++) { - res += (sets[i].size - same[i][j]) * (sets[j].size - same[i][j]) * 2; + res += + (sets[i].size - same[i][j]) * (sets[j].size - same[i][j]) * 2; } } return res; - -}; \ No newline at end of file +}; diff --git a/javascript/2331-evaluate-boolean-binary-tree.js b/javascript/2331-evaluate-boolean-binary-tree.js index 8f9018b57..1a09a90e4 100644 --- a/javascript/2331-evaluate-boolean-binary-tree.js +++ b/javascript/2331-evaluate-boolean-binary-tree.js @@ -13,19 +13,17 @@ * @param {TreeNode} root * @return {boolean} */ -var evaluateTree = function(root) { +var evaluateTree = function (root) { return dfs(root); }; const dfs = (node) => { - if (!node.left && !node.right && node.val) return true; if (!node.left && !node.right && !node.val) return false; - - const is2 = (node.val === 2); + + const is2 = node.val === 2; if (is2) return dfs(node.left) || dfs(node.right); - - const is3 = (node.val === 3); - if (is3) return dfs(node.left) && dfs(node.right); -} + const is3 = node.val === 3; + if (is3) return dfs(node.left) && dfs(node.right); +}; diff --git a/javascript/2348-number-of-zero-filled-subarrays.js b/javascript/2348-number-of-zero-filled-subarrays.js index 7d445f219..3b61a5cd9 100644 --- a/javascript/2348-number-of-zero-filled-subarrays.js +++ b/javascript/2348-number-of-zero-filled-subarrays.js @@ -32,4 +32,4 @@ let zeroFilledSubarray = function (nums) { } return result; -}; \ No newline at end of file +}; diff --git a/javascript/2390-removing-stars-from-a-string.js b/javascript/2390-removing-stars-from-a-string.js index d23be4497..5e519a343 100644 --- a/javascript/2390-removing-stars-from-a-string.js +++ b/javascript/2390-removing-stars-from-a-string.js @@ -1,13 +1,13 @@ -var removeStars = function(s) { - if(!s.length) return ''; +var removeStars = function (s) { + if (!s.length) return ''; const result = []; - for(let char of s){ - if(char == '*') result.pop() - else result.push(char) + for (let char of s) { + if (char == '*') result.pop(); + else result.push(char); } - return result.join('') + return result.join(''); }; // Time Complexity: O(n) // Space Complexity: O(n) diff --git a/javascript/2427-number-of-common-factors.js b/javascript/2427-number-of-common-factors.js index e6ebe8d5e..08f79f771 100644 --- a/javascript/2427-number-of-common-factors.js +++ b/javascript/2427-number-of-common-factors.js @@ -9,7 +9,6 @@ var commonFactors = function (a, b) { // loop thorugh every number from 1 to min for (let i = 1; i <= min; i++) { - // if a anf b both divisable by i then push i into array arr if (a % i == 0 && b % i == 0) { arr.push(i); @@ -18,4 +17,4 @@ var commonFactors = function (a, b) { // return length of array arr return arr.length; -}; \ No newline at end of file +}; diff --git a/javascript/2439-minimize-maximum-of-array.js b/javascript/2439-minimize-maximum-of-array.js index 5e106276d..3a9baf316 100644 --- a/javascript/2439-minimize-maximum-of-array.js +++ b/javascript/2439-minimize-maximum-of-array.js @@ -3,8 +3,7 @@ * @param {number[]} nums * @return {number} */ -var minimizeArrayValue = function(nums) { - +var minimizeArrayValue = function (nums) { let currTotal = nums[0]; let max = nums[0]; diff --git a/javascript/2469-convert-the-temperature.js b/javascript/2469-convert-the-temperature.js index 36e4359b7..308e45a3a 100644 --- a/javascript/2469-convert-the-temperature.js +++ b/javascript/2469-convert-the-temperature.js @@ -2,8 +2,8 @@ * @param {number} celsius * @return {number[]} */ -var convertTemperature = function(celsius) { +var convertTemperature = function (celsius) { let kelvin = celsius + 273.15; // initialize kelvin and add 273.15 to celsius - let fahrenheit = (celsius * 1.80) + 32; // initialize fahrenheit and multiply 1.80 to celsius and add 32 + let fahrenheit = celsius * 1.8 + 32; // initialize fahrenheit and multiply 1.80 to celsius and add 32 return [kelvin, fahrenheit]; // return kelvin and fahrenheit as an array -}; \ No newline at end of file +}; diff --git a/javascript/2485-find-the-pivot-integer.js b/javascript/2485-find-the-pivot-integer.js index 563788033..c81149ed1 100644 --- a/javascript/2485-find-the-pivot-integer.js +++ b/javascript/2485-find-the-pivot-integer.js @@ -3,13 +3,12 @@ * @return {number} */ var pivotInteger = function (n) { - // calculate the total sum fo n - const totalSum = n * (n + 1) / 2; + const totalSum = (n * (n + 1)) / 2; // find the square root of totalSum using Math.sqrt() const sqrtVal = Math.sqrt(totalSum); // if sqrtVal is equal to round down value of sqrtVal then return round down value of sqrtVal otherwise -1 return Math.floor(sqrtVal) === sqrtVal ? Math.floor(sqrtVal) : -1; -}; \ No newline at end of file +}; diff --git a/javascript/2542-maximum-subsequence-score.js b/javascript/2542-maximum-subsequence-score.js index 7e3d45ee7..c75831076 100644 --- a/javascript/2542-maximum-subsequence-score.js +++ b/javascript/2542-maximum-subsequence-score.js @@ -7,12 +7,11 @@ * @param {number} k * @return {number} */ -var maxScore = function(nums1, nums2, k) { - +var maxScore = function (nums1, nums2, k) { const minQ = new MinPriorityQueue({ - compare: (a,b) => { + compare: (a, b) => { return a - b; - } + }, }); let maxScore = 0; @@ -23,21 +22,21 @@ var maxScore = function(nums1, nums2, k) { return [num, nums2[idx]]; }); - nums12.sort((a,b) => { + nums12.sort((a, b) => { return b[1] - a[1]; }); - - for(let i = 0; i < nums12.length; i++) { + + for (let i = 0; i < nums12.length; i++) { const n1 = nums12[i][0]; const n2 = nums12[i][1]; runningTotal += n1; minQ.enqueue(n1); - if(minQ.size() === k) { + if (minQ.size() === k) { maxScore = Math.max(maxScore, runningTotal * n2); } - if(minQ.size() > k) { + if (minQ.size() > k) { runningTotal -= minQ.dequeue(); maxScore = Math.max(maxScore, runningTotal * n2); } diff --git a/javascript/2621-sleep.js b/javascript/2621-sleep.js index 3e79979bf..5b8d6dff6 100644 --- a/javascript/2621-sleep.js +++ b/javascript/2621-sleep.js @@ -3,10 +3,12 @@ * @return {Promise} */ async function sleep(millis) { - return new Promise(resolve => setTimeout(() => resolve("Completed!"), millis)); + return new Promise((resolve) => + setTimeout(() => resolve('Completed!'), millis), + ); } -/** +/** * let t = Date.now() * sleep(100).then(() => console.log(Date.now() - t)) // 100 */ diff --git a/javascript/2623-memoize.js b/javascript/2623-memoize.js index 9fd662e49..787320ec4 100644 --- a/javascript/2623-memoize.js +++ b/javascript/2623-memoize.js @@ -6,13 +6,12 @@ function memoize(fn) { let memo = {}; return function (...args) { let argsjson = JSON.stringify(args); - if (memo.hasOwnProperty(argsjson)) - return memo[argsjson]; - return memo[argsjson] = fn(...args); - } + if (memo.hasOwnProperty(argsjson)) return memo[argsjson]; + return (memo[argsjson] = fn(...args)); + }; } -/** +/** * let callCount = 0; * const memoizedFn = memoize(function (a, b) { * callCount += 1; @@ -20,5 +19,5 @@ function memoize(fn) { * }) * memoizedFn(2, 3) // 5 * memoizedFn(2, 3) // 5 - * console.log(callCount) // 1 + * console.log(callCount) // 1 */ diff --git a/javascript/2626-array-reduce-transformation.js b/javascript/2626-array-reduce-transformation.js index f695fe046..0fc48cee8 100644 --- a/javascript/2626-array-reduce-transformation.js +++ b/javascript/2626-array-reduce-transformation.js @@ -6,7 +6,6 @@ */ var reduce = function (nums, fn, init) { ans = init; - for (let n of nums) - ans = fn(ans, n); + for (let n of nums) ans = fn(ans, n); return ans; }; diff --git a/javascript/2627-debounce.js b/javascript/2627-debounce.js index 55c83420d..a41b1c987 100644 --- a/javascript/2627-debounce.js +++ b/javascript/2627-debounce.js @@ -8,7 +8,7 @@ var debounce = function (fn, t) { return function (...args) { clearTimeout(timeoutHandle); timeoutHandle = setTimeout(() => fn(...args), t); - } + }; }; /** diff --git a/javascript/2628-json-deep-equal.js b/javascript/2628-json-deep-equal.js index 908a392a2..188112033 100644 --- a/javascript/2628-json-deep-equal.js +++ b/javascript/2628-json-deep-equal.js @@ -3,18 +3,20 @@ * @param {any} o2 * @return {boolean} */ -var areDeeplyEqual = function(o1, o2) { +var areDeeplyEqual = function (o1, o2) { if (o1 === null || o2 === null) { return o1 === o2; } - if (typeof o1 !== typeof o2) { + if (typeof o1 !== typeof o2) { return false; } - if (typeof o1 !== 'object') { // primitives + if (typeof o1 !== 'object') { + // primitives return o1 === o2; } - if (Array.isArray(o1) && Array.isArray(o2)) { // Arrays + if (Array.isArray(o1) && Array.isArray(o2)) { + // Arrays if (o1.length !== o2.length) { return false; } @@ -23,7 +25,8 @@ var areDeeplyEqual = function(o1, o2) { return false; } } - } else if (!Array.isArray(o1) && !Array.isArray(o2)) { // Objects + } else if (!Array.isArray(o1) && !Array.isArray(o2)) { + // Objects if (Object.keys(o1).length !== Object.keys(o2).length) { return false; } diff --git a/javascript/2629-function-composition.js b/javascript/2629-function-composition.js index 6899a5d4e..c8ec62f79 100644 --- a/javascript/2629-function-composition.js +++ b/javascript/2629-function-composition.js @@ -5,10 +5,9 @@ var compose = function (functions) { return function (x) { let ans = x; - for (fn of functions.reverse()) - ans = fn(ans); + for (fn of functions.reverse()) ans = fn(ans); return ans; - } + }; }; /** diff --git a/javascript/2632-curry.js b/javascript/2632-curry.js index ed6ee86bb..160078d70 100644 --- a/javascript/2632-curry.js +++ b/javascript/2632-curry.js @@ -5,12 +5,10 @@ var curry = function (fn) { let accum = []; return function curried(...args) { - for (let arg of args) - accum.push(arg); - if (accum.length === fn.length) - return fn(...accum); + for (let arg of args) accum.push(arg); + if (accum.length === fn.length) return fn(...accum); return curried; - } + }; }; /** diff --git a/javascript/2634-filter-elements-from-array.js b/javascript/2634-filter-elements-from-array.js index 57ff4277c..f8e0ba8cb 100644 --- a/javascript/2634-filter-elements-from-array.js +++ b/javascript/2634-filter-elements-from-array.js @@ -5,8 +5,6 @@ */ var filter = function (arr, fn) { ans = []; - for (let i = 0; i < arr.length; i++) - if (fn(arr[i], i)) - ans.push(arr[i]); + for (let i = 0; i < arr.length; i++) if (fn(arr[i], i)) ans.push(arr[i]); return ans; }; diff --git a/javascript/2635-apply-transform-over-each-element-in-array.js b/javascript/2635-apply-transform-over-each-element-in-array.js index 419dd3ef2..e1624be1e 100644 --- a/javascript/2635-apply-transform-over-each-element-in-array.js +++ b/javascript/2635-apply-transform-over-each-element-in-array.js @@ -9,4 +9,4 @@ const map = (arr, fn) => { result.push(fn(arr[i], i)); } return result; -} \ No newline at end of file +}; diff --git a/javascript/2651-calculate-delayed-arrival-time.js b/javascript/2651-calculate-delayed-arrival-time.js index cc3c00c49..cbef451f4 100644 --- a/javascript/2651-calculate-delayed-arrival-time.js +++ b/javascript/2651-calculate-delayed-arrival-time.js @@ -6,11 +6,14 @@ var findDelayedArrivalTime = function (arrivalTime, delayedTime) { let totalTime = arrivalTime + delayedTime; // initialize totalTime is the sum of arrivalTime and delayedTime - if (totalTime == 24) { // if totalTime is equal to 24 then return 0 + if (totalTime == 24) { + // if totalTime is equal to 24 then return 0 return 0; - } else if (totalTime < 24) { // if totalTime is less than 24 then return totalTime + } else if (totalTime < 24) { + // if totalTime is less than 24 then return totalTime return totalTime; - } else { // else return subtraction of totalTime to 24 + } else { + // else return subtraction of totalTime to 24 return totalTime - 24; } -}; \ No newline at end of file +}; diff --git a/javascript/2652-sum-multiples.js b/javascript/2652-sum-multiples.js index 7cf8b0b48..8c93ca82b 100644 --- a/javascript/2652-sum-multiples.js +++ b/javascript/2652-sum-multiples.js @@ -4,11 +4,13 @@ */ var sumOfMultiples = function (n) { let arr = []; // initilialize an empty array - for (let i = 1; i <= n; i++) { // loop through the 1 to n - if ((i % 3 === 0) || (i % 5 === 0) || (i % 7 === 0)) { // if i is divisible by 3 or 5 or 7 then push i into arr + for (let i = 1; i <= n; i++) { + // loop through the 1 to n + if (i % 3 === 0 || i % 5 === 0 || i % 7 === 0) { + // if i is divisible by 3 or 5 or 7 then push i into arr arr.push(i); } } let result = arr.reduce((a, b) => a + b, 0); // find sum of all element of arr and store into result return result; // return the result -}; \ No newline at end of file +}; diff --git a/javascript/2665-counter-ii.js b/javascript/2665-counter-ii.js index 9c2d9b451..c2eb054a2 100644 --- a/javascript/2665-counter-ii.js +++ b/javascript/2665-counter-ii.js @@ -2,7 +2,7 @@ * @param {integer} init * @return { increment: Function, decrement: Function, reset: Function } */ -var createCounter = function(init) { +var createCounter = function (init) { let count = init; increment = () => ++count; @@ -10,15 +10,15 @@ var createCounter = function(init) { decrement = () => --count; reset = () => { - count = init; - return count; - } + count = init; + return count; + }; return { - increment, - decrement, - reset - } + increment, + decrement, + reset, + }; }; /** diff --git a/javascript/2666-allow-one-function-call.js b/javascript/2666-allow-one-function-call.js index 34afa8fba..a0f9bec40 100644 --- a/javascript/2666-allow-one-function-call.js +++ b/javascript/2666-allow-one-function-call.js @@ -9,7 +9,7 @@ var once = function (fn) { called = true; return fn(...args); } - } + }; }; /** diff --git a/javascript/2667-create-hello-world-function.js b/javascript/2667-create-hello-world-function.js index 034fe6c50..afe59a567 100644 --- a/javascript/2667-create-hello-world-function.js +++ b/javascript/2667-create-hello-world-function.js @@ -1,10 +1,10 @@ /** * @return {Function} */ -var createHelloWorld = function() { - return function(...args) { - return "Hello World" - } +var createHelloWorld = function () { + return function (...args) { + return 'Hello World'; + }; }; /** diff --git a/javascript/2704-to-be-or-not-to-be.js b/javascript/2704-to-be-or-not-to-be.js index 4231b276c..cea06d689 100644 --- a/javascript/2704-to-be-or-not-to-be.js +++ b/javascript/2704-to-be-or-not-to-be.js @@ -1,16 +1,18 @@ /** * Creates an expectation object for testing values. - * + * * @param {any} val - The value to be tested. * @returns {Object} An object with two methods: * - toBe(expected): Returns true if val === expected, otherwise throws an error "Not Equal". * - notToBe(expected): Returns true if val !== expected, otherwise throws an error "Equal". */ const expect = (val) => { - const throwError = (message) => { throw new Error(message); }; + const throwError = (message) => { + throw new Error(message); + }; return { - toBe: (expected) => val === expected || throwError("Not Equal"), - notToBe: (expected) => val !== expected || throwError("Equal") + toBe: (expected) => val === expected || throwError('Not Equal'), + notToBe: (expected) => val !== expected || throwError('Equal'), }; }; @@ -18,4 +20,4 @@ const expect = (val) => { // expect(5).toBe(5); // returns true // expect(5).notToBe(3); // returns true // expect(5).toBe(3); // throws "Not Equal" -// expect(5).notToBe(5); // throws "Equal" \ No newline at end of file +// expect(5).notToBe(5); // throws "Equal" diff --git a/javascript/2706-buy-two-chocolates.js b/javascript/2706-buy-two-chocolates.js index b3ec36584..17f091284 100644 --- a/javascript/2706-buy-two-chocolates.js +++ b/javascript/2706-buy-two-chocolates.js @@ -6,10 +6,15 @@ * @param {number} money * @return {number} */ -var buyChoco = function(prices, money) { - - const [cheapestChocolate] = prices.splice(prices.indexOf(Math.min(...prices)), 1); - const [secondCheapestChocolate] = prices.splice(prices.indexOf(Math.min(...prices)), 1); +var buyChoco = function (prices, money) { + const [cheapestChocolate] = prices.splice( + prices.indexOf(Math.min(...prices)), + 1, + ); + const [secondCheapestChocolate] = prices.splice( + prices.indexOf(Math.min(...prices)), + 1, + ); const leftOverMoney = money - (cheapestChocolate + secondCheapestChocolate); - return leftOverMoney > -1 ? leftOverMoney : money; + return leftOverMoney > -1 ? leftOverMoney : money; }; diff --git a/javascript/2710-remove-trailing-zeros-from-a-string.js b/javascript/2710-remove-trailing-zeros-from-a-string.js index 3a212df02..a7213f37d 100644 --- a/javascript/2710-remove-trailing-zeros-from-a-string.js +++ b/javascript/2710-remove-trailing-zeros-from-a-string.js @@ -3,10 +3,11 @@ * @return {string} */ var removeTrailingZeros = function (num) { - - for (let i = num.length - 1; i >= 0; i--) { // loop through the every element of string num from end - if (num[i] != 0) { // if every character of num is not equal to zero + for (let i = num.length - 1; i >= 0; i--) { + // loop through the every element of string num from end + if (num[i] != 0) { + // if every character of num is not equal to zero return num.slice(0, i + 1); // return the character of num upto ith character } } -}; \ No newline at end of file +}; diff --git a/javascript/2769-find-the-maximum-achievable-number.js b/javascript/2769-find-the-maximum-achievable-number.js index 7b4c3c11c..fe007e53b 100644 --- a/javascript/2769-find-the-maximum-achievable-number.js +++ b/javascript/2769-find-the-maximum-achievable-number.js @@ -4,5 +4,5 @@ * @return {number} */ var theMaximumAchievableX = function (num, t) { - return num + (t * 2) // return sum of value of num and twice the value of t -}; \ No newline at end of file + return num + t * 2; // return sum of value of num and twice the value of t +}; diff --git a/javascript/2810-faulty-keyboard.js b/javascript/2810-faulty-keyboard.js index 0db8aa2f2..362fe8426 100644 --- a/javascript/2810-faulty-keyboard.js +++ b/javascript/2810-faulty-keyboard.js @@ -4,11 +4,10 @@ */ var finalString = function (s) { // initialize empty string str - let str = ""; + let str = ''; // loop thorugh the every character of string s for (let i = 0; i < s.length; i++) { - // if every character of string is i then reverse the previous string character and store in string str if (s[i] == 'i') { str = [...str].reverse().join(''); @@ -20,4 +19,4 @@ var finalString = function (s) { // return string str return str; -}; \ No newline at end of file +}; diff --git a/javascript/2864-maximum-odd-binary-number.js b/javascript/2864-maximum-odd-binary-number.js index c44db142a..f59e75489 100644 --- a/javascript/2864-maximum-odd-binary-number.js +++ b/javascript/2864-maximum-odd-binary-number.js @@ -4,18 +4,17 @@ * @param {string} s * @return {string} */ -var maximumOddBinaryNumber = function(s) { - - let numberOf1s = s.split("").filter((bit) => bit === "1").length; - s = s.split("").map((bit) => "0"); +var maximumOddBinaryNumber = function (s) { + let numberOf1s = s.split('').filter((bit) => bit === '1').length; + s = s.split('').map((bit) => '0'); let i = 0; while (numberOf1s > 1) { - s[i] = "1"; + s[i] = '1'; i++; numberOf1s--; } s[s.length - 1] = 1; - return s.join(""); + return s.join(''); }; diff --git a/package.json b/package.json index 7348d0ad4..f8de3da1e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "scripts": { - "format": "prettier --write \"**/**/*.{js,ts,json,md,c,cpp,cs}\"" + "format": "prettier --write \"**/**/*.{js,ts,md,json}\"" }, "dependencies": { "prettier": "^3.6.2" diff --git a/typescript/0002-add-two-numbers.ts b/typescript/0002-add-two-numbers.ts index 94e91f412..469606fbb 100644 --- a/typescript/0002-add-two-numbers.ts +++ b/typescript/0002-add-two-numbers.ts @@ -12,7 +12,7 @@ function addTwoNumbers( l1: ListNode | null, - l2: ListNode | null + l2: ListNode | null, ): ListNode | null { let dummyNode: ListNode = new ListNode(); let currentNode: ListNode = dummyNode; diff --git a/typescript/0014-longest-common-prefix.ts b/typescript/0014-longest-common-prefix.ts index ca4e44848..0c12d85a7 100644 --- a/typescript/0014-longest-common-prefix.ts +++ b/typescript/0014-longest-common-prefix.ts @@ -1,14 +1,14 @@ function longestCommonPrefix(strs: string[]): string { - let res = ""; - + let res = ''; + for (let i = 0; i < strs[0].length; i++) { for (const s of strs) { if (i == s.length || s[i] !== strs[0][i]) { return res; } } - res += strs[0][i] + res += strs[0][i]; } - + return res; -}; \ No newline at end of file +} diff --git a/typescript/0018-4sum.ts b/typescript/0018-4sum.ts index dfe86108f..de17b4be3 100644 --- a/typescript/0018-4sum.ts +++ b/typescript/0018-4sum.ts @@ -25,7 +25,7 @@ function fourSum(nums: number[], target: number): number[][] { right--; } else { res.push( - quad.concat([sortedNums[left], sortedNums[right]]) + quad.concat([sortedNums[left], sortedNums[right]]), ); left++; while ( diff --git a/typescript/0021-merge-two-sorted-lists.ts b/typescript/0021-merge-two-sorted-lists.ts index 83dbbef75..6ecf9c179 100644 --- a/typescript/0021-merge-two-sorted-lists.ts +++ b/typescript/0021-merge-two-sorted-lists.ts @@ -12,7 +12,7 @@ function mergeTwoLists( list1: ListNode | null, - list2: ListNode | null + list2: ListNode | null, ): ListNode | null { let dummyList: ListNode = new ListNode(0); let currentNode: ListNode = dummyList; diff --git a/typescript/0023-merge-k-sorted-lists.ts b/typescript/0023-merge-k-sorted-lists.ts index 51a0c4bdf..50c3f21ca 100644 --- a/typescript/0023-merge-k-sorted-lists.ts +++ b/typescript/0023-merge-k-sorted-lists.ts @@ -31,7 +31,7 @@ function mergeKLists(lists: Array): ListNode | null { function mergeList( list1: ListNode | null, - list2: ListNode | null + list2: ListNode | null, ): ListNode | null { let dummyNode: ListNode | null = new ListNode(); let tail = dummyNode; diff --git a/typescript/0047-permutations-ii.ts b/typescript/0047-permutations-ii.ts index 259c0652e..447e41054 100644 --- a/typescript/0047-permutations-ii.ts +++ b/typescript/0047-permutations-ii.ts @@ -24,4 +24,4 @@ function permuteUnique(nums: number[]): number[][] { traverse(); return results; -}; +} diff --git a/typescript/0056-merge-intervals.ts b/typescript/0056-merge-intervals.ts index 0835cb77f..2785e9ea5 100644 --- a/typescript/0056-merge-intervals.ts +++ b/typescript/0056-merge-intervals.ts @@ -1,25 +1,27 @@ function merge(intervals: number[][]): number[][] { - intervals.sort(([aStart, aEnd], [bStart, bEnd]) => aStart !== bStart ? aStart - bStart : aEnd - bEnd); - + intervals.sort(([aStart, aEnd], [bStart, bEnd]) => + aStart !== bStart ? aStart - bStart : aEnd - bEnd, + ); + return mergeInterval(intervals); -}; +} function mergeInterval(intervals: number[][]): number[][] { let merged = []; let prev = intervals.shift(); - + for (const curr of intervals) { const [prevStart, prevEnd] = prev; const [currStart, currEnd] = curr; - + // Overlap occurs if (currStart <= prevEnd) { prev[1] = Math.max(prev[1], curr[1]); continue; } - + merged.push(prev); prev = curr; } return [...merged, prev]; -} \ No newline at end of file +} diff --git a/typescript/0057-insert-interval.ts b/typescript/0057-insert-interval.ts index 9b63bae71..22a587172 100644 --- a/typescript/0057-insert-interval.ts +++ b/typescript/0057-insert-interval.ts @@ -3,12 +3,13 @@ function insert(intervals: number[][], newInterval: number[]): number[][] { const afterIndex = mergeIntervals(intervals, newInterval, beforeIndex); const after = intervals.slice(afterIndex); - return [...before, newInterval, ...after]; -}; + return [...before, newInterval, ...after]; +} const getBefore = (intervals, newInterval, index = 0, before = []) => { - const hasGap = ([prevStart, prevEnd], [currStart, currEnd]) => prevEnd < currStart; - + const hasGap = ([prevStart, prevEnd], [currStart, currEnd]) => + prevEnd < currStart; + while (index < intervals.length && hasGap(intervals[index], newInterval)) { const current = intervals[index]; before.push(current); @@ -18,13 +19,17 @@ const getBefore = (intervals, newInterval, index = 0, before = []) => { }; const mergeIntervals = (intervals, newInterval, index) => { - const hasOverlap = ([prevStart, prevEnd], [currStart, currEnd]) => currStart <= prevEnd; + const hasOverlap = ([prevStart, prevEnd], [currStart, currEnd]) => + currStart <= prevEnd; - while (index < intervals.length && hasOverlap(newInterval, intervals[index])) { + while ( + index < intervals.length && + hasOverlap(newInterval, intervals[index]) + ) { const current = intervals[index]; newInterval[0] = Math.min(newInterval[0], current[0]); newInterval[1] = Math.max(newInterval[1], current[1]); index++; } return index; -}; \ No newline at end of file +}; diff --git a/typescript/0067-add-binary.ts b/typescript/0067-add-binary.ts index f77af8e62..7e61d5d50 100644 --- a/typescript/0067-add-binary.ts +++ b/typescript/0067-add-binary.ts @@ -1,11 +1,11 @@ function addBinary(a: string, b: string): string { - let res = "" - let carry = 0 + let res = ''; + let carry = 0; - a = a.split('').reverse().join('') - b = b.split('').reverse().join('') + a = a.split('').reverse().join(''); + b = b.split('').reverse().join(''); - for (let i = 0; i < (Math.max(a.length, b.length)); i++) { + for (let i = 0; i < Math.max(a.length, b.length); i++) { let digitA: number = i < a.length ? +a[i] : 0; let digitB: number = i < b.length ? +b[i] : 0; @@ -15,7 +15,7 @@ function addBinary(a: string, b: string): string { carry = Math.floor(total / 2); } if (carry) { - res = "1" + res; + res = '1' + res; } return res; -}; +} diff --git a/typescript/0072-edit-distance.ts b/typescript/0072-edit-distance.ts index 625810d41..ffca16ba4 100644 --- a/typescript/0072-edit-distance.ts +++ b/typescript/0072-edit-distance.ts @@ -1,5 +1,8 @@ function minDistance(word1: string, word2: string): number { - let dp = Array.from({ length: word2.length + 1 }, (_, i) => word2.length - i); + let dp = Array.from( + { length: word2.length + 1 }, + (_, i) => word2.length - i, + ); for (let i = word1.length - 1; i >= 0; i--) { const current = new Array(word2.length + 1); @@ -9,11 +12,7 @@ function minDistance(word1: string, word2: string): number { if (word1[i] === word2[j]) { current[j] = dp[j + 1]; } else { - current[j] = 1 + Math.min( - dp[j], - current[j + 1], - dp[j + 1], - ); + current[j] = 1 + Math.min(dp[j], current[j + 1], dp[j + 1]); } } @@ -21,4 +20,4 @@ function minDistance(word1: string, word2: string): number { } return dp[0]; -}; +} diff --git a/typescript/0073-set-matrix-zeroes.ts b/typescript/0073-set-matrix-zeroes.ts index 073c85ed0..7bc85a7e0 100644 --- a/typescript/0073-set-matrix-zeroes.ts +++ b/typescript/0073-set-matrix-zeroes.ts @@ -21,4 +21,4 @@ function setZeroes(matrix: number[][]): void { } } } -}; \ No newline at end of file +} diff --git a/typescript/0079-word-search.ts b/typescript/0079-word-search.ts index cbddab40a..7e4edc59d 100644 --- a/typescript/0079-word-search.ts +++ b/typescript/0079-word-search.ts @@ -1,46 +1,47 @@ function exist(board: string[][], word: string): boolean { - const rowsLength = board.length; - const colsLength = board[0].length; + const rowsLength = board.length; + const colsLength = board[0].length; - function outOfBounds(r: number, c: number) { - return r < 0 || c < 0 || r >= rowsLength || c >= colsLength; - } - - // idx: the index of the current character in the word we're looking for - function dfs(row: number, col: number, idx: number): boolean { - if (idx === word.length) { - return true; + function outOfBounds(r: number, c: number) { + return r < 0 || c < 0 || r >= rowsLength || c >= colsLength; } - if (outOfBounds(row, col) || word[idx] !== board[row][col]) { - return false; + + // idx: the index of the current character in the word we're looking for + function dfs(row: number, col: number, idx: number): boolean { + if (idx === word.length) { + return true; + } + if (outOfBounds(row, col) || word[idx] !== board[row][col]) { + return false; + } + + // Mark the current cell as visited + let currentCell = board[row][col]; + board[row][col] = '*'; + + // Pass idx + 1 because we're looking for + // the next character in the word now + let result = + dfs(row + 1, col, idx + 1) || // down + dfs(row - 1, col, idx + 1) || // up + dfs(row, col + 1, idx + 1) || // right + dfs(row, col - 1, idx + 1); // left + + // Reset the current cell to its original value + // because we're done visiting it + board[row][col] = currentCell; + + return result; } - // Mark the current cell as visited - let currentCell = board[row][col]; - board[row][col] = '*'; - - // Pass idx + 1 because we're looking for - // the next character in the word now - let result = dfs(row + 1, col, idx + 1) || // down - dfs(row - 1, col, idx + 1) || // up - dfs(row, col + 1, idx + 1) || // right - dfs(row, col - 1, idx + 1); // left - - // Reset the current cell to its original value - // because we're done visiting it - board[row][col] = currentCell; - - return result; - } - - // For each cell, do a depth-first search - for (let i = 0; i < rowsLength; i++) { - for (let j = 0; j < colsLength; j++) { - if (dfs(i, j, 0)) { - return true; - } + // For each cell, do a depth-first search + for (let i = 0; i < rowsLength; i++) { + for (let j = 0; j < colsLength; j++) { + if (dfs(i, j, 0)) { + return true; + } + } } - } - return false; + return false; } diff --git a/typescript/0094-binary-tree-inorder-traversal.ts b/typescript/0094-binary-tree-inorder-traversal.ts index 36aca4064..6f8ec1e72 100644 --- a/typescript/0094-binary-tree-inorder-traversal.ts +++ b/typescript/0094-binary-tree-inorder-traversal.ts @@ -1,23 +1,25 @@ -/** - * Definition for a binary tree node. - * class TreeNode { - * val: number - * left: TreeNode | null - * right: TreeNode | null - * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - * } - */ - function inorderTraversal(root: TreeNode | null, list: Array = [] ): number[] { - - if (!root) return []; - - inorderTraversal(root.left, list); - list.push(root.val) - inorderTraversal(root.right, list); - - return list -}; \ No newline at end of file +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ +function inorderTraversal( + root: TreeNode | null, + list: Array = [], +): number[] { + if (!root) return []; + + inorderTraversal(root.left, list); + list.push(root.val); + inorderTraversal(root.right, list); + + return list; +} diff --git a/typescript/0098-validate-binary-search-tree.ts b/typescript/0098-validate-binary-search-tree.ts index d0971ef2a..ab05b42c7 100644 --- a/typescript/0098-validate-binary-search-tree.ts +++ b/typescript/0098-validate-binary-search-tree.ts @@ -19,7 +19,7 @@ function isValidBST(root: TreeNode | null): boolean { function validate( root: TreeNode | null, max: number | null, - min: number | null + min: number | null, ): boolean { if (!root) { return true; diff --git a/typescript/0127-word-ladder.ts b/typescript/0127-word-ladder.ts index 523206043..7b49fd924 100644 --- a/typescript/0127-word-ladder.ts +++ b/typescript/0127-word-ladder.ts @@ -1,7 +1,7 @@ function ladderLength( beginWord: string, endWord: string, - wordList: string[] + wordList: string[], ): number { if (!wordList.includes(endWord)) { return 0; diff --git a/typescript/0130-surrounded-regions.ts b/typescript/0130-surrounded-regions.ts index 1dfcc3740..426cb5b02 100644 --- a/typescript/0130-surrounded-regions.ts +++ b/typescript/0130-surrounded-regions.ts @@ -29,7 +29,7 @@ function solve(board: string[][]): void { } } -function markSeen(r: number, c: number): void { + function markSeen(r: number, c: number): void { if (!inBounds(r, c) || board[r][c] !== 'O') { return; } @@ -40,9 +40,9 @@ function markSeen(r: number, c: number): void { markSeen(r + 1, c); markSeen(r, c - 1); markSeen(r, c + 1); -} + } -function inBounds(r: number, c: number): boolean { + function inBounds(r: number, c: number): boolean { return r >= 0 && c >= 0 && r < rowLen && c < colLen; + } } -}; \ No newline at end of file diff --git a/typescript/0146-lru-cache.ts b/typescript/0146-lru-cache.ts index b9b92f77e..123efa88c 100644 --- a/typescript/0146-lru-cache.ts +++ b/typescript/0146-lru-cache.ts @@ -6,10 +6,10 @@ */ type CacheNode = { - value: number, - key: number | null, - next: CacheNode | null, - prev: CacheNode | null, + value: number; + key: number | null; + next: CacheNode | null; + prev: CacheNode | null; }; class LRUCache { @@ -44,20 +44,20 @@ class LRUCache { this.head.next.prev = node; this.head.next = node; - + return node.value; } put(key: number, value: number): void { let node = this.data.get(key); if (!node) { - this.size++; - node = { value, key } as CacheNode; - this.data.set(key, node); + this.size++; + node = { value, key } as CacheNode; + this.data.set(key, node); } else { - node.value = value; - node.prev.next = node.next; - node.next.prev = node.prev; + node.value = value; + node.prev.next = node.next; + node.next.prev = node.prev; } node.next = this.head.next; @@ -67,7 +67,7 @@ class LRUCache { this.head.next = node; if (this.size > this.capacity) { - this.evict(); + this.evict(); } } diff --git a/typescript/0203-remove-linked-list-elements.ts b/typescript/0203-remove-linked-list-elements.ts index 19522876a..c2ae88785 100644 --- a/typescript/0203-remove-linked-list-elements.ts +++ b/typescript/0203-remove-linked-list-elements.ts @@ -1,33 +1,31 @@ -/** - * Definition for singly-linked list. - * class ListNode { - * val: number - * next: ListNode | null - * constructor(val?: number, next?: ListNode | null) { - * this.val = (val===undefined ? 0 : val) - * this.next = (next===undefined ? null : next) - * } - * } - */ - -function removeElements(head: ListNode | null, val: number): ListNode | null { - - let sentinel_node : ListNode = new ListNode(0, head); - let slow_pointer : ListNode | null = sentinel_node; - let fast_pointer : ListNode | null = null; - - while (slow_pointer) { - - // get next legible node - fast_pointer = slow_pointer.next; - while (fast_pointer && fast_pointer.val === val) { - fast_pointer = fast_pointer.next; - } - - // Set next node to the legible node - slow_pointer.next = fast_pointer; - slow_pointer = slow_pointer.next; - } - - return sentinel_node.next; -}; \ No newline at end of file +/** + * Definition for singly-linked list. + * class ListNode { + * val: number + * next: ListNode | null + * constructor(val?: number, next?: ListNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + * } + */ + +function removeElements(head: ListNode | null, val: number): ListNode | null { + let sentinel_node: ListNode = new ListNode(0, head); + let slow_pointer: ListNode | null = sentinel_node; + let fast_pointer: ListNode | null = null; + + while (slow_pointer) { + // get next legible node + fast_pointer = slow_pointer.next; + while (fast_pointer && fast_pointer.val === val) { + fast_pointer = fast_pointer.next; + } + + // Set next node to the legible node + slow_pointer.next = fast_pointer; + slow_pointer = slow_pointer.next; + } + + return sentinel_node.next; +} diff --git a/typescript/0211-design-add-and-search-words-data-structure.ts b/typescript/0211-design-add-and-search-words-data-structure.ts index 2bbcdd69a..2bdf84d47 100644 --- a/typescript/0211-design-add-and-search-words-data-structure.ts +++ b/typescript/0211-design-add-and-search-words-data-structure.ts @@ -37,7 +37,7 @@ class WordDictionary { if ( Object.prototype.hasOwnProperty.call( cur.children, - key + key, ) ) { const child = cur.children[key]; diff --git a/typescript/0212-word-search-ii.ts b/typescript/0212-word-search-ii.ts index bd23c5cc8..f766edf0d 100644 --- a/typescript/0212-word-search-ii.ts +++ b/typescript/0212-word-search-ii.ts @@ -35,7 +35,7 @@ function findWords(board: string[][], words: string[]): string[] { const currentChar = board[r][c]; const currentNode = node.children[currentChar]; if (!currentNode) return; - + const currentWord = word + currentChar; if (currentNode.word) { resultSet.add(currentWord); @@ -62,4 +62,4 @@ function findWords(board: string[][], words: string[]): string[] { } return [...resultSet]; -}; +} diff --git a/typescript/0213-house-robber-ii.ts b/typescript/0213-house-robber-ii.ts index b8cbfe6f8..1e08c1de3 100644 --- a/typescript/0213-house-robber-ii.ts +++ b/typescript/0213-house-robber-ii.ts @@ -15,6 +15,6 @@ function rob(nums: number[]): number { return Math.max( nums[0], helper(nums.slice(0, nums.length - 1)), - helper(nums.slice(1)) + helper(nums.slice(1)), ); } diff --git a/typescript/0219-contains-duplicate-ii.ts b/typescript/0219-contains-duplicate-ii.ts index 6e0443338..562957e78 100644 --- a/typescript/0219-contains-duplicate-ii.ts +++ b/typescript/0219-contains-duplicate-ii.ts @@ -1,15 +1,15 @@ function containsNearbyDuplicate(nums: number[], k: number): boolean { - let map = new Map() - for(let i = 0; i < nums.length; i++){ - if(!map.has(nums[i])){ - map.set(nums[i], i) - }else{ - if(i - map.get(nums[i]) <= k){ - return true - }else{ - map.set(nums[i], i) + let map = new Map(); + for (let i = 0; i < nums.length; i++) { + if (!map.has(nums[i])) { + map.set(nums[i], i); + } else { + if (i - map.get(nums[i]) <= k) { + return true; + } else { + map.set(nums[i], i); } } } - return false -}; + return false; +} diff --git a/typescript/0235-lowest-common-ancestor-of-a-binary-search-tree.ts b/typescript/0235-lowest-common-ancestor-of-a-binary-search-tree.ts index 6d4db5b9b..9b8383a4e 100644 --- a/typescript/0235-lowest-common-ancestor-of-a-binary-search-tree.ts +++ b/typescript/0235-lowest-common-ancestor-of-a-binary-search-tree.ts @@ -15,7 +15,7 @@ function lowestCommonAncestor( root: TreeNode | null, p: TreeNode | null, - q: TreeNode | null + q: TreeNode | null, ): TreeNode | null { let cur = root; diff --git a/typescript/0256-paint-house.ts b/typescript/0256-paint-house.ts index 91039e223..046ba77ef 100644 --- a/typescript/0256-paint-house.ts +++ b/typescript/0256-paint-house.ts @@ -1,11 +1,11 @@ // Dynamic Programming, Time Complexity: O(n), Space Complexity: O(1) function minCost(costs: number[][]): number { let dp: number[] = [0, 0, 0]; - for ( const cost of costs ) { + for (const cost of costs) { let currMin0: number = cost[0] + Math.min(dp[1], dp[2]); let currMin1: number = cost[1] + Math.min(dp[0], dp[2]); let currMin2: number = cost[2] + Math.min(dp[0], dp[1]); dp = [currMin0, currMin1, currMin2]; } return Math.min(...dp); -}; +} diff --git a/typescript/0261-graph-valid-tree.ts b/typescript/0261-graph-valid-tree.ts index 99d286cd9..444e2a29d 100644 --- a/typescript/0261-graph-valid-tree.ts +++ b/typescript/0261-graph-valid-tree.ts @@ -28,7 +28,7 @@ function dfs( node: number, prevNode: number, visited: Visited, - adjacent: Obj + adjacent: Obj, ): boolean { if (visited[node]) return false; visited[node] = true; diff --git a/typescript/0295-find-median-from-data-stream.ts b/typescript/0295-find-median-from-data-stream.ts index 4feaac219..41a0771bd 100644 --- a/typescript/0295-find-median-from-data-stream.ts +++ b/typescript/0295-find-median-from-data-stream.ts @@ -1,7 +1,7 @@ /* - * Time Complexity: O(logn) - * Space Complexity: O(n) -*/ + * Time Complexity: O(logn) + * Space Complexity: O(n) + */ class MedianFinder { public minHeap; @@ -19,7 +19,10 @@ class MedianFinder { findMedian(): number { if (this.minHeap.size() === this.maxHeap.size()) { - return (this.minHeap.front().element + this.maxHeap.front().element) / 2; + return ( + (this.minHeap.front().element + this.maxHeap.front().element) / + 2 + ); } return this.maxHeap.front().element; diff --git a/typescript/0297-serialize-and-deserialize-binary-tree.ts b/typescript/0297-serialize-and-deserialize-binary-tree.ts index c60a3cc68..de85e9a56 100644 --- a/typescript/0297-serialize-and-deserialize-binary-tree.ts +++ b/typescript/0297-serialize-and-deserialize-binary-tree.ts @@ -27,7 +27,7 @@ function serialize(root: TreeNode | null): string { cereal(root); return box.join(','); -}; +} /* * Decodes your encoded data to tree. @@ -45,10 +45,9 @@ function deserialize(data: string): TreeNode | null { } return decereal(); -}; - +} /** * Your functions will be called as such: * deserialize(serialize(root)); - */ \ No newline at end of file + */ diff --git a/typescript/0303-range-sum-query-immutable.ts b/typescript/0303-range-sum-query-immutable.ts index 757a620a6..263b2e2e1 100644 --- a/typescript/0303-range-sum-query-immutable.ts +++ b/typescript/0303-range-sum-query-immutable.ts @@ -1,17 +1,16 @@ class NumArray { - prefixSums: number[] = []; constructor(nums: number[]) { this.prefixSums.push(nums[0]); - for(let i=1; i> 1; if (leftIndex > mid) { return this.right.queryRange(leftIndex, rightIndex); - } else if (rightIndex <= mid){ + } else if (rightIndex <= mid) { return this.left.queryRange(leftIndex, rightIndex); } - return this.left.queryRange(leftIndex, mid) + this.right.queryRange(mid + 1, rightIndex); + return ( + this.left.queryRange(leftIndex, mid) + + this.right.queryRange(mid + 1, rightIndex) + ); } } diff --git a/typescript/0309-best-time-to-buy-and-sell-stock-with-cooldown.ts b/typescript/0309-best-time-to-buy-and-sell-stock-with-cooldown.ts index 4b595a789..1cf3ed6f6 100644 --- a/typescript/0309-best-time-to-buy-and-sell-stock-with-cooldown.ts +++ b/typescript/0309-best-time-to-buy-and-sell-stock-with-cooldown.ts @@ -1,5 +1,5 @@ function maxProfit(prices: number[]): number { - let [ sold, hold, rest ] = [ 0, Number.MIN_SAFE_INTEGER, 0]; + let [sold, hold, rest] = [0, Number.MIN_SAFE_INTEGER, 0]; for (let i = 0; i < prices.length; i++) { let prevSold = sold; @@ -8,4 +8,4 @@ function maxProfit(prices: number[]): number { rest = Math.max(rest, prevSold); } return Math.max(sold, rest); -}; \ No newline at end of file +} diff --git a/typescript/0312-burst-balloons.ts b/typescript/0312-burst-balloons.ts index 510cf5982..5c29e0b6b 100644 --- a/typescript/0312-burst-balloons.ts +++ b/typescript/0312-burst-balloons.ts @@ -11,7 +11,7 @@ function maxCoins(nums: number[]): number { dp[i][j], dp[i][k - 1] + vals[i - 1] * vals[k] * vals[j + 1] + - dp[k + 1][j] + dp[k + 1][j], ); } } diff --git a/typescript/0347-top-k-frequent-elements.ts b/typescript/0347-top-k-frequent-elements.ts index 0baa7d127..241cb4400 100644 --- a/typescript/0347-top-k-frequent-elements.ts +++ b/typescript/0347-top-k-frequent-elements.ts @@ -4,7 +4,7 @@ function topKFrequent(nums: number[], k: number): number[] | undefined { } = {}; const freq: number[][] = Array.apply(null, Array(nums.length + 1)).map( - () => [] + () => [], ); nums.forEach((item) => { @@ -44,7 +44,7 @@ function topKFrequentNLogN(nums: number[], k: number): number[] { return Object.entries(map) .sort( - ([, countA], [, countB]) => (countB as number) - (countA as number) + ([, countA], [, countB]) => (countB as number) - (countA as number), ) .slice(0, k) .map(([num]) => +num); diff --git a/typescript/0417-pacific-atlantic-water-flow.ts b/typescript/0417-pacific-atlantic-water-flow.ts index 6dcbfb892..8ea2d35e7 100644 --- a/typescript/0417-pacific-atlantic-water-flow.ts +++ b/typescript/0417-pacific-atlantic-water-flow.ts @@ -1,32 +1,44 @@ /** * Breath First Search implementation - * @param matrix - * @param queue - * @param visited + * @param matrix + * @param queue + * @param visited */ -const bfs = (matrix: number[][], queue: number[][], visited: boolean[][]): void => { - let m = matrix.length, n = matrix[0].length; - let directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; +const bfs = ( + matrix: number[][], + queue: number[][], + visited: boolean[][], +): void => { + let m = matrix.length, + n = matrix[0].length; + let directions = [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + ]; while (queue.length > 0) { const [qCordx, qCordy] = queue.shift()!; for (let dir of directions) { - const x = qCordx + dir[0], y = qCordy + dir[1]; - if (!( - x < 0 || - y < 0 || - x >= m || - y >= n || - visited[x][y] || - matrix[x][y] < matrix[qCordx][qCordy]) + const x = qCordx + dir[0], + y = qCordy + dir[1]; + if ( + !( + x < 0 || + y < 0 || + x >= m || + y >= n || + visited[x][y] || + matrix[x][y] < matrix[qCordx][qCordy] + ) ) { visited[x][y] = true; queue.push([x, y]); } - } } -} +}; /** * Creates a Matrix NXM with false values @@ -34,9 +46,9 @@ const bfs = (matrix: number[][], queue: number[][], visited: boolean[][]): void const createMatrix = (n: number, m: number): boolean[][] => Array.from({ length: n }, () => Array.from({ length: m }, () => false)); - function pacificAtlantic(heights: number[][]): number[][] { - const ROWS = heights.length, COLS = heights[0].length; + const ROWS = heights.length, + COLS = heights[0].length; let pacific: boolean[][] = createMatrix(ROWS, COLS); let atlantic: boolean[][] = createMatrix(ROWS, COLS); let pacQueue: number[][] = []; @@ -70,4 +82,4 @@ function pacificAtlantic(heights: number[][]): number[][] { } return results; -}; +} diff --git a/typescript/0435-non-overlapping-intervals.ts b/typescript/0435-non-overlapping-intervals.ts index f20df9d2b..8807ba711 100644 --- a/typescript/0435-non-overlapping-intervals.ts +++ b/typescript/0435-non-overlapping-intervals.ts @@ -1,24 +1,26 @@ function eraseOverlapIntervals(intervals: number[][]): number { - intervals.sort(([aStart, aEnd], [bStart, bEnd]) => aEnd !== bEnd ? aEnd - bEnd : aStart - bStart); - + intervals.sort(([aStart, aEnd], [bStart, bEnd]) => + aEnd !== bEnd ? aEnd - bEnd : aStart - bStart, + ); + return getGaps(intervals); -}; +} function getGaps(intervals: number[][]): number { let gaps = 0; const prev = intervals.shift(); - + for (const curr of intervals) { const [prevStart, prevEnd] = prev; const [currStart, currEnd] = curr; - + const hasGap = prevEnd <= currStart; if (!hasGap) { continue; } - + prev[1] = curr[1]; gaps++; } return intervals.length - gaps; -} \ No newline at end of file +} diff --git a/typescript/0438-find-all-anagrams-in-a-string.ts b/typescript/0438-find-all-anagrams-in-a-string.ts index 7b138b84b..3dbf81829 100644 --- a/typescript/0438-find-all-anagrams-in-a-string.ts +++ b/typescript/0438-find-all-anagrams-in-a-string.ts @@ -1,33 +1,34 @@ //Time Complexity -> O(n) //Space Complexity -> O(n) function findAnagrams(s: string, p: string): number[] { - if (p.length > s.length) return []; + if (p.length > s.length) return []; - const anagramIndexes: number[] = []; - const pCount = new Map(); - const sCount = new Map(); - for (const char of p) pCount.set(char, (pCount.get(char) || 0) + 1); - for (let i = 0; i < p.length; i++) sCount.set(s[i], (sCount.get(s[i]) || 0) + 1); + const anagramIndexes: number[] = []; + const pCount = new Map(); + const sCount = new Map(); + for (const char of p) pCount.set(char, (pCount.get(char) || 0) + 1); + for (let i = 0; i < p.length; i++) + sCount.set(s[i], (sCount.get(s[i]) || 0) + 1); - let l = 0; - let r = p.length - 1; - while (r < s.length) { - let isAnagram = true; - for (const [char, count] of pCount) { - if (!sCount.has(char) || sCount.get(char) !== count) { - isAnagram = false; - break; - } - } - if (isAnagram) anagramIndexes.push(l); + let l = 0; + let r = p.length - 1; + while (r < s.length) { + let isAnagram = true; + for (const [char, count] of pCount) { + if (!sCount.has(char) || sCount.get(char) !== count) { + isAnagram = false; + break; + } + } + if (isAnagram) anagramIndexes.push(l); - sCount.set(s[l], (sCount.get(s[l]) || 1) - 1); - if (sCount.get(s[l]) === 0) sCount.delete(s[l]); - l++; + sCount.set(s[l], (sCount.get(s[l]) || 1) - 1); + if (sCount.get(s[l]) === 0) sCount.delete(s[l]); + l++; - r++; - sCount.set(s[r], (sCount.get(s[r]) || 0) + 1); - } + r++; + sCount.set(s[r], (sCount.get(s[r]) || 0) + 1); + } - return anagramIndexes; + return anagramIndexes; } diff --git a/typescript/0474-ones-and-zeroes.ts b/typescript/0474-ones-and-zeroes.ts index 387c8765f..d4fdfd752 100644 --- a/typescript/0474-ones-and-zeroes.ts +++ b/typescript/0474-ones-and-zeroes.ts @@ -1,15 +1,17 @@ function findMaxForm(strs: string[], m: number, n: number): number { - const data = strs.reduce((accum, str) => { - let zeroes = 0; - for (let c of str) { - if (c === '0') zeroes++; - } - accum.push([zeroes, str.length - zeroes]); - return accum; - }, [] as [number, number][]); + const data = strs.reduce( + (accum, str) => { + let zeroes = 0; + for (let c of str) { + if (c === '0') zeroes++; + } + accum.push([zeroes, str.length - zeroes]); + return accum; + }, + [] as [number, number][], + ); - const dp = Array - .from({ length: m + 1 }, () => new Array(n + 1)); + const dp = Array.from({ length: m + 1 }, () => new Array(n + 1)); for (let i = 0; i < data.length; i++) { const [zeroes, ones] = data[i]; @@ -29,4 +31,4 @@ function findMaxForm(strs: string[], m: number, n: number): number { } return dp[m][n]; -}; +} diff --git a/typescript/0494-target-sum.ts b/typescript/0494-target-sum.ts index 7ce6bab2f..784d7c448 100644 --- a/typescript/0494-target-sum.ts +++ b/typescript/0494-target-sum.ts @@ -21,7 +21,7 @@ function findTargetSumWays(nums: number[], target: number): number { // DP: we memoize number of ways of each pair index, sum cache.set( `${i},${sum}`, - backTrack(i + 1, sum + nums[i]) + backTrack(i + 1, sum - nums[i]) + backTrack(i + 1, sum + nums[i]) + backTrack(i + 1, sum - nums[i]), ); return cache.get(`${i},${sum}`); @@ -30,7 +30,6 @@ function findTargetSumWays(nums: number[], target: number): number { return backTrack(0, 0); } - /** * DP - Bottom Up * Time O(N * M) | Space O(M) @@ -59,4 +58,4 @@ function findTargetSumWays(nums: number[], target: number): number { } return dp[total + target] ?? 0; -}; +} diff --git a/typescript/0502-ipo.ts b/typescript/0502-ipo.ts index 35c2f3ed2..e7bb0fc6d 100644 --- a/typescript/0502-ipo.ts +++ b/typescript/0502-ipo.ts @@ -1,4 +1,9 @@ -function findMaximizedCapital(k: number, w: number, profits: number[], capital: number[]): number { +function findMaximizedCapital( + k: number, + w: number, + profits: number[], + capital: number[], +): number { const minCapital = new PriorityQueue({ compare: (a, b) => a[1] - b[1] }); const maxProfit = new MaxPriorityQueue(); for (let i = 0; i < profits.length; i++) { @@ -18,4 +23,4 @@ function findMaximizedCapital(k: number, w: number, profits: number[], capital: } return profit; -}; +} diff --git a/typescript/0669-trim-a-binary-search-tree.ts b/typescript/0669-trim-a-binary-search-tree.ts index 30ef4f224..f136a9fe2 100644 --- a/typescript/0669-trim-a-binary-search-tree.ts +++ b/typescript/0669-trim-a-binary-search-tree.ts @@ -1,33 +1,36 @@ -/** - * Definition for a binary tree node. - * class TreeNode { - * val: number - * left: TreeNode | null - * right: TreeNode | null - * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { - * this.val = (val===undefined ? 0 : val) - * this.left = (left===undefined ? null : left) - * this.right = (right===undefined ? null : right) - * } - * } - */ - -function trimBST(root: TreeNode | null, low: number, high: number): TreeNode | null { - - if (!root) { - return null; - } - - if (root.val < low) { - return trimBST(root.right, low, high); - } - - if (root.val > high) { - return trimBST(root.left, low, high); - } - - root.left = trimBST(root.left, low, high); - root.right = trimBST(root.right, low, high); - - return root; -}; \ No newline at end of file +/** + * Definition for a binary tree node. + * class TreeNode { + * val: number + * left: TreeNode | null + * right: TreeNode | null + * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + * } + */ + +function trimBST( + root: TreeNode | null, + low: number, + high: number, +): TreeNode | null { + if (!root) { + return null; + } + + if (root.val < low) { + return trimBST(root.right, low, high); + } + + if (root.val > high) { + return trimBST(root.left, low, high); + } + + root.left = trimBST(root.left, low, high); + root.right = trimBST(root.right, low, high); + + return root; +} diff --git a/typescript/0703-kth-largest-element-in-a-stream.ts b/typescript/0703-kth-largest-element-in-a-stream.ts index a196e11ca..95964aed5 100644 --- a/typescript/0703-kth-largest-element-in-a-stream.ts +++ b/typescript/0703-kth-largest-element-in-a-stream.ts @@ -5,11 +5,11 @@ class KthLargest { constructor(k: number, nums: number[]) { this.backingArray = []; this.size = k; - for(const num of nums) this.add(num) + for (const num of nums) this.add(num); } add(val: number): number { - const newLength = this.backingArray.push(val) + const newLength = this.backingArray.push(val); this.shiftUp(newLength - 1); if (newLength > this.size) this.pop(); @@ -18,20 +18,30 @@ class KthLargest { } private pop() { - this.swap(0, this.backingArray.length - 1) + this.swap(0, this.backingArray.length - 1); this.backingArray.length -= 1; - this.shiftDown(0) + this.shiftDown(0); } private shiftDown(elementIndex: number) { let leftChildIndex = elementIndex * 2 + 1; let rightChildIndex = elementIndex * 2 + 2; - while ((leftChildIndex < this.backingArray.length && this.backingArray[leftChildIndex] < this.backingArray[elementIndex]) - || (rightChildIndex < this.backingArray.length && this.backingArray[rightChildIndex] < this.backingArray[elementIndex])) { + while ( + (leftChildIndex < this.backingArray.length && + this.backingArray[leftChildIndex] < + this.backingArray[elementIndex]) || + (rightChildIndex < this.backingArray.length && + this.backingArray[rightChildIndex] < + this.backingArray[elementIndex]) + ) { let smallestIndex = leftChildIndex; - if (rightChildIndex < this.backingArray.length && this.backingArray[rightChildIndex] < this.backingArray[smallestIndex]) { - smallestIndex = rightChildIndex + if ( + rightChildIndex < this.backingArray.length && + this.backingArray[rightChildIndex] < + this.backingArray[smallestIndex] + ) { + smallestIndex = rightChildIndex; } this.swap(elementIndex, smallestIndex); @@ -46,7 +56,9 @@ class KthLargest { if (elementIndex === 0) return; let parentIndex = Math.floor((elementIndex - 1) / 2); - while (this.backingArray[parentIndex] > this.backingArray[elementIndex]) { + while ( + this.backingArray[parentIndex] > this.backingArray[elementIndex] + ) { this.swap(elementIndex, parentIndex); elementIndex = parentIndex; parentIndex = Math.floor((elementIndex - 1) / 2); diff --git a/typescript/0705-design-hashset.ts b/typescript/0705-design-hashset.ts index b1f3816cc..788aac8d8 100644 --- a/typescript/0705-design-hashset.ts +++ b/typescript/0705-design-hashset.ts @@ -1,4 +1,5 @@ -class _ListNode { // ListNode has a confict +class _ListNode { + // ListNode has a confict key: number; next: _ListNode | undefined; @@ -18,10 +19,9 @@ class MyHashSet { add(key: number): void { let cur = this.set[key % this.set.length]; - + while (cur.next) { - if (cur.next.key === key) - return; + if (cur.next.key === key) return; cur = cur.next; } @@ -31,7 +31,7 @@ class MyHashSet { remove(key: number): void { let cur = this.set[key % this.set.length]; - + while (cur.next) { if (cur.next.key === key) { cur.next = cur.next.next; @@ -44,10 +44,9 @@ class MyHashSet { contains(key: number): boolean { let cur = this.set[key % this.set.length]; - + while (cur.next) { - if (cur.next.key === key) - return true; + if (cur.next.key === key) return true; cur = cur.next; } diff --git a/typescript/0743-network-delay-time.ts b/typescript/0743-network-delay-time.ts index 11817ea92..8adc7433e 100644 --- a/typescript/0743-network-delay-time.ts +++ b/typescript/0743-network-delay-time.ts @@ -1,5 +1,7 @@ function networkDelayTime(times: number[][], n: number, k: number): number { - const adjList = new Map(Array.from({ length: n + 1 }, (_, i) => [i, []])); + const adjList = new Map( + Array.from({ length: n + 1 }, (_, i) => [i, []]), + ); for (let [origin, destination, weight] of times) { adjList.get(origin).push([destination, weight]); } @@ -10,17 +12,18 @@ function networkDelayTime(times: number[][], n: number, k: number): number { } table[k] = 0; const heap = new MinPriorityQueue({ priority: (a) => a[1] }); - for (let [destination, weight] of (adjList.get(k) || [])) { + for (let [destination, weight] of adjList.get(k) || []) { heap.enqueue([destination, weight]); } while (!heap.isEmpty()) { const { element: minEdge } = heap.dequeue(); - if (table[minEdge[0]] !== -1 && minEdge[1] >= table[minEdge[0]]) continue; + if (table[minEdge[0]] !== -1 && minEdge[1] >= table[minEdge[0]]) + continue; table[minEdge[0]] = minEdge[1]; - for (let edge of (adjList.get(minEdge[0]) || [])) { + for (let edge of adjList.get(minEdge[0]) || []) { heap.enqueue([edge[0], minEdge[1] + edge[1]]); } } @@ -32,4 +35,4 @@ function networkDelayTime(times: number[][], n: number, k: number): number { } return max; -}; +} diff --git a/typescript/0778-swim-in-rising-water.ts b/typescript/0778-swim-in-rising-water.ts index 9f8cf29e0..95edf5ba7 100644 --- a/typescript/0778-swim-in-rising-water.ts +++ b/typescript/0778-swim-in-rising-water.ts @@ -3,11 +3,15 @@ function swimInWater(grid: number[][]): number { const n = grid[0].length; const heap = new MinPriorityQueue({ priority: (a) => a[0] }); - const visited = Array.from({ length: m }, () => Array.from({ length: n }, () => false)); + const visited = Array.from({ length: m }, () => + Array.from({ length: n }, () => false), + ); heap.enqueue([grid[0][0], 0, 0]); - + while (!heap.isEmpty()) { - const { element: [weight, r, c ] } = heap.dequeue(); + const { + element: [weight, r, c], + } = heap.dequeue(); if (r === m - 1 && c === n - 1) return weight; @@ -28,4 +32,4 @@ function swimInWater(grid: number[][]): number { } return 0; -}; +} diff --git a/typescript/0787-cheapest-flights-within-k-stops.ts b/typescript/0787-cheapest-flights-within-k-stops.ts index f86e7bec8..f798ec37c 100644 --- a/typescript/0787-cheapest-flights-within-k-stops.ts +++ b/typescript/0787-cheapest-flights-within-k-stops.ts @@ -3,7 +3,7 @@ function findCheapestPrice( flights: number[][], src: number, dst: number, - k: number + k: number, ): number { const adjacencyList = new Map(); diff --git a/typescript/0983-minimum-cost-for-tickets.ts b/typescript/0983-minimum-cost-for-tickets.ts index 74a97b993..b920bbca5 100644 --- a/typescript/0983-minimum-cost-for-tickets.ts +++ b/typescript/0983-minimum-cost-for-tickets.ts @@ -20,4 +20,4 @@ function mincostTickets(days: number[], costs: number[]): number { } return dp[0]; -}; +} diff --git a/typescript/1049-last-stone-weight-ii.ts b/typescript/1049-last-stone-weight-ii.ts index 006b45efa..b2ce04137 100644 --- a/typescript/1049-last-stone-weight-ii.ts +++ b/typescript/1049-last-stone-weight-ii.ts @@ -12,10 +12,7 @@ function lastStoneWeightII(stones: number[]): number { if (j >= target) { current[j] = Math.abs(j - (sum - j)); } else { - current[j] = Math.min( - dp[j], - dp[j + stones[i]], - ); + current[j] = Math.min(dp[j], dp[j + stones[i]]); } } @@ -23,4 +20,4 @@ function lastStoneWeightII(stones: number[]): number { } return dp[0]; -}; +} diff --git a/typescript/1209-remove-all-adjacent-duplicates-in-string-ii.ts b/typescript/1209-remove-all-adjacent-duplicates-in-string-ii.ts index 88cb24bb1..f63a0fd8d 100644 --- a/typescript/1209-remove-all-adjacent-duplicates-in-string-ii.ts +++ b/typescript/1209-remove-all-adjacent-duplicates-in-string-ii.ts @@ -15,6 +15,6 @@ function removeDuplicates(s: string, k: number): string { return stack.reduce( (acc, { char, count }) => (acc += char.repeat(count)), - '' + '', ); } diff --git a/typescript/1299-replace-elements-with-greatest-element-on-right-side.ts b/typescript/1299-replace-elements-with-greatest-element-on-right-side.ts index 6916a1834..702ed2e81 100644 --- a/typescript/1299-replace-elements-with-greatest-element-on-right-side.ts +++ b/typescript/1299-replace-elements-with-greatest-element-on-right-side.ts @@ -1,12 +1,12 @@ function replaceElements(arr: number[]): number[] { let currMax = -1; - - for(let i = arr.length -1 ; i >= 0; i--) { - let newMax = Math.max(currMax, arr[i]); + + for (let i = arr.length - 1; i >= 0; i--) { + let newMax = Math.max(currMax, arr[i]); arr[i] = currMax; - + currMax = newMax; } - + return arr; -}; +} diff --git a/typescript/1462-course-schedule-iv.ts b/typescript/1462-course-schedule-iv.ts index f6d3cf910..3f1136537 100644 --- a/typescript/1462-course-schedule-iv.ts +++ b/typescript/1462-course-schedule-iv.ts @@ -1,4 +1,8 @@ -function checkIfPrerequisite(numCourses: number, prerequisites: number[][], queries: number[][]): boolean[] { +function checkIfPrerequisite( + numCourses: number, + prerequisites: number[][], + queries: number[][], +): boolean[] { const adjList = new Map( Array.from({ length: numCourses }, (_, i) => [i, []]), ); @@ -28,4 +32,4 @@ function checkIfPrerequisite(numCourses: number, prerequisites: number[][], quer } return queries.map(([a, b]) => cache.get(b).has(a)); -}; +} diff --git a/typescript/1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.ts b/typescript/1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.ts index 657e0218a..b89e9154b 100644 --- a/typescript/1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.ts +++ b/typescript/1489-find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree.ts @@ -37,7 +37,11 @@ class UnionFind { } } -function findMST(n: number, edges: Edge[], heap: typeof MinPriorityQueue): { edges: Edge[], sum: number } { +function findMST( + n: number, + edges: Edge[], + heap: typeof MinPriorityQueue, +): { edges: Edge[]; sum: number } { const unionFind = new UnionFind(n); const resultingEdges = []; let sum = 0; @@ -67,15 +71,20 @@ function findMST(n: number, edges: Edge[], heap: typeof MinPriorityQueue): { edg } function buildHeap() { - return new MinPriorityQueue({ priority: edge => edge[2] }); + return new MinPriorityQueue({ priority: (edge) => edge[2] }); } -function findCriticalAndPseudoCriticalEdges(n: number, edges: Edge[]): number[][] { +function findCriticalAndPseudoCriticalEdges( + n: number, + edges: Edge[], +): number[][] { const generalMST = findMST(n, edges, buildHeap()); const criticalEdges = []; for (let edgeToExclude of generalMST.edges) { - const newEdges = edges.filter(edge => edge.join(',') !== edgeToExclude.join(',')); + const newEdges = edges.filter( + (edge) => edge.join(',') !== edgeToExclude.join(','), + ); const mst = findMST(n, newEdges, buildHeap()); if (mst.sum > generalMST.sum) { @@ -85,8 +94,11 @@ function findCriticalAndPseudoCriticalEdges(n: number, edges: Edge[]): number[][ const pseudoCriticalEdges = []; for (let edge of edges) { - if (criticalEdges.map(e => e.join(',')).includes(edge.join(','))) continue; - const newEdges = edges.filter(possibleEdge => possibleEdge.join(',') !== edge.join(',')); + if (criticalEdges.map((e) => e.join(',')).includes(edge.join(','))) + continue; + const newEdges = edges.filter( + (possibleEdge) => possibleEdge.join(',') !== edge.join(','), + ); const heap = buildHeap(); heap.enqueue(edge); @@ -98,7 +110,15 @@ function findCriticalAndPseudoCriticalEdges(n: number, edges: Edge[]): number[][ } return [ - criticalEdges.map(criticalEdge => edges.findIndex(edge => edge.join(',') === criticalEdge.join(','))), - pseudoCriticalEdges.map(pCriticalEdge => edges.findIndex(edge => edge.join(',') === pCriticalEdge.join(','))), + criticalEdges.map((criticalEdge) => + edges.findIndex( + (edge) => edge.join(',') === criticalEdge.join(','), + ), + ), + pseudoCriticalEdges.map((pCriticalEdge) => + edges.findIndex( + (edge) => edge.join(',') === pCriticalEdge.join(','), + ), + ), ]; -}; +} diff --git a/typescript/1514-path-with-maximum-probability.ts b/typescript/1514-path-with-maximum-probability.ts index 94b00afcc..01c5d9421 100644 --- a/typescript/1514-path-with-maximum-probability.ts +++ b/typescript/1514-path-with-maximum-probability.ts @@ -1,7 +1,11 @@ -function maxProbability(n: number, edges: number[][], succProb: number[], startNode: number, endNode: number): number { - const adjList = new Map( - Array.from({ length: n }, (_, i) => [i, []]) - ); +function maxProbability( + n: number, + edges: number[][], + succProb: number[], + startNode: number, + endNode: number, +): number { + const adjList = new Map(Array.from({ length: n }, (_, i) => [i, []])); for (let i = 0; i < edges.length; i++) { const [origin, target] = edges[i]; @@ -20,7 +24,7 @@ function maxProbability(n: number, edges: number[][], succProb: number[], startN } while (!heap.isEmpty()) { - const { element: maxEdge } = heap.dequeue(); + const { element: maxEdge } = heap.dequeue(); if (table[maxEdge[0]] >= maxEdge[1]) continue; table[maxEdge[0]] = maxEdge[1]; @@ -30,4 +34,4 @@ function maxProbability(n: number, edges: number[][], succProb: number[], startN } return table[endNode]; -}; +} diff --git a/typescript/1584-min-cost-to-connect-all-points.ts b/typescript/1584-min-cost-to-connect-all-points.ts index a21dd0848..619fc39d5 100644 --- a/typescript/1584-min-cost-to-connect-all-points.ts +++ b/typescript/1584-min-cost-to-connect-all-points.ts @@ -10,7 +10,7 @@ function minCostConnectPoints(points: number[][]): number { visited.add(points[0].join(',')); for (let point of points) { if (visited.has(point.join(','))) continue; - + minHeap.enqueue([points[0], point, getDistance(points[0], point)]); } @@ -24,9 +24,13 @@ function minCostConnectPoints(points: number[][]): number { for (let point of points) { if (visited.has(point.join(','))) continue; - minHeap.enqueue([minEdge[1], point, getDistance(minEdge[1], point)]); + minHeap.enqueue([ + minEdge[1], + point, + getDistance(minEdge[1], point), + ]); } } return result; -}; +} diff --git a/typescript/1838-frequency-of-the-most-frequent-element.ts b/typescript/1838-frequency-of-the-most-frequent-element.ts index 61d74f35a..50fc4785f 100644 --- a/typescript/1838-frequency-of-the-most-frequent-element.ts +++ b/typescript/1838-frequency-of-the-most-frequent-element.ts @@ -5,7 +5,11 @@ function maxFrequency(nums: number[], k: number): number { let currentSum: number = 0; let leftWindow: number = 0; - for (let rightWindow: number = 0; rightWindow < sortedNums.length; rightWindow++) { + for ( + let rightWindow: number = 0; + rightWindow < sortedNums.length; + rightWindow++ + ) { const currentLength: number = rightWindow - leftWindow + 1; const rightNum: number = sortedNums[rightWindow]; currentSum += rightNum; @@ -19,4 +23,4 @@ function maxFrequency(nums: number[], k: number): number { } } return maxLength; -}; \ No newline at end of file +} diff --git a/typescript/1929-concatenation-of-array.ts b/typescript/1929-concatenation-of-array.ts index 19350bb6c..d049c2483 100644 --- a/typescript/1929-concatenation-of-array.ts +++ b/typescript/1929-concatenation-of-array.ts @@ -1,9 +1,9 @@ function getConcatenation(nums: number[]): number[] { - let result: number[] = []; + let result: number[] = []; - for(let i = 0; i < 2; i++) { - nums.forEach(num => result.push(num)); - }; + for (let i = 0; i < 2; i++) { + nums.forEach((num) => result.push(num)); + } - return result; -}; + return result; +} diff --git a/typescript/2002-maximum-product-of-the-length-of-two-palindromic-subsequences.ts b/typescript/2002-maximum-product-of-the-length-of-two-palindromic-subsequences.ts index 9fb2b6e41..863ab9a3a 100644 --- a/typescript/2002-maximum-product-of-the-length-of-two-palindromic-subsequences.ts +++ b/typescript/2002-maximum-product-of-the-length-of-two-palindromic-subsequences.ts @@ -20,12 +20,14 @@ function maxProduct(s: string): number { if ((m & (m - 1)) === 0) { return m != 0; } - const l = last[m], f = first[m]; - const lb = 1 << l, fb = 1 << f; + const l = last[m], + f = first[m]; + const lb = 1 << l, + fb = 1 << f; return Math.max( dp(m - lb), dp(m - fb), - dp(m - lb - fb) + Number(s[l] === s[f]) * 2 + dp(m - lb - fb) + Number(s[l] === s[f]) * 2, ); }); let ans = 0; @@ -33,15 +35,15 @@ function maxProduct(s: string): number { ans = Math.max(ans, dp(m) * dp((1 << N) - 1 - m)); } return ans; -}; +} -function cache(func:Function){ +function cache(func: Function) { const map = new Map(); - var wrapper = (m:number) => { + var wrapper = (m: number) => { if (!map.get(m)) { map.set(m, func(m)); } return map.get(m); }; return wrapper; -}; +} diff --git a/typescript/2215-find-the-difference-of-two-arrays.ts b/typescript/2215-find-the-difference-of-two-arrays.ts index e7d331a4d..c6bd0e048 100644 --- a/typescript/2215-find-the-difference-of-two-arrays.ts +++ b/typescript/2215-find-the-difference-of-two-arrays.ts @@ -6,10 +6,10 @@ function findDifference(nums1: number[], nums2: number[]): number[][] { const nums2Set: Set = new Set(nums2); const lst1: number[] = Array.from(nums1Set).filter( - (num: number) => !nums2Set.has(num) + (num: number) => !nums2Set.has(num), ); const lst2: number[] = Array.from(nums2Set).filter( - (num: number) => !nums1Set.has(num) + (num: number) => !nums1Set.has(num), ); return [lst1, lst2]; diff --git a/typescript/2390-removing-stars-from-a-string.ts b/typescript/2390-removing-stars-from-a-string.ts index 9b5cf7edf..862940ca5 100644 --- a/typescript/2390-removing-stars-from-a-string.ts +++ b/typescript/2390-removing-stars-from-a-string.ts @@ -1,14 +1,14 @@ function removeStars(s: string): string { - if(!s.length) return ''; + if (!s.length) return ''; const result = []; - for(let char of s){ - if(char == '*') result.pop() - else result.push(char) + for (let char of s) { + if (char == '*') result.pop(); + else result.push(char); } - return result.join('') -}; + return result.join(''); +} // Time Complexity: O(n) // Space Complexity: O(n) diff --git a/typescript/2421-number-of-good-paths.ts b/typescript/2421-number-of-good-paths.ts index 15d381581..fdbced80c 100644 --- a/typescript/2421-number-of-good-paths.ts +++ b/typescript/2421-number-of-good-paths.ts @@ -63,7 +63,6 @@ function getValToIndex(vals: number[]): Map { return valToIndex; } - function numberOfGoodPaths(vals: number[], edges: number[][]): number { let adj = getAdjList(edges); let valToIndex = getValToIndex(vals); diff --git a/typescript/2469-convert-the-temperature.ts b/typescript/2469-convert-the-temperature.ts index 59d54b405..4f5902529 100644 --- a/typescript/2469-convert-the-temperature.ts +++ b/typescript/2469-convert-the-temperature.ts @@ -1,5 +1,5 @@ function convertTemperature(celsius: number): number[] { const kelvin = celsius + 273.15; - const fahrenheit = celsius * 1.80 + 32.00; + const fahrenheit = celsius * 1.8 + 32.0; return [kelvin, fahrenheit]; -}; +} diff --git a/typescript/2620-counter.ts b/typescript/2620-counter.ts index 898864eac..c3b85034e 100644 --- a/typescript/2620-counter.ts +++ b/typescript/2620-counter.ts @@ -1,11 +1,10 @@ function createCounter(n: number): () => number { - return function() { - return n++; - } + return function () { + return n++; + }; } - -/** +/** * const counter = createCounter(10) * counter() // 10 * counter() // 11 diff --git a/typescript/2667-create-hello-world-function.ts b/typescript/2667-create-hello-world-function.ts index 01320e958..ea6c206e9 100644 --- a/typescript/2667-create-hello-world-function.ts +++ b/typescript/2667-create-hello-world-function.ts @@ -1,8 +1,8 @@ function createHelloWorld() { - return function(...args): string { - return "Hello World"; + return function (...args): string { + return 'Hello World'; }; -}; +} /** * const f = createHelloWorld(); diff --git a/updateCompletionTable.js b/updateCompletionTable.js index 83b1a537e..e3da204a3 100644 --- a/updateCompletionTable.js +++ b/updateCompletionTable.js @@ -23,18 +23,24 @@ const PREPEND_PATH = process.argv[2] || './'; const TEMPLATE_PATH = process.argv[3] || './README_template.md'; const WRITE_PATH = process.argv[3] || './README.md'; -const PROBLEM_SITE_DATA = JSON.parse(fs.readFileSync('./.problemSiteData.json', 'utf8')); +const PROBLEM_SITE_DATA = JSON.parse( + fs.readFileSync('./.problemSiteData.json', 'utf8'), +); function createProblemsObj(PROBLEM_SITE_DATA) { - let PROBLEMS_OBJ = {} - for (const {problem, pattern, link, code} of PROBLEM_SITE_DATA) { - if (!(pattern in PROBLEMS_OBJ)) PROBLEMS_OBJ[pattern] = [] - PROBLEMS_OBJ[pattern].push([problem, "https://leetcode.com/problems/" + link, code.slice(0, 4)]) - } - return PROBLEMS_OBJ + let PROBLEMS_OBJ = {}; + for (const { problem, pattern, link, code } of PROBLEM_SITE_DATA) { + if (!(pattern in PROBLEMS_OBJ)) PROBLEMS_OBJ[pattern] = []; + PROBLEMS_OBJ[pattern].push([ + problem, + 'https://leetcode.com/problems/' + link, + code.slice(0, 4), + ]); + } + return PROBLEMS_OBJ; } -const PROBLEMS_OBJ = createProblemsObj(PROBLEM_SITE_DATA) +const PROBLEMS_OBJ = createProblemsObj(PROBLEM_SITE_DATA); const getDirectories = (source) => readdirSync(source, { withFileTypes: true }) @@ -61,7 +67,7 @@ function nestedFiles(dir) { } const directories = getDirectories(PREPEND_PATH).filter( - (dir) => !IGNORE_DIRS.includes(dir) + (dir) => !IGNORE_DIRS.includes(dir), ); const nestedFilesInDir = directories.reduce((acc, dir) => { acc[dir] = nestedFiles(dir); @@ -96,15 +102,13 @@ for (const problemCategory in PROBLEMS_OBJ) { ]; for (const dir of directories) { let filePath = nestedFilesInDir[dir].find((file) => - file - .match(/[\w-]+\..+/)?.[0] - ?.startsWith(problemNumber) + file.match(/[\w-]+\..+/)?.[0]?.startsWith(problemNumber), ); if (filePath) { problemRow.push( `
[✔️](${encodeURIComponent( - filePath - )})
` + filePath, + )})`, ); } else { problemRow.push("
"); diff --git a/updateSiteData.js b/updateSiteData.js index 78691d31c..dd8757948 100644 --- a/updateSiteData.js +++ b/updateSiteData.js @@ -2,80 +2,82 @@ const fs = require('fs'); -const PROBLEMS_SITE_DATA = JSON.parse(fs.readFileSync('./.problemSiteData.json', 'utf8')); +const PROBLEMS_SITE_DATA = JSON.parse( + fs.readFileSync('./.problemSiteData.json', 'utf8'), +); const languages = [ { name: 'C', directory: 'c', - extension: 'c' + extension: 'c', }, { name: 'C++', directory: 'cpp', - extension: 'cpp' + extension: 'cpp', }, { name: 'C#', directory: 'csharp', - extension: 'cs' + extension: 'cs', }, { name: 'Java', directory: 'java', - extension: 'java' + extension: 'java', }, - { + { name: 'Python', directory: 'python', - extension: 'py' + extension: 'py', }, { name: 'JavaScript', directory: 'javascript', - extension: 'js' + extension: 'js', }, { name: 'TypeScript', directory: 'typescript', - extension: 'ts' + extension: 'ts', }, { name: 'Go', directory: 'go', - extension: 'go' + extension: 'go', }, { name: 'Ruby', directory: 'ruby', - extension: 'rb' + extension: 'rb', }, { name: 'Swift', directory: 'swift', - extension: 'swift' + extension: 'swift', }, { name: 'Kotlin', directory: 'kotlin', - extension: 'kt' + extension: 'kt', }, { name: 'Rust', directory: 'rust', - extension: 'rs' + extension: 'rs', }, { name: 'Scala', directory: 'scala', - extension: 'scala' + extension: 'scala', }, { name: 'Dart', directory: 'dart', - extension: 'dart' + extension: 'dart', }, -] +]; // Rename files to match leetcode url path, and normalize problem number to four digits. for (const lang of languages) { @@ -92,8 +94,10 @@ for (const lang of languages) { // Use problem number to find code file const problemNumber = problem['code'].split('-')[0]; - const foundFile = files.find(file => file.name.startsWith(`${problemNumber.toString()}-`)); - + const foundFile = files.find((file) => + file.name.startsWith(`${problemNumber.toString()}-`), + ); + if (foundFile && foundFile.isFile()) { // rename file to match leetcode url path const oldFile = `${langDir}/${foundFile.name}`; @@ -105,11 +109,17 @@ for (const lang of languages) { problem[langDir] = true; // add language to problemSiteData } } - console.log(`Renamed ${counter} files in ${langDir}, which had ${files.length} total files.`); + console.log( + `Renamed ${counter} files in ${langDir}, which had ${files.length} total files.`, + ); } // Write updated problemSiteData to file -fs.writeFile('./.problemSiteData.json', JSON.stringify(PROBLEMS_SITE_DATA), function (err) { - if (err) throw err; - console.log('Saved!'); -}); +fs.writeFile( + './.problemSiteData.json', + JSON.stringify(PROBLEMS_SITE_DATA), + function (err) { + if (err) throw err; + console.log('Saved!'); + }, +); diff --git a/verifySiteData.js b/verifySiteData.js index f360d2332..5178e49d3 100644 --- a/verifySiteData.js +++ b/verifySiteData.js @@ -3,78 +3,80 @@ const fs = require('fs'); const https = require('/opt/homebrew/lib/node_modules/sync-request'); -const PROBLEMS_SITE_DATA = JSON.parse(fs.readFileSync('./.problemSiteData.json', 'utf8')); +const PROBLEMS_SITE_DATA = JSON.parse( + fs.readFileSync('./.problemSiteData.json', 'utf8'), +); const languageMap = { c: { name: 'C', directory: 'c', - extension: 'c' + extension: 'c', }, cpp: { name: 'C++', directory: 'cpp', - extension: 'cpp' + extension: 'cpp', }, csharp: { name: 'C#', directory: 'csharp', - extension: 'cs' + extension: 'cs', }, java: { name: 'Java', directory: 'java', - extension: 'java' + extension: 'java', }, - python: { + python: { name: 'Python', directory: 'python', - extension: 'py' + extension: 'py', }, javascript: { name: 'JavaScript', directory: 'javascript', - extension: 'js' + extension: 'js', }, typescript: { name: 'TypeScript', directory: 'typescript', - extension: 'ts' + extension: 'ts', }, go: { name: 'Go', directory: 'go', - extension: 'go' + extension: 'go', }, ruby: { name: 'Ruby', directory: 'ruby', - extension: 'rb' + extension: 'rb', }, swift: { name: 'Swift', directory: 'swift', - extension: 'swift' + extension: 'swift', }, kotlin: { name: 'Kotlin', directory: 'kotlin', - extension: 'kt' + extension: 'kt', }, rust: { name: 'Rust', directory: 'rust', - extension: 'rs' + extension: 'rs', }, scala: { name: 'Scala', directory: 'scala', - extension: 'scala' + extension: 'scala', }, dart: { name: 'Dart', directory: 'dart', - extension: 'dart' + extension: 'dart', }, }; @@ -89,8 +91,8 @@ for (const problem of PROBLEMS_SITE_DATA) { const res = https('GET', codeUrl).statusCode; if (res !== 200) { - console.log(codeUrl) - console.log(res) + console.log(codeUrl); + console.log(res); } } } From c5f75c4909345a16f2e1c97e951401ecd5ee8d5b Mon Sep 17 00:00:00 2001 From: Manideep Date: Thu, 3 Jul 2025 17:23:09 +0100 Subject: [PATCH 3/3] feat: Update JavaScript and TypeScript solutions --- javascript/0682-baseball-game.js | 10 +- javascript/1046-last-stone-weight.js | 20 ++- javascript/1143-longest-common-subsequence.js | 167 ++++++------------ ...nts-with-greatest-element-on-right-side.js | 40 ++--- .../1448-count-good-nodes-in-binary-tree.js | 118 ++++++------- .../1584-min-cost-to-connect-all-points.js | 36 ++-- ...-between-highest-and-lowest-of-k-scores.js | 7 +- javascript/2013-detect-squares.js | 51 +++--- ...ve-all-adjacent-duplicates-in-string-ii.ts | 2 +- ...nts-with-greatest-element-on-right-side.ts | 12 +- 10 files changed, 207 insertions(+), 256 deletions(-) diff --git a/javascript/0682-baseball-game.js b/javascript/0682-baseball-game.js index 9a93ac183..7df3428fb 100644 --- a/javascript/0682-baseball-game.js +++ b/javascript/0682-baseball-game.js @@ -2,21 +2,21 @@ * @param {string[]} operations * @return {number} */ -var calPoints = function (operations) { +var calPoints = function(operations) { let runningSum = 0; const stack = []; - for (const o of operations) { - if (o === 'C') { + for(const o of operations) { + if(o === 'C') { runningSum -= stack.pop(); continue; } - if (o === 'D') { + if(o === 'D') { const val = stack[stack.length - 1] * 2; stack.push(val); runningSum += val; continue; } - if (o === '+') { + if(o === '+') { const val = stack[stack.length - 1] + stack[stack.length - 2]; stack.push(val); runningSum += val; diff --git a/javascript/1046-last-stone-weight.js b/javascript/1046-last-stone-weight.js index 380580d93..d19a8999e 100644 --- a/javascript/1046-last-stone-weight.js +++ b/javascript/1046-last-stone-weight.js @@ -5,27 +5,29 @@ * @return {number} */ var lastStoneWeight = function (stones) { - const maxHeap = getMaxHeap(stones); + const maxHeap = getMaxHeap(stones) - shrink(maxHeap); + shrink(maxHeap) - return !maxHeap.isEmpty() ? maxHeap.front().element : 0; + return !maxHeap.isEmpty() + ? maxHeap.front().element + : 0 }; const getMaxHeap = (stones, maxHeap = new MaxPriorityQueue()) => { for (const stone of stones) { - maxHeap.enqueue(stone); + maxHeap.enqueue(stone) } - return maxHeap; -}; + return maxHeap +} const shrink = (maxHeap) => { while (1 < maxHeap.size()) { - const [x, y] = [maxHeap.dequeue().element, maxHeap.dequeue().element]; + const [ x, y ] = [ maxHeap.dequeue().element, maxHeap.dequeue().element ] const difference = x - y; - const isPositive = 0 < difference; + const isPositive = 0 < difference if (isPositive) maxHeap.enqueue(difference); } -}; +} \ No newline at end of file diff --git a/javascript/1143-longest-common-subsequence.js b/javascript/1143-longest-common-subsequence.js index 32d661c4c..66ce896f3 100644 --- a/javascript/1143-longest-common-subsequence.js +++ b/javascript/1143-longest-common-subsequence.js @@ -7,55 +7,32 @@ * @param {string} text2 * @return {number} */ -var longestCommonSubsequence = ( - text1, - text2, - p1 = 0, - p2 = 0, - memo = initMemo(text1, text2), -) => { - const isBaseCase = p1 === text1.length || p2 === text2.length; + var longestCommonSubsequence = (text1, text2, p1 = 0, p2 = 0, memo = initMemo(text1, text2)) => { + const isBaseCase = ((p1 === text1.length) || (p2 === text2.length)); if (isBaseCase) return 0; - const hasSeen = memo[p1][p2] !== null; + const hasSeen = (memo[p1][p2] !== null); if (hasSeen) return memo[p1][p2]; - return dfs( - text1, - text2, - p1, - p2, - memo, - ); /* Time O((N * M) * M)) | Space O((N * M) + HEIGHT) */ -}; + return dfs(text1, text2, p1, p2, memo);/* Time O((N * M) * M)) | Space O((N * M) + HEIGHT) */ +} -var initMemo = (text1, text2) => - new Array(text1.length + 1) - .fill() /* Time O(N) | Space O(N) */ - .map(() => - new Array(text2.length + 1).fill(null), - ); /* Time O(M) | Space O(M) */ +var initMemo = (text1, text2) => new Array((text1.length + 1)).fill()/* Time O(N) | Space O(N) */ + .map(() => new Array((text2.length + 1)).fill(null)); /* Time O(M) | Space O(M) */ var dfs = (text1, text2, p1, p2, memo) => { - const left = longestCommonSubsequence( - text1, - text2, - p1 + 1, - p2, - memo, - ); /* Time O(N * M) | Space O(HEIGHT) */ + const left = longestCommonSubsequence(text1, text2, (p1 + 1), p2, memo); /* Time O(N * M) | Space O(HEIGHT) */ - const index = text2.indexOf(text1[p1], p2); /* Time O(M) */ - const isPrefix = index !== -1; + const index = text2.indexOf(text1[p1], p2); /* Time O(M) */ + const isPrefix = (index !== -1); const right = isPrefix - ? longestCommonSubsequence(text1, text2, p1 + 1, index + 1, memo) + - 1 /* Time O(N * M) | Space O(HEIGHT) */ + ? (longestCommonSubsequence(text1, text2, (p1 + 1), (index + 1), memo) + 1)/* Time O(N * M) | Space O(HEIGHT) */ : 0; - memo[p1][p2] = Math.max(left, right); /* | Space O(N * M) */ + memo[p1][p2] = Math.max(left, right); /* | Space O(N * M) */ return memo[p1][p2]; -}; +} /** * DP - Top Down @@ -66,52 +43,32 @@ var dfs = (text1, text2, p1, p2, memo) => { * @param {string} text2 * @return {number} */ -var longestCommonSubsequence = ( - text1, - text2, - p1 = 0, - p2 = 0, - memo = initMemo(text1, text2), -) => { - const isBaseCase = p1 === text1.length || p2 === text2.length; +var longestCommonSubsequence = (text1, text2, p1 = 0, p2 = 0, memo = initMemo(text1, text2)) => { + const isBaseCase = ((p1 === text1.length) || (p2 === text2.length)); if (isBaseCase) return 0; - const hasSeen = memo[p1][p2] !== null; + const hasSeen = (memo[p1][p2] !== null); if (hasSeen) return memo[p1][p2]; - return dfs( - text1, - text2, - p1, - p2, - memo, - ); /* Time O(N * M) | Space O((N * M) + HEIGHT) */ -}; + return dfs(text1, text2, p1, p2, memo);/* Time O(N * M) | Space O((N * M) + HEIGHT) */ +} -var initMemo = (text1, text2) => - new Array(text1.length + 1) - .fill() /* Time O(N) | Space O(N) */ - .map(() => - new Array(text2.length + 1).fill(null), - ); /* Time O(M) | Space O(M) */ +var initMemo = (text1, text2) => new Array((text1.length + 1)).fill()/* Time O(N) | Space O(N) */ + .map(() => new Array((text2.length + 1)).fill(null)); /* Time O(M) | Space O(M) */ var dfs = (text1, text2, p1, p2, memo) => { - const left = - longestCommonSubsequence(text1, text2, p1 + 1, p2 + 1, memo) + - 1; /* Time O(N * M) | Space O(HEIGHT) */ - const right = - /* Time O(N * M) | Space O(HEIGHT) */ - Math.max( - longestCommonSubsequence(text1, text2, p1, p2 + 1, memo), - longestCommonSubsequence(text1, text2, p1 + 1, p2, memo), - ); - - const isEqual = text1[p1] == text2[p2]; - const count = isEqual ? left : right; - - memo[p1][p2] = count; /* | Space O(N * M) */ + const left = (longestCommonSubsequence(text1, text2, (p1 + 1), (p2 + 1), memo) + 1);/* Time O(N * M) | Space O(HEIGHT) */ + const right = /* Time O(N * M) | Space O(HEIGHT) */ + Math.max(longestCommonSubsequence(text1, text2, p1, (p2 + 1), memo), longestCommonSubsequence(text1, text2, (p1 + 1), p2, memo)); + + const isEqual = (text1[p1] == text2[p2]); + const count = isEqual + ? left + : right + + memo[p1][p2] = count; /* | Space O(N * M) */ return memo[p1][p2]; -}; +} /** * DP - Bottom Up @@ -123,34 +80,28 @@ var dfs = (text1, text2, p1, p2, memo) => { * @return {number} */ var longestCommonSubsequence = (text1, text2) => { - const tabu = initTabu(text1, text2); /* Time O(N * M) | Space O(N * M) */ + const tabu = initTabu(text1, text2);/* Time O(N * M) | Space O(N * M) */ - search(text1, text2, tabu); /* Time O(N * M) | Space O(N * M) */ + search(text1, text2, tabu); /* Time O(N * M) | Space O(N * M) */ return tabu[0][0]; }; -var initTabu = (text1, text2) => - new Array(text1.length + 1) - .fill() /* Time O(N) | Space O(N) */ - .map(() => - new Array(text2.length + 1).fill(0), - ); /* Time O(M) | Space O(M) */ +var initTabu = (text1, text2) => + new Array((text1.length + 1)).fill() /* Time O(N) | Space O(N) */ + .map(() => new Array((text2.length + 1)).fill(0));/* Time O(M) | Space O(M) */ var search = (text1, text2, tabu) => { - const [n, m] = [text1.length, text2.length]; - - for (let x = n - 1; 0 <= x; x--) { - /* Time O(N) */ - for (let y = m - 1; 0 <= y; y--) { - /* Time O(M) */ - tabu[x][y] = - text1[x] === text2[y] /* Space O(N * M) */ - ? tabu[x + 1][y + 1] + 1 - : Math.max(tabu[x + 1][y], tabu[x][y + 1]); + const [ n, m ] = [ text1.length, text2.length ]; + + for (let x = (n - 1); (0 <= x); x--) {/* Time O(N) */ + for (let y = (m - 1); (0 <= y); y--) {/* Time O(M) */ + tabu[x][y] = (text1[x] === text2[y]) /* Space O(N * M) */ + ? (tabu[x + 1][y + 1] + 1) + : Math.max(tabu[x + 1][y], tabu[x][y + 1]); } } -}; +} /** * DP - Bottom Up @@ -162,34 +113,32 @@ var search = (text1, text2, tabu) => { * @return {number} */ var longestCommonSubsequence = (text1, text2) => { - const canSwap = text2.length < text1.length; - if (canSwap) [text1, text2] = [text2, text1]; + const canSwap = (text2.length < text1.length); + if (canSwap) [ text1, text2 ] = [ text2, text1 ]; - let tabu = initTabu(text1); /* Time O(M) | Space O(M) */ + let tabu = initTabu(text1); /* Time O(M) | Space O(M) */ - tabu = search(text1, text2, tabu); /* Time O(N * M) | Space O(M) */ + tabu = search(text1, text2, tabu);/* Time O(N * M) | Space O(M) */ return tabu[0]; }; -var initTabu = (text1) => new Array(text1.length + 1).fill(0); +var initTabu = (text1) => new Array((text1.length + 1)).fill(0) var search = (text1, text2, tabu) => { - for (let col = text2.length - 1; 0 <= col; col--) { - /* Time O(N) */ - const temp = initTabu(text1); /* Space O(M) */ + for (let col = (text2.length - 1); (0 <= col); col--) {/* Time O(N) */ + const temp = initTabu(text1); /* Space O(M) */ - for (let row = text1.length - 1; 0 <= row; row--) { - /* Time O(M) */ - const isEqual = text1[row] == text2[col]; + for (let row = (text1.length - 1); (0 <= row); row--) {/* Time O(M) */ + const isEqual = (text1[row] == text2[col]); - temp[row] = isEqual /* Space O(M) */ - ? tabu[row + 1] + 1 - : Math.max(tabu[row], temp[row + 1]); + temp[row] = isEqual /* Space O(M) */ + ? (tabu[(row + 1)] + 1) + : Math.max(tabu[row], temp[(row + 1)]); } - tabu = temp; /* Space O(M) */ + tabu = temp; /* Space O(M) */ } return tabu; -}; +} diff --git a/javascript/1299-replace-elements-with-greatest-element-on-right-side.js b/javascript/1299-replace-elements-with-greatest-element-on-right-side.js index 7d282c268..f2283a7e4 100644 --- a/javascript/1299-replace-elements-with-greatest-element-on-right-side.js +++ b/javascript/1299-replace-elements-with-greatest-element-on-right-side.js @@ -5,16 +5,15 @@ * @param {number[]} arr * @return {number[]} */ -var replaceElements = (arr, max = -1, ans = [-1]) => { - arr = arr.reverse(); /* Time O(N) */ - - for (let i = 0; i < arr.length - 1; i++) { - /* Time O(N) */ +var replaceElements = (arr, max = -1, ans = [ -1 ]) => { + arr = arr.reverse(); /* Time O(N) */ + + for (let i = 0; (i < (arr.length - 1)); i++) {/* Time O(N) */ max = Math.max(max, arr[i]); - ans[i + 1] = max; /* Space O(N) */ + ans[(i + 1)] = max; /* Space O(N) */ } - - return ans.reverse(); /* Time O(N) */ + + return ans.reverse(); /* Time O(N) */ }; /** @@ -24,21 +23,21 @@ var replaceElements = (arr, max = -1, ans = [-1]) => { * @param {number[]} arr * @return {number[]} */ -var replaceElements = (arr, max = -1) => { - for (let i = arr.length - 1; 0 <= i; i--) { - /* Time O(N) */ - const num = arr[i]; +var replaceElements = (arr, max = -1) => { + for (let i = (arr.length - 1); (0 <= i); i--) {/* Time O(N) */ + const num = arr[i]; - arr[i] = max; - max = Math.max(max, num); - } + arr[i] = max; + max = Math.max(max, num); + } - return arr; + return arr; }; -// This is brute force with O(n^2). Just for reference's sake. +// This is brute force with O(n^2). Just for reference's sake. // submission link: https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/submissions/844439163/ -var replaceElementsBrute = function (arr) { - for (let i = 0; i < arr.length; i++) { +var replaceElementsBrute = function(arr) { + + for(let i = 0; i < arr.length; i++) { arr[i] = biggestElement(i, arr); } @@ -47,8 +46,9 @@ var replaceElementsBrute = function (arr) { }; function biggestElement(index, arr) { + let biggest = 0; - for (let i = index + 1; i < arr.length; i++) { + for(let i = index + 1; i < arr.length; i++) { biggest = Math.max(biggest, arr[i]); } diff --git a/javascript/1448-count-good-nodes-in-binary-tree.js b/javascript/1448-count-good-nodes-in-binary-tree.js index d28996622..21cfd6d56 100644 --- a/javascript/1448-count-good-nodes-in-binary-tree.js +++ b/javascript/1448-count-good-nodes-in-binary-tree.js @@ -1,59 +1,59 @@ -/** - * https://leetcode.com/problems/count-good-nodes-in-binary-tree/ - * Time O(N) | Space O(H) - * @param {TreeNode} root - * @return {number} - */ -var goodNodes = function (root, max = -Infinity, total = [0]) { - count(root, max, total); - - return total[0]; -}; - -const count = (root, max, total) => { - const isBaseCase = root === null; - if (isBaseCase) return 0; - - return dfs(root, max, total); -}; - -const dfs = (root, max, total) => { - const isGood = max <= root.val; - if (isGood) total[0]++; - - max = Math.max(max, root.val); - - count(root.left, max, total); - count(root.right, max, total); -}; - -/** - * https://leetcode.com/problems/count-good-nodes-in-binary-tree/ - * Time O(N) | Space O(W) - * @param {TreeNode} root - * @return {number} - */ -var goodNodes = function (root) { - const isBaseCase = root === null; - if (isBaseCase) return 0; - - return bfs([[root, -Infinity]]); -}; - -const bfs = (queue, total = 0) => { - while (queue.length) { - for (let i = queue.length - 1; 0 <= i; i--) { - let [root, max] = queue.shift(); - - const isGood = max <= root.val; - if (isGood) total++; - - max = Math.max(max, root.val); - - if (root.right) queue.push([root.right, max]); - if (root.left) queue.push([root.left, max]); - } - } - - return total; -}; +/** + * https://leetcode.com/problems/count-good-nodes-in-binary-tree/ + * Time O(N) | Space O(H) + * @param {TreeNode} root + * @return {number} + */ + var goodNodes = function(root, max = -Infinity, total = [ 0 ]) { + count(root, max, total); + + return total[0] +}; + +const count = (root, max, total) => { + const isBaseCase = root === null; + if (isBaseCase) return 0; + + return dfs(root, max, total); +} + +const dfs = (root, max, total) => { + const isGood = max <= root.val + if (isGood) total[0]++; + + max = Math.max(max, root.val); + + count(root.left, max, total); + count(root.right, max, total); +} + +/** + * https://leetcode.com/problems/count-good-nodes-in-binary-tree/ + * Time O(N) | Space O(W) + * @param {TreeNode} root + * @return {number} + */ +var goodNodes = function(root, ) { + const isBaseCase = root === null; + if (isBaseCase) return 0 + + return bfs([[ root, -Infinity ]]); +} + +const bfs = (queue, total = 0) => { + while (queue.length) { + for (let i = (queue.length - 1); 0 <= i; i--) { + let [ root, max ] = queue.shift(); + + const isGood = max <= root.val; + if (isGood) total++; + + max = Math.max(max, root.val); + + if (root.right) queue.push([ root.right, max ]); + if (root.left) queue.push([ root.left, max ]); + } + } + + return total; +} diff --git a/javascript/1584-min-cost-to-connect-all-points.js b/javascript/1584-min-cost-to-connect-all-points.js index bd2f3a4d3..b5d3a295a 100644 --- a/javascript/1584-min-cost-to-connect-all-points.js +++ b/javascript/1584-min-cost-to-connect-all-points.js @@ -5,7 +5,7 @@ * @return {number} */ const minCostConnectPoints = (points) => { - const isBaseCase = points.length === 0 || 1000 <= points.length; + const isBaseCase = ((points.length === 0) || (1000 <= points.length)); if (isBaseCase) return 0; const { graph, seen, minHeap } = buildGraph(points); @@ -16,38 +16,38 @@ const minCostConnectPoints = (points) => { const initGraph = (points) => ({ graph: new Array(points.length).fill().map(() => []), seen: new Array(points.length).fill(false), - minHeap: new MinPriorityQueue(), -}); + minHeap: new MinPriorityQueue() +}) const buildGraph = (points) => { const { graph, seen, minHeap } = initGraph(points); - for (let src = 0; src < points.length - 1; src++) { - for (let dst = src + 1; dst < points.length; dst++) { + for (let src = 0; src < (points.length - 1); src++) { + for (let dst = (src + 1); (dst < points.length); dst++) { const cost = getCost(points, src, dst); - graph[src].push([dst, cost]); - graph[dst].push([src, cost]); + graph[src].push([ dst, cost ]); + graph[dst].push([ src, cost ]); } } - const [src, cost, priority] = [0, 0, 0]; - const node = [src, cost]; + const [ src, cost, priority ] = [ 0, 0, 0 ]; + const node = [ src, cost ]; minHeap.enqueue(node, priority); return { graph, seen, minHeap }; -}; +} const getCost = (points, src, dst) => { - const [[x1, y1], [x2, y2]] = [points[src], points[dst]]; + const [ [ x1, y1 ], [ x2, y2 ] ] = [ points[src], points[dst] ]; - return Math.abs(x1 - x2) + Math.abs(y1 - y2); -}; + return (Math.abs(x1 - x2) + Math.abs(y1 - y2)); +} const search = (points, graph, seen, minHeap, nodeCount = 0, cost = 0) => { while (nodeCount < points.length) { - let [src, srcCost] = minHeap.dequeue().element; + let [ src, srcCost ] = minHeap.dequeue().element; if (seen[src]) continue; seen[src] = true; @@ -59,12 +59,12 @@ const search = (points, graph, seen, minHeap, nodeCount = 0, cost = 0) => { } return cost; -}; +} const checkNeighbors = (graph, src, seen, minHeap) => { - for (const [dst, dstCost] of graph[src]) { + for (const [ dst, dstCost ] of graph[src]) { if (seen[dst]) continue; - minHeap.enqueue([dst, dstCost], dstCost); + minHeap.enqueue([ dst, dstCost ], dstCost); } -}; +} \ No newline at end of file diff --git a/javascript/1984-minimum-difference-between-highest-and-lowest-of-k-scores.js b/javascript/1984-minimum-difference-between-highest-and-lowest-of-k-scores.js index 32df3884e..b50b93538 100644 --- a/javascript/1984-minimum-difference-between-highest-and-lowest-of-k-scores.js +++ b/javascript/1984-minimum-difference-between-highest-and-lowest-of-k-scores.js @@ -2,13 +2,14 @@ * Loglinear/N*log(N) * Time O(N*log(N)) | Space O(1) * https://leetcode.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores - * + * * @param {number[]} nums * @param {number} k * @return {number} */ -var minimumDifference = function (nums, k) { - const isEdgeCase = k === 1; +var minimumDifference = function(nums, k) { + + const isEdgeCase = (k === 1); if (isEdgeCase) return 0; nums = nums.sort((a, b) => { diff --git a/javascript/2013-detect-squares.js b/javascript/2013-detect-squares.js index b31646728..ed26ae11a 100644 --- a/javascript/2013-detect-squares.js +++ b/javascript/2013-detect-squares.js @@ -3,51 +3,50 @@ * https://leetcode.com/problems/detect-squares */ class DetectSquares { - constructor() { - this.map = {}; /* Space O(N) */ - this.points = []; /* Space O(N) */ + constructor () { + this.map = {}; /* Space O(N) */ + this.points = [];/* Space O(N) */ } - - add(point, { map, points } = this) { - const [x, y] = point; + + add (point, { map, points } = this) { + const [ x, y ] = point; const key = this.getKey(x, y); - const value = (map[key] || 0) + 1; + const value = ((map[key] || 0) + 1); - map[key] = value; /* Space O(N) */ - points.push(point); /* Space O(N) */ + map[key] = value; /* Space O(N) */ + points.push(point);/* Space O(N) */ } - count(point, { points } = this, score = 0) { - const [x1, y1] = point; + count (point, { points } = this, score = 0) { + const [ x1, y1 ] = point; - for (const [x2, y2] of points) { - /* Time O(N) */ - const isSame = Math.abs(x2 - x1) === Math.abs(y2 - y1); - const isEqual = x1 === x2 || y1 === y2; - const canSkip = !isSame || isEqual; + for (const [ x2, y2 ] of points) {/* Time O(N) */ + const isSame = (Math.abs(x2 - x1) === Math.abs(y2 - y1)); + const isEqual = ((x1 === x2) || (y1 === y2)); + const canSkip = (!isSame || isEqual); if (canSkip) continue; score += this.getScore(x1, y1, x2, y2); } return score; - } + }; - getKey(x, y) { + getKey (x, y) { return `${x},${y}`; } - getScore(x1, y1, x2, y2, { map } = this) { - const [aKey, bKey] = [this.getKey(x1, y2), this.getKey(x2, y1)]; - const [aScore, bScore] = [map[aKey] || 0, map[bKey] || 0]; - - return aScore * bScore; + getScore (x1, y1, x2, y2, { map } = this) { + const [ aKey, bKey ] = [ this.getKey(x1, y2), this.getKey(x2, y1) ]; + const [ aScore, bScore ] = [ (map[aKey] || 0), (map[bKey] || 0) ]; + + return (aScore * bScore); } -} +}; -/** +/** * Your DetectSquares object will be instantiated and called as such: * var obj = new DetectSquares() * obj.add(point) * var param_2 = obj.count(point) - */ + */ \ No newline at end of file diff --git a/typescript/1209-remove-all-adjacent-duplicates-in-string-ii.ts b/typescript/1209-remove-all-adjacent-duplicates-in-string-ii.ts index f63a0fd8d..88cb24bb1 100644 --- a/typescript/1209-remove-all-adjacent-duplicates-in-string-ii.ts +++ b/typescript/1209-remove-all-adjacent-duplicates-in-string-ii.ts @@ -15,6 +15,6 @@ function removeDuplicates(s: string, k: number): string { return stack.reduce( (acc, { char, count }) => (acc += char.repeat(count)), - '', + '' ); } diff --git a/typescript/1299-replace-elements-with-greatest-element-on-right-side.ts b/typescript/1299-replace-elements-with-greatest-element-on-right-side.ts index 702ed2e81..6916a1834 100644 --- a/typescript/1299-replace-elements-with-greatest-element-on-right-side.ts +++ b/typescript/1299-replace-elements-with-greatest-element-on-right-side.ts @@ -1,12 +1,12 @@ function replaceElements(arr: number[]): number[] { let currMax = -1; - - for (let i = arr.length - 1; i >= 0; i--) { - let newMax = Math.max(currMax, arr[i]); + + for(let i = arr.length -1 ; i >= 0; i--) { + let newMax = Math.max(currMax, arr[i]); arr[i] = currMax; - + currMax = newMax; } - + return arr; -} +};