interview-reps 0.0.0-stage → 0.3.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 +4418 -0
- package/package.json +38 -4
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { timeMs } from '../../lib/perf'
|
|
3
|
+
import { partition } from './solution'
|
|
4
|
+
|
|
5
|
+
// The ways can come back in any order, but the pieces inside each way keep their order.
|
|
6
|
+
const normalise = (ways: readonly (readonly string[])[]): string[] =>
|
|
7
|
+
ways.map((pieces) => pieces.join('|')).sort()
|
|
8
|
+
|
|
9
|
+
const isPalindrome = (piece: string): boolean => piece === [...piece].reverse().join('')
|
|
10
|
+
|
|
11
|
+
describe('218 palindrome partitioning', () => {
|
|
12
|
+
it('finds every way to cut a string that is a palindrome itself', () => {
|
|
13
|
+
expect(normalise(partition('noon'))).toEqual(
|
|
14
|
+
normalise([['n', 'o', 'o', 'n'], ['n', 'oo', 'n'], ['noon']]),
|
|
15
|
+
)
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
it('finds an odd-length palindrome as one piece', () => {
|
|
19
|
+
expect(normalise(partition('xyx'))).toEqual(normalise([['x', 'y', 'x'], ['xyx']]))
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
it('returns only single letters when nothing longer is a palindrome', () => {
|
|
23
|
+
expect(partition('abc')).toEqual([['a', 'b', 'c']])
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
it('handles a single letter', () => {
|
|
27
|
+
expect(partition('q')).toEqual([['q']])
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
it('handles two letters, equal or not', () => {
|
|
31
|
+
expect(normalise(partition('zz'))).toEqual(normalise([['z', 'z'], ['zz']]))
|
|
32
|
+
expect(partition('zy')).toEqual([['z', 'y']])
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
it('lists all four ways for three equal letters', () => {
|
|
36
|
+
expect(normalise(partition('ccc'))).toEqual(
|
|
37
|
+
normalise([['c', 'c', 'c'], ['c', 'cc'], ['cc', 'c'], ['ccc']]),
|
|
38
|
+
)
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
it('finds palindromes that overlap and nest', () => {
|
|
42
|
+
expect(normalise(partition('abbab'))).toEqual(
|
|
43
|
+
normalise([
|
|
44
|
+
['a', 'b', 'b', 'a', 'b'],
|
|
45
|
+
['a', 'b', 'bab'],
|
|
46
|
+
['a', 'bb', 'a', 'b'],
|
|
47
|
+
['abba', 'b'],
|
|
48
|
+
]),
|
|
49
|
+
)
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
it('lists all 2^15 ways for 16 equal letters', () => {
|
|
53
|
+
const s = 'k'.repeat(16)
|
|
54
|
+
const result = partition(s)
|
|
55
|
+
expect(result).toHaveLength(2 ** 15)
|
|
56
|
+
expect(new Set(normalise(result)).size).toBe(2 ** 15)
|
|
57
|
+
for (const pieces of result) expect(pieces.join('')).toBe(s)
|
|
58
|
+
})
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
describe('218 performance', () => {
|
|
62
|
+
it('cuts a 25-letter string with few palindromes in under 75 ms (trying every set of cuts is too slow here)', () => {
|
|
63
|
+
const s = 'xyxwqrqpkmnoonzstuvdefegh'
|
|
64
|
+
let result: string[][] = []
|
|
65
|
+
const ms = timeMs(() => {
|
|
66
|
+
result = partition(s)
|
|
67
|
+
})
|
|
68
|
+
expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(75)
|
|
69
|
+
|
|
70
|
+
expect(result).toHaveLength(24)
|
|
71
|
+
expect(new Set(normalise(result)).size).toBe(24)
|
|
72
|
+
for (const pieces of result) {
|
|
73
|
+
expect(pieces.join('')).toBe(s)
|
|
74
|
+
for (const piece of pieces) expect(isPalindrome(piece)).toBe(true)
|
|
75
|
+
}
|
|
76
|
+
})
|
|
77
|
+
})
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# 219 · Max Area of Island
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: graphs (grid DFS/BFS) · Target: 25 min · NeetCode 150 · LeetCode 695
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
`grid` is a map made of `1`s (land) and `0`s (water). Land cells that touch along a side (up, down, left or right, never diagonally) belong to the same island, and everything outside the grid is water. The **area** of an island is how many land cells it has.
|
|
8
|
+
|
|
9
|
+
Return the area of the biggest island, or `0` if there is no land at all.
|
|
10
|
+
|
|
11
|
+
Don't modify `grid` (it's `readonly`). Keep track of the cells you've already counted some other way.
|
|
12
|
+
|
|
13
|
+
## Examples
|
|
14
|
+
|
|
15
|
+
| `grid` | Output | Why |
|
|
16
|
+
|---|---|---|
|
|
17
|
+
| `[[1, 1, 0, 0], [0, 1, 0, 1], [0, 0, 0, 1], [1, 0, 1, 1]]` | `4` | the island on the right has 4 cells; the top-left one has 3 |
|
|
18
|
+
| `[[0, 1, 0], [1, 0, 1], [0, 1, 0]]` | `1` | four islands of one cell each, none joined diagonally |
|
|
19
|
+
| `[[0, 0], [0, 0]]` | `0` | no land |
|
|
20
|
+
|
|
21
|
+
## Constraints
|
|
22
|
+
|
|
23
|
+
- `1 <= rows, cols <= 200` (the performance test uses a 200 x 200 grid)
|
|
24
|
+
- `grid[r][c]` is `0` or `1`.
|
|
25
|
+
- Every island in the tests has at most about 2,000 cells, so a recursive solution won't overflow the call stack.
|
|
26
|
+
|
|
27
|
+
## Run it
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pnpm watch 219
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
34
|
+
|
|
35
|
+
Time O(rows · cols) · Space O(rows · cols) for the visited marks and the stack or queue. Starting a fresh search with a fresh visited set from every land cell (instead of skipping cells already counted) costs O((rows · cols)²) on big islands, which the performance test rejects.
|
|
36
|
+
|
|
37
|
+
</details>
|
|
38
|
+
|
|
39
|
+
## Follow-ups an interviewer might ask
|
|
40
|
+
|
|
41
|
+
- You used recursion. A 1000 x 1000 grid of all land crashes it: why, and how do you fix it (explicit stack or BFS queue)?
|
|
42
|
+
- Count the islands of each size and return the sizes sorted.
|
|
43
|
+
- You may flip one water cell to land. What's the biggest island you can make (LeetCode 827)?
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { timeMs } from '../../lib/perf'
|
|
3
|
+
import { maxAreaOfIsland } from './solution'
|
|
4
|
+
|
|
5
|
+
/** Builds a rows x cols grid with land wherever isLand(r, c) is true. */
|
|
6
|
+
function gridWhere(rows: number, cols: number, isLand: (r: number, c: number) => boolean): number[][] {
|
|
7
|
+
return Array.from({ length: rows }, (_, r) => Array.from({ length: cols }, (_, c) => (isLand(r, c) ? 1 : 0)))
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
describe('219 max area of island', () => {
|
|
11
|
+
it('finds the bigger of two islands', () => {
|
|
12
|
+
expect(maxAreaOfIsland([[1, 1, 0, 0], [0, 1, 0, 1], [0, 0, 0, 1], [1, 0, 1, 1]])).toBe(4)
|
|
13
|
+
})
|
|
14
|
+
|
|
15
|
+
it('does not join diagonal neighbours', () => {
|
|
16
|
+
expect(maxAreaOfIsland([[0, 1, 0], [1, 0, 1], [0, 1, 0]])).toBe(1)
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
it('returns 0 when there is no land', () => {
|
|
20
|
+
expect(maxAreaOfIsland([[0, 0], [0, 0]])).toBe(0)
|
|
21
|
+
expect(maxAreaOfIsland([[0]])).toBe(0)
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
it('handles a single land cell and all land', () => {
|
|
25
|
+
expect(maxAreaOfIsland([[1]])).toBe(1)
|
|
26
|
+
expect(maxAreaOfIsland([[1, 1, 1], [1, 1, 1]])).toBe(6)
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
it('handles a single row and a single column', () => {
|
|
30
|
+
expect(maxAreaOfIsland([[1, 1, 0, 1, 1, 1, 0, 1]])).toBe(3)
|
|
31
|
+
expect(maxAreaOfIsland([[1], [0], [1], [1]])).toBe(2)
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
it('follows land that turns up or left', () => {
|
|
35
|
+
// A U shape: from the top-left, the top-right cell is only reached by going down, right, then up.
|
|
36
|
+
expect(maxAreaOfIsland([[1, 0, 1], [1, 1, 1]])).toBe(5)
|
|
37
|
+
// A ring with water in the middle.
|
|
38
|
+
expect(maxAreaOfIsland([[1, 1, 1], [1, 0, 1], [1, 1, 1]])).toBe(8)
|
|
39
|
+
// A spiral that winds back left and up.
|
|
40
|
+
expect(maxAreaOfIsland([[1, 1, 1, 1], [0, 0, 0, 1], [1, 1, 0, 1], [1, 0, 0, 1], [1, 1, 1, 1]])).toBe(14)
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
it('finds the biggest island when it is not the first one found', () => {
|
|
44
|
+
expect(maxAreaOfIsland([[1, 0, 0, 0, 1], [0, 0, 1, 0, 1], [0, 1, 1, 0, 1], [0, 0, 0, 0, 1]])).toBe(4)
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
it('counts islands touching every edge', () => {
|
|
48
|
+
expect(maxAreaOfIsland([[1, 1, 0, 1], [0, 0, 0, 1], [1, 0, 0, 1], [1, 1, 0, 1]])).toBe(4)
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
it('does not modify the grid', () => {
|
|
52
|
+
const grid = [[1, 1, 0], [0, 1, 1], [1, 0, 1]]
|
|
53
|
+
maxAreaOfIsland(grid)
|
|
54
|
+
expect(grid).toEqual([[1, 1, 0], [0, 1, 1], [1, 0, 1]])
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
it('measures a long winding island', () => {
|
|
58
|
+
// A 1-cell-wide snake through a 61 x 61 grid: every even row is land, joined at alternating ends.
|
|
59
|
+
const n = 61
|
|
60
|
+
const grid = gridWhere(n, n, (r, c) => r % 2 === 0 || (r % 4 === 1 && c === n - 1) || (r % 4 === 3 && c === 0))
|
|
61
|
+
expect(maxAreaOfIsland(grid)).toBe(31 * 61 + 30)
|
|
62
|
+
})
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
describe('219 performance', () => {
|
|
66
|
+
it('handles a 200 x 200 grid of 81 islands in under 300 ms (a fresh search from every land cell, O((rows·cols)²), is too slow here)', () => {
|
|
67
|
+
// 81 blocks of land separated by one-cell channels of water. Every block is 20 x 19 except
|
|
68
|
+
// the one in the middle, which keeps its 20th column, so it is the only biggest island.
|
|
69
|
+
const isChannel = (v: number): boolean => v % 21 === 20
|
|
70
|
+
const inMiddle = (v: number): boolean => v >= 84 && v <= 103
|
|
71
|
+
const grid = gridWhere(200, 200, (r, c) => {
|
|
72
|
+
const inBlock = !isChannel(r) && !isChannel(c) && r < 189 && c < 189
|
|
73
|
+
return inBlock && (c % 21 !== 19 || (inMiddle(r) && inMiddle(c)))
|
|
74
|
+
})
|
|
75
|
+
const ms = timeMs(() => expect(maxAreaOfIsland(grid)).toBe(20 * 20))
|
|
76
|
+
expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(300)
|
|
77
|
+
})
|
|
78
|
+
})
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# 220 · Pacific Atlantic Water Flow
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: graphs (multi-source DFS/BFS from the borders) · Target: 30 min · NeetCode 150 · LeetCode 417
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
`heights` is a rectangular island, one height per cell. The **Pacific** ocean runs along the island's top and left edges; the **Atlantic** runs along its bottom and right edges.
|
|
8
|
+
|
|
9
|
+
When rain falls on a cell, the water can run into a side neighbour (up, down, left or right) whose height is **less than or equal to** the current cell's, and keeps running from there. Water in a cell on an edge can run off into the ocean on that edge, so a corner cell touching both oceans reaches both.
|
|
10
|
+
|
|
11
|
+
Return the coordinates `[r, c]` of every cell from which water can reach **both** oceans. Return them in any order; the tests sort your answer. Don't modify `heights`.
|
|
12
|
+
|
|
13
|
+
## Examples
|
|
14
|
+
|
|
15
|
+
| `heights` | Output |
|
|
16
|
+
|---|---|
|
|
17
|
+
| `[[3, 3, 5], [2, 6, 4], [7, 1, 2]]` | `[[0, 2], [1, 1], [2, 0]]` (the 6 in the middle drains to the 3 above it and the 4 on its right) |
|
|
18
|
+
| `[[9]]` | `[[0, 0]]` |
|
|
19
|
+
| `[[1, 1], [1, 1]]` | all four cells (water runs between equal heights) |
|
|
20
|
+
|
|
21
|
+
## Constraints
|
|
22
|
+
|
|
23
|
+
- `1 <= rows, cols <= 200` (the performance test uses a 60 x 60 grid)
|
|
24
|
+
- `0 <= heights[r][c] <= 10^5`
|
|
25
|
+
- No test needs a search more than 3,600 cells deep, so a recursive solution won't overflow the call stack.
|
|
26
|
+
|
|
27
|
+
## Run it
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pnpm watch 220
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
34
|
+
|
|
35
|
+
Time O(rows · cols) · Space O(rows · cols). Following the water downhill from every cell separately costs O((rows · cols)²) when many cells can't reach an ocean, which the performance test rejects.
|
|
36
|
+
|
|
37
|
+
</details>
|
|
38
|
+
|
|
39
|
+
## Follow-ups an interviewer might ask
|
|
40
|
+
|
|
41
|
+
- Why is it easier to start from the oceans and walk *uphill* than to follow the rain downhill from each cell?
|
|
42
|
+
- Did you use DFS or BFS from the edges? Would the other one change the complexity?
|
|
43
|
+
- Return only the cells that reach exactly one ocean.
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { timeMs } from '../../lib/perf'
|
|
3
|
+
import { pacificAtlantic } from './solution'
|
|
4
|
+
|
|
5
|
+
type Cell = [number, number]
|
|
6
|
+
|
|
7
|
+
/** Sorts cells by row, then column, so any output order is accepted. */
|
|
8
|
+
const sorted = (cells: readonly (readonly number[])[]): number[][] =>
|
|
9
|
+
cells.map((cell) => [...cell]).sort((a, b) => a[0]! - b[0]! || a[1]! - b[1]!)
|
|
10
|
+
|
|
11
|
+
const flows = (heights: readonly (readonly number[])[]): number[][] => sorted(pacificAtlantic(heights))
|
|
12
|
+
|
|
13
|
+
/** Every cell of a rows x cols grid where keep(r, c) is true. */
|
|
14
|
+
function cellsWhere(rows: number, cols: number, keep: (r: number, c: number) => boolean): Cell[] {
|
|
15
|
+
const cells: Cell[] = []
|
|
16
|
+
for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) if (keep(r, c)) cells.push([r, c])
|
|
17
|
+
return cells
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
describe('220 pacific atlantic water flow', () => {
|
|
21
|
+
it('finds the corners and a peak that drains both ways', () => {
|
|
22
|
+
expect(flows([[3, 3, 5], [2, 6, 4], [7, 1, 2]])).toEqual([[0, 2], [1, 1], [2, 0]])
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
it('handles a single cell', () => {
|
|
26
|
+
expect(flows([[9]])).toEqual([[0, 0]])
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
it('lets water run between equal heights', () => {
|
|
30
|
+
expect(flows([[1, 1], [1, 1]])).toEqual([[0, 0], [0, 1], [1, 0], [1, 1]])
|
|
31
|
+
expect(flows([[4, 4, 4], [4, 4, 4], [4, 4, 4]])).toEqual(sorted(cellsWhere(3, 3, () => true)))
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
it('includes every cell of a single row or a single column', () => {
|
|
35
|
+
expect(flows([[5, 1, 8, 2]])).toEqual([[0, 0], [0, 1], [0, 2], [0, 3]])
|
|
36
|
+
expect(flows([[5], [1], [8]])).toEqual([[0, 0], [1, 0], [2, 0]])
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
it('leaves out a pit that cannot drain anywhere', () => {
|
|
40
|
+
expect(flows([[5, 5, 5], [5, 1, 5], [5, 5, 5]])).toEqual(sorted(cellsWhere(3, 3, (r, c) => r !== 1 || c !== 1)))
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
it('keeps only the Atlantic edge on a slope that falls towards the Pacific', () => {
|
|
44
|
+
// Every cell drains to the Pacific, but the middle cell can only run uphill towards the Atlantic.
|
|
45
|
+
expect(flows([[1, 2, 3], [2, 3, 4], [3, 4, 5]])).toEqual([[0, 2], [1, 2], [2, 0], [2, 1], [2, 2]])
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
it('follows water that has to turn up and left on its way', () => {
|
|
49
|
+
// The 9 drains straight into the Atlantic through the 8 below it. Its only way to the Pacific is a
|
|
50
|
+
// path that goes right, up, then left along the second row to the 1 on the left edge.
|
|
51
|
+
const heights = [
|
|
52
|
+
[20, 20, 20, 20, 20],
|
|
53
|
+
[1, 2, 3, 4, 20],
|
|
54
|
+
[20, 20, 20, 5, 20],
|
|
55
|
+
[20, 9, 7, 6, 20],
|
|
56
|
+
[20, 8, 20, 20, 20],
|
|
57
|
+
]
|
|
58
|
+
const result = flows(heights)
|
|
59
|
+
expect(result).toContainEqual([3, 1])
|
|
60
|
+
expect(result).not.toContainEqual([1, 0])
|
|
61
|
+
expect(result).not.toContainEqual([4, 1])
|
|
62
|
+
expect(result).toEqual(sorted([...cellsWhere(5, 5, (r, c) => heights[r]![c] === 20), [3, 1]]))
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
it('does not modify heights', () => {
|
|
66
|
+
const heights = [[3, 3, 5], [2, 6, 4], [7, 1, 2]]
|
|
67
|
+
pacificAtlantic(heights)
|
|
68
|
+
expect(heights).toEqual([[3, 3, 5], [2, 6, 4], [7, 1, 2]])
|
|
69
|
+
})
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
describe('220 performance', () => {
|
|
73
|
+
it('handles a 60 x 60 basin in under 300 ms (following the water from every cell, O((rows·cols)²), is too slow here)', () => {
|
|
74
|
+
// A ring of height 10 around a flat floor of height 5: only the ring reaches both oceans,
|
|
75
|
+
// and every one of the 3,364 floor cells is trapped inside it.
|
|
76
|
+
const n = 60
|
|
77
|
+
const onRing = (r: number, c: number): boolean => r === 0 || c === 0 || r === n - 1 || c === n - 1
|
|
78
|
+
const heights = Array.from({ length: n }, (_, r) => Array.from({ length: n }, (_, c) => (onRing(r, c) ? 10 : 5)))
|
|
79
|
+
let result: number[][] = []
|
|
80
|
+
const ms = timeMs(() => {
|
|
81
|
+
result = flows(heights)
|
|
82
|
+
})
|
|
83
|
+
expect(result).toEqual(sorted(cellsWhere(n, n, onRing)))
|
|
84
|
+
expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(300)
|
|
85
|
+
})
|
|
86
|
+
})
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# 221 · Course Schedule II
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: graphs (topological sort) · Target: 30 min · NeetCode 150 · LeetCode 210
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
A degree has `numCourses` courses, numbered `0` to `numCourses - 1`. Each pair `[a, b]` in `prerequisites` says course `b` must be finished before course `a` can start.
|
|
8
|
+
|
|
9
|
+
Return an order in which to take **every** course exactly once so that each course comes after all of its prerequisites. If several orders work, return any of them: the tests check that your order is valid rather than comparing it with one answer. If no order works, return an empty array.
|
|
10
|
+
|
|
11
|
+
## Examples
|
|
12
|
+
|
|
13
|
+
| `numCourses` | `prerequisites` | Output (one valid answer) |
|
|
14
|
+
|---|---|---|
|
|
15
|
+
| `3` | `[[2, 1], [1, 0]]` | `[0, 1, 2]` (the only valid order) |
|
|
16
|
+
| `5` | `[[1, 4], [3, 4], [0, 1], [0, 3]]` | `[4, 1, 3, 0, 2]` (also `[2, 4, 3, 1, 0]`, and others) |
|
|
17
|
+
| `3` | `[[0, 1], [1, 2], [2, 0]]` | `[]` (each course waits on another in a loop) |
|
|
18
|
+
|
|
19
|
+
## Constraints
|
|
20
|
+
|
|
21
|
+
- `1 <= numCourses <= 2100` (the performance test uses 2,048)
|
|
22
|
+
- `0 <= prerequisites.length <= 5000`, and every pair is distinct
|
|
23
|
+
- `0 <= a, b < numCourses`. A pair can have `a === b`: a course that requires itself, which makes an order impossible.
|
|
24
|
+
- The longest chain of prerequisites in any test is 2,000 courses, so a recursive solution won't overflow the call stack.
|
|
25
|
+
|
|
26
|
+
## Run it
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pnpm watch 221
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
33
|
+
|
|
34
|
+
Time O(V + E) · Space O(V + E), where V is `numCourses` and E is the number of pairs. A search that doesn't remember which courses are already placed revisits them along every path, which is exponential on the layered graph in the performance test.
|
|
35
|
+
|
|
36
|
+
</details>
|
|
37
|
+
|
|
38
|
+
## Follow-ups an interviewer might ask
|
|
39
|
+
|
|
40
|
+
- Did you use in-degree counting (Kahn's algorithm) or DFS post-order? Explain why your DFS output needs reversing (or doesn't).
|
|
41
|
+
- When several courses are available at once, return the order that is smallest in dictionary order. What changes?
|
|
42
|
+
- Group the courses into semesters, taking as many as possible each semester. How many semesters do you need?
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { timeMs } from '../../lib/perf'
|
|
3
|
+
import { findOrder } from './solution'
|
|
4
|
+
|
|
5
|
+
type Pair = [number, number]
|
|
6
|
+
|
|
7
|
+
/** Checks that `order` takes every course exactly once and puts each prerequisite before the course that needs it. */
|
|
8
|
+
function expectValidOrder(numCourses: number, prerequisites: readonly Pair[], order: readonly number[]): void {
|
|
9
|
+
expect([...order].sort((a, b) => a - b), 'every course exactly once').toEqual(
|
|
10
|
+
Array.from({ length: numCourses }, (_, i) => i),
|
|
11
|
+
)
|
|
12
|
+
const position = new Map(order.map((course, i) => [course, i]))
|
|
13
|
+
const broken = prerequisites.filter(([a, b]) => position.get(b)! > position.get(a)!)
|
|
14
|
+
expect(broken, 'pairs [a, b] where b comes after a').toEqual([])
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function expectOrder(numCourses: number, prerequisites: readonly Pair[]): void {
|
|
18
|
+
expectValidOrder(numCourses, prerequisites, findOrder(numCourses, prerequisites))
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Courses 0..n-1 in a line. forward: each course needs the one before it; otherwise the one after it. */
|
|
22
|
+
function chain(n: number, forward: boolean): Pair[] {
|
|
23
|
+
return Array.from({ length: n - 1 }, (_, i): Pair => (forward ? [i + 1, i] : [i, i + 1]))
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* `layers` layers of two courses each, starting at course `start`. Both courses in a layer need
|
|
28
|
+
* both courses in the next layer, so there are 2^layers distinct paths from the top to the bottom.
|
|
29
|
+
*/
|
|
30
|
+
function ladder(start: number, layers: number): Pair[] {
|
|
31
|
+
const pairs: Pair[] = []
|
|
32
|
+
for (let i = 0; i < layers - 1; i++) {
|
|
33
|
+
const a = start + 2 * i
|
|
34
|
+
for (const from of [a, a + 1]) pairs.push([from, a + 2], [from, a + 3])
|
|
35
|
+
}
|
|
36
|
+
return pairs
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
describe('221 course schedule II', () => {
|
|
40
|
+
it('orders a simple chain', () => {
|
|
41
|
+
expect(findOrder(3, [[2, 1], [1, 0]])).toEqual([0, 1, 2])
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
it('orders a graph with several valid answers', () => {
|
|
45
|
+
expectOrder(5, [[1, 4], [3, 4], [0, 1], [0, 3]])
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
it('returns an empty array for a cycle', () => {
|
|
49
|
+
expect(findOrder(3, [[0, 1], [1, 2], [2, 0]])).toEqual([])
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
it('handles a single course and no prerequisites', () => {
|
|
53
|
+
expect(findOrder(1, [])).toEqual([0])
|
|
54
|
+
expectOrder(4, [])
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
it('returns an empty array for a course that requires itself', () => {
|
|
58
|
+
expect(findOrder(3, [[1, 0], [2, 2]])).toEqual([])
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
it('returns an empty array for a two-course cycle', () => {
|
|
62
|
+
expect(findOrder(2, [[0, 1], [1, 0]])).toEqual([])
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
it('includes courses with no pairs at all', () => {
|
|
66
|
+
expectOrder(6, [[3, 1], [5, 3]])
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
it('orders a diamond, where one course is reached two ways', () => {
|
|
70
|
+
expectOrder(4, [[1, 0], [2, 0], [3, 1], [3, 2]])
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
it('detects a cycle in a component that does not contain course 0', () => {
|
|
74
|
+
expect(findOrder(6, [[1, 0], [3, 2], [4, 3], [2, 4]])).toEqual([])
|
|
75
|
+
expectOrder(6, [[1, 0], [3, 2], [4, 3], [5, 4]])
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
it('orders a graph where many courses share prerequisites', () => {
|
|
79
|
+
const pairs: Pair[] = [[4, 0], [4, 1], [5, 1], [5, 2], [6, 4], [6, 5], [6, 3], [7, 6], [7, 0]]
|
|
80
|
+
expectOrder(8, pairs)
|
|
81
|
+
expect(findOrder(8, [...pairs, [1, 7]])).toEqual([])
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
it('handles a 2,000-course chain in either direction', () => {
|
|
85
|
+
expect(findOrder(2_000, chain(2_000, true))).toEqual(Array.from({ length: 2_000 }, (_, i) => i))
|
|
86
|
+
expect(findOrder(2_000, chain(2_000, false))).toEqual(Array.from({ length: 2_000 }, (_, i) => 1_999 - i))
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
it('detects a cycle that closes a 2,000-course chain', () => {
|
|
90
|
+
expect(findOrder(2_000, [...chain(2_000, true), [0, 1_999]])).toEqual([])
|
|
91
|
+
})
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
describe('221 performance', () => {
|
|
95
|
+
it('orders a 2,000-course chain plus a 24-layer ladder in under 100 ms (a search that forgets placed courses is exponential here)', () => {
|
|
96
|
+
const chainLength = 2_000
|
|
97
|
+
const layers = 24
|
|
98
|
+
const numCourses = chainLength + 2 * layers
|
|
99
|
+
const pairs: Pair[] = [...chain(chainLength, false), ...ladder(chainLength, layers)]
|
|
100
|
+
let order: number[] = []
|
|
101
|
+
const ms = timeMs(() => {
|
|
102
|
+
order = findOrder(numCourses, pairs)
|
|
103
|
+
})
|
|
104
|
+
expectValidOrder(numCourses, pairs, order)
|
|
105
|
+
expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(100)
|
|
106
|
+
})
|
|
107
|
+
})
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# 222 · Graph Valid Tree
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: graphs (union-find or DFS) · Target: 25 min · NeetCode 150 · LeetCode 261
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
There are `n` nodes labelled `0` to `n - 1`. Each pair `[u, v]` in `edges` is an undirected edge between nodes `u` and `v`.
|
|
8
|
+
|
|
9
|
+
Return `true` if these edges make the `n` nodes into a single **tree**, and `false` otherwise. A tree here means every node can reach every other node, and there is exactly one route (no loops) between any two of them.
|
|
10
|
+
|
|
11
|
+
## Examples
|
|
12
|
+
|
|
13
|
+
| `n` | `edges` | Output | Why |
|
|
14
|
+
|---|---|---|---|
|
|
15
|
+
| `6` | `[[2, 0], [2, 5], [0, 4], [3, 2], [4, 1]]` | `true` | five edges join all six nodes without a loop |
|
|
16
|
+
| `4` | `[[0, 1], [1, 3], [3, 0]]` | `false` | 0, 1, 3 form a loop and node 2 is cut off |
|
|
17
|
+
| `4` | `[[0, 1], [2, 3]]` | `false` | two separate pieces |
|
|
18
|
+
|
|
19
|
+
## Constraints
|
|
20
|
+
|
|
21
|
+
- `1 <= n <= 10^4` (the performance test uses 10,000 nodes)
|
|
22
|
+
- `0 <= edges.length <= 2 · 10^4`
|
|
23
|
+
- `0 <= u, v < n`, `u !== v`, and no edge appears twice (in either direction).
|
|
24
|
+
- The deepest path from node 0 in any test is about 1,000 nodes, so a recursive solution won't overflow the call stack.
|
|
25
|
+
|
|
26
|
+
## Run it
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pnpm watch 222
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
33
|
+
|
|
34
|
+
Time O(n + E) (union-find with path compression is nearly the same: O(E · α(n))) · Space O(n + E) for an adjacency list, or O(n) for union-find. Searching the graph from scratch for every edge to see whether its ends are already connected is O(E · n), which the performance test rejects.
|
|
35
|
+
|
|
36
|
+
</details>
|
|
37
|
+
|
|
38
|
+
## Follow-ups an interviewer might ask
|
|
39
|
+
|
|
40
|
+
- What does knowing the number of edges tell you on its own? What does it not tell you?
|
|
41
|
+
- Union-find: what do path compression and union by rank each buy you?
|
|
42
|
+
- The edges arrive one at a time. After each one, report whether the graph is a tree yet.
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { timeMs } from '../../lib/perf'
|
|
3
|
+
import { validTree } from './solution'
|
|
4
|
+
|
|
5
|
+
type Edge = [number, number]
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* A "broom" on n nodes: a path 0-1-...-(spine-1), with every other node hanging off one spine node.
|
|
9
|
+
* The spine comes first, and the hanging edges alternate which end is listed first.
|
|
10
|
+
*/
|
|
11
|
+
function broom(n: number, spine: number): Edge[] {
|
|
12
|
+
const edges: Edge[] = Array.from({ length: spine - 1 }, (_, i): Edge => [i, i + 1])
|
|
13
|
+
for (let leaf = spine; leaf < n; leaf++) {
|
|
14
|
+
const hub = leaf % spine
|
|
15
|
+
edges.push(leaf % 2 === 0 ? [hub, leaf] : [leaf, hub])
|
|
16
|
+
}
|
|
17
|
+
return edges
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
describe('222 graph valid tree', () => {
|
|
21
|
+
it('accepts a tree', () => {
|
|
22
|
+
expect(validTree(6, [[2, 0], [2, 5], [0, 4], [3, 2], [4, 1]])).toBe(true)
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
it('rejects the right number of edges when they form a loop and leave a node out', () => {
|
|
26
|
+
expect(validTree(4, [[0, 1], [1, 3], [3, 0]])).toBe(false)
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
it('rejects two separate pieces', () => {
|
|
30
|
+
expect(validTree(4, [[0, 1], [2, 3]])).toBe(false)
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
it('accepts a single node with no edges', () => {
|
|
34
|
+
expect(validTree(1, [])).toBe(true)
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
it('rejects several nodes with no edges', () => {
|
|
38
|
+
expect(validTree(2, [])).toBe(false)
|
|
39
|
+
expect(validTree(5, [])).toBe(false)
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
it('accepts a single edge and a path', () => {
|
|
43
|
+
expect(validTree(2, [[1, 0]])).toBe(true)
|
|
44
|
+
expect(validTree(5, [[3, 4], [0, 1], [2, 3], [1, 2]])).toBe(true)
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
it('rejects a connected graph with one edge too many', () => {
|
|
48
|
+
expect(validTree(4, [[0, 1], [1, 2], [2, 3], [3, 1]])).toBe(false)
|
|
49
|
+
expect(validTree(3, [[0, 1], [1, 2], [0, 2]])).toBe(false)
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
it('accepts a tree whose edges do not touch node 0 first', () => {
|
|
53
|
+
expect(validTree(7, [[5, 6], [3, 4], [4, 6], [1, 2], [2, 4], [0, 1]])).toBe(true)
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
it('rejects a loop that does not contain node 0', () => {
|
|
57
|
+
// 5 edges for 6 nodes, but 3-4-5 is a loop, so 0-1-2 can't be joined to it.
|
|
58
|
+
expect(validTree(6, [[0, 1], [1, 2], [3, 4], [4, 5], [5, 3]])).toBe(false)
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
it('handles a 10,000-node broom, whole and with one edge moved', () => {
|
|
62
|
+
const edges = broom(10_000, 1_000)
|
|
63
|
+
expect(validTree(10_000, edges)).toBe(true)
|
|
64
|
+
// Moving the last edge so it joins two spine nodes leaves the last leaf cut off and closes a loop.
|
|
65
|
+
expect(validTree(10_000, [...edges.slice(0, -1), [0, 999]])).toBe(false)
|
|
66
|
+
})
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
describe('222 performance', () => {
|
|
70
|
+
it('checks a 10,000-node tree in under 150 ms (searching the graph again for every edge, O(n · E), is too slow here)', () => {
|
|
71
|
+
const edges = broom(10_000, 1_000)
|
|
72
|
+
const ms = timeMs(() => expect(validTree(10_000, edges)).toBe(true))
|
|
73
|
+
expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(150)
|
|
74
|
+
})
|
|
75
|
+
})
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# 223 · Redundant Connection
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: graphs (union-find) · Target: 25 min · NeetCode 150 · LeetCode 684
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
Someone started with a tree on the nodes `1` to `n` (connected, no loops) and then added **one** extra edge between two different nodes that weren't already directly joined. `edges` lists all `n` undirected edges of the result, so `edges.length === n`.
|
|
8
|
+
|
|
9
|
+
Find an edge you could delete to get a tree on all `n` nodes back. If more than one edge would work, return the one that comes **last** in `edges`. Return it exactly as it is written there (same order of the two nodes).
|
|
10
|
+
|
|
11
|
+
## Examples
|
|
12
|
+
|
|
13
|
+
| `edges` | Output | Why |
|
|
14
|
+
|---|---|---|
|
|
15
|
+
| `[[1, 3], [3, 4], [1, 2], [2, 4], [4, 5]]` | `[2, 4]` | the loop is 1-3-4-2-1; `[4, 5]` is later but not on it |
|
|
16
|
+
| `[[2, 1], [3, 1], [3, 2]]` | `[3, 2]` | all three edges form the loop |
|
|
17
|
+
| `[[1, 2], [2, 3], [3, 4], [4, 1], [1, 5]]` | `[4, 1]` | the loop is 1-2-3-4-1, and `[1, 5]` is a branch |
|
|
18
|
+
|
|
19
|
+
## Constraints
|
|
20
|
+
|
|
21
|
+
- `3 <= n <= 14,000` (the performance test uses 14,000 edges)
|
|
22
|
+
- `1 <= u, v <= n`, `u !== v`, and no edge appears twice (in either direction).
|
|
23
|
+
- The graph is connected, and has exactly one loop.
|
|
24
|
+
- No path in any test is longer than about 1,000 edges, so a recursive solution won't overflow the call stack.
|
|
25
|
+
|
|
26
|
+
## Run it
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pnpm watch 223
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
33
|
+
|
|
34
|
+
Time O(n · α(n)), which is effectively O(n) · Space O(n). Checking each edge with a fresh search of the graph built so far, or deleting each edge in turn and testing whether a tree is left, is O(n²), which the performance test rejects.
|
|
35
|
+
|
|
36
|
+
</details>
|
|
37
|
+
|
|
38
|
+
## Follow-ups an interviewer might ask
|
|
39
|
+
|
|
40
|
+
- Why is the first edge that joins two already-connected nodes also the *last* edge on the loop in input order?
|
|
41
|
+
- Without union-find: find every edge on the loop with one DFS, then pick the right one.
|
|
42
|
+
- The edges are directed and the result must be a rooted tree, where every node except the root has exactly one parent (LeetCode 685).
|