interview-reps 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +59 -2
- package/content/CLAUDE.md +131 -0
- package/content/LADDER.md +166 -0
- package/content/behavioral/QUESTIONS.md +93 -0
- package/content/behavioral/REVIEW.md +86 -0
- package/content/design/D01-short-links/README.md +20 -0
- package/content/design/D02-rate-limiter/README.md +21 -0
- package/content/design/D03-news-feed/README.md +20 -0
- package/content/design/D04-chat-messaging/README.md +20 -0
- package/content/design/D05-notification-service/README.md +20 -0
- package/content/design/D06-typeahead-search/README.md +20 -0
- package/content/design/D07-web-crawler/README.md +20 -0
- package/content/design/D08-file-sync/README.md +20 -0
- package/content/design/D09-ride-matching/README.md +20 -0
- package/content/design/D10-job-scheduler/README.md +20 -0
- package/content/design/D11-metrics-alerting/README.md +20 -0
- package/content/design/D12-payments-ledger/README.md +20 -0
- package/content/design/REVIEW.md +94 -0
- package/content/lib/binary-tree.ts +69 -0
- package/content/lib/graph.ts +50 -0
- package/content/lib/linked-list.ts +37 -0
- package/content/lib/perf.ts +9 -0
- package/content/problems/001-contains-duplicate/README.md +37 -0
- package/content/problems/001-contains-duplicate/solution.test.ts +38 -0
- package/content/problems/002-valid-anagram/README.md +36 -0
- package/content/problems/002-valid-anagram/solution.test.ts +38 -0
- package/content/problems/003-two-sum/README.md +40 -0
- package/content/problems/003-two-sum/solution.test.ts +40 -0
- package/content/problems/004-valid-palindrome/README.md +39 -0
- package/content/problems/004-valid-palindrome/solution.test.ts +38 -0
- package/content/problems/005-best-time-to-buy-and-sell-stock/README.md +38 -0
- package/content/problems/005-best-time-to-buy-and-sell-stock/solution.test.ts +39 -0
- package/content/problems/006-valid-parentheses/README.md +42 -0
- package/content/problems/006-valid-parentheses/solution.test.ts +41 -0
- package/content/problems/007-binary-search/README.md +39 -0
- package/content/problems/007-binary-search/solution.test.ts +56 -0
- package/content/problems/008-reverse-linked-list/README.md +39 -0
- package/content/problems/008-reverse-linked-list/solution.test.ts +41 -0
- package/content/problems/009-merge-two-sorted-lists/README.md +36 -0
- package/content/problems/009-merge-two-sorted-lists/solution.test.ts +43 -0
- package/content/problems/010-linked-list-cycle/README.md +37 -0
- package/content/problems/010-linked-list-cycle/solution.test.ts +39 -0
- package/content/problems/011-invert-binary-tree/README.md +39 -0
- package/content/problems/011-invert-binary-tree/solution.test.ts +32 -0
- package/content/problems/012-maximum-depth-of-binary-tree/README.md +37 -0
- package/content/problems/012-maximum-depth-of-binary-tree/solution.test.ts +29 -0
- package/content/problems/013-same-tree/README.md +37 -0
- package/content/problems/013-same-tree/solution.test.ts +38 -0
- package/content/problems/014-balanced-binary-tree/README.md +37 -0
- package/content/problems/014-balanced-binary-tree/solution.test.ts +38 -0
- package/content/problems/015-climbing-stairs/README.md +35 -0
- package/content/problems/015-climbing-stairs/solution.test.ts +27 -0
- package/content/problems/016-diameter-of-binary-tree/README.md +38 -0
- package/content/problems/016-diameter-of-binary-tree/solution.test.ts +63 -0
- package/content/problems/017-subtree-of-another-tree/README.md +42 -0
- package/content/problems/017-subtree-of-another-tree/solution.test.ts +61 -0
- package/content/problems/018-kth-largest-element-in-a-stream/README.md +49 -0
- package/content/problems/018-kth-largest-element-in-a-stream/solution.test.ts +104 -0
- package/content/problems/019-last-stone-weight/README.md +44 -0
- package/content/problems/019-last-stone-weight/solution.test.ts +67 -0
- package/content/problems/020-min-cost-climbing-stairs/README.md +40 -0
- package/content/problems/020-min-cost-climbing-stairs/solution.test.ts +44 -0
- package/content/problems/021-single-number/README.md +41 -0
- package/content/problems/021-single-number/solution.test.ts +46 -0
- package/content/problems/022-missing-number/README.md +40 -0
- package/content/problems/022-missing-number/solution.test.ts +44 -0
- package/content/problems/101-group-anagrams/README.md +41 -0
- package/content/problems/101-group-anagrams/solution.test.ts +83 -0
- package/content/problems/102-top-k-frequent-elements/README.md +44 -0
- package/content/problems/102-top-k-frequent-elements/solution.test.ts +59 -0
- package/content/problems/103-product-of-array-except-self/README.md +43 -0
- package/content/problems/103-product-of-array-except-self/solution.test.ts +59 -0
- package/content/problems/104-longest-consecutive-sequence/README.md +40 -0
- package/content/problems/104-longest-consecutive-sequence/solution.test.ts +62 -0
- package/content/problems/105-encode-and-decode-strings/README.md +47 -0
- package/content/problems/105-encode-and-decode-strings/solution.test.ts +50 -0
- package/content/problems/106-two-sum-ii-input-array-is-sorted/README.md +43 -0
- package/content/problems/106-two-sum-ii-input-array-is-sorted/solution.test.ts +47 -0
- package/content/problems/107-three-sum/README.md +42 -0
- package/content/problems/107-three-sum/solution.test.ts +79 -0
- package/content/problems/108-container-with-most-water/README.md +40 -0
- package/content/problems/108-container-with-most-water/solution.test.ts +53 -0
- package/content/problems/109-longest-substring-without-repeating-characters/README.md +40 -0
- package/content/problems/109-longest-substring-without-repeating-characters/solution.test.ts +56 -0
- package/content/problems/110-longest-repeating-character-replacement/README.md +41 -0
- package/content/problems/110-longest-repeating-character-replacement/solution.test.ts +51 -0
- package/content/problems/111-permutation-in-string/README.md +38 -0
- package/content/problems/111-permutation-in-string/solution.test.ts +54 -0
- package/content/problems/112-min-stack/README.md +51 -0
- package/content/problems/112-min-stack/solution.test.ts +123 -0
- package/content/problems/113-daily-temperatures/README.md +40 -0
- package/content/problems/113-daily-temperatures/solution.test.ts +56 -0
- package/content/problems/114-evaluate-reverse-polish-notation/README.md +44 -0
- package/content/problems/114-evaluate-reverse-polish-notation/solution.test.ts +56 -0
- package/content/problems/115-generate-parentheses/README.md +38 -0
- package/content/problems/115-generate-parentheses/solution.test.ts +59 -0
- package/content/problems/116-koko-eating-bananas/README.md +41 -0
- package/content/problems/116-koko-eating-bananas/solution.test.ts +53 -0
- package/content/problems/117-find-minimum-in-rotated-sorted-array/README.md +41 -0
- package/content/problems/117-find-minimum-in-rotated-sorted-array/solution.test.ts +69 -0
- package/content/problems/118-search-in-rotated-sorted-array/README.md +41 -0
- package/content/problems/118-search-in-rotated-sorted-array/solution.test.ts +95 -0
- package/content/problems/119-time-based-key-value-store/README.md +50 -0
- package/content/problems/119-time-based-key-value-store/solution.test.ts +107 -0
- package/content/problems/120-reorder-list/README.md +43 -0
- package/content/problems/120-reorder-list/solution.test.ts +83 -0
- package/content/problems/121-remove-nth-node-from-end-of-list/README.md +40 -0
- package/content/problems/121-remove-nth-node-from-end-of-list/solution.test.ts +55 -0
- package/content/problems/122-lru-cache/README.md +55 -0
- package/content/problems/122-lru-cache/solution.test.ts +152 -0
- package/content/problems/123-binary-tree-level-order-traversal/README.md +40 -0
- package/content/problems/123-binary-tree-level-order-traversal/solution.test.ts +42 -0
- package/content/problems/124-binary-tree-right-side-view/README.md +40 -0
- package/content/problems/124-binary-tree-right-side-view/solution.test.ts +56 -0
- package/content/problems/125-validate-binary-search-tree/README.md +46 -0
- package/content/problems/125-validate-binary-search-tree/solution.test.ts +78 -0
- package/content/problems/126-kth-smallest-element-in-a-bst/README.md +39 -0
- package/content/problems/126-kth-smallest-element-in-a-bst/solution.test.ts +61 -0
- package/content/problems/127-lowest-common-ancestor-of-a-bst/README.md +46 -0
- package/content/problems/127-lowest-common-ancestor-of-a-bst/solution.test.ts +106 -0
- package/content/problems/128-kth-largest-element-in-an-array/README.md +42 -0
- package/content/problems/128-kth-largest-element-in-an-array/solution.test.ts +67 -0
- package/content/problems/129-k-closest-points-to-origin/README.md +43 -0
- package/content/problems/129-k-closest-points-to-origin/solution.test.ts +74 -0
- package/content/problems/130-number-of-islands/README.md +44 -0
- package/content/problems/130-number-of-islands/solution.test.ts +69 -0
- package/content/problems/131-course-schedule/README.md +42 -0
- package/content/problems/131-course-schedule/solution.test.ts +82 -0
- package/content/problems/132-rotting-oranges/README.md +46 -0
- package/content/problems/132-rotting-oranges/solution.test.ts +74 -0
- package/content/problems/133-clone-graph/README.md +42 -0
- package/content/problems/133-clone-graph/solution.test.ts +58 -0
- package/content/problems/134-house-robber/README.md +38 -0
- package/content/problems/134-house-robber/solution.test.ts +45 -0
- package/content/problems/135-coin-change/README.md +40 -0
- package/content/problems/135-coin-change/solution.test.ts +45 -0
- package/content/problems/136-longest-increasing-subsequence/README.md +41 -0
- package/content/problems/136-longest-increasing-subsequence/solution.test.ts +53 -0
- package/content/problems/137-word-break/README.md +39 -0
- package/content/problems/137-word-break/solution.test.ts +49 -0
- package/content/problems/138-merge-intervals/README.md +40 -0
- package/content/problems/138-merge-intervals/solution.test.ts +84 -0
- package/content/problems/139-insert-interval/README.md +40 -0
- package/content/problems/139-insert-interval/solution.test.ts +75 -0
- package/content/problems/201-valid-sudoku/README.md +63 -0
- package/content/problems/201-valid-sudoku/solution.test.ts +104 -0
- package/content/problems/202-car-fleet/README.md +46 -0
- package/content/problems/202-car-fleet/solution.test.ts +85 -0
- package/content/problems/203-search-a-2d-matrix/README.md +47 -0
- package/content/problems/203-search-a-2d-matrix/solution.test.ts +108 -0
- package/content/problems/204-copy-list-with-random-pointer/README.md +46 -0
- package/content/problems/204-copy-list-with-random-pointer/solution.test.ts +120 -0
- package/content/problems/205-add-two-numbers/README.md +45 -0
- package/content/problems/205-add-two-numbers/solution.test.ts +74 -0
- package/content/problems/206-find-the-duplicate-number/README.md +47 -0
- package/content/problems/206-find-the-duplicate-number/solution.test.ts +72 -0
- package/content/problems/207-count-good-nodes/README.md +44 -0
- package/content/problems/207-count-good-nodes/solution.test.ts +63 -0
- package/content/problems/208-construct-tree-from-preorder-and-inorder/README.md +52 -0
- package/content/problems/208-construct-tree-from-preorder-and-inorder/solution.test.ts +126 -0
- package/content/problems/209-implement-trie/README.md +52 -0
- package/content/problems/209-implement-trie/solution.test.ts +138 -0
- package/content/problems/210-design-add-and-search-words/README.md +50 -0
- package/content/problems/210-design-add-and-search-words/solution.test.ts +127 -0
- package/content/problems/211-task-scheduler/README.md +47 -0
- package/content/problems/211-task-scheduler/solution.test.ts +64 -0
- package/content/problems/212-design-twitter/README.md +63 -0
- package/content/problems/212-design-twitter/solution.test.ts +137 -0
- package/content/problems/213-subsets/README.md +42 -0
- package/content/problems/213-subsets/solution.test.ts +63 -0
- package/content/problems/214-combination-sum/README.md +44 -0
- package/content/problems/214-combination-sum/solution.test.ts +75 -0
- package/content/problems/215-permutations/README.md +42 -0
- package/content/problems/215-permutations/solution.test.ts +70 -0
- package/content/problems/216-word-search/README.md +50 -0
- package/content/problems/216-word-search/solution.test.ts +86 -0
- package/content/problems/217-letter-combinations-of-a-phone-number/README.md +53 -0
- package/content/problems/217-letter-combinations-of-a-phone-number/solution.test.ts +57 -0
- package/content/problems/218-palindrome-partitioning/README.md +42 -0
- package/content/problems/218-palindrome-partitioning/solution.test.ts +77 -0
- package/content/problems/219-max-area-of-island/README.md +43 -0
- package/content/problems/219-max-area-of-island/solution.test.ts +78 -0
- package/content/problems/220-pacific-atlantic-water-flow/README.md +43 -0
- package/content/problems/220-pacific-atlantic-water-flow/solution.test.ts +86 -0
- package/content/problems/221-course-schedule-ii/README.md +42 -0
- package/content/problems/221-course-schedule-ii/solution.test.ts +107 -0
- package/content/problems/222-graph-valid-tree/README.md +42 -0
- package/content/problems/222-graph-valid-tree/solution.test.ts +75 -0
- package/content/problems/223-redundant-connection/README.md +42 -0
- package/content/problems/223-redundant-connection/solution.test.ts +68 -0
- package/content/problems/224-network-delay-time/README.md +44 -0
- package/content/problems/224-network-delay-time/solution.test.ts +70 -0
- package/content/problems/225-cheapest-flights-within-k-stops/README.md +45 -0
- package/content/problems/225-cheapest-flights-within-k-stops/solution.test.ts +85 -0
- package/content/problems/226-house-robber-ii/README.md +41 -0
- package/content/problems/226-house-robber-ii/solution.test.ts +51 -0
- package/content/problems/227-longest-palindromic-substring/README.md +41 -0
- package/content/problems/227-longest-palindromic-substring/solution.test.ts +69 -0
- package/content/problems/228-decode-ways/README.md +44 -0
- package/content/problems/228-decode-ways/solution.test.ts +50 -0
- package/content/problems/229-maximum-product-subarray/README.md +40 -0
- package/content/problems/229-maximum-product-subarray/solution.test.ts +55 -0
- package/content/problems/230-partition-equal-subset-sum/README.md +39 -0
- package/content/problems/230-partition-equal-subset-sum/solution.test.ts +54 -0
- package/content/problems/231-unique-paths/README.md +41 -0
- package/content/problems/231-unique-paths/solution.test.ts +45 -0
- package/content/problems/232-longest-common-subsequence/README.md +41 -0
- package/content/problems/232-longest-common-subsequence/solution.test.ts +48 -0
- package/content/problems/233-coin-change-ii/README.md +44 -0
- package/content/problems/233-coin-change-ii/solution.test.ts +45 -0
- package/content/problems/234-edit-distance/README.md +45 -0
- package/content/problems/234-edit-distance/solution.test.ts +48 -0
- package/content/problems/235-maximum-subarray/README.md +40 -0
- package/content/problems/235-maximum-subarray/solution.test.ts +63 -0
- package/content/problems/236-jump-game/README.md +40 -0
- package/content/problems/236-jump-game/solution.test.ts +68 -0
- package/content/problems/237-gas-station/README.md +42 -0
- package/content/problems/237-gas-station/solution.test.ts +56 -0
- package/content/problems/238-partition-labels/README.md +40 -0
- package/content/problems/238-partition-labels/solution.test.ts +54 -0
- package/content/problems/239-non-overlapping-intervals/README.md +40 -0
- package/content/problems/239-non-overlapping-intervals/solution.test.ts +61 -0
- package/content/problems/240-meeting-rooms-ii/README.md +42 -0
- package/content/problems/240-meeting-rooms-ii/solution.test.ts +65 -0
- package/content/problems/241-rotate-image/README.md +41 -0
- package/content/problems/241-rotate-image/solution.test.ts +72 -0
- package/content/problems/242-spiral-matrix/README.md +40 -0
- package/content/problems/242-spiral-matrix/solution.test.ts +90 -0
- package/content/problems/243-set-matrix-zeroes/README.md +44 -0
- package/content/problems/243-set-matrix-zeroes/solution.test.ts +153 -0
- package/content/problems/301-trapping-rain-water/README.md +42 -0
- package/content/problems/301-trapping-rain-water/solution.test.ts +63 -0
- package/content/problems/302-minimum-window-substring/README.md +43 -0
- package/content/problems/302-minimum-window-substring/solution.test.ts +56 -0
- package/content/problems/303-sliding-window-maximum/README.md +42 -0
- package/content/problems/303-sliding-window-maximum/solution.test.ts +63 -0
- package/content/problems/304-largest-rectangle-in-histogram/README.md +42 -0
- package/content/problems/304-largest-rectangle-in-histogram/solution.test.ts +57 -0
- package/content/problems/305-median-of-two-sorted-arrays/README.md +42 -0
- package/content/problems/305-median-of-two-sorted-arrays/solution.test.ts +84 -0
- package/content/problems/306-merge-k-sorted-lists/README.md +42 -0
- package/content/problems/306-merge-k-sorted-lists/solution.test.ts +72 -0
- package/content/problems/307-reverse-nodes-in-k-group/README.md +42 -0
- package/content/problems/307-reverse-nodes-in-k-group/solution.test.ts +86 -0
- package/content/problems/308-binary-tree-maximum-path-sum/README.md +44 -0
- package/content/problems/308-binary-tree-maximum-path-sum/solution.test.ts +91 -0
- package/content/problems/309-serialize-and-deserialize-binary-tree/README.md +50 -0
- package/content/problems/309-serialize-and-deserialize-binary-tree/solution.test.ts +120 -0
- package/content/problems/310-find-median-from-data-stream/README.md +47 -0
- package/content/problems/310-find-median-from-data-stream/solution.test.ts +102 -0
- package/content/problems/311-word-search-ii/README.md +51 -0
- package/content/problems/311-word-search-ii/solution.test.ts +144 -0
- package/content/problems/312-n-queens/README.md +41 -0
- package/content/problems/312-n-queens/solution.test.ts +91 -0
- package/content/problems/313-word-ladder/README.md +42 -0
- package/content/problems/313-word-ladder/solution.test.ts +85 -0
- package/content/problems/314-alien-dictionary/README.md +43 -0
- package/content/problems/314-alien-dictionary/solution.test.ts +127 -0
- package/content/problems/315-longest-increasing-path-in-a-matrix/README.md +42 -0
- package/content/problems/315-longest-increasing-path-in-a-matrix/solution.test.ts +118 -0
- package/content/problems/316-swim-in-rising-water/README.md +44 -0
- package/content/problems/316-swim-in-rising-water/solution.test.ts +138 -0
- package/content/product/P01-tool-lending/README.md +28 -0
- package/content/product/P02-city-bike-share/README.md +28 -0
- package/content/product/P03-caring-from-afar/README.md +29 -0
- package/content/product/P04-first-garden/README.md +28 -0
- package/content/product/P05-save-for-later/README.md +28 -0
- package/content/product/P06-ship-or-hold/README.md +28 -0
- package/content/product/P07-photo-backup-goals/README.md +28 -0
- package/content/product/P08-quarter-roadmap/README.md +28 -0
- package/content/product/P09-grocer-delivery/README.md +29 -0
- package/content/product/P10-notes-for-work/README.md +28 -0
- package/content/product/P11-fitness-coaching/README.md +28 -0
- package/content/product/P12-low-price-rival/README.md +28 -0
- package/content/product/P13-coffee-cups/README.md +28 -0
- package/content/product/P14-bike-repair-market/README.md +27 -0
- package/content/product/P15-scooter-rides/README.md +27 -0
- package/content/product/P16-school-lunch-boxes/README.md +28 -0
- package/content/product/P17-weekly-users-drop/README.md +28 -0
- package/content/product/P18-ride-cancellations/README.md +28 -0
- package/content/product/P19-signups-up-revenue-flat/README.md +28 -0
- package/content/product/P20-longer-sessions/README.md +28 -0
- package/content/product/REVIEW.md +107 -0
- package/dist/cli.mjs +4418 -0
- package/package.json +38 -4
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { TreeNode, findNode, treeFrom } from '../../lib/binary-tree'
|
|
3
|
+
import { lowestCommonAncestor } from './solution'
|
|
4
|
+
|
|
5
|
+
const EXAMPLE = [6, 2, 8, 0, 4, 7, 9, null, null, 3, 5]
|
|
6
|
+
|
|
7
|
+
/** Looks up p, q and the expected answer by value, then checks the returned node is that exact node. */
|
|
8
|
+
function expectLca(levelOrder: (number | null)[], p: number, q: number, expected: number): void {
|
|
9
|
+
const root = treeFrom(levelOrder)
|
|
10
|
+
const pNode = findNode(root, p)!
|
|
11
|
+
const qNode = findNode(root, q)!
|
|
12
|
+
expect(lowestCommonAncestor(root, pNode, qNode)).toBe(findNode(root, expected))
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Builds a height-balanced BST holding lo..hi. */
|
|
16
|
+
function balancedBST(lo: number, hi: number): TreeNode | null {
|
|
17
|
+
if (lo > hi) return null
|
|
18
|
+
const mid = Math.floor((lo + hi) / 2)
|
|
19
|
+
return new TreeNode(mid, balancedBST(lo, mid - 1), balancedBST(mid + 1, hi))
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Replaces every node's `left`/`right` with getters that count reads. */
|
|
23
|
+
function countChildReads(root: TreeNode | null): { reads: () => number; reset: () => void } {
|
|
24
|
+
let reads = 0
|
|
25
|
+
const stack: TreeNode[] = root ? [root] : []
|
|
26
|
+
while (stack.length > 0) {
|
|
27
|
+
const node = stack.pop()!
|
|
28
|
+
for (const side of ['left', 'right'] as const) {
|
|
29
|
+
let child = node[side]
|
|
30
|
+
if (child) stack.push(child)
|
|
31
|
+
Object.defineProperty(node, side, {
|
|
32
|
+
configurable: true,
|
|
33
|
+
enumerable: true,
|
|
34
|
+
get: () => {
|
|
35
|
+
reads++
|
|
36
|
+
return child
|
|
37
|
+
},
|
|
38
|
+
set: (value: TreeNode | null) => {
|
|
39
|
+
child = value
|
|
40
|
+
},
|
|
41
|
+
})
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return { reads: () => reads, reset: () => (reads = 0) }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
describe('127 lowest common ancestor of a bst', () => {
|
|
48
|
+
it('returns the root when p and q are on opposite sides', () => {
|
|
49
|
+
expectLca(EXAMPLE, 2, 8, 6)
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
it('returns p when p is an ancestor of q', () => {
|
|
53
|
+
expectLca(EXAMPLE, 2, 4, 2)
|
|
54
|
+
expectLca(EXAMPLE, 2, 0, 2)
|
|
55
|
+
expectLca(EXAMPLE, 6, 5, 6)
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it('finds an ancestor deeper down', () => {
|
|
59
|
+
expectLca(EXAMPLE, 3, 5, 4)
|
|
60
|
+
expectLca(EXAMPLE, 0, 5, 2)
|
|
61
|
+
expectLca(EXAMPLE, 7, 9, 8)
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
it('does not care about the order of p and q', () => {
|
|
65
|
+
expectLca(EXAMPLE, 8, 2, 6)
|
|
66
|
+
expectLca(EXAMPLE, 5, 3, 4)
|
|
67
|
+
expectLca(EXAMPLE, 4, 2, 2)
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
it('handles a two-node tree', () => {
|
|
71
|
+
expectLca([2, 1], 2, 1, 2)
|
|
72
|
+
expectLca([2, 1], 1, 2, 2)
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
it('handles negative values', () => {
|
|
76
|
+
expectLca([0, -5, 5, -8, -2, 3, 8], -8, -2, -5)
|
|
77
|
+
expectLca([0, -5, 5, -8, -2, 3, 8], -2, 3, 0)
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
it('handles a deep chain', () => {
|
|
81
|
+
// 1 → 2 → ... → 2000, every node on the right.
|
|
82
|
+
const values: (number | null)[] = [1]
|
|
83
|
+
for (let v = 2; v <= 2_000; v++) values.push(null, v)
|
|
84
|
+
expectLca(values, 1_500, 2_000, 1_500)
|
|
85
|
+
})
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
describe('127 read count', () => {
|
|
89
|
+
it('reads at most 200 child pointers in a 65,535-node BST (a full traversal reads about 130,000)', () => {
|
|
90
|
+
const root = balancedBST(1, 65_535)
|
|
91
|
+
const pairs: [number, number, number][] = [
|
|
92
|
+
[1, 65_535, 32_768],
|
|
93
|
+
[3, 1, 2],
|
|
94
|
+
[40_000, 40_001, 40_000],
|
|
95
|
+
[100, 200, 128],
|
|
96
|
+
[65_534, 65_535, 65_534],
|
|
97
|
+
]
|
|
98
|
+
const lookups = pairs.map(([p, q, lca]) => [findNode(root, p)!, findNode(root, q)!, findNode(root, lca)!] as const)
|
|
99
|
+
const counter = countChildReads(root)
|
|
100
|
+
for (const [p, q, lca] of lookups) {
|
|
101
|
+
counter.reset()
|
|
102
|
+
expect(lowestCommonAncestor(root, p, q)).toBe(lca)
|
|
103
|
+
expect(counter.reads(), `read ${counter.reads()} child pointers for p=${p.val}, q=${q.val}`).toBeLessThanOrEqual(200)
|
|
104
|
+
}
|
|
105
|
+
})
|
|
106
|
+
})
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# 128 · Kth Largest Element in an Array
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: heap / priority queue · Target: 25 min · NeetCode 150 · LeetCode 215
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
Given an array of integers `nums` and an integer `k`, return the `k`-th largest value. This is by position in sorted order, so duplicates count separately: in `[3, 3, 1]` the 1st and 2nd largest are both `3`.
|
|
8
|
+
|
|
9
|
+
Don't modify `nums` (it's `readonly`). Copy it first if your approach needs to rearrange values.
|
|
10
|
+
|
|
11
|
+
TypeScript has no built-in priority queue. You can write a small binary heap yourself, sort, or use quickselect. All are fine here.
|
|
12
|
+
|
|
13
|
+
## Examples
|
|
14
|
+
|
|
15
|
+
| `nums` | `k` | Output |
|
|
16
|
+
|---|---|---|
|
|
17
|
+
| `[3, 2, 1, 5, 6, 4]` | `2` | `5` |
|
|
18
|
+
| `[3, 2, 3, 1, 2, 4, 5, 5, 6]` | `4` | `4` |
|
|
19
|
+
| `[1]` | `1` | `1` |
|
|
20
|
+
|
|
21
|
+
## Constraints
|
|
22
|
+
|
|
23
|
+
- `1 <= k <= nums.length <= 10^5` (the performance test uses 100,000 values with `k = 8,000`)
|
|
24
|
+
- `-10^4 <= nums[i] <= 10^4` in the examples. Some tests use a wider range.
|
|
25
|
+
|
|
26
|
+
## Run it
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pnpm watch 128
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
33
|
+
|
|
34
|
+
Sorting is O(n log n) and passes. A min-heap of size `k` is O(n log k) time and O(k) space. Quickselect is O(n) on average (O(n²) worst case unless the pivot is random). Repeatedly scanning for the maximum is O(n·k), which is too slow for large `k`.
|
|
35
|
+
|
|
36
|
+
</details>
|
|
37
|
+
|
|
38
|
+
## Follow-ups an interviewer might ask
|
|
39
|
+
|
|
40
|
+
- Why a **min**-heap of size `k`, not a max-heap of everything?
|
|
41
|
+
- Quickselect: what's the worst case, and how do you avoid it? What happens if every value is equal?
|
|
42
|
+
- The numbers arrive as a stream and you're asked for the k-th largest after each one (LeetCode 703).
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { timeMs } from '../../lib/perf'
|
|
3
|
+
import { findKthLargest } from './solution'
|
|
4
|
+
|
|
5
|
+
/** Deterministic shuffle of 0..n-1 (Fisher-Yates with a seeded MINSTD generator), so test data is the same every run. */
|
|
6
|
+
function shuffledRange(n: number, seed: number): number[] {
|
|
7
|
+
const out = Array.from({ length: n }, (_, i) => i)
|
|
8
|
+
let state = seed
|
|
9
|
+
for (let i = n - 1; i > 0; i--) {
|
|
10
|
+
state = (state * 48_271) % 2_147_483_647
|
|
11
|
+
const j = state % (i + 1)
|
|
12
|
+
;[out[i], out[j]] = [out[j]!, out[i]!]
|
|
13
|
+
}
|
|
14
|
+
return out
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
describe('128 kth largest element in an array', () => {
|
|
18
|
+
it('finds the 2nd largest', () => {
|
|
19
|
+
expect(findKthLargest([3, 2, 1, 5, 6, 4], 2)).toBe(5)
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
it('counts duplicates separately', () => {
|
|
23
|
+
expect(findKthLargest([3, 2, 3, 1, 2, 4, 5, 5, 6], 4)).toBe(4)
|
|
24
|
+
expect(findKthLargest([3, 3, 1], 2)).toBe(3)
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
it('handles a single element', () => {
|
|
28
|
+
expect(findKthLargest([1], 1)).toBe(1)
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('finds the largest and the smallest', () => {
|
|
32
|
+
expect(findKthLargest([7, -2, 9, 4], 1)).toBe(9)
|
|
33
|
+
expect(findKthLargest([7, -2, 9, 4], 4)).toBe(-2)
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
it('compares numbers, not strings', () => {
|
|
37
|
+
// A plain .sort() without a comparator would order these as strings.
|
|
38
|
+
expect(findKthLargest([10, 9, 100, 2, 25], 2)).toBe(25)
|
|
39
|
+
expect(findKthLargest([-1, -10, -2, 5], 2)).toBe(-1)
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
it('handles all-equal values', () => {
|
|
43
|
+
expect(findKthLargest([4, 4, 4, 4], 3)).toBe(4)
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
it('handles sorted and reverse-sorted input', () => {
|
|
47
|
+
const up = Array.from({ length: 1_000 }, (_, i) => i)
|
|
48
|
+
expect(findKthLargest(up, 10)).toBe(990)
|
|
49
|
+
expect(findKthLargest([...up].reverse(), 10)).toBe(990)
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
it('does not modify the input', () => {
|
|
53
|
+
const nums = [5, 1, 4, 2, 3]
|
|
54
|
+
findKthLargest(nums, 2)
|
|
55
|
+
expect(nums).toEqual([5, 1, 4, 2, 3])
|
|
56
|
+
})
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
describe('128 performance', () => {
|
|
60
|
+
it('finds the 8,000th largest of 100,000 values in under 150 ms (scanning for the max k times, O(n·k), is too slow here)', () => {
|
|
61
|
+
const n = 100_000
|
|
62
|
+
const k = 8_000
|
|
63
|
+
const nums = shuffledRange(n, 42).map((v) => v - 50_000)
|
|
64
|
+
const ms = timeMs(() => expect(findKthLargest(nums, k)).toBe(n - k - 50_000))
|
|
65
|
+
expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(150)
|
|
66
|
+
})
|
|
67
|
+
})
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# 129 · K Closest Points to Origin
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: heap / priority queue · Target: 25 min · NeetCode 150 · LeetCode 973
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
You get a list of points on a plane, each as `[x, y]`, and an integer `k`. Return the `k` points closest to the origin `(0, 0)`, measured by ordinary straight-line (Euclidean) distance.
|
|
8
|
+
|
|
9
|
+
You can return the points in any order; the tests sort your answer before comparing. Every test is built so the answer is unique (no tie at the `k`-th place). Don't modify `points`.
|
|
10
|
+
|
|
11
|
+
TypeScript has no built-in priority queue. You can write a small binary heap yourself, sort, or use quickselect. All are fine here.
|
|
12
|
+
|
|
13
|
+
## Examples
|
|
14
|
+
|
|
15
|
+
| `points` | `k` | Output |
|
|
16
|
+
|---|---|---|
|
|
17
|
+
| `[[1, 3], [-2, 2]]` | `1` | `[[-2, 2]]` |
|
|
18
|
+
| `[[3, 3], [5, -1], [-2, 4]]` | `2` | `[[3, 3], [-2, 4]]` (any order) |
|
|
19
|
+
|
|
20
|
+
## Constraints
|
|
21
|
+
|
|
22
|
+
- `1 <= k <= points.length <= 10^4` (the performance test uses 50,000 points with `k = 10,000`)
|
|
23
|
+
- `-10^4 <= x, y <= 10^4` in the examples. The performance test uses a wider range.
|
|
24
|
+
|
|
25
|
+
## Run it
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pnpm watch 129
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
32
|
+
|
|
33
|
+
Sorting by distance is O(n log n) and passes. A max-heap of size `k` is O(n log k) time and O(k) space. Quickselect is O(n) on average. Repeatedly scanning for the closest remaining point is O(n·k), which is too slow for large `k`.
|
|
34
|
+
|
|
35
|
+
You never need the square root: comparing `x² + y²` gives the same order.
|
|
36
|
+
|
|
37
|
+
</details>
|
|
38
|
+
|
|
39
|
+
## Follow-ups an interviewer might ask
|
|
40
|
+
|
|
41
|
+
- Why a **max**-heap of size `k` here, when 128 used a min-heap?
|
|
42
|
+
- The points arrive as a stream too large to store. Which approach still works?
|
|
43
|
+
- What would you do if there could be ties at the `k`-th place?
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { timeMs } from '../../lib/perf'
|
|
3
|
+
import { kClosest } from './solution'
|
|
4
|
+
|
|
5
|
+
type Point = readonly [number, number]
|
|
6
|
+
|
|
7
|
+
/** Copies and sorts points by x, then y, so any valid order compares equal. */
|
|
8
|
+
const normalise = (points: readonly Point[]): [number, number][] =>
|
|
9
|
+
points.map(([x, y]): [number, number] => [x, y]).sort((a, b) => a[0] - b[0] || a[1] - b[1])
|
|
10
|
+
|
|
11
|
+
const closest = (points: Point[], k: number): [number, number][] => normalise(kClosest(points, k))
|
|
12
|
+
|
|
13
|
+
/** Deterministic shuffle of 0..n-1 (Fisher-Yates with a seeded MINSTD generator), so test data is the same every run. */
|
|
14
|
+
function shuffledRange(n: number, seed: number): number[] {
|
|
15
|
+
const out = Array.from({ length: n }, (_, i) => i)
|
|
16
|
+
let state = seed
|
|
17
|
+
for (let i = n - 1; i > 0; i--) {
|
|
18
|
+
state = (state * 48_271) % 2_147_483_647
|
|
19
|
+
const j = state % (i + 1)
|
|
20
|
+
;[out[i], out[j]] = [out[j]!, out[i]!]
|
|
21
|
+
}
|
|
22
|
+
return out
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Point number v sits at distance v·√2, in one of two quadrants. */
|
|
26
|
+
const pointFor = (v: number): Point => (v % 2 === 0 ? [v, 0 - v] : [0 - v, v]) // 0 - v avoids -0
|
|
27
|
+
|
|
28
|
+
describe('129 k closest points to origin', () => {
|
|
29
|
+
it('picks the single closest point', () => {
|
|
30
|
+
expect(closest([[1, 3], [-2, 2]], 1)).toEqual([[-2, 2]])
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
it('returns k points in any order', () => {
|
|
34
|
+
expect(closest([[3, 3], [5, -1], [-2, 4]], 2)).toEqual(normalise([[3, 3], [-2, 4]]))
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
it('returns every point when k equals the length', () => {
|
|
38
|
+
expect(closest([[1, 1], [-3, 0], [0, 2]], 3)).toEqual(normalise([[1, 1], [-3, 0], [0, 2]]))
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
it('uses straight-line distance, not |x| + |y|', () => {
|
|
42
|
+
// (2, 2) is closer (8 < 9) even though |2| + |2| = 4 > 3.
|
|
43
|
+
expect(closest([[3, 0], [2, 2]], 1)).toEqual([[2, 2]])
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
it('handles the origin and negative coordinates', () => {
|
|
47
|
+
expect(closest([[-5, -5], [0, 0], [4, -1], [-1, -1]], 2)).toEqual(normalise([[0, 0], [-1, -1]]))
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
it('keeps duplicate points', () => {
|
|
51
|
+
expect(closest([[1, 1], [2, 2], [1, 1]], 2)).toEqual([[1, 1], [1, 1]])
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
it('handles a single point', () => {
|
|
55
|
+
expect(closest([[7, -7]], 1)).toEqual([[7, -7]])
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it('does not modify the input', () => {
|
|
59
|
+
const points: Point[] = [[5, 5], [1, 0], [3, 3]]
|
|
60
|
+
kClosest(points, 1)
|
|
61
|
+
expect(points).toEqual([[5, 5], [1, 0], [3, 3]])
|
|
62
|
+
})
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
describe('129 performance', () => {
|
|
66
|
+
it('picks 10,000 of 50,000 points in under 150 ms (scanning for the closest point k times, O(n·k), is too slow here)', () => {
|
|
67
|
+
const n = 50_000
|
|
68
|
+
const k = 10_000
|
|
69
|
+
const points = shuffledRange(n, 7).map(pointFor)
|
|
70
|
+
const expected = normalise(Array.from({ length: k }, (_, v) => pointFor(v)))
|
|
71
|
+
const ms = timeMs(() => expect(normalise(kClosest(points, k))).toEqual(expected))
|
|
72
|
+
expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(150)
|
|
73
|
+
})
|
|
74
|
+
})
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# 130 · Number of Islands
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: graphs (grid DFS/BFS) · Target: 25 min · NeetCode 150 · LeetCode 200
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
You get a 2-D grid where each cell is `'1'` (land) or `'0'` (water). An island is a group of land cells joined up, down, left or right (diagonals don't count). Everything outside the grid is water. Return how many islands there are.
|
|
8
|
+
|
|
9
|
+
**You may modify `grid`**, for example by overwriting visited land with `'0'`. The tests build a fresh grid for every call. Mention to your interviewer that you're doing it, though: in a real codebase you'd usually copy first or keep a separate `visited` set.
|
|
10
|
+
|
|
11
|
+
## Examples
|
|
12
|
+
|
|
13
|
+
| `grid` | Output |
|
|
14
|
+
|---|---|
|
|
15
|
+
| `["11110", "11010", "11000", "00000"]` | `1` |
|
|
16
|
+
| `["11000", "11000", "00100", "00011"]` | `3` |
|
|
17
|
+
| `["101", "010", "101"]` | `5` (diagonal cells aren't joined) |
|
|
18
|
+
|
|
19
|
+
Each string is one row; the tests split it into single-character cells, so `grid[r][c]` is `'0'` or `'1'`.
|
|
20
|
+
|
|
21
|
+
## Constraints
|
|
22
|
+
|
|
23
|
+
- `1 <= rows, cols <= 300`
|
|
24
|
+
- `grid[r][c]` is `'0'` or `'1'`.
|
|
25
|
+
- The tests keep every single island under about 2,000 cells, so a recursive DFS won't overflow the call stack. (On a fully land 1000 x 1000 grid it would: recursion that deep needs an explicit stack or a BFS queue.)
|
|
26
|
+
|
|
27
|
+
## Run it
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pnpm watch 130
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
34
|
+
|
|
35
|
+
Time O(rows · cols) · Space O(rows · cols) in the worst case, for the recursion stack or the BFS queue (plus a `visited` set if you don't modify the grid).
|
|
36
|
+
|
|
37
|
+
</details>
|
|
38
|
+
|
|
39
|
+
## Follow-ups an interviewer might ask
|
|
40
|
+
|
|
41
|
+
- Do it without modifying the grid.
|
|
42
|
+
- Your recursive DFS crashes on a 1000 x 1000 grid of all land. Why, and how do you fix it?
|
|
43
|
+
- Return the size of the largest island instead (LeetCode 695).
|
|
44
|
+
- Land is added one cell at a time and you must report the island count after each addition (LeetCode 305). Hint word: union-find.
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { numIslands } from './solution'
|
|
3
|
+
|
|
4
|
+
/** Builds a fresh grid from row strings, so a solution that sinks islands in place can't affect other tests. */
|
|
5
|
+
const gridOf = (rows: readonly string[]): string[][] => rows.map((row) => row.split(''))
|
|
6
|
+
|
|
7
|
+
const islands = (rows: readonly string[]): number => numIslands(gridOf(rows))
|
|
8
|
+
|
|
9
|
+
/** Builds a fresh rows x cols grid, with land wherever isLand(r, c) is true. */
|
|
10
|
+
function gridWhere(rows: number, cols: number, isLand: (r: number, c: number) => boolean): string[][] {
|
|
11
|
+
return Array.from({ length: rows }, (_, r) => Array.from({ length: cols }, (_, c) => (isLand(r, c) ? '1' : '0')))
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
describe('130 number of islands', () => {
|
|
15
|
+
it('counts one large island', () => {
|
|
16
|
+
expect(islands(['11110', '11010', '11000', '00000'])).toBe(1)
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
it('counts several islands', () => {
|
|
20
|
+
expect(islands(['11000', '11000', '00100', '00011'])).toBe(3)
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
it('does not join diagonal neighbours', () => {
|
|
24
|
+
expect(islands(['101', '010', '101'])).toBe(5)
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
it('handles all water and all land', () => {
|
|
28
|
+
expect(islands(['000', '000'])).toBe(0)
|
|
29
|
+
expect(islands(['111', '111'])).toBe(1)
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
it('handles a single cell', () => {
|
|
33
|
+
expect(islands(['1'])).toBe(1)
|
|
34
|
+
expect(islands(['0'])).toBe(0)
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
it('handles a single row and a single column', () => {
|
|
38
|
+
expect(islands(['1011101'])).toBe(3)
|
|
39
|
+
expect(islands(['1', '1', '0', '1'])).toBe(2)
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
it('follows land that turns up or left', () => {
|
|
43
|
+
// A U shape: reaching the top-right cell from the top-left needs a step up.
|
|
44
|
+
expect(islands(['101', '111'])).toBe(1)
|
|
45
|
+
// A spiral that winds back left and up.
|
|
46
|
+
expect(islands(['11111', '00001', '11101', '10001', '11111'])).toBe(1)
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
it('counts land touching every edge', () => {
|
|
50
|
+
expect(islands(['10001', '00000', '10101'])).toBe(5)
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
it('counts 10,000 small islands in a 300 x 300 grid', () => {
|
|
54
|
+
// 2 x 2 blocks of land separated by one-cell channels of water.
|
|
55
|
+
const grid = gridWhere(300, 300, (r, c) => r % 3 !== 2 && c % 3 !== 2)
|
|
56
|
+
expect(numIslands(grid)).toBe(10_000)
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
it('follows a long winding island', () => {
|
|
60
|
+
// A 1-cell-wide snake through a 61 x 61 grid: every even row is land, joined at alternating ends.
|
|
61
|
+
const n = 61
|
|
62
|
+
const grid = gridWhere(n, n, (r, c) => r % 2 === 0 || (r % 4 === 1 && c === n - 1) || (r % 4 === 3 && c === 0))
|
|
63
|
+
expect(numIslands(grid)).toBe(1)
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
it('handles a 40 x 40 grid of all land', () => {
|
|
67
|
+
expect(numIslands(gridWhere(40, 40, () => true))).toBe(1)
|
|
68
|
+
})
|
|
69
|
+
})
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# 131 · Course Schedule
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: graphs (topological sort / cycle detection) · Target: 25 min · NeetCode 150 · LeetCode 207
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
There are `numCourses` courses, numbered `0` to `numCourses - 1`. Each pair `[a, b]` in `prerequisites` means you must finish course `b` before you can take course `a`.
|
|
8
|
+
|
|
9
|
+
Return `true` if it's possible to finish every course, and `false` otherwise. (Think about what would make it impossible.)
|
|
10
|
+
|
|
11
|
+
## Examples
|
|
12
|
+
|
|
13
|
+
| `numCourses` | `prerequisites` | Output | Why |
|
|
14
|
+
|---|---|---|---|
|
|
15
|
+
| `2` | `[[1, 0]]` | `true` | take 0, then 1 |
|
|
16
|
+
| `2` | `[[1, 0], [0, 1]]` | `false` | each needs the other first |
|
|
17
|
+
| `4` | `[[1, 0], [2, 0], [3, 1], [3, 2]]` | `true` | 0, then 1 and 2, then 3 |
|
|
18
|
+
|
|
19
|
+
## Constraints
|
|
20
|
+
|
|
21
|
+
- `1 <= numCourses <= 2000` (the performance test uses about 2,050)
|
|
22
|
+
- `0 <= prerequisites.length <= 5000`, and every pair is distinct
|
|
23
|
+
- `0 <= a, b < numCourses`. A pair can have `a === b`, which is a course that requires itself.
|
|
24
|
+
- The longest chain of prerequisites in any test is 2,000 courses, so a recursive DFS won't overflow the call stack.
|
|
25
|
+
|
|
26
|
+
## Run it
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pnpm watch 131
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
33
|
+
|
|
34
|
+
Time O(V + E) · Space O(V + E), where V is `numCourses` and E is the number of pairs. Either Kahn's algorithm (BFS over in-degrees) or DFS with three states per course (unvisited, in progress, done). A DFS that forgets which courses are already *done* revisits them along every path, which is exponential on the layered graph in the performance test.
|
|
35
|
+
|
|
36
|
+
</details>
|
|
37
|
+
|
|
38
|
+
## Follow-ups an interviewer might ask
|
|
39
|
+
|
|
40
|
+
- Return an actual order to take the courses in (LeetCode 210).
|
|
41
|
+
- In DFS, why do you need both "in progress" and "done"? What goes wrong with a single `visited` set?
|
|
42
|
+
- How would you report *which* courses form the cycle?
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { timeMs } from '../../lib/perf'
|
|
3
|
+
import { canFinish } from './solution'
|
|
4
|
+
|
|
5
|
+
type Pair = [number, number]
|
|
6
|
+
|
|
7
|
+
/** Courses 0..n-1 in a line. forward: each course needs the one before it; otherwise the one after it. */
|
|
8
|
+
function chain(n: number, forward: boolean): Pair[] {
|
|
9
|
+
return Array.from({ length: n - 1 }, (_, i): Pair => (forward ? [i + 1, i] : [i, i + 1]))
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* `layers` layers of two courses each, starting at course `start`. Both courses in a layer need
|
|
14
|
+
* both courses in the next layer, so there are 2^layers distinct paths from the top to the bottom.
|
|
15
|
+
*/
|
|
16
|
+
function ladder(start: number, layers: number): Pair[] {
|
|
17
|
+
const pairs: Pair[] = []
|
|
18
|
+
for (let i = 0; i < layers - 1; i++) {
|
|
19
|
+
const a = start + 2 * i
|
|
20
|
+
for (const from of [a, a + 1]) pairs.push([from, a + 2], [from, a + 3])
|
|
21
|
+
}
|
|
22
|
+
return pairs
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
describe('131 course schedule', () => {
|
|
26
|
+
it('finishes a simple dependency', () => {
|
|
27
|
+
expect(canFinish(2, [[1, 0]])).toBe(true)
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
it('detects a two-course cycle', () => {
|
|
31
|
+
expect(canFinish(2, [[1, 0], [0, 1]])).toBe(false)
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
it('finishes a diamond, where one course is reached two ways', () => {
|
|
35
|
+
expect(canFinish(4, [[1, 0], [2, 0], [3, 1], [3, 2]])).toBe(true)
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
it('finishes with no prerequisites', () => {
|
|
39
|
+
expect(canFinish(1, [])).toBe(true)
|
|
40
|
+
expect(canFinish(5, [])).toBe(true)
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
it('detects a course that requires itself', () => {
|
|
44
|
+
expect(canFinish(3, [[1, 0], [2, 2]])).toBe(false)
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
it('detects a longer cycle', () => {
|
|
48
|
+
expect(canFinish(4, [[1, 0], [2, 1], [3, 2], [1, 3]])).toBe(false)
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
it('detects a cycle in a component that does not contain course 0', () => {
|
|
52
|
+
expect(canFinish(6, [[1, 0], [3, 2], [4, 3], [2, 4]])).toBe(false)
|
|
53
|
+
expect(canFinish(6, [[1, 0], [3, 2], [4, 3], [5, 4]])).toBe(true)
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
it('finishes a graph where many courses share prerequisites', () => {
|
|
57
|
+
const pairs: Pair[] = [[4, 0], [4, 1], [5, 1], [5, 2], [6, 4], [6, 5], [6, 3], [7, 6], [7, 0]]
|
|
58
|
+
expect(canFinish(8, pairs)).toBe(true)
|
|
59
|
+
expect(canFinish(8, [...pairs, [1, 7]])).toBe(false)
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
it('handles a 2,000-course chain in either direction', () => {
|
|
63
|
+
expect(canFinish(2_000, chain(2_000, true))).toBe(true)
|
|
64
|
+
expect(canFinish(2_000, chain(2_000, false))).toBe(true)
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
it('detects a cycle that closes a 2,000-course chain', () => {
|
|
68
|
+
expect(canFinish(2_000, [...chain(2_000, true), [0, 1_999]])).toBe(false)
|
|
69
|
+
expect(canFinish(2_000, [...chain(2_000, false), [1_999, 0]])).toBe(false)
|
|
70
|
+
})
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
describe('131 performance', () => {
|
|
74
|
+
it('handles a 2,000-course chain plus a 23-layer ladder in under 100 ms (DFS that forgets finished courses is exponential here)', () => {
|
|
75
|
+
const chainLength = 2_000
|
|
76
|
+
const layers = 23
|
|
77
|
+
const numCourses = chainLength + 2 * layers
|
|
78
|
+
const pairs: Pair[] = [...chain(chainLength, true), ...ladder(chainLength, layers)]
|
|
79
|
+
const ms = timeMs(() => expect(canFinish(numCourses, pairs)).toBe(true))
|
|
80
|
+
expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(100)
|
|
81
|
+
})
|
|
82
|
+
})
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# 132 · Rotting Oranges
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: graphs (multi-source BFS) · Target: 25 min · NeetCode 150 · LeetCode 994
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
You get a grid where each cell is:
|
|
8
|
+
|
|
9
|
+
- `0`: empty,
|
|
10
|
+
- `1`: a fresh orange,
|
|
11
|
+
- `2`: a rotten orange.
|
|
12
|
+
|
|
13
|
+
Every minute, each fresh orange that sits directly up, down, left or right of a rotten orange becomes rotten. All rotten oranges spread at the same time. Return the number of minutes until no fresh orange is left. If some fresh orange can never rot, return `-1`. If there are no fresh oranges to begin with, the answer is `0`.
|
|
14
|
+
|
|
15
|
+
**You may modify `grid`.** The tests build a fresh grid for every call.
|
|
16
|
+
|
|
17
|
+
## Examples
|
|
18
|
+
|
|
19
|
+
| `grid` | Output | Why |
|
|
20
|
+
|---|---|---|
|
|
21
|
+
| `[[2, 1, 1], [1, 1, 0], [0, 1, 1]]` | `4` | the bottom-right orange rots last |
|
|
22
|
+
| `[[2, 1, 1], [0, 1, 1], [1, 0, 1]]` | `-1` | the bottom-left orange is cut off |
|
|
23
|
+
| `[[0, 2]]` | `0` | nothing fresh to rot |
|
|
24
|
+
|
|
25
|
+
## Constraints
|
|
26
|
+
|
|
27
|
+
- `1 <= rows, cols <= 10` (the performance test uses a 151 x 151 grid)
|
|
28
|
+
- `grid[r][c]` is `0`, `1` or `2`.
|
|
29
|
+
|
|
30
|
+
## Run it
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pnpm watch 132
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
37
|
+
|
|
38
|
+
Time O(rows · cols) · Space O(rows · cols). Re-scanning the whole grid once per minute is O((rows · cols)²) in the worst case, which the winding grid in the performance test exposes.
|
|
39
|
+
|
|
40
|
+
</details>
|
|
41
|
+
|
|
42
|
+
## Follow-ups an interviewer might ask
|
|
43
|
+
|
|
44
|
+
- Why must all the initially rotten oranges start in the queue together, rather than running a BFS from each one?
|
|
45
|
+
- How do you know when one minute ends and the next begins in your queue?
|
|
46
|
+
- Some cells are walls and some are empty. How would you return, for every empty cell, the distance to the nearest gate (LeetCode 286)?
|