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,53 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { timeMs } from '../../lib/perf'
|
|
3
|
+
import { minEatingSpeed } from './solution'
|
|
4
|
+
|
|
5
|
+
describe('116 koko eating bananas', () => {
|
|
6
|
+
it('finds the slowest speed that fits', () => {
|
|
7
|
+
expect(minEatingSpeed([3, 6, 7, 11], 8)).toBe(4)
|
|
8
|
+
})
|
|
9
|
+
|
|
10
|
+
it('needs the largest pile when there is one hour per pile', () => {
|
|
11
|
+
expect(minEatingSpeed([30, 11, 23, 4, 20], 5)).toBe(30)
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
it('uses a spare hour to slow down', () => {
|
|
15
|
+
expect(minEatingSpeed([30, 11, 23, 4, 20], 6)).toBe(23)
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
it('handles a single pile', () => {
|
|
19
|
+
expect(minEatingSpeed([1], 1)).toBe(1)
|
|
20
|
+
expect(minEatingSpeed([10], 3)).toBe(4)
|
|
21
|
+
expect(minEatingSpeed([10], 5)).toBe(2)
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
it('rounds partial hours up', () => {
|
|
25
|
+
// At speed 3, the piles take 1 + 1 + 2 = 4 hours; at speed 2 they take 2 + 2 + 2 = 6.
|
|
26
|
+
expect(minEatingSpeed([3, 3, 4], 4)).toBe(3)
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
it('returns 1 when there is plenty of time', () => {
|
|
30
|
+
expect(minEatingSpeed([3, 6, 7, 11], 1_000)).toBe(1)
|
|
31
|
+
expect(minEatingSpeed([5, 5, 5], 15)).toBe(1)
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
it('handles piles of equal size', () => {
|
|
35
|
+
expect(minEatingSpeed([8, 8, 8, 8], 8)).toBe(4)
|
|
36
|
+
expect(minEatingSpeed([8, 8, 8, 8], 9)).toBe(4)
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
it('handles very large piles', () => {
|
|
40
|
+
expect(minEatingSpeed([1_000_000_000], 1_000_000_000)).toBe(1)
|
|
41
|
+
expect(minEatingSpeed([1_000_000_000], 100_000_000)).toBe(10)
|
|
42
|
+
expect(minEatingSpeed([999_999_999, 1_000_000_000], 200_000_000)).toBe(10)
|
|
43
|
+
})
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
describe('116 performance', () => {
|
|
47
|
+
it('finds a speed of 500,000,000 in under 100 ms (trying speeds one by one is too slow here)', () => {
|
|
48
|
+
// The big pile needs 2 hours at the answer and 3 hours just below it.
|
|
49
|
+
const piles = [999_999_999, 3, 5, 7]
|
|
50
|
+
const ms = timeMs(() => expect(minEatingSpeed(piles, 5)).toBe(500_000_000))
|
|
51
|
+
expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(100)
|
|
52
|
+
})
|
|
53
|
+
})
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# 117 · Find Minimum in Rotated Sorted Array
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: binary search · Target: 25 min · NeetCode 150 · LeetCode 153
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
An ascending array of distinct numbers has been rotated: some suffix was moved to the front, so `[0, 1, 2, 4, 5, 6, 7]` might now be `[4, 5, 6, 7, 0, 1, 2]`. The rotation might also be zero steps, leaving the array fully sorted. Return the smallest element.
|
|
8
|
+
|
|
9
|
+
Your solution must read O(log n) elements. The test counts every element you read, so a linear scan (or `Math.min(...nums)`) won't pass.
|
|
10
|
+
|
|
11
|
+
## Examples
|
|
12
|
+
|
|
13
|
+
| `nums` | Output | Why |
|
|
14
|
+
|---|---|---|
|
|
15
|
+
| `[3, 4, 5, 1, 2]` | `1` | `[1, 2, 3, 4, 5]` rotated 3 times |
|
|
16
|
+
| `[4, 5, 6, 7, 0, 1, 2]` | `0` | rotated 4 times |
|
|
17
|
+
| `[11, 13, 15, 17]` | `11` | not rotated at all |
|
|
18
|
+
|
|
19
|
+
## Constraints
|
|
20
|
+
|
|
21
|
+
- `1 <= nums.length <= 5000` (the read-count test uses 1,000,000 and allows up to 200 reads)
|
|
22
|
+
- `-5000 <= nums[i] <= 5000` (the read-count test uses wider values)
|
|
23
|
+
- All values are distinct, and `nums` is a rotation of an ascending array.
|
|
24
|
+
|
|
25
|
+
## Run it
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pnpm watch 117
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
32
|
+
|
|
33
|
+
Time O(log n) · Space O(1).
|
|
34
|
+
|
|
35
|
+
</details>
|
|
36
|
+
|
|
37
|
+
## Follow-ups an interviewer might ask
|
|
38
|
+
|
|
39
|
+
- Return the rotation count (the index of the minimum) instead.
|
|
40
|
+
- Which element do you compare against at each step, and why that one? Does your choice still work on an array that wasn't rotated?
|
|
41
|
+
- What if the array can contain duplicates (LeetCode 154)? What happens to the worst case?
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { findMin } from './solution'
|
|
3
|
+
|
|
4
|
+
/** Wraps an array so every element read is counted. */
|
|
5
|
+
function counted(values: readonly number[]): { nums: readonly number[]; reads: () => number } {
|
|
6
|
+
let reads = 0
|
|
7
|
+
const nums = new Proxy(values, {
|
|
8
|
+
get(target, prop, receiver) {
|
|
9
|
+
if (typeof prop === 'string' && /^\d+$/.test(prop)) reads++
|
|
10
|
+
return Reflect.get(target, prop, receiver)
|
|
11
|
+
},
|
|
12
|
+
})
|
|
13
|
+
return { nums, reads: () => reads }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Moves the first k elements to the end. */
|
|
17
|
+
const rotate = (values: readonly number[], k: number): number[] => [...values.slice(k), ...values.slice(0, k)]
|
|
18
|
+
|
|
19
|
+
describe('117 find minimum in rotated sorted array', () => {
|
|
20
|
+
it('finds the minimum after a rotation', () => {
|
|
21
|
+
expect(findMin([3, 4, 5, 1, 2])).toBe(1)
|
|
22
|
+
expect(findMin([4, 5, 6, 7, 0, 1, 2])).toBe(0)
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
it('handles an array that was not rotated', () => {
|
|
26
|
+
expect(findMin([11, 13, 15, 17])).toBe(11)
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
it('handles a single element', () => {
|
|
30
|
+
expect(findMin([1])).toBe(1)
|
|
31
|
+
expect(findMin([-5])).toBe(-5)
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
it('handles two elements', () => {
|
|
35
|
+
expect(findMin([2, 1])).toBe(1)
|
|
36
|
+
expect(findMin([1, 2])).toBe(1)
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
it('finds the minimum at the very end', () => {
|
|
40
|
+
expect(findMin([2, 3, 4, 5, 1])).toBe(1)
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
it('finds the minimum right after the first element', () => {
|
|
44
|
+
expect(findMin([5, 1, 2, 3, 4])).toBe(1)
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
it('handles negatives', () => {
|
|
48
|
+
expect(findMin([0, 7, -9, -4, -1])).toBe(-9)
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
it('finds the minimum for every rotation of a small array', () => {
|
|
52
|
+
const base = [-3, 1, 4, 8, 10, 15, 22]
|
|
53
|
+
for (let k = 0; k < base.length; k++) {
|
|
54
|
+
expect(findMin(rotate(base, k)), `rotation ${k}`).toBe(-3)
|
|
55
|
+
}
|
|
56
|
+
})
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
describe('117 read count', () => {
|
|
60
|
+
it('reads at most 200 elements of a 1,000,000-element array (a linear scan reads about a million)', () => {
|
|
61
|
+
const n = 1_000_000
|
|
62
|
+
const base = Array.from({ length: n }, (_, i) => i * 2 - 700_000)
|
|
63
|
+
for (const k of [0, 1, 2, n / 2, 123_457, 777_777, n - 2, n - 1]) {
|
|
64
|
+
const { nums, reads } = counted(rotate(base, k))
|
|
65
|
+
expect(findMin(nums), `rotation ${k}`).toBe(-700_000)
|
|
66
|
+
expect(reads(), `read ${reads()} elements for rotation ${k}`).toBeLessThanOrEqual(200)
|
|
67
|
+
}
|
|
68
|
+
})
|
|
69
|
+
})
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# 118 · Search in Rotated Sorted Array
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: binary search · Target: 25 min · NeetCode 150 · LeetCode 33
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
`nums` started as an ascending array of distinct numbers and was then rotated by an unknown amount (possibly zero): a suffix was moved to the front, so `[0, 1, 2, 4, 5, 6, 7]` might now be `[4, 5, 6, 7, 0, 1, 2]`. Return the index of `target` in `nums`, or `-1` if it isn't there.
|
|
8
|
+
|
|
9
|
+
Your solution must read O(log n) elements. The test counts every element you read, so a linear scan (or `indexOf`) won't pass.
|
|
10
|
+
|
|
11
|
+
## Examples
|
|
12
|
+
|
|
13
|
+
| `nums` | `target` | Output |
|
|
14
|
+
|---|---|---|
|
|
15
|
+
| `[4, 5, 6, 7, 0, 1, 2]` | `0` | `4` |
|
|
16
|
+
| `[4, 5, 6, 7, 0, 1, 2]` | `3` | `-1` |
|
|
17
|
+
| `[1]` | `0` | `-1` |
|
|
18
|
+
|
|
19
|
+
## Constraints
|
|
20
|
+
|
|
21
|
+
- `1 <= nums.length <= 5000` (the read-count test uses 1,000,000 and allows up to 300 reads)
|
|
22
|
+
- `-10^4 <= nums[i], target <= 10^4` (the read-count test uses wider values)
|
|
23
|
+
- All values are distinct, and `nums` is a rotation of an ascending array.
|
|
24
|
+
|
|
25
|
+
## Run it
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pnpm watch 118
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
32
|
+
|
|
33
|
+
Time O(log n) · Space O(1).
|
|
34
|
+
|
|
35
|
+
</details>
|
|
36
|
+
|
|
37
|
+
## Follow-ups an interviewer might ask
|
|
38
|
+
|
|
39
|
+
- Is there a different way to solve it, also in O(log n)? Which version is easier to get right under pressure?
|
|
40
|
+
- What if `nums` may contain duplicates (LeetCode 81)? Why can the worst case become O(n)?
|
|
41
|
+
- Return the rotation amount as well as the index.
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { search } from './solution'
|
|
3
|
+
|
|
4
|
+
/** Wraps an array so every element read is counted. */
|
|
5
|
+
function counted(values: readonly number[]): { nums: readonly number[]; reads: () => number } {
|
|
6
|
+
let reads = 0
|
|
7
|
+
const nums = new Proxy(values, {
|
|
8
|
+
get(target, prop, receiver) {
|
|
9
|
+
if (typeof prop === 'string' && /^\d+$/.test(prop)) reads++
|
|
10
|
+
return Reflect.get(target, prop, receiver)
|
|
11
|
+
},
|
|
12
|
+
})
|
|
13
|
+
return { nums, reads: () => reads }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Moves the first k elements to the end. */
|
|
17
|
+
const rotate = (values: readonly number[], k: number): number[] => [...values.slice(k), ...values.slice(0, k)]
|
|
18
|
+
|
|
19
|
+
describe('118 search in rotated sorted array', () => {
|
|
20
|
+
it('finds a value in the rotated part', () => {
|
|
21
|
+
expect(search([4, 5, 6, 7, 0, 1, 2], 0)).toBe(4)
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
it('returns -1 when the value is missing', () => {
|
|
25
|
+
expect(search([4, 5, 6, 7, 0, 1, 2], 3)).toBe(-1)
|
|
26
|
+
expect(search([4, 5, 6, 7, 0, 1, 2], 8)).toBe(-1)
|
|
27
|
+
expect(search([4, 5, 6, 7, 0, 1, 2], -1)).toBe(-1)
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
it('handles a single element', () => {
|
|
31
|
+
expect(search([1], 0)).toBe(-1)
|
|
32
|
+
expect(search([1], 1)).toBe(0)
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
it('handles two elements', () => {
|
|
36
|
+
expect(search([1, 3], 3)).toBe(1)
|
|
37
|
+
expect(search([3, 1], 1)).toBe(1)
|
|
38
|
+
expect(search([3, 1], 3)).toBe(0)
|
|
39
|
+
expect(search([3, 1], 2)).toBe(-1)
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
it('finds values on both sides of the rotation point', () => {
|
|
43
|
+
expect(search([5, 1, 3], 5)).toBe(0)
|
|
44
|
+
expect(search([5, 1, 3], 3)).toBe(2)
|
|
45
|
+
expect(search([4, 5, 6, 7, 0, 1, 2], 7)).toBe(3)
|
|
46
|
+
expect(search([4, 5, 6, 7, 0, 1, 2], 4)).toBe(0)
|
|
47
|
+
expect(search([4, 5, 6, 7, 0, 1, 2], 2)).toBe(6)
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
it('handles an array that was not rotated', () => {
|
|
51
|
+
expect(search([1, 2, 3, 4, 5], 1)).toBe(0)
|
|
52
|
+
expect(search([1, 2, 3, 4, 5], 5)).toBe(4)
|
|
53
|
+
expect(search([1, 2, 3, 4, 5], 6)).toBe(-1)
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
it('handles negatives', () => {
|
|
57
|
+
expect(search([3, 8, -10, -4, 0], -4)).toBe(3)
|
|
58
|
+
expect(search([3, 8, -10, -4, 0], -5)).toBe(-1)
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
it('finds every value in every rotation of a small array', () => {
|
|
62
|
+
const base = [-7, -2, 0, 3, 9, 14, 20, 31]
|
|
63
|
+
for (let k = 0; k < base.length; k++) {
|
|
64
|
+
const nums = rotate(base, k)
|
|
65
|
+
nums.forEach((value, i) => expect(search(nums, value), `rotation ${k}, value ${value}`).toBe(i))
|
|
66
|
+
for (const missing of [-8, 1, 10, 32]) {
|
|
67
|
+
expect(search(nums, missing), `rotation ${k}, missing ${missing}`).toBe(-1)
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
})
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
describe('118 read count', () => {
|
|
74
|
+
it('reads at most 300 elements of a 1,000,000-element array (a linear scan reads about a million)', () => {
|
|
75
|
+
const n = 1_000_000
|
|
76
|
+
const base = Array.from({ length: n }, (_, i) => i * 2 - 700_000)
|
|
77
|
+
for (const k of [0, 1, n / 2, 123_457, n - 1]) {
|
|
78
|
+
const rotated = rotate(base, k)
|
|
79
|
+
const cases: [number, number][] = [
|
|
80
|
+
[base[0]!, (n - k) % n], // the minimum
|
|
81
|
+
[base[n - 1]!, (2 * n - k - 1) % n], // the maximum
|
|
82
|
+
[base[314_159]!, (314_159 - k + n) % n],
|
|
83
|
+
[base[999_000]!, (999_000 - k + n) % n],
|
|
84
|
+
[1, -1], // odd, so missing
|
|
85
|
+
[-700_002, -1], // below every value
|
|
86
|
+
[1_300_000, -1], // above every value
|
|
87
|
+
]
|
|
88
|
+
for (const [target, expected] of cases) {
|
|
89
|
+
const { nums, reads } = counted(rotated)
|
|
90
|
+
expect(search(nums, target), `rotation ${k}, target ${target}`).toBe(expected)
|
|
91
|
+
expect(reads(), `read ${reads()} elements for rotation ${k}, target ${target}`).toBeLessThanOrEqual(300)
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
})
|
|
95
|
+
})
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# 119 · Time Based Key-Value Store
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: binary search (design) · Target: 30 min · NeetCode 150 · LeetCode 981
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
Build a class, `TimeMap`, that stores several values for the same key at different times, and can answer "what was this key's value at time `t`?".
|
|
8
|
+
|
|
9
|
+
- `set(key, value, timestamp)` records that `key` had `value` from `timestamp` onward.
|
|
10
|
+
- `get(key, timestamp)` returns the value from the latest `set` for `key` whose timestamp is `<= timestamp`. If there isn't one (the key was never set, or only set after `timestamp`), return the empty string `''`.
|
|
11
|
+
|
|
12
|
+
The timestamps passed to `set` are strictly increasing across all calls, so each key's history arrives already in time order.
|
|
13
|
+
|
|
14
|
+
## Examples
|
|
15
|
+
|
|
16
|
+
| Call | Returns | Why |
|
|
17
|
+
|---|---|---|
|
|
18
|
+
| `new TimeMap()` | | |
|
|
19
|
+
| `set('foo', 'bar', 1)` | | |
|
|
20
|
+
| `get('foo', 1)` | `'bar'` | exact match |
|
|
21
|
+
| `get('foo', 3)` | `'bar'` | latest at or before 3 is time 1 |
|
|
22
|
+
| `set('foo', 'bar2', 4)` | | |
|
|
23
|
+
| `get('foo', 4)` | `'bar2'` | exact match |
|
|
24
|
+
| `get('foo', 5)` | `'bar2'` | latest at or before 5 is time 4 |
|
|
25
|
+
| `get('foo', 0)` | `''` | nothing at or before 0 |
|
|
26
|
+
|
|
27
|
+
## Constraints
|
|
28
|
+
|
|
29
|
+
- `1 <= key.length, value.length <= 100`; keys and values are lowercase letters and digits.
|
|
30
|
+
- `1 <= timestamp <= 10^7` for `set`; `get` may ask about any timestamp from `0` to `10^7`.
|
|
31
|
+
- Timestamps passed to `set` are strictly increasing.
|
|
32
|
+
- At most `2 * 10^5` calls in total (the performance test makes 50,000 sets on one key and then about 60,000 gets).
|
|
33
|
+
|
|
34
|
+
## Run it
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pnpm watch 119
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
41
|
+
|
|
42
|
+
`set` O(1) · `get` O(log n), where n is the number of values stored for that key · Space O(total sets).
|
|
43
|
+
|
|
44
|
+
</details>
|
|
45
|
+
|
|
46
|
+
## Follow-ups an interviewer might ask
|
|
47
|
+
|
|
48
|
+
- What changes if `set` timestamps can arrive out of order?
|
|
49
|
+
- How would you support deleting a key's history before some time?
|
|
50
|
+
- If one key gets millions of writes and most reads ask for "now", how could you make the common case O(1)?
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { timeMs } from '../../lib/perf'
|
|
3
|
+
import { TimeMap } from './solution'
|
|
4
|
+
|
|
5
|
+
describe('119 time based key-value store', () => {
|
|
6
|
+
it('runs the README example', () => {
|
|
7
|
+
const map = new TimeMap()
|
|
8
|
+
map.set('foo', 'bar', 1)
|
|
9
|
+
expect(map.get('foo', 1)).toBe('bar')
|
|
10
|
+
expect(map.get('foo', 3)).toBe('bar')
|
|
11
|
+
map.set('foo', 'bar2', 4)
|
|
12
|
+
expect(map.get('foo', 4)).toBe('bar2')
|
|
13
|
+
expect(map.get('foo', 5)).toBe('bar2')
|
|
14
|
+
expect(map.get('foo', 0)).toBe('')
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
it('returns an empty string for a key that was never set', () => {
|
|
18
|
+
const map = new TimeMap()
|
|
19
|
+
expect(map.get('missing', 10)).toBe('')
|
|
20
|
+
map.set('a', 'x', 1)
|
|
21
|
+
expect(map.get('b', 10)).toBe('')
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
it('returns an empty string before the first timestamp', () => {
|
|
25
|
+
const map = new TimeMap()
|
|
26
|
+
map.set('k', 'v', 10)
|
|
27
|
+
expect(map.get('k', 9)).toBe('')
|
|
28
|
+
expect(map.get('k', 10)).toBe('v')
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('returns the latest value at or before the timestamp, not the next one', () => {
|
|
32
|
+
const map = new TimeMap()
|
|
33
|
+
map.set('k', 'a', 10)
|
|
34
|
+
map.set('k', 'b', 20)
|
|
35
|
+
map.set('k', 'c', 30)
|
|
36
|
+
expect(map.get('k', 19)).toBe('a')
|
|
37
|
+
expect(map.get('k', 20)).toBe('b')
|
|
38
|
+
expect(map.get('k', 21)).toBe('b')
|
|
39
|
+
expect(map.get('k', 29)).toBe('b')
|
|
40
|
+
expect(map.get('k', 30)).toBe('c')
|
|
41
|
+
expect(map.get('k', 10_000_000)).toBe('c')
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
it('keeps each key separate', () => {
|
|
45
|
+
const map = new TimeMap()
|
|
46
|
+
map.set('love', 'high', 10)
|
|
47
|
+
map.set('hate', 'low', 15)
|
|
48
|
+
map.set('love', 'low', 20)
|
|
49
|
+
expect(map.get('love', 5)).toBe('')
|
|
50
|
+
expect(map.get('love', 15)).toBe('high')
|
|
51
|
+
expect(map.get('hate', 15)).toBe('low')
|
|
52
|
+
expect(map.get('hate', 14)).toBe('')
|
|
53
|
+
expect(map.get('love', 25)).toBe('low')
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
it('handles the same value stored at different times', () => {
|
|
57
|
+
const map = new TimeMap()
|
|
58
|
+
map.set('k', 'same', 1)
|
|
59
|
+
map.set('k', 'other', 2)
|
|
60
|
+
map.set('k', 'same', 3)
|
|
61
|
+
expect(map.get('k', 1)).toBe('same')
|
|
62
|
+
expect(map.get('k', 2)).toBe('other')
|
|
63
|
+
expect(map.get('k', 3)).toBe('same')
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
it('finds the right value among many timestamps', () => {
|
|
67
|
+
const map = new TimeMap()
|
|
68
|
+
for (let i = 1; i <= 100; i++) map.set('k', `v${i}`, i * 3)
|
|
69
|
+
for (let t = 0; t <= 310; t++) {
|
|
70
|
+
const expected = t < 3 ? '' : `v${Math.min(Math.floor(t / 3), 100)}`
|
|
71
|
+
expect(map.get('k', t), `timestamp ${t}`).toBe(expected)
|
|
72
|
+
}
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
it('keeps separate instances independent', () => {
|
|
76
|
+
const a = new TimeMap()
|
|
77
|
+
const b = new TimeMap()
|
|
78
|
+
a.set('k', 'from-a', 1)
|
|
79
|
+
b.set('k', 'from-b', 2)
|
|
80
|
+
expect(a.get('k', 5)).toBe('from-a')
|
|
81
|
+
expect(b.get('k', 5)).toBe('from-b')
|
|
82
|
+
expect(b.get('k', 1)).toBe('')
|
|
83
|
+
})
|
|
84
|
+
})
|
|
85
|
+
|
|
86
|
+
describe('119 performance', () => {
|
|
87
|
+
it('handles 50,000 sets on one key and ~60,000 gets in under 150 ms (scanning the stored values per get is too slow here)', () => {
|
|
88
|
+
const n = 50_000
|
|
89
|
+
const values = Array.from({ length: n }, (_, i) => `v${i}`)
|
|
90
|
+
let mismatches = 0
|
|
91
|
+
const ms = timeMs(() => {
|
|
92
|
+
const map = new TimeMap()
|
|
93
|
+
for (let i = 0; i < n; i++) map.set('key', values[i]!, i * 100 + 1)
|
|
94
|
+
// Spread the lookups over the whole history, landing between stored timestamps.
|
|
95
|
+
for (let q = 0; q < 60_000; q++) {
|
|
96
|
+
const i = (q * 7_919) % n
|
|
97
|
+
if (map.get('key', i * 100 + 50) !== values[i]) mismatches++
|
|
98
|
+
}
|
|
99
|
+
// Far past the last set: stepping back one timestamp at a time is too slow too.
|
|
100
|
+
for (let q = 0; q < 20; q++) {
|
|
101
|
+
if (map.get('key', 10_000_000) !== values[n - 1]) mismatches++
|
|
102
|
+
}
|
|
103
|
+
})
|
|
104
|
+
expect(mismatches, 'wrong get results').toBe(0)
|
|
105
|
+
expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(150)
|
|
106
|
+
})
|
|
107
|
+
})
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# 120 · Reorder List
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: linked list (fast/slow pointers, reverse, merge) · Target: 25 min · NeetCode 150 · LeetCode 143
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
You get the head of a singly linked list whose nodes, in order, are `L0 → L1 → … → Ln-1 → Ln`. Rearrange it so the nodes alternate from the front and the back:
|
|
8
|
+
|
|
9
|
+
`L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …`
|
|
10
|
+
|
|
11
|
+
Do it **in place**: relink the existing nodes, don't change any `val` and don't create new nodes. The function returns nothing (`void`); the tests read the list from the head they passed in.
|
|
12
|
+
|
|
13
|
+
## Examples
|
|
14
|
+
|
|
15
|
+
| Input | After reordering |
|
|
16
|
+
|---|---|
|
|
17
|
+
| `1 → 2 → 3 → 4` | `1 → 4 → 2 → 3` |
|
|
18
|
+
| `1 → 2 → 3 → 4 → 5` | `1 → 5 → 2 → 4 → 3` |
|
|
19
|
+
| `1` | `1` |
|
|
20
|
+
|
|
21
|
+
## Constraints
|
|
22
|
+
|
|
23
|
+
- `0 <= nodes <= 5 * 10^4`
|
|
24
|
+
- `1 <= val <= 1000`
|
|
25
|
+
- The tests check node identity, not just values: the k-th node of the result must be the exact original node that belongs there. Swapping `val`s between nodes fails.
|
|
26
|
+
|
|
27
|
+
## Run it
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pnpm watch 120
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
34
|
+
|
|
35
|
+
Time O(n) · Space O(1). Copying the nodes into an array and relinking them with two indices is O(n) time and O(n) space, a fine first answer. The O(1) version splits the list at the middle, reverses the second half, then interleaves the two halves. The tests don't time this one, so judge yourself: an approach that walks to the tail for every node is O(n²) and still passes.
|
|
36
|
+
|
|
37
|
+
</details>
|
|
38
|
+
|
|
39
|
+
## Follow-ups an interviewer might ask
|
|
40
|
+
|
|
41
|
+
- Can you do it with O(1) extra space?
|
|
42
|
+
- Where exactly do you split for odd vs even lengths, and why does it matter?
|
|
43
|
+
- How would you check a linked list is a palindrome in O(1) space? (LeetCode 234 uses the same three steps.)
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { ListNode, listFrom, listToArray } from '../../lib/linked-list'
|
|
3
|
+
import { reorderList } from './solution'
|
|
4
|
+
|
|
5
|
+
function nodesOf(head: ListNode | null, maxLength: number): ListNode[] {
|
|
6
|
+
const nodes: ListNode[] = []
|
|
7
|
+
for (let n = head; n; n = n.next) {
|
|
8
|
+
if (nodes.length >= maxLength) throw new Error('List is longer than expected — is there a cycle?')
|
|
9
|
+
nodes.push(n)
|
|
10
|
+
}
|
|
11
|
+
return nodes
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Reorders a list built from `values` and returns the resulting values. */
|
|
15
|
+
function reordered(values: number[]): number[] {
|
|
16
|
+
const head = listFrom(values)
|
|
17
|
+
reorderList(head)
|
|
18
|
+
return listToArray(head, values.length + 1)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** For each length, the original positions of the nodes in the order they should end up. */
|
|
22
|
+
const EXPECTED_POSITIONS: Record<number, number[]> = {
|
|
23
|
+
1: [0],
|
|
24
|
+
2: [0, 1],
|
|
25
|
+
3: [0, 2, 1],
|
|
26
|
+
4: [0, 3, 1, 2],
|
|
27
|
+
5: [0, 4, 1, 3, 2],
|
|
28
|
+
6: [0, 5, 1, 4, 2, 3],
|
|
29
|
+
7: [0, 6, 1, 5, 2, 4, 3],
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
describe('120 reorder list', () => {
|
|
33
|
+
it('reorders an even-length list', () => {
|
|
34
|
+
expect(reordered([1, 2, 3, 4])).toEqual([1, 4, 2, 3])
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
it('reorders an odd-length list', () => {
|
|
38
|
+
expect(reordered([1, 2, 3, 4, 5])).toEqual([1, 5, 2, 4, 3])
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
it('handles an empty list', () => {
|
|
42
|
+
expect(() => reorderList(null)).not.toThrow()
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
it('leaves one- and two-node lists alone', () => {
|
|
46
|
+
expect(reordered([1])).toEqual([1])
|
|
47
|
+
expect(reordered([1, 2])).toEqual([1, 2])
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
it('handles three nodes', () => {
|
|
51
|
+
expect(reordered([1, 2, 3])).toEqual([1, 3, 2])
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
it('handles duplicate values', () => {
|
|
55
|
+
expect(reordered([7, 7, 3, 3, 7])).toEqual([7, 7, 7, 3, 3])
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it('handles a longer list', () => {
|
|
59
|
+
expect(reordered([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])).toEqual([1, 10, 2, 9, 3, 8, 4, 7, 5, 6])
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
it('relinks the original nodes in place instead of swapping values', () => {
|
|
63
|
+
for (let n = 1; n <= 7; n++) {
|
|
64
|
+
const head = listFrom(Array.from({ length: n }, (_, i) => i + 1))
|
|
65
|
+
const original = nodesOf(head, n)
|
|
66
|
+
const position = new Map(original.map((node, i) => [node, i]))
|
|
67
|
+
reorderList(head)
|
|
68
|
+
const positions = nodesOf(head, n + 1).map((node) => position.get(node))
|
|
69
|
+
expect(positions, `length ${n}`).toEqual(EXPECTED_POSITIONS[n])
|
|
70
|
+
original.forEach((node, i) => expect(node.val).toBe(i + 1))
|
|
71
|
+
}
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
it('handles 3,000 nodes', () => {
|
|
75
|
+
const n = 3_000
|
|
76
|
+
const head = listFrom(Array.from({ length: n }, (_, i) => i))
|
|
77
|
+
reorderList(head)
|
|
78
|
+
const result = listToArray(head, n + 1)
|
|
79
|
+
expect(result).toHaveLength(n)
|
|
80
|
+
expect(result.slice(0, 6)).toEqual([0, n - 1, 1, n - 2, 2, n - 3])
|
|
81
|
+
expect(result.slice(-2)).toEqual([n / 2 - 1, n / 2])
|
|
82
|
+
})
|
|
83
|
+
})
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# 121 · Remove Nth Node From End of List
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: linked list (two pointers with a gap) · Target: 25 min · NeetCode 150 · LeetCode 19
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
You get the head of a singly linked list and a number `n`. Unlink the `n`-th node counting from the **end** (`n = 1` is the last node) and return the head of the resulting list. The head itself may be the node that gets removed.
|
|
8
|
+
|
|
9
|
+
## Examples
|
|
10
|
+
|
|
11
|
+
| `head` | `n` | Output |
|
|
12
|
+
|---|---|---|
|
|
13
|
+
| `1 → 2 → 3 → 4 → 5` | `2` | `1 → 2 → 3 → 5` |
|
|
14
|
+
| `1` | `1` | empty |
|
|
15
|
+
| `1 → 2` | `1` | `1` |
|
|
16
|
+
| `1 → 2` | `2` | `2` |
|
|
17
|
+
|
|
18
|
+
## Constraints
|
|
19
|
+
|
|
20
|
+
- The list has `sz` nodes, `1 <= sz <= 30`.
|
|
21
|
+
- `0 <= val <= 100`
|
|
22
|
+
- `1 <= n <= sz`, so the node always exists.
|
|
23
|
+
|
|
24
|
+
## Run it
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pnpm watch 121
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
31
|
+
|
|
32
|
+
Time O(sz) · Space O(1). Counting the length first and then walking `sz - n` steps is two passes and still O(sz), a fine answer. The classic follow-up wants **one** pass: keep two pointers `n` nodes apart.
|
|
33
|
+
|
|
34
|
+
</details>
|
|
35
|
+
|
|
36
|
+
## Follow-ups an interviewer might ask
|
|
37
|
+
|
|
38
|
+
- Can you do it in one pass?
|
|
39
|
+
- How do you avoid a special case when the head is the node being removed?
|
|
40
|
+
- What would you change if `n` might be larger than the list length?
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { ListNode, listFrom, listToArray } from '../../lib/linked-list'
|
|
3
|
+
import { removeNthFromEnd } from './solution'
|
|
4
|
+
|
|
5
|
+
const removed = (values: number[], n: number): number[] =>
|
|
6
|
+
listToArray(removeNthFromEnd(listFrom(values), n), values.length + 1)
|
|
7
|
+
|
|
8
|
+
describe('121 remove nth node from end of list', () => {
|
|
9
|
+
it('removes a node from the middle', () => {
|
|
10
|
+
expect(removed([1, 2, 3, 4, 5], 2)).toEqual([1, 2, 3, 5])
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
it('empties a single-node list', () => {
|
|
14
|
+
expect(removeNthFromEnd(listFrom([1]), 1)).toBeNull()
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
it('removes the last node', () => {
|
|
18
|
+
expect(removed([1, 2], 1)).toEqual([1])
|
|
19
|
+
expect(removed([1, 2, 3, 4, 5], 1)).toEqual([1, 2, 3, 4])
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
it('removes the head', () => {
|
|
23
|
+
expect(removed([1, 2], 2)).toEqual([2])
|
|
24
|
+
expect(removed([1, 2, 3, 4, 5], 5)).toEqual([2, 3, 4, 5])
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
it('removes the second node', () => {
|
|
28
|
+
expect(removed([1, 2, 3, 4, 5], 4)).toEqual([1, 3, 4, 5])
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('removes the right one among duplicate values', () => {
|
|
32
|
+
const head = listFrom([0, 0, 0])
|
|
33
|
+
const nodes = [head!, head!.next!, head!.next!.next!]
|
|
34
|
+
const result = removeNthFromEnd(head, 2)
|
|
35
|
+
expect(result).toBe(nodes[0])
|
|
36
|
+
expect(result!.next).toBe(nodes[2])
|
|
37
|
+
expect(nodes[2]!.next).toBeNull()
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
it('keeps the original nodes', () => {
|
|
41
|
+
const head = listFrom([10, 20, 30, 40])
|
|
42
|
+
const third: ListNode = head!.next!.next!
|
|
43
|
+
const result = removeNthFromEnd(head, 3)
|
|
44
|
+
expect(result).toBe(head)
|
|
45
|
+
expect(result!.next).toBe(third)
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
it('works at the size limit', () => {
|
|
49
|
+
const values = Array.from({ length: 30 }, (_, i) => i)
|
|
50
|
+
for (let n = 1; n <= 30; n++) {
|
|
51
|
+
const expected = values.filter((_, i) => i !== 30 - n)
|
|
52
|
+
expect(removed(values, n), `n = ${n}`).toEqual(expected)
|
|
53
|
+
}
|
|
54
|
+
})
|
|
55
|
+
})
|