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,120 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { timeMs } from '../../lib/perf'
|
|
3
|
+
import { RandomListNode } from './node'
|
|
4
|
+
import { copyRandomList } from './solution'
|
|
5
|
+
|
|
6
|
+
type Spec = readonly (readonly [number, number | null])[]
|
|
7
|
+
|
|
8
|
+
/** Builds a list from [val, randomIndex] pairs. */
|
|
9
|
+
function build(spec: Spec): RandomListNode | null {
|
|
10
|
+
const nodes = spec.map(([val]) => new RandomListNode(val))
|
|
11
|
+
nodes.forEach((node, i) => {
|
|
12
|
+
node.next = nodes[i + 1] ?? null
|
|
13
|
+
const randomIndex = spec[i]![1]
|
|
14
|
+
node.random = randomIndex === null ? null : nodes[randomIndex]!
|
|
15
|
+
})
|
|
16
|
+
return nodes[0] ?? null
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** The nodes reachable through `next`, guarding against cycles. */
|
|
20
|
+
function nodesOf(head: RandomListNode | null, maxLength: number): RandomListNode[] {
|
|
21
|
+
const nodes: RandomListNode[] = []
|
|
22
|
+
for (let node = head; node; node = node.next) {
|
|
23
|
+
if (nodes.length >= maxLength) throw new Error('List is longer than expected — is there a cycle?')
|
|
24
|
+
nodes.push(node)
|
|
25
|
+
}
|
|
26
|
+
return nodes
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Describes a list as [val, randomIndex] pairs. A random pointer outside the list shows up as 'outside'. */
|
|
30
|
+
function describeList(head: RandomListNode | null, maxLength: number): (readonly [number, number | null | 'outside'])[] {
|
|
31
|
+
const nodes = nodesOf(head, maxLength)
|
|
32
|
+
const index = new Map(nodes.map((node, i) => [node, i]))
|
|
33
|
+
return nodes.map((node) => [node.val, node.random === null ? null : index.get(node.random) ?? 'outside'])
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Copies the list built from `spec`, checks the copy is deep and the original untouched, and describes the copy. */
|
|
37
|
+
function copied(spec: Spec): ReturnType<typeof describeList> {
|
|
38
|
+
const head = build(spec)
|
|
39
|
+
const originals = nodesOf(head, spec.length)
|
|
40
|
+
const before = originals.map((node) => ({ val: node.val, next: node.next, random: node.random }))
|
|
41
|
+
const copy = copyRandomList(head)
|
|
42
|
+
const copyNodes = nodesOf(copy, spec.length + 1)
|
|
43
|
+
const shared = copyNodes.filter((node) => originals.includes(node) || (node.random !== null && originals.includes(node.random)))
|
|
44
|
+
expect(shared, 'the copy must not use or point to any original node').toHaveLength(0)
|
|
45
|
+
originals.forEach((node, i) => {
|
|
46
|
+
expect({ val: node.val, next: node.next, random: node.random }, `original node ${i} was changed`).toEqual(before[i])
|
|
47
|
+
expect(node.next === before[i]!.next && node.random === before[i]!.random, `original node ${i} was relinked`).toBe(true)
|
|
48
|
+
})
|
|
49
|
+
return describeList(copy, spec.length + 1)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
describe('204 copy list with random pointer', () => {
|
|
53
|
+
it('copies a list with forward, backward and null random pointers', () => {
|
|
54
|
+
const spec = [[3, 2], [8, null], [3, 0]] as const
|
|
55
|
+
expect(copied(spec)).toEqual(spec)
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it('copies a node whose random points to itself', () => {
|
|
59
|
+
const spec = [[6, 0]] as const
|
|
60
|
+
expect(copied(spec)).toEqual(spec)
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
it('returns null for an empty list', () => {
|
|
64
|
+
expect(copyRandomList(null)).toBeNull()
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
it('copies a single node with no random pointer', () => {
|
|
68
|
+
expect(copied([[-4, null]])).toEqual([[-4, null]])
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
it('copies a list where every random is null', () => {
|
|
72
|
+
const spec = [[1, null], [2, null], [3, null], [4, null]] as const
|
|
73
|
+
expect(copied(spec)).toEqual(spec)
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
it('points each random at the copy in the same position, even when values repeat', () => {
|
|
77
|
+
const spec = [[7, 3], [7, 0], [7, 2], [7, 1], [7, null]] as const
|
|
78
|
+
expect(copied(spec)).toEqual(spec)
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
it('copies a list where every random points to the last node', () => {
|
|
82
|
+
const spec = [[0, 4], [-1, 4], [2, 4], [0, 4], [9, 4]] as const
|
|
83
|
+
expect(copied(spec)).toEqual(spec)
|
|
84
|
+
})
|
|
85
|
+
|
|
86
|
+
it('copies a list where every random points to the head', () => {
|
|
87
|
+
const spec = [[5, 0], [5, 0], [1, 0], [10_000, 0], [-10_000, 0]] as const
|
|
88
|
+
expect(copied(spec)).toEqual(spec)
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
it('copies two nodes pointing at each other', () => {
|
|
92
|
+
const spec = [[1, 1], [2, 0]] as const
|
|
93
|
+
expect(copied(spec)).toEqual(spec)
|
|
94
|
+
})
|
|
95
|
+
|
|
96
|
+
it('copies a longer list with mixed pointers', () => {
|
|
97
|
+
const spec: Spec = Array.from({ length: 200 }, (_, i) => [i % 7, i % 5 === 0 ? null : (i * 37 + 11) % 200])
|
|
98
|
+
expect(copied(spec)).toEqual(spec)
|
|
99
|
+
})
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
describe('204 performance', () => {
|
|
103
|
+
it('copies 30 lists of 5,000 nodes in under 300 ms (walking from the head to find each random is O(n²))', () => {
|
|
104
|
+
const n = 5_000
|
|
105
|
+
const lists = Array.from({ length: 30 }, (_, k) => {
|
|
106
|
+
const spec: Spec = Array.from({ length: n }, (_, i) => [i, i % 9 === 0 ? null : (i * 7_919 + k * 31 + 13) % n])
|
|
107
|
+
return { spec, head: build(spec) }
|
|
108
|
+
})
|
|
109
|
+
const copies: (RandomListNode | null)[] = []
|
|
110
|
+
const ms = timeMs(() => {
|
|
111
|
+
for (const { head } of lists) copies.push(copyRandomList(head))
|
|
112
|
+
})
|
|
113
|
+
lists.forEach(({ spec }, k) => {
|
|
114
|
+
const description = describeList(copies[k]!, n + 1)
|
|
115
|
+
expect(description.length).toBe(n)
|
|
116
|
+
expect(description.every(([val, random], i) => val === spec[i]![0] && random === spec[i]![1])).toBe(true)
|
|
117
|
+
})
|
|
118
|
+
expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(300)
|
|
119
|
+
})
|
|
120
|
+
})
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# 205 · Add Two Numbers
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: linked list (walk both lists with a carry) · Target: 25 min · NeetCode 150 · LeetCode 2
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
`l1` and `l2` each hold a non-negative whole number, one decimal digit per node, with the **ones digit first**. So `4 → 7 → 1` is the number 174.
|
|
8
|
+
|
|
9
|
+
Return a new list, in the same format, holding the sum of the two numbers.
|
|
10
|
+
|
|
11
|
+
- Each list has at least one node, and neither number has leading zeros (apart from the number 0 itself, which is the single node `0`). Your answer mustn't have leading zeros either.
|
|
12
|
+
- The numbers can be hundreds of digits long, far too big for a JavaScript `number`.
|
|
13
|
+
- Don't change the input lists: build the answer from new nodes. The tests check that `l1` and `l2` are untouched.
|
|
14
|
+
|
|
15
|
+
## Examples
|
|
16
|
+
|
|
17
|
+
| `l1` | `l2` | Output | Why |
|
|
18
|
+
|---|---|---|---|
|
|
19
|
+
| `[4, 7, 1]` | `[9, 3]` | `[3, 1, 2]` | 174 + 39 = 213 |
|
|
20
|
+
| `[5]` | `[5]` | `[0, 1]` | 5 + 5 = 10: the answer can be longer than both inputs |
|
|
21
|
+
| `[9, 9, 9, 9]` | `[1]` | `[0, 0, 0, 0, 1]` | 9999 + 1 = 10000 |
|
|
22
|
+
|
|
23
|
+
## Constraints
|
|
24
|
+
|
|
25
|
+
- Each list has `1` to `100` nodes in an interview (the tests go up to 400).
|
|
26
|
+
- Every `val` is a digit from `0` to `9`.
|
|
27
|
+
- There's no performance test: any sensible approach is linear. The long-number tests are there to catch converting the lists to a JavaScript `number`.
|
|
28
|
+
|
|
29
|
+
## Run it
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pnpm watch 205
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
36
|
+
|
|
37
|
+
Time O(max(m, n)) · Space O(max(m, n)) for the answer list, O(1) besides it. Converting the lists to numbers loses precision past about 15 digits, and the tests catch that.
|
|
38
|
+
|
|
39
|
+
</details>
|
|
40
|
+
|
|
41
|
+
## Follow-ups an interviewer might ask
|
|
42
|
+
|
|
43
|
+
- What if the digits were stored with the most significant digit first? (LeetCode 445)
|
|
44
|
+
- Can you write it recursively? What does the recursion cost in stack space?
|
|
45
|
+
- How would you subtract or multiply two numbers stored this way?
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { ListNode, listFrom, listToArray } from '../../lib/linked-list'
|
|
3
|
+
import { addTwoNumbers } from './solution'
|
|
4
|
+
|
|
5
|
+
function nodesOf(head: ListNode | null, maxLength: number): ListNode[] {
|
|
6
|
+
const nodes: ListNode[] = []
|
|
7
|
+
for (let node = head; node; node = node.next) {
|
|
8
|
+
if (nodes.length >= maxLength) throw new Error('List is longer than expected — is there a cycle?')
|
|
9
|
+
nodes.push(node)
|
|
10
|
+
}
|
|
11
|
+
return nodes
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Adds two digit lists (ones digit first), checks neither input changed, and returns the result's digits. */
|
|
15
|
+
function added(a: readonly number[], b: readonly number[]): number[] {
|
|
16
|
+
const l1 = listFrom(a)
|
|
17
|
+
const l2 = listFrom(b)
|
|
18
|
+
const inputs = [...nodesOf(l1, a.length), ...nodesOf(l2, b.length)]
|
|
19
|
+
const before = inputs.map((node) => ({ val: node.val, next: node.next }))
|
|
20
|
+
const result = addTwoNumbers(l1, l2)
|
|
21
|
+
inputs.forEach((node, i) => {
|
|
22
|
+
expect(node.val === before[i]!.val && node.next === before[i]!.next, 'an input list was changed').toBe(true)
|
|
23
|
+
})
|
|
24
|
+
const resultNodes = nodesOf(result, Math.max(a.length, b.length) + 1)
|
|
25
|
+
expect(resultNodes.some((node) => inputs.includes(node)), 'the answer reuses input nodes').toBe(false)
|
|
26
|
+
return listToArray(result, Math.max(a.length, b.length) + 1)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
describe('205 add two numbers', () => {
|
|
30
|
+
it('adds two numbers with a carry in the middle', () => {
|
|
31
|
+
expect(added([4, 7, 1], [9, 3])).toEqual([3, 1, 2])
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
it('adds zero and zero', () => {
|
|
35
|
+
expect(added([0], [0])).toEqual([0])
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
it('carries all the way past the end of the longer list', () => {
|
|
39
|
+
expect(added([9, 9, 9, 9], [1])).toEqual([0, 0, 0, 0, 1])
|
|
40
|
+
expect(added([1], [9, 9, 9, 9])).toEqual([0, 0, 0, 0, 1])
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
it('adds two single digits with and without a carry', () => {
|
|
44
|
+
expect(added([5], [5])).toEqual([0, 1])
|
|
45
|
+
expect(added([2], [6])).toEqual([8])
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
it('handles lists of different lengths in either order', () => {
|
|
49
|
+
expect(added([3, 0, 0, 0, 6], [8, 2])).toEqual([1, 3, 0, 0, 6])
|
|
50
|
+
expect(added([8, 2], [3, 0, 0, 0, 6])).toEqual([1, 3, 0, 0, 6])
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
it('adds zero to a number', () => {
|
|
54
|
+
expect(added([0], [7, 0, 4])).toEqual([7, 0, 4])
|
|
55
|
+
expect(added([7, 0, 4], [0])).toEqual([7, 0, 4])
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it('does not add a trailing zero when there is no final carry', () => {
|
|
59
|
+
expect(added([1, 2, 3], [4, 5, 6])).toEqual([5, 7, 9])
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
it('adds two 300-digit numbers (too big for a JavaScript number)', () => {
|
|
63
|
+
const a = Array.from({ length: 300 }, (_, i) => (i * 7 + 3) % 10)
|
|
64
|
+
const b = Array.from({ length: 300 }, (_, i) => 9 - ((i * 7 + 3) % 10))
|
|
65
|
+
// Every column sums to 9, so the answer is 300 nines.
|
|
66
|
+
expect(added(a, b)).toEqual(Array.from({ length: 300 }, () => 9))
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
it('carries through 400 nines', () => {
|
|
70
|
+
const nines = Array.from({ length: 400 }, () => 9)
|
|
71
|
+
expect(added(nines, [1])).toEqual([...Array.from({ length: 400 }, () => 0), 1])
|
|
72
|
+
expect(added(nines, nines)).toEqual([8, ...Array.from({ length: 399 }, () => 9), 1])
|
|
73
|
+
})
|
|
74
|
+
})
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# 206 · Find the Duplicate Number
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: fast and slow pointers (Floyd's cycle detection on index → value) · Target: 30 min · NeetCode 150 · LeetCode 287
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
`nums` holds `n + 1` integers, and every one of them is between `1` and `n` inclusive. So at least one value must repeat. Exactly one value repeats: it may appear twice or many more times, and every other value appears at most once (some values in `1..n` may be missing).
|
|
8
|
+
|
|
9
|
+
Return the repeated value.
|
|
10
|
+
|
|
11
|
+
Two rules make this harder than it looks:
|
|
12
|
+
|
|
13
|
+
- **Don't modify `nums`.** No sorting it, no writing marks into it, not even temporarily. The tests pass a frozen array, so any write throws.
|
|
14
|
+
- **Use only O(1) extra space.** No set, map, counting array or copy of `nums`. The tests can't measure memory, so this one is on your honour.
|
|
15
|
+
|
|
16
|
+
## Examples
|
|
17
|
+
|
|
18
|
+
| `nums` | Output |
|
|
19
|
+
|---|---|
|
|
20
|
+
| `[3, 1, 4, 2, 4]` | `4` |
|
|
21
|
+
| `[5, 2, 1, 3, 5, 4]` | `5` |
|
|
22
|
+
| `[2, 5, 2, 1, 2, 3]` | `2` |
|
|
23
|
+
| `[1, 1]` | `1` |
|
|
24
|
+
|
|
25
|
+
## Constraints
|
|
26
|
+
|
|
27
|
+
- `1 <= n <= 10^5`, `nums.length == n + 1` (the performance test uses n = 30,000)
|
|
28
|
+
- `1 <= nums[i] <= n`
|
|
29
|
+
- Exactly one value appears more than once.
|
|
30
|
+
|
|
31
|
+
## Run it
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pnpm watch 206
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
38
|
+
|
|
39
|
+
Time O(n) · Space O(1). The performance test rejects comparing every pair (O(n²) time). A set, or sorting a copy, passes the timer but breaks the O(1)-space rule. Counting how many values are `<= mid` and halving the range of values is O(n log n) time and O(1) space: a good answer, but not the best one.
|
|
40
|
+
|
|
41
|
+
</details>
|
|
42
|
+
|
|
43
|
+
## Follow-ups an interviewer might ask
|
|
44
|
+
|
|
45
|
+
- Prove that the repeated value is where the two walks meet the second time.
|
|
46
|
+
- Why does the O(n log n) approach that counts values `<= mid` work, and what does it rely on?
|
|
47
|
+
- What if you were allowed to modify `nums`? Could you do it in O(n) time and O(1) space more simply?
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { timeMs } from '../../lib/perf'
|
|
3
|
+
import { findDuplicate } from './solution'
|
|
4
|
+
|
|
5
|
+
/** Runs findDuplicate on a frozen copy, so any attempt to write to the input throws. */
|
|
6
|
+
function duplicateIn(values: readonly number[]): number {
|
|
7
|
+
return findDuplicate(Object.freeze([...values]))
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Deterministic shuffle (a small linear congruential generator), so runs are repeatable. */
|
|
11
|
+
function shuffled<T>(items: readonly T[], seed: number): T[] {
|
|
12
|
+
const out = [...items]
|
|
13
|
+
let state = seed
|
|
14
|
+
for (let i = out.length - 1; i > 0; i--) {
|
|
15
|
+
state = (state * 1_103_515_245 + 12_345) % 2_147_483_648
|
|
16
|
+
const j = state % (i + 1)
|
|
17
|
+
;[out[i], out[j]] = [out[j]!, out[i]!]
|
|
18
|
+
}
|
|
19
|
+
return out
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
describe('206 find the duplicate number', () => {
|
|
23
|
+
it('finds a value repeated twice', () => {
|
|
24
|
+
expect(duplicateIn([3, 1, 4, 2, 4])).toBe(4)
|
|
25
|
+
expect(duplicateIn([5, 2, 1, 3, 5, 4])).toBe(5)
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
it('finds a value repeated more than twice', () => {
|
|
29
|
+
expect(duplicateIn([2, 5, 2, 1, 2, 3])).toBe(2)
|
|
30
|
+
expect(duplicateIn([4, 4, 1, 4, 4])).toBe(4)
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
it('handles the smallest input', () => {
|
|
34
|
+
expect(duplicateIn([1, 1])).toBe(1)
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
it('handles every element being the same', () => {
|
|
38
|
+
expect(duplicateIn([3, 3, 3, 3])).toBe(3)
|
|
39
|
+
expect(duplicateIn([1, 1, 1, 1, 1, 1])).toBe(1)
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
it('finds the repeat at the very start and the very end', () => {
|
|
43
|
+
expect(duplicateIn([6, 2, 3, 1, 5, 4, 6])).toBe(6)
|
|
44
|
+
expect(duplicateIn([1, 1, 2, 3, 4, 5])).toBe(1)
|
|
45
|
+
expect(duplicateIn([2, 3, 4, 5, 1, 5])).toBe(5)
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
it('finds the smallest and largest possible values as the repeat', () => {
|
|
49
|
+
expect(duplicateIn([7, 1, 6, 1, 3, 2, 5, 4])).toBe(1)
|
|
50
|
+
expect(duplicateIn([7, 1, 6, 7, 3, 2, 5, 4])).toBe(7)
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
it('does not write to nums, even temporarily', () => {
|
|
54
|
+
const nums = Object.freeze([4, 3, 1, 4, 2])
|
|
55
|
+
expect(findDuplicate(nums)).toBe(4)
|
|
56
|
+
expect(nums).toEqual([4, 3, 1, 4, 2])
|
|
57
|
+
})
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
describe('206 performance', () => {
|
|
61
|
+
it('handles n = 30,000 in under 300 ms (comparing every pair is O(n²), too slow here)', () => {
|
|
62
|
+
const n = 30_000
|
|
63
|
+
// A shuffle of 1..n with the repeated value n moved to the second-to-last place, then n again at the end.
|
|
64
|
+
const order = shuffled(
|
|
65
|
+
Array.from({ length: n - 1 }, (_, i) => i + 1),
|
|
66
|
+
7,
|
|
67
|
+
)
|
|
68
|
+
const nums = Object.freeze([...order, n, n])
|
|
69
|
+
const ms = timeMs(() => expect(findDuplicate(nums)).toBe(n))
|
|
70
|
+
expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(300)
|
|
71
|
+
})
|
|
72
|
+
})
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# 207 · Count Good Nodes
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: trees (DFS, carrying the path maximum) · Target: 25 min · NeetCode 150 · LeetCode 1448
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
You get the `root` of a binary tree. Call a node **good** when no node on the path from the root down to it (including the root, and not counting the node itself) holds a value **strictly greater** than the node's own value. Ties are fine: a node equal to the largest value above it is still good.
|
|
8
|
+
|
|
9
|
+
Return how many good nodes the tree has. The root is always good, and an empty tree (`root` is `null`) has `0`.
|
|
10
|
+
|
|
11
|
+
## Examples
|
|
12
|
+
|
|
13
|
+
| Tree (level order) | Output | Good nodes |
|
|
14
|
+
|---|---|---|
|
|
15
|
+
| `[5, 2, 8, 4, null, 8, 1]` | `3` | `5`, `8` (child of 5), `8` (grandchild) |
|
|
16
|
+
| `[4, 4, null, 2, 7]` | `3` | `4`, `4`, `7` |
|
|
17
|
+
| `[-3]` | `1` | `-3` |
|
|
18
|
+
|
|
19
|
+
In the first tree, `2` and `4` both have the `5` above them, and `1` has the `5` and the `8`, so none of those count. In the second, the left `4` ties the root, which is allowed.
|
|
20
|
+
|
|
21
|
+
## Constraints
|
|
22
|
+
|
|
23
|
+
- `0 <= nodes <= 10^5` (one test uses about 100,000 nodes, another a 2,000-node chain)
|
|
24
|
+
- `-10^4 <= val <= 10^4`
|
|
25
|
+
|
|
26
|
+
## Run it
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pnpm watch 207
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
33
|
+
|
|
34
|
+
Time O(n) · Space O(h) for the recursion stack (or an explicit stack/queue), where `h` is the height: O(log n) for a balanced tree, O(n) for a chain.
|
|
35
|
+
|
|
36
|
+
There's no timed test: the natural slower version, re-walking from the root to each node, is O(n·h), which is only slow on deep trees. Mention it if you think of it.
|
|
37
|
+
|
|
38
|
+
</details>
|
|
39
|
+
|
|
40
|
+
## Follow-ups an interviewer might ask
|
|
41
|
+
|
|
42
|
+
- Write it iteratively (an explicit stack of `[node, maxSoFar]` pairs, or a BFS queue). When would you have to?
|
|
43
|
+
- Return the good nodes themselves, or the count per level, instead of the total.
|
|
44
|
+
- What if "good" meant strictly greater than everything above it? Which test changes?
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { rightSpine, TreeNode, treeFrom } from '../../lib/binary-tree'
|
|
3
|
+
import { goodNodes } from './solution'
|
|
4
|
+
|
|
5
|
+
const count = (levelOrder: (number | null)[]): number => goodNodes(treeFrom(levelOrder))
|
|
6
|
+
|
|
7
|
+
/** A chain where every node is the left child of the one before it, with the given values from the top down. */
|
|
8
|
+
function leftChain(values: readonly number[]): TreeNode | null {
|
|
9
|
+
let root: TreeNode | null = null
|
|
10
|
+
for (let i = values.length - 1; i >= 0; i--) root = new TreeNode(values[i], root, null)
|
|
11
|
+
return root
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
describe('207 count good nodes', () => {
|
|
15
|
+
it('runs the README examples', () => {
|
|
16
|
+
expect(count([5, 2, 8, 4, null, 8, 1])).toBe(3)
|
|
17
|
+
expect(count([4, 4, null, 2, 7])).toBe(3)
|
|
18
|
+
expect(count([-3])).toBe(1)
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
it('returns 0 for an empty tree', () => {
|
|
22
|
+
expect(goodNodes(null)).toBe(0)
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
it('counts a node equal to the largest value above it as good', () => {
|
|
26
|
+
expect(count([2, 2, 2, 2, null, null, 2])).toBe(5)
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
it('compares against the whole path, not just the parent', () => {
|
|
30
|
+
// 3 is bigger than its parent 1, but the root 5 is above it.
|
|
31
|
+
expect(count([5, 1, null, 3])).toBe(1)
|
|
32
|
+
// 6 beats everything above it; 4 and 5 under the 6 don't.
|
|
33
|
+
expect(count([3, 1, null, 6, null, 4, 5])).toBe(2)
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
it('counts only the root when every path decreases', () => {
|
|
37
|
+
expect(count([10, 7, 9, 3, 6, 8, 1])).toBe(1)
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
it('handles all-negative values', () => {
|
|
41
|
+
// -1 at the root; -1 below it ties, -5 and -2 don't; -1 under -2 ties again.
|
|
42
|
+
expect(count([-1, -5, -1, null, null, -2, null, -1])).toBe(3)
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
it('handles zero and a path that dips and recovers', () => {
|
|
46
|
+
expect(count([0, -4, 4, 0, null, 3, 9])).toBe(4)
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
it('handles 2,000-node chains', () => {
|
|
50
|
+
// Values 1..2000 going down: each one is a new maximum.
|
|
51
|
+
expect(goodNodes(rightSpine(2_000))).toBe(2_000)
|
|
52
|
+
// Values 2000..1 going down: only the root.
|
|
53
|
+
expect(goodNodes(leftChain(Array.from({ length: 2_000 }, (_, i) => 2_000 - i)))).toBe(1)
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
it('handles a complete tree of 100,000 nodes', () => {
|
|
57
|
+
// Left children hold their depth (a new maximum on every path); right children hold -1 (never good).
|
|
58
|
+
const n = 100_000
|
|
59
|
+
const depth = (i: number): number => 31 - Math.clz32(i + 1)
|
|
60
|
+
const values = Array.from({ length: n }, (_, i) => (i === 0 ? 0 : i % 2 === 1 ? depth(i) : -1))
|
|
61
|
+
expect(count(values)).toBe(1 + Math.floor(n / 2))
|
|
62
|
+
})
|
|
63
|
+
})
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# 208 · Construct Tree from Preorder and Inorder
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: trees (recursion with an index map) · Target: 30 min · NeetCode 150 · LeetCode 105
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
A binary tree was written down twice:
|
|
8
|
+
|
|
9
|
+
- `preorder`: each node, then its whole left subtree, then its whole right subtree.
|
|
10
|
+
- `inorder`: each node's whole left subtree, then the node, then its whole right subtree.
|
|
11
|
+
|
|
12
|
+
Every value in the tree is different, and both lists describe the same tree. Rebuild that tree and return its root, as a `TreeNode` from `lib/binary-tree.ts`. Empty lists mean an empty tree: return `null`.
|
|
13
|
+
|
|
14
|
+
The tree isn't a search tree, so `inorder` is not necessarily sorted. Don't modify either input.
|
|
15
|
+
|
|
16
|
+
## Examples
|
|
17
|
+
|
|
18
|
+
Outputs are shown in level order (as `treeToArray` prints them).
|
|
19
|
+
|
|
20
|
+
| `preorder` | `inorder` | Output |
|
|
21
|
+
|---|---|---|
|
|
22
|
+
| `[7, 3, 1, 5, 9, 8]` | `[1, 3, 5, 7, 8, 9]` | `[7, 3, 9, 1, 5, 8]` |
|
|
23
|
+
| `[4, 6, 2]` | `[6, 2, 4]` | `[4, 6, null, null, 2]` |
|
|
24
|
+
| `[-1]` | `[-1]` | `[-1]` |
|
|
25
|
+
|
|
26
|
+
In the second example, `4` comes first in `preorder`, so it's the root. In `inorder`, both `6` and `2` sit before the `4`, so they form its left subtree and the right subtree is empty.
|
|
27
|
+
|
|
28
|
+
## Constraints
|
|
29
|
+
|
|
30
|
+
- `0 <= preorder.length == inorder.length <= 3 × 10^5`; values are unique integers.
|
|
31
|
+
- The performance test rebuilds a tree of 240,080 nodes that is up to about 3,080 levels deep (80 chains of 3,000 nodes hanging off a spine). Recursion that deep is fine here.
|
|
32
|
+
|
|
33
|
+
## Run it
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pnpm watch 208
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
40
|
+
|
|
41
|
+
Time O(n) · Space O(n) for the value → in-order position map, plus O(h) recursion stack.
|
|
42
|
+
|
|
43
|
+
Searching `inorder` for each root (`indexOf`) costs O(n) per node, so O(n²) overall, and the performance test rejects it: look positions up in a map built once. Copying sub-arrays with `slice` at each step costs O(size of the subtree), so O(n·h), which is O(n²) on deep trees; even with a map, that fails the performance test here (about 165 ms against 120 ms). Passing index ranges instead of copies avoids the question.
|
|
44
|
+
|
|
45
|
+
</details>
|
|
46
|
+
|
|
47
|
+
## Follow-ups an interviewer might ask
|
|
48
|
+
|
|
49
|
+
- Why must the values be unique? Show two different trees that give the same pair of lists when they aren't.
|
|
50
|
+
- Rebuild from `inorder` and `postorder` instead (LeetCode 106). What changes?
|
|
51
|
+
- Can you rebuild it from `preorder` and `postorder` alone? When is the answer ambiguous?
|
|
52
|
+
- Write it without recursion, for trees too deep for the call stack.
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { TreeNode, treeToArray } from '../../lib/binary-tree'
|
|
3
|
+
import { timeMs } from '../../lib/perf'
|
|
4
|
+
import { buildTree } from './solution'
|
|
5
|
+
|
|
6
|
+
const build = (preorder: number[], inorder: number[]): (number | null)[] => treeToArray(buildTree(preorder, inorder))
|
|
7
|
+
|
|
8
|
+
/** Pre-order values, without recursion (test trees can be deep). */
|
|
9
|
+
function preorderOf(root: TreeNode | null): number[] {
|
|
10
|
+
const out: number[] = []
|
|
11
|
+
const stack: TreeNode[] = root ? [root] : []
|
|
12
|
+
while (stack.length > 0) {
|
|
13
|
+
const node = stack.pop()!
|
|
14
|
+
out.push(node.val)
|
|
15
|
+
if (node.right) stack.push(node.right)
|
|
16
|
+
if (node.left) stack.push(node.left)
|
|
17
|
+
}
|
|
18
|
+
return out
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** In-order values, without recursion. */
|
|
22
|
+
function inorderOf(root: TreeNode | null): number[] {
|
|
23
|
+
const out: number[] = []
|
|
24
|
+
const stack: TreeNode[] = []
|
|
25
|
+
let node = root
|
|
26
|
+
while (node || stack.length > 0) {
|
|
27
|
+
while (node) {
|
|
28
|
+
stack.push(node)
|
|
29
|
+
node = node.left
|
|
30
|
+
}
|
|
31
|
+
node = stack.pop()!
|
|
32
|
+
out.push(node.val)
|
|
33
|
+
node = node.right
|
|
34
|
+
}
|
|
35
|
+
return out
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Deterministic shuffle of 0..n-1 (Fisher-Yates with a seeded MINSTD generator), so test data is the same every run. */
|
|
39
|
+
function shuffledRange(n: number, seed: number): number[] {
|
|
40
|
+
const out = Array.from({ length: n }, (_, i) => i)
|
|
41
|
+
let state = seed
|
|
42
|
+
for (let i = n - 1; i > 0; i--) {
|
|
43
|
+
state = (state * 48_271) % 2_147_483_647
|
|
44
|
+
const j = state % (i + 1)
|
|
45
|
+
;[out[i], out[j]] = [out[j]!, out[i]!]
|
|
46
|
+
}
|
|
47
|
+
return out
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* A right-leaning spine of `chains` nodes; each spine node's left child starts a left-only chain of
|
|
52
|
+
* `chainLength` nodes. Deep enough to punish per-node copying or searching, shallow enough for recursion.
|
|
53
|
+
*/
|
|
54
|
+
function chainsOffSpine(chains: number, chainLength: number): TreeNode | null {
|
|
55
|
+
const values = shuffledRange(chains * (chainLength + 1), 7).map((v) => v - 100_000)
|
|
56
|
+
let next = 0
|
|
57
|
+
let root: TreeNode | null = null
|
|
58
|
+
for (let c = 0; c < chains; c++) {
|
|
59
|
+
let chain: TreeNode | null = null
|
|
60
|
+
for (let i = 0; i < chainLength; i++) chain = new TreeNode(values[next++], chain, null)
|
|
61
|
+
root = new TreeNode(values[next++], chain, root)
|
|
62
|
+
}
|
|
63
|
+
return root
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
describe('208 construct tree from preorder and inorder', () => {
|
|
67
|
+
it('runs the README examples', () => {
|
|
68
|
+
expect(build([7, 3, 1, 5, 9, 8], [1, 3, 5, 7, 8, 9])).toEqual([7, 3, 9, 1, 5, 8])
|
|
69
|
+
expect(build([4, 6, 2], [6, 2, 4])).toEqual([4, 6, null, null, 2])
|
|
70
|
+
expect(build([-1], [-1])).toEqual([-1])
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
it('returns null for empty input', () => {
|
|
74
|
+
expect(buildTree([], [])).toBeNull()
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
it('handles values that are not in sorted order', () => {
|
|
78
|
+
// Not a search tree: the in-order list is not sorted.
|
|
79
|
+
expect(build([10, 30, 20, 40, 50], [20, 30, 10, 50, 40])).toEqual([10, 30, 40, 20, null, 50])
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
it('handles a left-only chain and a right-only chain', () => {
|
|
83
|
+
expect(build([1, 2, 3, 4], [4, 3, 2, 1])).toEqual([1, 2, null, 3, null, 4])
|
|
84
|
+
expect(build([1, 2, 3, 4], [1, 2, 3, 4])).toEqual([1, null, 2, null, 3, null, 4])
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
it('handles a zigzag path', () => {
|
|
88
|
+
// 5 -> left 9 -> right 2 -> left 8
|
|
89
|
+
expect(build([5, 9, 2, 8], [9, 8, 2, 5])).toEqual([5, 9, null, null, 2, 8])
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
it('handles negatives and zero', () => {
|
|
93
|
+
expect(build([0, -3, -7, 6, -1], [-7, -3, 0, -1, 6])).toEqual([0, -3, 6, -7, null, -1])
|
|
94
|
+
})
|
|
95
|
+
|
|
96
|
+
it('does not modify the inputs', () => {
|
|
97
|
+
const preorder = [3, 9, 1, 2]
|
|
98
|
+
const inorder = [9, 3, 2, 1]
|
|
99
|
+
buildTree(preorder, inorder)
|
|
100
|
+
expect(preorder).toEqual([3, 9, 1, 2])
|
|
101
|
+
expect(inorder).toEqual([9, 3, 2, 1])
|
|
102
|
+
})
|
|
103
|
+
|
|
104
|
+
it('rebuilds a 2,000-node chain', () => {
|
|
105
|
+
const values = Array.from({ length: 2_000 }, (_, i) => 2 * i - 1_000)
|
|
106
|
+
const root = buildTree(values, [...values].reverse())
|
|
107
|
+
expect(preorderOf(root)).toEqual(values)
|
|
108
|
+
expect(inorderOf(root)).toEqual([...values].reverse())
|
|
109
|
+
})
|
|
110
|
+
})
|
|
111
|
+
|
|
112
|
+
describe('208 performance', () => {
|
|
113
|
+
it('rebuilds a 240,080-node tree made of 80 chains of 3,000 nodes in under 120 ms (searching the in-order list for each root is too slow here)', () => {
|
|
114
|
+
const original = chainsOffSpine(80, 3_000)
|
|
115
|
+
const preorder = preorderOf(original)
|
|
116
|
+
const inorder = inorderOf(original)
|
|
117
|
+
let root: TreeNode | null = null
|
|
118
|
+
const ms = timeMs(() => {
|
|
119
|
+
root = buildTree(preorder, inorder)
|
|
120
|
+
})
|
|
121
|
+
// Values are unique, so matching both orders means it's the same tree.
|
|
122
|
+
expect(preorderOf(root)).toEqual(preorder)
|
|
123
|
+
expect(inorderOf(root)).toEqual(inorder)
|
|
124
|
+
expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(120)
|
|
125
|
+
})
|
|
126
|
+
})
|