interview-reps 0.0.0-stage → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +59 -2
- package/content/CLAUDE.md +131 -0
- package/content/LADDER.md +166 -0
- package/content/behavioral/QUESTIONS.md +93 -0
- package/content/behavioral/REVIEW.md +86 -0
- package/content/design/D01-short-links/README.md +20 -0
- package/content/design/D02-rate-limiter/README.md +21 -0
- package/content/design/D03-news-feed/README.md +20 -0
- package/content/design/D04-chat-messaging/README.md +20 -0
- package/content/design/D05-notification-service/README.md +20 -0
- package/content/design/D06-typeahead-search/README.md +20 -0
- package/content/design/D07-web-crawler/README.md +20 -0
- package/content/design/D08-file-sync/README.md +20 -0
- package/content/design/D09-ride-matching/README.md +20 -0
- package/content/design/D10-job-scheduler/README.md +20 -0
- package/content/design/D11-metrics-alerting/README.md +20 -0
- package/content/design/D12-payments-ledger/README.md +20 -0
- package/content/design/REVIEW.md +94 -0
- package/content/lib/binary-tree.ts +69 -0
- package/content/lib/graph.ts +50 -0
- package/content/lib/linked-list.ts +37 -0
- package/content/lib/perf.ts +9 -0
- package/content/problems/001-contains-duplicate/README.md +37 -0
- package/content/problems/001-contains-duplicate/solution.test.ts +38 -0
- package/content/problems/002-valid-anagram/README.md +36 -0
- package/content/problems/002-valid-anagram/solution.test.ts +38 -0
- package/content/problems/003-two-sum/README.md +40 -0
- package/content/problems/003-two-sum/solution.test.ts +40 -0
- package/content/problems/004-valid-palindrome/README.md +39 -0
- package/content/problems/004-valid-palindrome/solution.test.ts +38 -0
- package/content/problems/005-best-time-to-buy-and-sell-stock/README.md +38 -0
- package/content/problems/005-best-time-to-buy-and-sell-stock/solution.test.ts +39 -0
- package/content/problems/006-valid-parentheses/README.md +42 -0
- package/content/problems/006-valid-parentheses/solution.test.ts +41 -0
- package/content/problems/007-binary-search/README.md +39 -0
- package/content/problems/007-binary-search/solution.test.ts +56 -0
- package/content/problems/008-reverse-linked-list/README.md +39 -0
- package/content/problems/008-reverse-linked-list/solution.test.ts +41 -0
- package/content/problems/009-merge-two-sorted-lists/README.md +36 -0
- package/content/problems/009-merge-two-sorted-lists/solution.test.ts +43 -0
- package/content/problems/010-linked-list-cycle/README.md +37 -0
- package/content/problems/010-linked-list-cycle/solution.test.ts +39 -0
- package/content/problems/011-invert-binary-tree/README.md +39 -0
- package/content/problems/011-invert-binary-tree/solution.test.ts +32 -0
- package/content/problems/012-maximum-depth-of-binary-tree/README.md +37 -0
- package/content/problems/012-maximum-depth-of-binary-tree/solution.test.ts +29 -0
- package/content/problems/013-same-tree/README.md +37 -0
- package/content/problems/013-same-tree/solution.test.ts +38 -0
- package/content/problems/014-balanced-binary-tree/README.md +37 -0
- package/content/problems/014-balanced-binary-tree/solution.test.ts +38 -0
- package/content/problems/015-climbing-stairs/README.md +35 -0
- package/content/problems/015-climbing-stairs/solution.test.ts +27 -0
- package/content/problems/016-diameter-of-binary-tree/README.md +38 -0
- package/content/problems/016-diameter-of-binary-tree/solution.test.ts +63 -0
- package/content/problems/017-subtree-of-another-tree/README.md +42 -0
- package/content/problems/017-subtree-of-another-tree/solution.test.ts +61 -0
- package/content/problems/018-kth-largest-element-in-a-stream/README.md +49 -0
- package/content/problems/018-kth-largest-element-in-a-stream/solution.test.ts +104 -0
- package/content/problems/019-last-stone-weight/README.md +44 -0
- package/content/problems/019-last-stone-weight/solution.test.ts +67 -0
- package/content/problems/020-min-cost-climbing-stairs/README.md +40 -0
- package/content/problems/020-min-cost-climbing-stairs/solution.test.ts +44 -0
- package/content/problems/021-single-number/README.md +41 -0
- package/content/problems/021-single-number/solution.test.ts +46 -0
- package/content/problems/022-missing-number/README.md +40 -0
- package/content/problems/022-missing-number/solution.test.ts +44 -0
- package/content/problems/101-group-anagrams/README.md +41 -0
- package/content/problems/101-group-anagrams/solution.test.ts +83 -0
- package/content/problems/102-top-k-frequent-elements/README.md +44 -0
- package/content/problems/102-top-k-frequent-elements/solution.test.ts +59 -0
- package/content/problems/103-product-of-array-except-self/README.md +43 -0
- package/content/problems/103-product-of-array-except-self/solution.test.ts +59 -0
- package/content/problems/104-longest-consecutive-sequence/README.md +40 -0
- package/content/problems/104-longest-consecutive-sequence/solution.test.ts +62 -0
- package/content/problems/105-encode-and-decode-strings/README.md +47 -0
- package/content/problems/105-encode-and-decode-strings/solution.test.ts +50 -0
- package/content/problems/106-two-sum-ii-input-array-is-sorted/README.md +43 -0
- package/content/problems/106-two-sum-ii-input-array-is-sorted/solution.test.ts +47 -0
- package/content/problems/107-three-sum/README.md +42 -0
- package/content/problems/107-three-sum/solution.test.ts +79 -0
- package/content/problems/108-container-with-most-water/README.md +40 -0
- package/content/problems/108-container-with-most-water/solution.test.ts +53 -0
- package/content/problems/109-longest-substring-without-repeating-characters/README.md +40 -0
- package/content/problems/109-longest-substring-without-repeating-characters/solution.test.ts +56 -0
- package/content/problems/110-longest-repeating-character-replacement/README.md +41 -0
- package/content/problems/110-longest-repeating-character-replacement/solution.test.ts +51 -0
- package/content/problems/111-permutation-in-string/README.md +38 -0
- package/content/problems/111-permutation-in-string/solution.test.ts +54 -0
- package/content/problems/112-min-stack/README.md +51 -0
- package/content/problems/112-min-stack/solution.test.ts +123 -0
- package/content/problems/113-daily-temperatures/README.md +40 -0
- package/content/problems/113-daily-temperatures/solution.test.ts +56 -0
- package/content/problems/114-evaluate-reverse-polish-notation/README.md +44 -0
- package/content/problems/114-evaluate-reverse-polish-notation/solution.test.ts +56 -0
- package/content/problems/115-generate-parentheses/README.md +38 -0
- package/content/problems/115-generate-parentheses/solution.test.ts +59 -0
- package/content/problems/116-koko-eating-bananas/README.md +41 -0
- package/content/problems/116-koko-eating-bananas/solution.test.ts +53 -0
- package/content/problems/117-find-minimum-in-rotated-sorted-array/README.md +41 -0
- package/content/problems/117-find-minimum-in-rotated-sorted-array/solution.test.ts +69 -0
- package/content/problems/118-search-in-rotated-sorted-array/README.md +41 -0
- package/content/problems/118-search-in-rotated-sorted-array/solution.test.ts +95 -0
- package/content/problems/119-time-based-key-value-store/README.md +50 -0
- package/content/problems/119-time-based-key-value-store/solution.test.ts +107 -0
- package/content/problems/120-reorder-list/README.md +43 -0
- package/content/problems/120-reorder-list/solution.test.ts +83 -0
- package/content/problems/121-remove-nth-node-from-end-of-list/README.md +40 -0
- package/content/problems/121-remove-nth-node-from-end-of-list/solution.test.ts +55 -0
- package/content/problems/122-lru-cache/README.md +55 -0
- package/content/problems/122-lru-cache/solution.test.ts +152 -0
- package/content/problems/123-binary-tree-level-order-traversal/README.md +40 -0
- package/content/problems/123-binary-tree-level-order-traversal/solution.test.ts +42 -0
- package/content/problems/124-binary-tree-right-side-view/README.md +40 -0
- package/content/problems/124-binary-tree-right-side-view/solution.test.ts +56 -0
- package/content/problems/125-validate-binary-search-tree/README.md +46 -0
- package/content/problems/125-validate-binary-search-tree/solution.test.ts +78 -0
- package/content/problems/126-kth-smallest-element-in-a-bst/README.md +39 -0
- package/content/problems/126-kth-smallest-element-in-a-bst/solution.test.ts +61 -0
- package/content/problems/127-lowest-common-ancestor-of-a-bst/README.md +46 -0
- package/content/problems/127-lowest-common-ancestor-of-a-bst/solution.test.ts +106 -0
- package/content/problems/128-kth-largest-element-in-an-array/README.md +42 -0
- package/content/problems/128-kth-largest-element-in-an-array/solution.test.ts +67 -0
- package/content/problems/129-k-closest-points-to-origin/README.md +43 -0
- package/content/problems/129-k-closest-points-to-origin/solution.test.ts +74 -0
- package/content/problems/130-number-of-islands/README.md +44 -0
- package/content/problems/130-number-of-islands/solution.test.ts +69 -0
- package/content/problems/131-course-schedule/README.md +42 -0
- package/content/problems/131-course-schedule/solution.test.ts +82 -0
- package/content/problems/132-rotting-oranges/README.md +46 -0
- package/content/problems/132-rotting-oranges/solution.test.ts +74 -0
- package/content/problems/133-clone-graph/README.md +42 -0
- package/content/problems/133-clone-graph/solution.test.ts +58 -0
- package/content/problems/134-house-robber/README.md +38 -0
- package/content/problems/134-house-robber/solution.test.ts +45 -0
- package/content/problems/135-coin-change/README.md +40 -0
- package/content/problems/135-coin-change/solution.test.ts +45 -0
- package/content/problems/136-longest-increasing-subsequence/README.md +41 -0
- package/content/problems/136-longest-increasing-subsequence/solution.test.ts +53 -0
- package/content/problems/137-word-break/README.md +39 -0
- package/content/problems/137-word-break/solution.test.ts +49 -0
- package/content/problems/138-merge-intervals/README.md +40 -0
- package/content/problems/138-merge-intervals/solution.test.ts +84 -0
- package/content/problems/139-insert-interval/README.md +40 -0
- package/content/problems/139-insert-interval/solution.test.ts +75 -0
- package/content/problems/201-valid-sudoku/README.md +63 -0
- package/content/problems/201-valid-sudoku/solution.test.ts +104 -0
- package/content/problems/202-car-fleet/README.md +46 -0
- package/content/problems/202-car-fleet/solution.test.ts +85 -0
- package/content/problems/203-search-a-2d-matrix/README.md +47 -0
- package/content/problems/203-search-a-2d-matrix/solution.test.ts +108 -0
- package/content/problems/204-copy-list-with-random-pointer/README.md +46 -0
- package/content/problems/204-copy-list-with-random-pointer/solution.test.ts +120 -0
- package/content/problems/205-add-two-numbers/README.md +45 -0
- package/content/problems/205-add-two-numbers/solution.test.ts +74 -0
- package/content/problems/206-find-the-duplicate-number/README.md +47 -0
- package/content/problems/206-find-the-duplicate-number/solution.test.ts +72 -0
- package/content/problems/207-count-good-nodes/README.md +44 -0
- package/content/problems/207-count-good-nodes/solution.test.ts +63 -0
- package/content/problems/208-construct-tree-from-preorder-and-inorder/README.md +52 -0
- package/content/problems/208-construct-tree-from-preorder-and-inorder/solution.test.ts +126 -0
- package/content/problems/209-implement-trie/README.md +52 -0
- package/content/problems/209-implement-trie/solution.test.ts +138 -0
- package/content/problems/210-design-add-and-search-words/README.md +50 -0
- package/content/problems/210-design-add-and-search-words/solution.test.ts +127 -0
- package/content/problems/211-task-scheduler/README.md +47 -0
- package/content/problems/211-task-scheduler/solution.test.ts +64 -0
- package/content/problems/212-design-twitter/README.md +63 -0
- package/content/problems/212-design-twitter/solution.test.ts +137 -0
- package/content/problems/213-subsets/README.md +42 -0
- package/content/problems/213-subsets/solution.test.ts +63 -0
- package/content/problems/214-combination-sum/README.md +44 -0
- package/content/problems/214-combination-sum/solution.test.ts +75 -0
- package/content/problems/215-permutations/README.md +42 -0
- package/content/problems/215-permutations/solution.test.ts +70 -0
- package/content/problems/216-word-search/README.md +50 -0
- package/content/problems/216-word-search/solution.test.ts +86 -0
- package/content/problems/217-letter-combinations-of-a-phone-number/README.md +53 -0
- package/content/problems/217-letter-combinations-of-a-phone-number/solution.test.ts +57 -0
- package/content/problems/218-palindrome-partitioning/README.md +42 -0
- package/content/problems/218-palindrome-partitioning/solution.test.ts +77 -0
- package/content/problems/219-max-area-of-island/README.md +43 -0
- package/content/problems/219-max-area-of-island/solution.test.ts +78 -0
- package/content/problems/220-pacific-atlantic-water-flow/README.md +43 -0
- package/content/problems/220-pacific-atlantic-water-flow/solution.test.ts +86 -0
- package/content/problems/221-course-schedule-ii/README.md +42 -0
- package/content/problems/221-course-schedule-ii/solution.test.ts +107 -0
- package/content/problems/222-graph-valid-tree/README.md +42 -0
- package/content/problems/222-graph-valid-tree/solution.test.ts +75 -0
- package/content/problems/223-redundant-connection/README.md +42 -0
- package/content/problems/223-redundant-connection/solution.test.ts +68 -0
- package/content/problems/224-network-delay-time/README.md +44 -0
- package/content/problems/224-network-delay-time/solution.test.ts +70 -0
- package/content/problems/225-cheapest-flights-within-k-stops/README.md +45 -0
- package/content/problems/225-cheapest-flights-within-k-stops/solution.test.ts +85 -0
- package/content/problems/226-house-robber-ii/README.md +41 -0
- package/content/problems/226-house-robber-ii/solution.test.ts +51 -0
- package/content/problems/227-longest-palindromic-substring/README.md +41 -0
- package/content/problems/227-longest-palindromic-substring/solution.test.ts +69 -0
- package/content/problems/228-decode-ways/README.md +44 -0
- package/content/problems/228-decode-ways/solution.test.ts +50 -0
- package/content/problems/229-maximum-product-subarray/README.md +40 -0
- package/content/problems/229-maximum-product-subarray/solution.test.ts +55 -0
- package/content/problems/230-partition-equal-subset-sum/README.md +39 -0
- package/content/problems/230-partition-equal-subset-sum/solution.test.ts +54 -0
- package/content/problems/231-unique-paths/README.md +41 -0
- package/content/problems/231-unique-paths/solution.test.ts +45 -0
- package/content/problems/232-longest-common-subsequence/README.md +41 -0
- package/content/problems/232-longest-common-subsequence/solution.test.ts +48 -0
- package/content/problems/233-coin-change-ii/README.md +44 -0
- package/content/problems/233-coin-change-ii/solution.test.ts +45 -0
- package/content/problems/234-edit-distance/README.md +45 -0
- package/content/problems/234-edit-distance/solution.test.ts +48 -0
- package/content/problems/235-maximum-subarray/README.md +40 -0
- package/content/problems/235-maximum-subarray/solution.test.ts +63 -0
- package/content/problems/236-jump-game/README.md +40 -0
- package/content/problems/236-jump-game/solution.test.ts +68 -0
- package/content/problems/237-gas-station/README.md +42 -0
- package/content/problems/237-gas-station/solution.test.ts +56 -0
- package/content/problems/238-partition-labels/README.md +40 -0
- package/content/problems/238-partition-labels/solution.test.ts +54 -0
- package/content/problems/239-non-overlapping-intervals/README.md +40 -0
- package/content/problems/239-non-overlapping-intervals/solution.test.ts +61 -0
- package/content/problems/240-meeting-rooms-ii/README.md +42 -0
- package/content/problems/240-meeting-rooms-ii/solution.test.ts +65 -0
- package/content/problems/241-rotate-image/README.md +41 -0
- package/content/problems/241-rotate-image/solution.test.ts +72 -0
- package/content/problems/242-spiral-matrix/README.md +40 -0
- package/content/problems/242-spiral-matrix/solution.test.ts +90 -0
- package/content/problems/243-set-matrix-zeroes/README.md +44 -0
- package/content/problems/243-set-matrix-zeroes/solution.test.ts +153 -0
- package/content/problems/301-trapping-rain-water/README.md +42 -0
- package/content/problems/301-trapping-rain-water/solution.test.ts +63 -0
- package/content/problems/302-minimum-window-substring/README.md +43 -0
- package/content/problems/302-minimum-window-substring/solution.test.ts +56 -0
- package/content/problems/303-sliding-window-maximum/README.md +42 -0
- package/content/problems/303-sliding-window-maximum/solution.test.ts +63 -0
- package/content/problems/304-largest-rectangle-in-histogram/README.md +42 -0
- package/content/problems/304-largest-rectangle-in-histogram/solution.test.ts +57 -0
- package/content/problems/305-median-of-two-sorted-arrays/README.md +42 -0
- package/content/problems/305-median-of-two-sorted-arrays/solution.test.ts +84 -0
- package/content/problems/306-merge-k-sorted-lists/README.md +42 -0
- package/content/problems/306-merge-k-sorted-lists/solution.test.ts +72 -0
- package/content/problems/307-reverse-nodes-in-k-group/README.md +42 -0
- package/content/problems/307-reverse-nodes-in-k-group/solution.test.ts +86 -0
- package/content/problems/308-binary-tree-maximum-path-sum/README.md +44 -0
- package/content/problems/308-binary-tree-maximum-path-sum/solution.test.ts +91 -0
- package/content/problems/309-serialize-and-deserialize-binary-tree/README.md +50 -0
- package/content/problems/309-serialize-and-deserialize-binary-tree/solution.test.ts +120 -0
- package/content/problems/310-find-median-from-data-stream/README.md +47 -0
- package/content/problems/310-find-median-from-data-stream/solution.test.ts +102 -0
- package/content/problems/311-word-search-ii/README.md +51 -0
- package/content/problems/311-word-search-ii/solution.test.ts +144 -0
- package/content/problems/312-n-queens/README.md +41 -0
- package/content/problems/312-n-queens/solution.test.ts +91 -0
- package/content/problems/313-word-ladder/README.md +42 -0
- package/content/problems/313-word-ladder/solution.test.ts +85 -0
- package/content/problems/314-alien-dictionary/README.md +43 -0
- package/content/problems/314-alien-dictionary/solution.test.ts +127 -0
- package/content/problems/315-longest-increasing-path-in-a-matrix/README.md +42 -0
- package/content/problems/315-longest-increasing-path-in-a-matrix/solution.test.ts +118 -0
- package/content/problems/316-swim-in-rising-water/README.md +44 -0
- package/content/problems/316-swim-in-rising-water/solution.test.ts +138 -0
- package/content/product/P01-tool-lending/README.md +28 -0
- package/content/product/P02-city-bike-share/README.md +28 -0
- package/content/product/P03-caring-from-afar/README.md +29 -0
- package/content/product/P04-first-garden/README.md +28 -0
- package/content/product/P05-save-for-later/README.md +28 -0
- package/content/product/P06-ship-or-hold/README.md +28 -0
- package/content/product/P07-photo-backup-goals/README.md +28 -0
- package/content/product/P08-quarter-roadmap/README.md +28 -0
- package/content/product/P09-grocer-delivery/README.md +29 -0
- package/content/product/P10-notes-for-work/README.md +28 -0
- package/content/product/P11-fitness-coaching/README.md +28 -0
- package/content/product/P12-low-price-rival/README.md +28 -0
- package/content/product/P13-coffee-cups/README.md +28 -0
- package/content/product/P14-bike-repair-market/README.md +27 -0
- package/content/product/P15-scooter-rides/README.md +27 -0
- package/content/product/P16-school-lunch-boxes/README.md +28 -0
- package/content/product/P17-weekly-users-drop/README.md +28 -0
- package/content/product/P18-ride-cancellations/README.md +28 -0
- package/content/product/P19-signups-up-revenue-flat/README.md +28 -0
- package/content/product/P20-longer-sessions/README.md +28 -0
- package/content/product/REVIEW.md +107 -0
- package/dist/cli.mjs +4462 -0
- package/package.json +38 -4
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { timeMs } from '../../lib/perf'
|
|
3
|
+
import { orangesRotting } from './solution'
|
|
4
|
+
|
|
5
|
+
/** Copies the grid first, so a solution that rots oranges in place can't affect other tests. */
|
|
6
|
+
const minutes = (grid: readonly (readonly number[])[]): number => orangesRotting(grid.map((row) => [...row]))
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* An n x n grid (n odd) with a one-cell-wide winding path of fresh oranges: every even row is
|
|
10
|
+
* full, and odd rows join them at alternating ends. The only rotten orange is at the top left.
|
|
11
|
+
*/
|
|
12
|
+
function windingGrid(n: number): number[][] {
|
|
13
|
+
return Array.from({ length: n }, (_, r) =>
|
|
14
|
+
Array.from({ length: n }, (_, c) => {
|
|
15
|
+
if (r === 0 && c === 0) return 2
|
|
16
|
+
if (r % 2 === 0) return 1
|
|
17
|
+
return (r % 4 === 1 && c === n - 1) || (r % 4 === 3 && c === 0) ? 1 : 0
|
|
18
|
+
}),
|
|
19
|
+
)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
describe('132 rotting oranges', () => {
|
|
23
|
+
it('counts the minutes until the last orange rots', () => {
|
|
24
|
+
expect(minutes([[2, 1, 1], [1, 1, 0], [0, 1, 1]])).toBe(4)
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
it('returns -1 when an orange is cut off', () => {
|
|
28
|
+
expect(minutes([[2, 1, 1], [0, 1, 1], [1, 0, 1]])).toBe(-1)
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('returns 0 when there is nothing fresh', () => {
|
|
32
|
+
expect(minutes([[0, 2]])).toBe(0)
|
|
33
|
+
expect(minutes([[0]])).toBe(0)
|
|
34
|
+
expect(minutes([[2, 2], [2, 0]])).toBe(0)
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
it('returns -1 when there is fresh fruit but nothing rotten', () => {
|
|
38
|
+
expect(minutes([[1]])).toBe(-1)
|
|
39
|
+
expect(minutes([[1, 1], [0, 1]])).toBe(-1)
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
it('spreads from every rotten orange at once', () => {
|
|
43
|
+
expect(minutes([[2, 1, 1, 1, 2]])).toBe(2)
|
|
44
|
+
expect(minutes([[2, 1, 1], [1, 1, 1], [1, 1, 2]])).toBe(2)
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
it('spreads outward from the middle', () => {
|
|
48
|
+
expect(minutes([[1, 1, 1], [1, 2, 1], [1, 1, 1]])).toBe(2)
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
it('does not spread diagonally', () => {
|
|
52
|
+
expect(minutes([[2, 0], [0, 1]])).toBe(-1)
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
it('handles a single column', () => {
|
|
56
|
+
expect(minutes([[1], [1], [2], [1]])).toBe(2)
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
it('follows a winding path', () => {
|
|
60
|
+
// 5 x 5: path of 3 full rows (15 cells) plus 2 connectors = 17 cells, so 16 minutes.
|
|
61
|
+
expect(minutes(windingGrid(5))).toBe(16)
|
|
62
|
+
})
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
describe('132 performance', () => {
|
|
66
|
+
it('handles a 151 x 151 winding grid in under 100 ms (re-scanning the grid every minute is too slow here)', () => {
|
|
67
|
+
const n = 151
|
|
68
|
+
// 76 full rows of 151, plus 75 connectors, minus the starting cell.
|
|
69
|
+
const expected = 76 * n + 75 - 1
|
|
70
|
+
const grid = windingGrid(n)
|
|
71
|
+
const ms = timeMs(() => expect(orangesRotting(grid)).toBe(expected))
|
|
72
|
+
expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(100)
|
|
73
|
+
})
|
|
74
|
+
})
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# 133 · Clone Graph
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: graphs (DFS/BFS + hash map) · Target: 25 min · NeetCode 150 · LeetCode 133
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
You get one node of a connected, undirected graph (or `null`). Each node has a `val` and a list of `neighbors`. Return a **deep copy** of the whole graph: a brand-new node for every original node, wired up the same way, and return the copy of the node you were given.
|
|
8
|
+
|
|
9
|
+
No node in your copy may be one of the original nodes, and the original graph must be left unchanged.
|
|
10
|
+
|
|
11
|
+
In the tests, node values are `1..n`, and a graph is written as a 1-indexed adjacency list: entry `i` lists the neighbours of node `i + 1`. `GraphNode` and the helpers that build and read these graphs live in `lib/graph.ts`.
|
|
12
|
+
|
|
13
|
+
## Examples
|
|
14
|
+
|
|
15
|
+
| Graph (adjacency list) | Output |
|
|
16
|
+
|---|---|
|
|
17
|
+
| `[[2, 4], [1, 3], [2, 4], [1, 3]]` (a 4-cycle) | a copy with the same adjacency list |
|
|
18
|
+
| `[[]]` (a single node, no edges) | a copy of that one node |
|
|
19
|
+
| `[]` (no graph, `null` input) | `null` |
|
|
20
|
+
|
|
21
|
+
## Constraints
|
|
22
|
+
|
|
23
|
+
- `0 <= nodes <= 100` (one test uses 2,000)
|
|
24
|
+
- Values are unique and run `1..n`. No self-loops or repeated edges. The graph is connected.
|
|
25
|
+
|
|
26
|
+
## Run it
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pnpm watch 133
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
33
|
+
|
|
34
|
+
Time O(V + E) · Space O(V) for the original-to-copy map (plus the queue or recursion stack).
|
|
35
|
+
|
|
36
|
+
</details>
|
|
37
|
+
|
|
38
|
+
## Follow-ups an interviewer might ask
|
|
39
|
+
|
|
40
|
+
- Why do you need a map from original to copy? What happens on a cycle without one?
|
|
41
|
+
- Did you use DFS or BFS? Write the other one.
|
|
42
|
+
- Copy a linked list where every node also has a `random` pointer (LeetCode 138). Same idea.
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { graphFrom, graphNodes, graphToAdjList } from '../../lib/graph'
|
|
3
|
+
import { cloneGraph } from './solution'
|
|
4
|
+
|
|
5
|
+
/** Clones the graph built from `adj` and checks the copy: same shape, no shared nodes, original untouched. */
|
|
6
|
+
function expectDeepCopy(adj: readonly (readonly number[])[]): void {
|
|
7
|
+
const original = graphFrom(adj)
|
|
8
|
+
const originals = new Set(graphNodes(original))
|
|
9
|
+
const clone = cloneGraph(original)
|
|
10
|
+
|
|
11
|
+
expect(graphToAdjList(clone)).toEqual(adj)
|
|
12
|
+
expect(clone?.val).toBe(original?.val)
|
|
13
|
+
const shared = graphNodes(clone).filter((node) => originals.has(node))
|
|
14
|
+
expect(shared.map((node) => node.val), 'nodes in the copy that are original nodes').toEqual([])
|
|
15
|
+
expect(graphToAdjList(original), 'the original graph changed').toEqual(adj)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Every node is joined to every other node. */
|
|
19
|
+
const complete = (n: number): number[][] =>
|
|
20
|
+
Array.from({ length: n }, (_, i) => Array.from({ length: n }, (_, j) => j + 1).filter((v) => v !== i + 1))
|
|
21
|
+
|
|
22
|
+
/** Nodes 1..n in a line. */
|
|
23
|
+
const path = (n: number): number[][] =>
|
|
24
|
+
Array.from({ length: n }, (_, i) => [i, i + 2].filter((v) => v >= 1 && v <= n))
|
|
25
|
+
|
|
26
|
+
describe('133 clone graph', () => {
|
|
27
|
+
it('copies a 4-cycle', () => {
|
|
28
|
+
expectDeepCopy([[2, 4], [1, 3], [2, 4], [1, 3]])
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('copies a single node with no neighbours', () => {
|
|
32
|
+
expectDeepCopy([[]])
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
it('returns null for no graph', () => {
|
|
36
|
+
expect(cloneGraph(null)).toBeNull()
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
it('copies two connected nodes', () => {
|
|
40
|
+
expectDeepCopy([[2], [1]])
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
it('copies a star whose centre is not the starting node', () => {
|
|
44
|
+
expectDeepCopy([[2], [1, 3, 4, 5], [2], [2], [2]])
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
it('keeps the neighbour order of every node', () => {
|
|
48
|
+
expectDeepCopy([[3, 2, 4], [4, 1], [1, 4], [2, 1, 3]])
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
it('copies a complete graph', () => {
|
|
52
|
+
expectDeepCopy(complete(8))
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
it('copies a 2,000-node path', () => {
|
|
56
|
+
expectDeepCopy(path(2_000))
|
|
57
|
+
})
|
|
58
|
+
})
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# 134 · House Robber
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: 1-D dynamic programming · Target: 25 min · NeetCode 150 · LeetCode 198
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
A row of houses each holds some cash, given as `nums[i]`. You want to collect as much as possible, but you may never take from two **neighbouring** houses. Return the largest total you can collect.
|
|
8
|
+
|
|
9
|
+
## Examples
|
|
10
|
+
|
|
11
|
+
| `nums` | Output | Why |
|
|
12
|
+
|---|---|---|
|
|
13
|
+
| `[1, 2, 3, 1]` | `4` | houses 0 and 2: `1 + 3` |
|
|
14
|
+
| `[2, 7, 9, 3, 1]` | `12` | houses 0, 2 and 4: `2 + 9 + 1` |
|
|
15
|
+
| `[2, 1, 1, 2]` | `4` | houses 0 and 3; neither "all even" nor "all odd" positions is best |
|
|
16
|
+
|
|
17
|
+
## Constraints
|
|
18
|
+
|
|
19
|
+
- `1 <= nums.length <= 100`
|
|
20
|
+
- `0 <= nums[i] <= 400`
|
|
21
|
+
|
|
22
|
+
## Run it
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
pnpm watch 134
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
29
|
+
|
|
30
|
+
Time O(n) · Space O(1), keeping only the best totals for the last two houses. Plain "take it or skip it" recursion is O(2^n) and fails the performance test; memoising it gives O(n) time and O(n) space.
|
|
31
|
+
|
|
32
|
+
</details>
|
|
33
|
+
|
|
34
|
+
## Follow-ups an interviewer might ask
|
|
35
|
+
|
|
36
|
+
- What if the houses form a circle, so the first and last are neighbours? (LeetCode 213, the next problem in this ladder)
|
|
37
|
+
- Return which houses to rob, not just the total.
|
|
38
|
+
- What if the houses form a binary tree? (LeetCode 337)
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { timeMs } from '../../lib/perf'
|
|
3
|
+
import { rob } from './solution'
|
|
4
|
+
|
|
5
|
+
describe('134 house robber', () => {
|
|
6
|
+
it('runs the README examples', () => {
|
|
7
|
+
expect(rob([1, 2, 3, 1])).toBe(4)
|
|
8
|
+
expect(rob([2, 7, 9, 3, 1])).toBe(12)
|
|
9
|
+
})
|
|
10
|
+
|
|
11
|
+
it('beats "every other house" when skipping two in a row pays off', () => {
|
|
12
|
+
expect(rob([2, 1, 1, 2])).toBe(4)
|
|
13
|
+
expect(rob([5, 1, 1, 5, 1, 1, 5])).toBe(15)
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
it('handles one and two houses', () => {
|
|
17
|
+
expect(rob([7])).toBe(7)
|
|
18
|
+
expect(rob([0])).toBe(0)
|
|
19
|
+
expect(rob([3, 9])).toBe(9)
|
|
20
|
+
expect(rob([9, 3])).toBe(9)
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
it('handles zeros', () => {
|
|
24
|
+
expect(rob([0, 0, 0])).toBe(0)
|
|
25
|
+
expect(rob([0, 5, 0, 0, 5])).toBe(10)
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
it('handles equal values', () => {
|
|
29
|
+
expect(rob([4, 4, 4, 4, 4])).toBe(12)
|
|
30
|
+
expect(rob([4, 4, 4, 4])).toBe(8)
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
it('handles a longer row', () => {
|
|
34
|
+
expect(rob([6, 3, 10, 8, 2, 10, 3, 5, 10, 5, 3])).toBe(39)
|
|
35
|
+
})
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
describe('134 performance', () => {
|
|
39
|
+
it('handles 40 houses in under 50 ms (plain recursion takes seconds)', () => {
|
|
40
|
+
// Odd positions hold 1 and even positions hold 2, so taking every even house (20 × 2) is best.
|
|
41
|
+
const nums = Array.from({ length: 40 }, (_, i) => (i % 2 === 0 ? 2 : 1))
|
|
42
|
+
const ms = timeMs(() => expect(rob(nums)).toBe(40))
|
|
43
|
+
expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(50)
|
|
44
|
+
})
|
|
45
|
+
})
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# 135 · Coin Change
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: 1-D dynamic programming (unbounded knapsack) · Target: 25 min · NeetCode 150 · LeetCode 322
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
You get a list of coin denominations and a target `amount`. You have an unlimited supply of every denomination. Return the **fewest** coins that add up to exactly `amount`, or `-1` if no combination does. An `amount` of `0` needs `0` coins.
|
|
8
|
+
|
|
9
|
+
## Examples
|
|
10
|
+
|
|
11
|
+
| `coins` | `amount` | Output | Why |
|
|
12
|
+
|---|---|---|---|
|
|
13
|
+
| `[1, 2, 5]` | `11` | `3` | `5 + 5 + 1` |
|
|
14
|
+
| `[2]` | `3` | `-1` | only even totals are possible |
|
|
15
|
+
| `[1]` | `0` | `0` | nothing to pay |
|
|
16
|
+
| `[1, 3, 4]` | `6` | `2` | `3 + 3`; grabbing the largest coin first gives `4 + 1 + 1` |
|
|
17
|
+
|
|
18
|
+
## Constraints
|
|
19
|
+
|
|
20
|
+
- `1 <= coins.length <= 12`
|
|
21
|
+
- `1 <= coins[i] <= 2^31 - 1`, all distinct, in any order
|
|
22
|
+
- `0 <= amount <= 10^4`. The performance test uses a small amount (36), where plain recursion already takes seconds.
|
|
23
|
+
|
|
24
|
+
## Run it
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pnpm watch 135
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
31
|
+
|
|
32
|
+
Time O(amount · coins) · Space O(amount). Plain recursion over "which coin do I use next?" is exponential and fails the performance tests. Memoised recursion and a bottom-up table both pass; if you memoise, remember to cache "impossible" results too.
|
|
33
|
+
|
|
34
|
+
</details>
|
|
35
|
+
|
|
36
|
+
## Follow-ups an interviewer might ask
|
|
37
|
+
|
|
38
|
+
- Why doesn't "always take the largest coin that fits" work? When would it?
|
|
39
|
+
- Count the **number of ways** to make the amount instead. (LeetCode 518)
|
|
40
|
+
- Can you solve it with BFS, treating each amount as a node?
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { timeMs } from '../../lib/perf'
|
|
3
|
+
import { coinChange } from './solution'
|
|
4
|
+
|
|
5
|
+
describe('135 coin change', () => {
|
|
6
|
+
it('runs the README examples', () => {
|
|
7
|
+
expect(coinChange([1, 2, 5], 11)).toBe(3)
|
|
8
|
+
expect(coinChange([2], 3)).toBe(-1)
|
|
9
|
+
expect(coinChange([1], 0)).toBe(0)
|
|
10
|
+
})
|
|
11
|
+
|
|
12
|
+
it('beats "largest coin first"', () => {
|
|
13
|
+
expect(coinChange([1, 3, 4], 6)).toBe(2)
|
|
14
|
+
expect(coinChange([1, 5, 6, 9], 11)).toBe(2)
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
it('returns -1 when greedy gets stuck but nothing else works either', () => {
|
|
18
|
+
expect(coinChange([5, 10], 3)).toBe(-1)
|
|
19
|
+
expect(coinChange([4, 6], 7)).toBe(-1)
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
it('needs 0 coins for amount 0, whatever the coins', () => {
|
|
23
|
+
expect(coinChange([7, 11], 0)).toBe(0)
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
it('uses a single coin when one matches exactly', () => {
|
|
27
|
+
expect(coinChange([3, 7, 10], 7)).toBe(1)
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
it('handles coins in any order', () => {
|
|
31
|
+
expect(coinChange([5, 1, 2], 11)).toBe(3)
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
it('handles coins larger than the amount', () => {
|
|
35
|
+
expect(coinChange([2_147_483_647], 2)).toBe(-1)
|
|
36
|
+
expect(coinChange([1, 2_147_483_647], 2)).toBe(2)
|
|
37
|
+
})
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
describe('135 performance', () => {
|
|
41
|
+
it('makes amount 36 from [1, 2, 5] in under 50 ms (plain recursion takes about 2 seconds)', () => {
|
|
42
|
+
const ms = timeMs(() => expect(coinChange([1, 2, 5], 36)).toBe(8))
|
|
43
|
+
expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(50)
|
|
44
|
+
})
|
|
45
|
+
})
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# 136 · Longest Increasing Subsequence
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: 1-D dynamic programming · Target: 25 min · NeetCode 150 · LeetCode 300
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
You get an array of integers. A subsequence keeps some of the elements, in their original order, and drops the rest (they don't have to be next to each other). Return the length of the longest subsequence whose values are **strictly** increasing.
|
|
8
|
+
|
|
9
|
+
## Examples
|
|
10
|
+
|
|
11
|
+
| `nums` | Output | Why |
|
|
12
|
+
|---|---|---|
|
|
13
|
+
| `[10, 9, 2, 5, 3, 7, 101, 18]` | `4` | e.g. `2, 3, 7, 101` |
|
|
14
|
+
| `[0, 1, 0, 3, 2, 3]` | `4` | `0, 1, 2, 3` |
|
|
15
|
+
| `[7, 7, 7, 7]` | `1` | equal values don't count as increasing |
|
|
16
|
+
|
|
17
|
+
## Constraints
|
|
18
|
+
|
|
19
|
+
- `1 <= nums.length <= 2500`
|
|
20
|
+
- `-10^4 <= nums[i] <= 10^4`
|
|
21
|
+
|
|
22
|
+
## Run it
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
pnpm watch 136
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
29
|
+
|
|
30
|
+
Time O(n²) · Space O(n) is the standard first answer, and it passes the tests: for each `i`, the longest increasing subsequence that ends at `i`. Trying every subsequence is O(2^n) and fails the performance test.
|
|
31
|
+
|
|
32
|
+
The follow-up is **O(n log n)**: keep an array where entry `k` is the smallest value that can end an increasing subsequence of length `k + 1`, and update it with binary search.
|
|
33
|
+
|
|
34
|
+
</details>
|
|
35
|
+
|
|
36
|
+
## Follow-ups an interviewer might ask
|
|
37
|
+
|
|
38
|
+
- Can you do it in O(n log n)?
|
|
39
|
+
- Return one actual longest subsequence, not just its length.
|
|
40
|
+
- What changes for "non-decreasing" instead of strictly increasing?
|
|
41
|
+
- Russian Doll Envelopes (LeetCode 354) reduces to this problem.
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { timeMs } from '../../lib/perf'
|
|
3
|
+
import { lengthOfLIS } from './solution'
|
|
4
|
+
|
|
5
|
+
describe('136 longest increasing subsequence', () => {
|
|
6
|
+
it('runs the README examples', () => {
|
|
7
|
+
expect(lengthOfLIS([10, 9, 2, 5, 3, 7, 101, 18])).toBe(4)
|
|
8
|
+
expect(lengthOfLIS([0, 1, 0, 3, 2, 3])).toBe(4)
|
|
9
|
+
})
|
|
10
|
+
|
|
11
|
+
it('counts only strictly increasing runs', () => {
|
|
12
|
+
expect(lengthOfLIS([7, 7, 7, 7, 7, 7, 7])).toBe(1)
|
|
13
|
+
expect(lengthOfLIS([1, 2, 2, 3])).toBe(3)
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
it('handles a single element', () => {
|
|
17
|
+
expect(lengthOfLIS([5])).toBe(1)
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
it('handles sorted and reverse-sorted input', () => {
|
|
21
|
+
expect(lengthOfLIS([1, 2, 3, 4, 5])).toBe(5)
|
|
22
|
+
expect(lengthOfLIS([5, 4, 3, 2, 1])).toBe(1)
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
it('handles negatives', () => {
|
|
26
|
+
expect(lengthOfLIS([-2, -1, -5, 0, -3, 1])).toBe(4)
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
it('finds the best subsequence even when it does not end at the last element', () => {
|
|
30
|
+
expect(lengthOfLIS([1, 2, 3, 4, 0])).toBe(4)
|
|
31
|
+
expect(lengthOfLIS([3, 4, 5, 1, 2])).toBe(3)
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
it('does not just start from the smallest value', () => {
|
|
35
|
+
expect(lengthOfLIS([4, 10, 4, 3, 8, 9])).toBe(3)
|
|
36
|
+
expect(lengthOfLIS([3, 5, 6, 2, 5, 4, 19, 5, 6, 7, 12])).toBe(6)
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
it('takes at most one number from each falling run', () => {
|
|
40
|
+
// 6 blocks of 5; each block counts down, and every block sits above the one before.
|
|
41
|
+
// An increasing subsequence can take at most one number per block, so the answer is 6.
|
|
42
|
+
const nums = Array.from({ length: 30 }, (_, i) => Math.floor(i / 5) * 10 - (i % 5))
|
|
43
|
+
expect(lengthOfLIS(nums)).toBe(6)
|
|
44
|
+
})
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
describe('136 performance', () => {
|
|
48
|
+
it('handles 27 increasing numbers in under 50 ms (trying every subsequence takes seconds)', () => {
|
|
49
|
+
const nums = Array.from({ length: 27 }, (_, i) => i * 3 - 40)
|
|
50
|
+
const ms = timeMs(() => expect(lengthOfLIS(nums)).toBe(27))
|
|
51
|
+
expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(50)
|
|
52
|
+
})
|
|
53
|
+
})
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# 137 · Word Break
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: 1-D dynamic programming · Target: 25 min · NeetCode 150 · LeetCode 139
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
You get a string `s` and a list of dictionary words. Return `true` if `s` can be cut into pieces so that every piece is a dictionary word. A word may be used any number of times, and not every word has to be used.
|
|
8
|
+
|
|
9
|
+
## Examples
|
|
10
|
+
|
|
11
|
+
| `s` | `wordDict` | Output | Why |
|
|
12
|
+
|---|---|---|---|
|
|
13
|
+
| `"leetcode"` | `["leet", "code"]` | `true` | `leet` + `code` |
|
|
14
|
+
| `"applepenapple"` | `["apple", "pen"]` | `true` | `apple` is used twice |
|
|
15
|
+
| `"catsandog"` | `["cats", "dog", "sand", "and", "cat"]` | `false` | every split leaves `og` or `sandog` |
|
|
16
|
+
|
|
17
|
+
## Constraints
|
|
18
|
+
|
|
19
|
+
- `1 <= s.length <= 300`
|
|
20
|
+
- `1 <= wordDict.length <= 1000`, `1 <= wordDict[i].length <= 20`
|
|
21
|
+
- `s` and the words use lowercase English letters only, and the words are distinct.
|
|
22
|
+
|
|
23
|
+
## Run it
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
pnpm watch 137
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
30
|
+
|
|
31
|
+
Time O(n² · L) or O(n · w · L) · Space O(n), where `n = s.length`, `w` is the number of words and `L` the longest word (string slicing and comparing costs up to `L`). Backtracking that tries every split without remembering results is exponential and fails the performance test.
|
|
32
|
+
|
|
33
|
+
</details>
|
|
34
|
+
|
|
35
|
+
## Follow-ups an interviewer might ask
|
|
36
|
+
|
|
37
|
+
- Return every possible sentence, not just yes/no. (LeetCode 140) What does that do to the complexity?
|
|
38
|
+
- Would a trie of the dictionary help? When?
|
|
39
|
+
- Can you limit the work by using the length of the longest word?
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { timeMs } from '../../lib/perf'
|
|
3
|
+
import { wordBreak } from './solution'
|
|
4
|
+
|
|
5
|
+
describe('137 word break', () => {
|
|
6
|
+
it('runs the README examples', () => {
|
|
7
|
+
expect(wordBreak('leetcode', ['leet', 'code'])).toBe(true)
|
|
8
|
+
expect(wordBreak('applepenapple', ['apple', 'pen'])).toBe(true)
|
|
9
|
+
expect(wordBreak('catsandog', ['cats', 'dog', 'sand', 'and', 'cat'])).toBe(false)
|
|
10
|
+
})
|
|
11
|
+
|
|
12
|
+
it('beats greedy longest-match and greedy shortest-match', () => {
|
|
13
|
+
expect(wordBreak('goalspecial', ['go', 'goal', 'goals', 'special'])).toBe(true)
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
it('handles a string that is exactly one word', () => {
|
|
17
|
+
expect(wordBreak('a', ['a'])).toBe(true)
|
|
18
|
+
expect(wordBreak('b', ['a'])).toBe(false)
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
it('needs the whole string to be used', () => {
|
|
22
|
+
expect(wordBreak('aaaaaaa', ['aaaa', 'aaa'])).toBe(true)
|
|
23
|
+
expect(wordBreak('aaaaaaa', ['aaaa', 'aa'])).toBe(false)
|
|
24
|
+
expect(wordBreak('abcd', ['a', 'abc', 'b', 'cd'])).toBe(true)
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
it('ignores words longer than the string', () => {
|
|
28
|
+
expect(wordBreak('cat', ['cats', 'catsdog'])).toBe(false)
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('handles a word that is a prefix of another', () => {
|
|
32
|
+
expect(wordBreak('cars', ['car', 'ca', 'rs'])).toBe(true)
|
|
33
|
+
expect(wordBreak('bb', ['a', 'b', 'bbb', 'bbbb'])).toBe(true)
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
it('handles a word reused many times', () => {
|
|
37
|
+
expect(wordBreak('ab'.repeat(150), ['ab'])).toBe(true)
|
|
38
|
+
expect(wordBreak(`${'ab'.repeat(149)}a`, ['ab'])).toBe(false)
|
|
39
|
+
})
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
describe('137 performance', () => {
|
|
43
|
+
it('rejects "aaa…ab" in under 50 ms (backtracking without memo takes seconds)', () => {
|
|
44
|
+
const s = `${'a'.repeat(25)}b`
|
|
45
|
+
const dict = Array.from({ length: 10 }, (_, i) => 'a'.repeat(i + 1))
|
|
46
|
+
const ms = timeMs(() => expect(wordBreak(s, dict)).toBe(false))
|
|
47
|
+
expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(50)
|
|
48
|
+
})
|
|
49
|
+
})
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# 138 · Merge Intervals
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: intervals (sort, then sweep) · Target: 25 min · NeetCode 150 · LeetCode 56
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
You get a list of closed intervals `[start, end]`, in **no particular order**. Combine every group of overlapping intervals into one interval and return the result, sorted by start. Intervals that only touch, like `[1, 4]` and `[4, 5]`, count as overlapping.
|
|
8
|
+
|
|
9
|
+
Return a new array and **don't modify the input**: the tests check that the input array and its intervals are unchanged afterwards. (Sort a copy if you need to sort.)
|
|
10
|
+
|
|
11
|
+
## Examples
|
|
12
|
+
|
|
13
|
+
| `intervals` | Output | Why |
|
|
14
|
+
|---|---|---|
|
|
15
|
+
| `[[1, 3], [2, 6], [8, 10], [15, 18]]` | `[[1, 6], [8, 10], [15, 18]]` | `[1, 3]` and `[2, 6]` overlap |
|
|
16
|
+
| `[[1, 4], [4, 5]]` | `[[1, 5]]` | touching counts |
|
|
17
|
+
| `[[4, 7], [1, 4]]` | `[[1, 7]]` | input order doesn't matter |
|
|
18
|
+
|
|
19
|
+
## Constraints
|
|
20
|
+
|
|
21
|
+
- `1 <= intervals.length <= 10^4`. The performance test uses `30,000` intervals.
|
|
22
|
+
- `0 <= start <= end <= 10^4` on LeetCode; the tests also use larger and negative values.
|
|
23
|
+
|
|
24
|
+
## Run it
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pnpm watch 138
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
31
|
+
|
|
32
|
+
Time O(n log n) · Space O(n). Sorting by start dominates; the merge itself is one pass. Repeatedly comparing every interval against every other is O(n²) or worse and fails the performance test.
|
|
33
|
+
|
|
34
|
+
</details>
|
|
35
|
+
|
|
36
|
+
## Follow-ups an interviewer might ask
|
|
37
|
+
|
|
38
|
+
- What if the intervals arrive one at a time, as a stream?
|
|
39
|
+
- Why is sorting by start enough? Would sorting by end work?
|
|
40
|
+
- Given meetings as intervals, how many rooms do you need? (Meeting Rooms II, LeetCode 253)
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { timeMs } from '../../lib/perf'
|
|
3
|
+
import { merge } from './solution'
|
|
4
|
+
|
|
5
|
+
type Interval = [number, number]
|
|
6
|
+
|
|
7
|
+
/** Merges, and also checks that the input was left exactly as it was. */
|
|
8
|
+
function merged(intervals: Interval[]): Interval[] {
|
|
9
|
+
const before = structuredClone(intervals)
|
|
10
|
+
const result = merge(intervals)
|
|
11
|
+
expect(intervals, 'the input was modified').toEqual(before)
|
|
12
|
+
return result
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
describe('138 merge intervals', () => {
|
|
16
|
+
it('runs the README examples', () => {
|
|
17
|
+
expect(merged([[1, 3], [2, 6], [8, 10], [15, 18]])).toEqual([[1, 6], [8, 10], [15, 18]])
|
|
18
|
+
expect(merged([[1, 4], [4, 5]])).toEqual([[1, 5]])
|
|
19
|
+
expect(merged([[4, 7], [1, 4]])).toEqual([[1, 7]])
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
it('handles a single interval', () => {
|
|
23
|
+
expect(merged([[2, 3]])).toEqual([[2, 3]])
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
it('handles zero-length intervals', () => {
|
|
27
|
+
expect(merged([[5, 5], [5, 5]])).toEqual([[5, 5]])
|
|
28
|
+
expect(merged([[1, 4], [0, 0]])).toEqual([[0, 0], [1, 4]])
|
|
29
|
+
expect(merged([[1, 4], [4, 4]])).toEqual([[1, 4]])
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
it('keeps the larger end when one interval contains another', () => {
|
|
33
|
+
expect(merged([[1, 10], [2, 3], [4, 5]])).toEqual([[1, 10]])
|
|
34
|
+
expect(merged([[2, 3], [1, 10]])).toEqual([[1, 10]])
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
it('does not merge intervals with a gap between them', () => {
|
|
38
|
+
expect(merged([[1, 2], [3, 4]])).toEqual([[1, 2], [3, 4]])
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
it('sorts unsorted input', () => {
|
|
42
|
+
expect(merged([[8, 10], [15, 18], [1, 3], [2, 6]])).toEqual([[1, 6], [8, 10], [15, 18]])
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
it('merges a chain into one interval', () => {
|
|
46
|
+
expect(merged([[5, 6], [1, 2], [4, 5], [2, 3], [3, 4]])).toEqual([[1, 6]])
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
it('merges two groups whose link only appears after sorting', () => {
|
|
50
|
+
expect(merged([[1, 4], [6, 8], [0, 2], [3, 7], [10, 11]])).toEqual([[0, 8], [10, 11]])
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
it('handles negatives and duplicates', () => {
|
|
54
|
+
expect(merged([[-5, -1], [-3, 2], [-5, -1], [4, 6]])).toEqual([[-5, 2], [4, 6]])
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
it('does not change the input when it merges', () => {
|
|
58
|
+
const input: Interval[] = [[3, 9], [1, 4], [2, 5], [20, 30]]
|
|
59
|
+
const before = structuredClone(input)
|
|
60
|
+
const result = merge(input)
|
|
61
|
+
expect(result).toEqual([[1, 9], [20, 30]])
|
|
62
|
+
expect(input).toEqual(before)
|
|
63
|
+
})
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
describe('138 performance', () => {
|
|
67
|
+
it('merges 30,000 intervals in under 100 ms (O(n²) is too slow here)', () => {
|
|
68
|
+
const n = 30_000
|
|
69
|
+
// Disjoint intervals [4k, 4k + 2], in a scrambled order, then one more interval that links k = 0..9.
|
|
70
|
+
const intervals: Interval[] = Array.from({ length: n }, (_, i) => {
|
|
71
|
+
const k = (i * 7_919) % n
|
|
72
|
+
return [4 * k, 4 * k + 2]
|
|
73
|
+
})
|
|
74
|
+
intervals.push([1, 37])
|
|
75
|
+
const ms = timeMs(() => {
|
|
76
|
+
const result = merge(intervals)
|
|
77
|
+
expect(result).toHaveLength(n - 9)
|
|
78
|
+
expect(result[0]).toEqual([0, 38])
|
|
79
|
+
expect(result[1]).toEqual([40, 42])
|
|
80
|
+
expect(result.at(-1)).toEqual([4 * (n - 1), 4 * (n - 1) + 2])
|
|
81
|
+
})
|
|
82
|
+
expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(100)
|
|
83
|
+
})
|
|
84
|
+
})
|