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,55 @@
|
|
|
1
|
+
# 122 · LRU Cache
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: design (hash map + doubly linked list) · Target: 30 min · NeetCode 150 · LeetCode 146
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
Build a key–value cache with a fixed `capacity` that evicts the **least recently used** entry when it runs out of room. Export a class `LRUCache` with:
|
|
8
|
+
|
|
9
|
+
- `constructor(capacity)`: an empty cache that holds at most `capacity` entries.
|
|
10
|
+
- `get(key)`: return the value stored for `key`, or `-1` if it isn't there. A successful `get` counts as a use.
|
|
11
|
+
- `put(key, value)`: store `value` under `key`, replacing any old value. This also counts as a use. If adding a **new** key pushes the size above `capacity`, first remove the entry that has gone longest without being used.
|
|
12
|
+
|
|
13
|
+
Both `get` and `put` must run in O(1) on average.
|
|
14
|
+
|
|
15
|
+
## Examples
|
|
16
|
+
|
|
17
|
+
`capacity = 2`, then:
|
|
18
|
+
|
|
19
|
+
| Call | Returns | Cache afterwards (least → most recent) |
|
|
20
|
+
|---|---|---|
|
|
21
|
+
| `put(1, 1)` | | `1` |
|
|
22
|
+
| `put(2, 2)` | | `1, 2` |
|
|
23
|
+
| `get(1)` | `1` | `2, 1` |
|
|
24
|
+
| `put(3, 3)` | | `1, 3` (evicts 2) |
|
|
25
|
+
| `get(2)` | `-1` | `1, 3` |
|
|
26
|
+
| `put(4, 4)` | | `3, 4` (evicts 1) |
|
|
27
|
+
| `get(1)` | `-1` | `3, 4` |
|
|
28
|
+
| `get(3)` | `3` | `4, 3` |
|
|
29
|
+
| `get(4)` | `4` | `3, 4` |
|
|
30
|
+
|
|
31
|
+
## Constraints
|
|
32
|
+
|
|
33
|
+
- `1 <= capacity <= 3000` on LeetCode. The performance test uses `capacity = 50,000` and about 200,000 calls, so anything that scans the cache on each call is too slow.
|
|
34
|
+
- `0 <= key <= 10^5`, `0 <= value <= 10^5`. Note that `0` is a valid key and a valid value.
|
|
35
|
+
|
|
36
|
+
## Run it
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pnpm watch 122
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
43
|
+
|
|
44
|
+
O(1) average for `get` and `put` · Space O(capacity).
|
|
45
|
+
|
|
46
|
+
In JavaScript a `Map` iterates in insertion order, so deleting and re-inserting a key moves it to the "most recent" end, and `map.keys().next()` gives the least recent one. That passes the tests and is worth mentioning. Interviewers very often ask for the language-neutral version anyway: a hash map from key to node, plus a doubly linked list ordered by recency, with dummy head and tail nodes. Be ready to write that one too.
|
|
47
|
+
|
|
48
|
+
</details>
|
|
49
|
+
|
|
50
|
+
## Follow-ups an interviewer might ask
|
|
51
|
+
|
|
52
|
+
- Write it without relying on `Map`'s insertion order.
|
|
53
|
+
- Why a **doubly** linked list? What goes wrong with a singly linked one?
|
|
54
|
+
- How would you make it safe for concurrent access?
|
|
55
|
+
- How would you add expiry times (TTL) to entries? Or an LFU policy (LeetCode 460)?
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { timeMs } from '../../lib/perf'
|
|
3
|
+
import { LRUCache } from './solution'
|
|
4
|
+
|
|
5
|
+
describe('122 lru cache', () => {
|
|
6
|
+
it('runs the README example', () => {
|
|
7
|
+
const cache = new LRUCache(2)
|
|
8
|
+
cache.put(1, 1)
|
|
9
|
+
cache.put(2, 2)
|
|
10
|
+
expect(cache.get(1)).toBe(1)
|
|
11
|
+
cache.put(3, 3)
|
|
12
|
+
expect(cache.get(2)).toBe(-1)
|
|
13
|
+
cache.put(4, 4)
|
|
14
|
+
expect(cache.get(1)).toBe(-1)
|
|
15
|
+
expect(cache.get(3)).toBe(3)
|
|
16
|
+
expect(cache.get(4)).toBe(4)
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
it('returns -1 for a key it has never seen', () => {
|
|
20
|
+
const cache = new LRUCache(3)
|
|
21
|
+
expect(cache.get(7)).toBe(-1)
|
|
22
|
+
cache.put(1, 10)
|
|
23
|
+
expect(cache.get(7)).toBe(-1)
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
it('stores 0 as a key and as a value', () => {
|
|
27
|
+
const cache = new LRUCache(2)
|
|
28
|
+
cache.put(0, 0)
|
|
29
|
+
expect(cache.get(0)).toBe(0)
|
|
30
|
+
cache.put(1, 0)
|
|
31
|
+
expect(cache.get(1)).toBe(0)
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
it('with capacity 1, each new key evicts the previous one', () => {
|
|
35
|
+
const cache = new LRUCache(1)
|
|
36
|
+
cache.put(2, 1)
|
|
37
|
+
expect(cache.get(2)).toBe(1)
|
|
38
|
+
cache.put(3, 2)
|
|
39
|
+
expect(cache.get(2)).toBe(-1)
|
|
40
|
+
expect(cache.get(3)).toBe(2)
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
it('updating an existing key replaces the value without evicting anything', () => {
|
|
44
|
+
const cache = new LRUCache(2)
|
|
45
|
+
cache.put(1, 1)
|
|
46
|
+
cache.put(2, 2)
|
|
47
|
+
cache.put(1, 10)
|
|
48
|
+
expect(cache.get(1)).toBe(10)
|
|
49
|
+
expect(cache.get(2)).toBe(2)
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
it('updating an existing key makes it the most recently used', () => {
|
|
53
|
+
const cache = new LRUCache(2)
|
|
54
|
+
cache.put(1, 1)
|
|
55
|
+
cache.put(2, 2)
|
|
56
|
+
cache.put(1, 5) // 2 is now the least recently used
|
|
57
|
+
cache.put(3, 3)
|
|
58
|
+
expect(cache.get(2)).toBe(-1)
|
|
59
|
+
expect(cache.get(1)).toBe(5)
|
|
60
|
+
expect(cache.get(3)).toBe(3)
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
it('a successful get makes the key the most recently used', () => {
|
|
64
|
+
const cache = new LRUCache(3)
|
|
65
|
+
cache.put(1, 1)
|
|
66
|
+
cache.put(2, 2)
|
|
67
|
+
cache.put(3, 3)
|
|
68
|
+
expect(cache.get(1)).toBe(1) // order is now 2, 3, 1
|
|
69
|
+
cache.put(4, 4) // evicts 2
|
|
70
|
+
expect(cache.get(2)).toBe(-1)
|
|
71
|
+
cache.put(5, 5) // evicts 3
|
|
72
|
+
expect(cache.get(3)).toBe(-1)
|
|
73
|
+
expect(cache.get(1)).toBe(1)
|
|
74
|
+
expect(cache.get(4)).toBe(4)
|
|
75
|
+
expect(cache.get(5)).toBe(5)
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
it('a missed get does not change the order', () => {
|
|
79
|
+
const cache = new LRUCache(2)
|
|
80
|
+
cache.put(1, 1)
|
|
81
|
+
cache.put(2, 2)
|
|
82
|
+
expect(cache.get(9)).toBe(-1)
|
|
83
|
+
cache.put(3, 3)
|
|
84
|
+
expect(cache.get(1)).toBe(-1)
|
|
85
|
+
expect(cache.get(2)).toBe(2)
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
it('can re-add a key after it was evicted', () => {
|
|
89
|
+
const cache = new LRUCache(2)
|
|
90
|
+
cache.put(1, 1)
|
|
91
|
+
cache.put(2, 2)
|
|
92
|
+
cache.put(3, 3) // evicts 1
|
|
93
|
+
cache.put(1, 100) // evicts 2
|
|
94
|
+
expect(cache.get(1)).toBe(100)
|
|
95
|
+
expect(cache.get(2)).toBe(-1)
|
|
96
|
+
expect(cache.get(3)).toBe(3)
|
|
97
|
+
})
|
|
98
|
+
|
|
99
|
+
it('keeps separate caches independent', () => {
|
|
100
|
+
const a = new LRUCache(1)
|
|
101
|
+
const b = new LRUCache(1)
|
|
102
|
+
a.put(1, 1)
|
|
103
|
+
b.put(2, 2)
|
|
104
|
+
expect(a.get(1)).toBe(1)
|
|
105
|
+
expect(a.get(2)).toBe(-1)
|
|
106
|
+
expect(b.get(2)).toBe(2)
|
|
107
|
+
expect(b.get(1)).toBe(-1)
|
|
108
|
+
})
|
|
109
|
+
})
|
|
110
|
+
|
|
111
|
+
describe('122 performance', () => {
|
|
112
|
+
it('handles capacity 50,000 and 205,000 calls in under 200 ms (scanning the cache on each call is too slow here)', () => {
|
|
113
|
+
const capacity = 50_000
|
|
114
|
+
const newKeys = 5_000
|
|
115
|
+
// Each order visits every key 0..capacity-1 exactly once, scrambled.
|
|
116
|
+
const firstOrder = Array.from({ length: capacity }, (_, i) => (i * 7_919) % capacity)
|
|
117
|
+
const secondOrder = Array.from({ length: capacity }, (_, i) => (i * 12_347) % capacity)
|
|
118
|
+
// Pass 1 below reads keys at even positions of firstOrder and overwrites those at odd positions with 3k.
|
|
119
|
+
const valueAfterPass1 = new Array<number>(capacity)
|
|
120
|
+
firstOrder.forEach((k, i) => {
|
|
121
|
+
valueAfterPass1[k] = i % 2 === 0 ? 2 * k : 3 * k
|
|
122
|
+
})
|
|
123
|
+
const mismatches: string[] = []
|
|
124
|
+
const check = (actual: number, expected: number, label: string): void => {
|
|
125
|
+
if (actual !== expected && mismatches.length < 5) mismatches.push(`${label}: got ${actual}, expected ${expected}`)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const ms = timeMs(() => {
|
|
129
|
+
const cache = new LRUCache(capacity)
|
|
130
|
+
// Fill the cache: key k holds 2k.
|
|
131
|
+
for (let k = 0; k < capacity; k++) cache.put(k, 2 * k)
|
|
132
|
+
// Pass 1: touch every key in firstOrder.
|
|
133
|
+
firstOrder.forEach((k, i) => {
|
|
134
|
+
if (i % 2 === 0) check(cache.get(k), 2 * k, `pass 1 get(${k})`)
|
|
135
|
+
else cache.put(k, 3 * k)
|
|
136
|
+
})
|
|
137
|
+
// Pass 2: read every key in secondOrder, which becomes the recency order.
|
|
138
|
+
for (const k of secondOrder) check(cache.get(k), valueAfterPass1[k]!, `pass 2 get(${k})`)
|
|
139
|
+
// Add new keys; each one evicts the next key at the front of secondOrder.
|
|
140
|
+
for (let k = capacity; k < capacity + newKeys; k++) cache.put(k, 1)
|
|
141
|
+
// The rest of secondOrder is still cached; its first `newKeys` keys are gone.
|
|
142
|
+
for (let i = newKeys; i < capacity; i++) {
|
|
143
|
+
const k = secondOrder[i]!
|
|
144
|
+
check(cache.get(k), valueAfterPass1[k]!, `get(${k}) after evictions`)
|
|
145
|
+
}
|
|
146
|
+
for (let i = 0; i < newKeys; i++) check(cache.get(secondOrder[i]!), -1, `get(${secondOrder[i]}) should be evicted`)
|
|
147
|
+
})
|
|
148
|
+
|
|
149
|
+
expect(mismatches).toEqual([])
|
|
150
|
+
expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(200)
|
|
151
|
+
})
|
|
152
|
+
})
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# 123 · Binary Tree Level Order Traversal
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: trees (BFS) · Target: 25 min · NeetCode 150 · LeetCode 102
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
Given the root of a binary tree, list its values level by level. Return an array with one inner array per depth, starting at the root. Within each level, values go from left to right.
|
|
8
|
+
|
|
9
|
+
An empty tree gives `[]`.
|
|
10
|
+
|
|
11
|
+
## Examples
|
|
12
|
+
|
|
13
|
+
| Tree (level order) | Output |
|
|
14
|
+
|---|---|
|
|
15
|
+
| `[3, 9, 20, null, null, 15, 7]` | `[[3], [9, 20], [15, 7]]` |
|
|
16
|
+
| `[1]` | `[[1]]` |
|
|
17
|
+
| `[]` | `[]` |
|
|
18
|
+
|
|
19
|
+
## Constraints
|
|
20
|
+
|
|
21
|
+
- `0 <= nodes <= 2000` (one test is a 2,000-node chain)
|
|
22
|
+
- `-1000 <= val <= 1000`
|
|
23
|
+
|
|
24
|
+
## Run it
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pnpm watch 123
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
31
|
+
|
|
32
|
+
Time O(n) · Space O(w), where `w` is the widest level (up to about n/2 in a full tree). A recursive DFS that passes the depth down also works in O(n) time and O(h) stack.
|
|
33
|
+
|
|
34
|
+
</details>
|
|
35
|
+
|
|
36
|
+
## Follow-ups an interviewer might ask
|
|
37
|
+
|
|
38
|
+
- Return the levels bottom-up (LeetCode 107) or in zigzag order (LeetCode 103).
|
|
39
|
+
- How does your queue handle `shift()` on a large array? What does that cost in JavaScript, and how would you avoid it?
|
|
40
|
+
- Return the average of each level instead (LeetCode 637).
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { rightSpine, treeFrom } from '../../lib/binary-tree'
|
|
3
|
+
import { levelOrder } from './solution'
|
|
4
|
+
|
|
5
|
+
const levels = (levelOrderInput: (number | null)[]): number[][] => levelOrder(treeFrom(levelOrderInput))
|
|
6
|
+
|
|
7
|
+
describe('123 binary tree level order traversal', () => {
|
|
8
|
+
it('groups values by depth', () => {
|
|
9
|
+
expect(levels([3, 9, 20, null, null, 15, 7])).toEqual([[3], [9, 20], [15, 7]])
|
|
10
|
+
})
|
|
11
|
+
|
|
12
|
+
it('handles a single node', () => {
|
|
13
|
+
expect(levels([1])).toEqual([[1]])
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
it('returns an empty array for an empty tree', () => {
|
|
17
|
+
expect(levelOrder(null)).toEqual([])
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
it('keeps left-to-right order within a level', () => {
|
|
21
|
+
expect(levels([1, 2, 3, 4, 5, 6, 7])).toEqual([[1], [2, 3], [4, 5, 6, 7]])
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
it('handles gaps and uneven depths', () => {
|
|
25
|
+
expect(levels([1, 2, 3, 4, null, null, 5, 6, null, null, 7])).toEqual([[1], [2, 3], [4, 5], [6, 7]])
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
it('handles a left-only chain', () => {
|
|
29
|
+
expect(levels([1, 2, null, 3, null, 4])).toEqual([[1], [2], [3], [4]])
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
it('handles negatives, zero and repeated values', () => {
|
|
33
|
+
expect(levels([0, -1, -1, 5, null, null, 5])).toEqual([[0], [-1, -1], [5, 5]])
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
it('handles a 2,000-node chain', () => {
|
|
37
|
+
const result = levelOrder(rightSpine(2_000))
|
|
38
|
+
expect(result).toHaveLength(2_000)
|
|
39
|
+
expect(result[0]).toEqual([1])
|
|
40
|
+
expect(result[1_999]).toEqual([2_000])
|
|
41
|
+
})
|
|
42
|
+
})
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# 124 · Binary Tree Right Side View
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: trees (BFS/DFS) · Target: 25 min · NeetCode 150 · LeetCode 199
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
Picture yourself standing to the right of a binary tree, looking at it. At each depth you can see only the rightmost node. Return the values you can see, from the top of the tree to the bottom.
|
|
8
|
+
|
|
9
|
+
Note that the visible node at a given depth isn't always in the root's right subtree: if the left subtree is deeper, its lower nodes show through.
|
|
10
|
+
|
|
11
|
+
## Examples
|
|
12
|
+
|
|
13
|
+
| Tree (level order) | Output |
|
|
14
|
+
|---|---|
|
|
15
|
+
| `[1, 2, 3, null, 5, null, 4]` | `[1, 3, 4]` |
|
|
16
|
+
| `[1, 2, 3, 4]` | `[1, 3, 4]` |
|
|
17
|
+
| `[1, null, 3]` | `[1, 3]` |
|
|
18
|
+
| `[]` | `[]` |
|
|
19
|
+
|
|
20
|
+
## Constraints
|
|
21
|
+
|
|
22
|
+
- `0 <= nodes <= 100` (one test uses a 2,000-node chain)
|
|
23
|
+
- `-100 <= val <= 100`
|
|
24
|
+
|
|
25
|
+
## Run it
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pnpm watch 124
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
32
|
+
|
|
33
|
+
Time O(n) · Space O(w) for BFS (widest level) or O(h) for DFS (tree height).
|
|
34
|
+
|
|
35
|
+
</details>
|
|
36
|
+
|
|
37
|
+
## Follow-ups an interviewer might ask
|
|
38
|
+
|
|
39
|
+
- Return the left side view instead. What's the smallest change?
|
|
40
|
+
- Can you do it with DFS and no queue? Which child do you visit first, and why?
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { TreeNode, rightSpine, treeFrom } from '../../lib/binary-tree'
|
|
3
|
+
import { rightSideView } from './solution'
|
|
4
|
+
|
|
5
|
+
const view = (levelOrder: (number | null)[]): number[] => rightSideView(treeFrom(levelOrder))
|
|
6
|
+
|
|
7
|
+
/** A chain where every node only has a left child: depth n. */
|
|
8
|
+
function leftSpine(n: number): TreeNode | null {
|
|
9
|
+
let root: TreeNode | null = null
|
|
10
|
+
for (let v = n; v >= 1; v--) root = new TreeNode(v, root, null)
|
|
11
|
+
return root
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
describe('124 binary tree right side view', () => {
|
|
15
|
+
it('sees the rightmost node at each depth', () => {
|
|
16
|
+
expect(view([1, 2, 3, null, 5, null, 4])).toEqual([1, 3, 4])
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
it('sees a left-subtree node when the left side is deeper', () => {
|
|
20
|
+
expect(view([1, 2, 3, 4])).toEqual([1, 3, 4])
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
it('handles a right-only tree', () => {
|
|
24
|
+
expect(view([1, null, 3])).toEqual([1, 3])
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
it('returns an empty array for an empty tree', () => {
|
|
28
|
+
expect(rightSideView(null)).toEqual([])
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('handles a single node', () => {
|
|
32
|
+
expect(view([7])).toEqual([7])
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
it('handles a left-only chain', () => {
|
|
36
|
+
expect(view([1, 2, null, 3])).toEqual([1, 2, 3])
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
it('switches between subtrees level by level', () => {
|
|
40
|
+
// Levels: [1], [2, 3], [4, 5], [6]. The last level only exists under the left subtree.
|
|
41
|
+
expect(view([1, 2, 3, 4, null, 5, null, 6])).toEqual([1, 3, 5, 6])
|
|
42
|
+
expect(view([1, 2, 3, 4, 5, null, null, null, 8, 9])).toEqual([1, 3, 5, 9])
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
it('handles negatives and repeated values', () => {
|
|
46
|
+
expect(view([-1, -2, -2, -3, null, null, -3])).toEqual([-1, -2, -3])
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
it('handles 2,000-node chains on either side', () => {
|
|
50
|
+
const fromRight = rightSideView(rightSpine(2_000))
|
|
51
|
+
const fromLeft = rightSideView(leftSpine(2_000))
|
|
52
|
+
expect(fromRight).toHaveLength(2_000)
|
|
53
|
+
expect(fromLeft).toHaveLength(2_000)
|
|
54
|
+
expect(fromLeft.at(-1)).toBe(2_000)
|
|
55
|
+
})
|
|
56
|
+
})
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# 125 · Validate Binary Search Tree
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: trees (BST) · Target: 25 min · NeetCode 150 · LeetCode 98
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
Given the root of a binary tree, decide whether it is a valid binary search tree. In a valid BST, for **every** node:
|
|
8
|
+
|
|
9
|
+
- every value in its left subtree is strictly smaller than the node's value,
|
|
10
|
+
- every value in its right subtree is strictly larger than the node's value,
|
|
11
|
+
- and both subtrees are themselves valid BSTs.
|
|
12
|
+
|
|
13
|
+
Equal values are **not** allowed anywhere, so a duplicate on either side makes the tree invalid. An empty tree counts as valid.
|
|
14
|
+
|
|
15
|
+
## Examples
|
|
16
|
+
|
|
17
|
+
| Tree (level order) | Output | Why |
|
|
18
|
+
|---|---|---|
|
|
19
|
+
| `[2, 1, 3]` | `true` | |
|
|
20
|
+
| `[5, 1, 4, null, null, 3, 6]` | `false` | `4` is in the root's right subtree but smaller than `5` |
|
|
21
|
+
| `[5, 4, 6, null, null, 3, 7]` | `false` | each parent/child pair looks fine, but `3` sits in `5`'s right subtree |
|
|
22
|
+
| `[2, 2, 2]` | `false` | duplicates aren't allowed |
|
|
23
|
+
|
|
24
|
+
## Constraints
|
|
25
|
+
|
|
26
|
+
- `0 <= nodes <= 10^4` (one test uses a 2,000-node chain)
|
|
27
|
+
- `-2^31 <= val <= 2^31 - 1`. Values can sit exactly on either boundary.
|
|
28
|
+
|
|
29
|
+
## Run it
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pnpm watch 125
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
36
|
+
|
|
37
|
+
Time O(n) · Space O(h). Either pass a valid `(low, high)` range down the tree, or do an in-order traversal and check that values strictly increase. Checking every node against the min/max of its whole subtree separately is O(n²) in the worst case.
|
|
38
|
+
|
|
39
|
+
</details>
|
|
40
|
+
|
|
41
|
+
## Follow-ups an interviewer might ask
|
|
42
|
+
|
|
43
|
+
- Why isn't comparing each node with just its two children enough? Draw a counterexample.
|
|
44
|
+
- What bounds did you start with, and do they still work when a value equals `2^31 - 1`?
|
|
45
|
+
- Do it iteratively with an explicit stack (in-order).
|
|
46
|
+
- What changes if duplicates were allowed on the left?
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { TreeNode, rightSpine, treeFrom } from '../../lib/binary-tree'
|
|
3
|
+
import { isValidBST } from './solution'
|
|
4
|
+
|
|
5
|
+
const valid = (levelOrder: (number | null)[]): boolean => isValidBST(treeFrom(levelOrder))
|
|
6
|
+
|
|
7
|
+
const MIN = -(2 ** 31)
|
|
8
|
+
const MAX = 2 ** 31 - 1
|
|
9
|
+
|
|
10
|
+
/** Builds a height-balanced BST holding lo..hi. */
|
|
11
|
+
function balancedBST(lo: number, hi: number): TreeNode | null {
|
|
12
|
+
if (lo > hi) return null
|
|
13
|
+
const mid = Math.floor((lo + hi) / 2)
|
|
14
|
+
return new TreeNode(mid, balancedBST(lo, mid - 1), balancedBST(mid + 1, hi))
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
describe('125 validate binary search tree', () => {
|
|
18
|
+
it('accepts a small valid tree', () => {
|
|
19
|
+
expect(valid([2, 1, 3])).toBe(true)
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
it('rejects a right child smaller than its parent', () => {
|
|
23
|
+
expect(valid([5, 1, 4, null, null, 3, 6])).toBe(false)
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
it('rejects a deep node that breaks an ancestor bound on the right', () => {
|
|
27
|
+
// 6's children are fine locally, but 3 is in 5's right subtree.
|
|
28
|
+
expect(valid([5, 4, 6, null, null, 3, 7])).toBe(false)
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('rejects a deep node that breaks an ancestor bound on the left', () => {
|
|
32
|
+
// 12 > 5 is fine locally, but 12 is in 10's left subtree.
|
|
33
|
+
expect(valid([10, 5, 15, null, 12])).toBe(false)
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
it('rejects duplicates on either side', () => {
|
|
37
|
+
expect(valid([2, 2, 2])).toBe(false)
|
|
38
|
+
expect(valid([1, 1])).toBe(false)
|
|
39
|
+
expect(valid([1, null, 1])).toBe(false)
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
it('rejects a duplicate of an ancestor deeper down', () => {
|
|
43
|
+
expect(valid([5, 3, 8, null, 5])).toBe(false)
|
|
44
|
+
expect(valid([5, 3, 8, 5])).toBe(false)
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
it('accepts empty and single-node trees', () => {
|
|
48
|
+
expect(isValidBST(null)).toBe(true)
|
|
49
|
+
expect(valid([0])).toBe(true)
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
it('accepts values exactly on the 32-bit boundaries', () => {
|
|
53
|
+
expect(valid([MAX])).toBe(true)
|
|
54
|
+
expect(valid([MIN])).toBe(true)
|
|
55
|
+
expect(valid([MIN, null, MAX])).toBe(true)
|
|
56
|
+
expect(valid([MAX, MIN])).toBe(true)
|
|
57
|
+
expect(valid([0, MIN, MAX])).toBe(true)
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
it('rejects duplicates on the 32-bit boundaries', () => {
|
|
61
|
+
expect(valid([MAX, null, MAX])).toBe(false)
|
|
62
|
+
expect(valid([MIN, MIN])).toBe(false)
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
it('accepts a larger valid tree and rejects it after one swap', () => {
|
|
66
|
+
const root = balancedBST(1, 1_000)
|
|
67
|
+
expect(isValidBST(root)).toBe(true)
|
|
68
|
+
// Swap the root's two children's values: each side now breaks the root's bound.
|
|
69
|
+
const left = root!.left!
|
|
70
|
+
const right = root!.right!
|
|
71
|
+
;[left.val, right.val] = [right.val, left.val]
|
|
72
|
+
expect(isValidBST(root)).toBe(false)
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
it('handles a 2,000-node chain', () => {
|
|
76
|
+
expect(isValidBST(rightSpine(2_000))).toBe(true)
|
|
77
|
+
})
|
|
78
|
+
})
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# 126 · Kth Smallest Element in a BST
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: trees (BST, in-order) · Target: 25 min · NeetCode 150 · LeetCode 230
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
You get the root of a binary search tree and an integer `k`. Return the `k`-th smallest value in the tree. `k` is **1-indexed**, so `k = 1` means the smallest value.
|
|
8
|
+
|
|
9
|
+
All values in the tree are distinct, and `k` is always between `1` and the number of nodes.
|
|
10
|
+
|
|
11
|
+
## Examples
|
|
12
|
+
|
|
13
|
+
| Tree (level order) | `k` | Output |
|
|
14
|
+
|---|---|---|
|
|
15
|
+
| `[3, 1, 4, null, 2]` | `1` | `1` |
|
|
16
|
+
| `[5, 3, 6, 2, 4, null, null, 1]` | `3` | `3` |
|
|
17
|
+
| `[5, 3, 6, 2, 4, null, null, 1]` | `6` | `6` |
|
|
18
|
+
|
|
19
|
+
## Constraints
|
|
20
|
+
|
|
21
|
+
- `1 <= k <= nodes <= 10^4` (one test uses a 2,000-node chain)
|
|
22
|
+
- `0 <= val <= 10^4` in the examples. Some tests use negative values too.
|
|
23
|
+
|
|
24
|
+
## Run it
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pnpm watch 126
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
31
|
+
|
|
32
|
+
Time O(h + k) · Space O(h). Collecting the whole in-order list and indexing into it is O(n) time and space: correct, but an interviewer will ask you to stop early.
|
|
33
|
+
|
|
34
|
+
</details>
|
|
35
|
+
|
|
36
|
+
## Follow-ups an interviewer might ask
|
|
37
|
+
|
|
38
|
+
- Can you stop as soon as you've seen `k` values? Do it iteratively with an explicit stack.
|
|
39
|
+
- The tree is modified often (inserts and deletes) and you're asked for the k-th smallest many times. What would you store in each node to answer in O(h)?
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { TreeNode, rightSpine, treeFrom } from '../../lib/binary-tree'
|
|
3
|
+
import { kthSmallest } from './solution'
|
|
4
|
+
|
|
5
|
+
const kth = (levelOrder: (number | null)[], k: number): number => kthSmallest(treeFrom(levelOrder), k)
|
|
6
|
+
|
|
7
|
+
/** Builds a height-balanced BST holding lo..hi. */
|
|
8
|
+
function balancedBST(lo: number, hi: number): TreeNode | null {
|
|
9
|
+
if (lo > hi) return null
|
|
10
|
+
const mid = Math.floor((lo + hi) / 2)
|
|
11
|
+
return new TreeNode(mid, balancedBST(lo, mid - 1), balancedBST(mid + 1, hi))
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** A chain where every node only has a left child, holding n down to 1. */
|
|
15
|
+
function leftSpine(n: number): TreeNode | null {
|
|
16
|
+
let root: TreeNode | null = null
|
|
17
|
+
for (let v = 1; v <= n; v++) root = new TreeNode(v, root, null)
|
|
18
|
+
return root
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
describe('126 kth smallest element in a bst', () => {
|
|
22
|
+
it('finds the smallest value (k is 1-indexed)', () => {
|
|
23
|
+
expect(kth([3, 1, 4, null, 2], 1)).toBe(1)
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
it('finds a middle value', () => {
|
|
27
|
+
expect(kth([5, 3, 6, 2, 4, null, null, 1], 3)).toBe(3)
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
it('finds the largest value when k equals the size', () => {
|
|
31
|
+
expect(kth([5, 3, 6, 2, 4, null, null, 1], 6)).toBe(6)
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
it('finds every rank in a small tree', () => {
|
|
35
|
+
const tree = [5, 3, 6, 2, 4, null, null, 1]
|
|
36
|
+
expect([1, 2, 3, 4, 5, 6].map((k) => kth(tree, k))).toEqual([1, 2, 3, 4, 5, 6])
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
it('handles a single node', () => {
|
|
40
|
+
expect(kth([42], 1)).toBe(42)
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
it('handles negative values', () => {
|
|
44
|
+
expect(kth([0, -10, 10, -20, -5], 2)).toBe(-10)
|
|
45
|
+
expect(kth([0, -10, 10, -20, -5], 4)).toBe(0)
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
it('handles a larger balanced tree', () => {
|
|
49
|
+
const root = balancedBST(1, 1_000)
|
|
50
|
+
expect(kthSmallest(root, 1)).toBe(1)
|
|
51
|
+
expect(kthSmallest(root, 500)).toBe(500)
|
|
52
|
+
expect(kthSmallest(root, 1_000)).toBe(1_000)
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
it('handles 2,000-node chains on either side', () => {
|
|
56
|
+
expect(kthSmallest(rightSpine(2_000), 2_000)).toBe(2_000)
|
|
57
|
+
expect(kthSmallest(rightSpine(2_000), 1)).toBe(1)
|
|
58
|
+
expect(kthSmallest(leftSpine(2_000), 1)).toBe(1)
|
|
59
|
+
expect(kthSmallest(leftSpine(2_000), 1_999)).toBe(1_999)
|
|
60
|
+
})
|
|
61
|
+
})
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# 127 · Lowest Common Ancestor of a BST
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: trees (BST) · Target: 25 min · NeetCode 150 · LeetCode 235
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
You get the root of a binary search tree and two different nodes `p` and `q` that are both in it. Return their lowest common ancestor: the deepest node that has both `p` and `q` in its subtree. A node counts as being in its own subtree, so if `p` is an ancestor of `q`, the answer is `p`.
|
|
8
|
+
|
|
9
|
+
Return the actual node from the tree, not a copy. The tests check identity (`toBe`).
|
|
10
|
+
|
|
11
|
+
All values are distinct.
|
|
12
|
+
|
|
13
|
+
## Examples
|
|
14
|
+
|
|
15
|
+
Tree for every example: `[6, 2, 8, 0, 4, 7, 9, null, null, 3, 5]`
|
|
16
|
+
|
|
17
|
+
| `p` | `q` | Output | Why |
|
|
18
|
+
|---|---|---|---|
|
|
19
|
+
| `2` | `8` | `6` | they're on opposite sides of the root |
|
|
20
|
+
| `2` | `4` | `2` | `2` is an ancestor of `4` |
|
|
21
|
+
| `3` | `5` | `4` | both hang under `4` |
|
|
22
|
+
|
|
23
|
+
## Constraints
|
|
24
|
+
|
|
25
|
+
- `2 <= nodes <= 10^5`
|
|
26
|
+
- `-10^9 <= val <= 10^9`, all distinct
|
|
27
|
+
- `p !== q`, and both are in the tree.
|
|
28
|
+
- The read-count test uses a balanced BST of 65,535 nodes and allows up to 200 child-pointer reads (`.left` / `.right`). Visiting every node would take about 130,000.
|
|
29
|
+
|
|
30
|
+
## Run it
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pnpm watch 127
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
37
|
+
|
|
38
|
+
Time O(h) · Space O(1) iterative (O(h) recursive). Use the ordering: you never need to look at a subtree that can't contain both nodes.
|
|
39
|
+
|
|
40
|
+
</details>
|
|
41
|
+
|
|
42
|
+
## Follow-ups an interviewer might ask
|
|
43
|
+
|
|
44
|
+
- Now the tree is a plain binary tree with no ordering (LeetCode 236). What changes, and what does it cost?
|
|
45
|
+
- What if `p` or `q` might not be in the tree?
|
|
46
|
+
- Do it iteratively with O(1) extra space.
|