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,68 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { timeMs } from '../../lib/perf'
|
|
3
|
+
import { findRedundantConnection } from './solution'
|
|
4
|
+
|
|
5
|
+
type Edge = [number, number]
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Edges on nodes 1..n: a path 1-2-...-spine first, then every node up to `split` hanging off a
|
|
9
|
+
* spine node, then `extra`, then the remaining nodes hanging off the spine. Hanging edges alternate
|
|
10
|
+
* which end is listed first.
|
|
11
|
+
*/
|
|
12
|
+
function broomWith(n: number, spine: number, split: number, extra: Edge): Edge[] {
|
|
13
|
+
const hang = (leaf: number): Edge => {
|
|
14
|
+
const hub = ((leaf - 1) % spine) + 1
|
|
15
|
+
return leaf % 2 === 0 ? [hub, leaf] : [leaf, hub]
|
|
16
|
+
}
|
|
17
|
+
const edges: Edge[] = Array.from({ length: spine - 1 }, (_, i): Edge => [i + 1, i + 2])
|
|
18
|
+
for (let leaf = spine + 1; leaf <= split; leaf++) edges.push(hang(leaf))
|
|
19
|
+
edges.push(extra)
|
|
20
|
+
for (let leaf = split + 1; leaf <= n; leaf++) edges.push(hang(leaf))
|
|
21
|
+
return edges
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
describe('223 redundant connection', () => {
|
|
25
|
+
it('returns the last edge on the loop, not the last edge overall', () => {
|
|
26
|
+
expect(findRedundantConnection([[1, 3], [3, 4], [1, 2], [2, 4], [4, 5]])).toEqual([2, 4])
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
it('handles a triangle and keeps the edge as written', () => {
|
|
30
|
+
expect(findRedundantConnection([[2, 1], [3, 1], [3, 2]])).toEqual([3, 2])
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
it('finds a loop with a branch after it', () => {
|
|
34
|
+
expect(findRedundantConnection([[1, 2], [2, 3], [3, 4], [4, 1], [1, 5]])).toEqual([4, 1])
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
it('finds a loop whose first edge is listed first', () => {
|
|
38
|
+
expect(findRedundantConnection([[2, 5], [1, 2], [2, 3], [3, 4], [4, 5]])).toEqual([4, 5])
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
it('finds a loop when the redundant edge is the very last one', () => {
|
|
42
|
+
expect(findRedundantConnection([[1, 2], [1, 3], [3, 4], [3, 5], [5, 6], [6, 4]])).toEqual([6, 4])
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
it('finds a loop that joins two branches far from node 1', () => {
|
|
46
|
+
// Two branches 1-2-4-6 and 1-3-5-7 are joined by [6, 7]; the leaves 8 and 9 come after it.
|
|
47
|
+
const edges: Edge[] = [[1, 2], [1, 3], [2, 4], [3, 5], [4, 6], [5, 7], [7, 6], [8, 1], [9, 4]]
|
|
48
|
+
expect(findRedundantConnection(edges)).toEqual([7, 6])
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
it('does not depend on the labels being in order', () => {
|
|
52
|
+
expect(findRedundantConnection([[5, 3], [3, 1], [4, 2], [1, 5], [2, 1]])).toEqual([1, 5])
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
it('finds the extra edge in a large graph', () => {
|
|
56
|
+
const edges = broomWith(5_000, 1_000, 3_000, [993, 7])
|
|
57
|
+
expect(findRedundantConnection(edges)).toEqual([993, 7])
|
|
58
|
+
})
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
describe('223 performance', () => {
|
|
62
|
+
it('handles 14,000 edges in under 150 ms (testing each edge with a fresh search, O(n²), is too slow here)', () => {
|
|
63
|
+
// The loop closes in the middle of the list, after 10,000 edges, with 4,000 more edges after it.
|
|
64
|
+
const edges = broomWith(14_000, 1_000, 10_000, [993, 7])
|
|
65
|
+
const ms = timeMs(() => expect(findRedundantConnection(edges)).toEqual([993, 7]))
|
|
66
|
+
expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(150)
|
|
67
|
+
})
|
|
68
|
+
})
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# 224 · Network Delay Time
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: graphs (shortest paths with weights: Dijkstra) · Target: 30 min · NeetCode 150 · LeetCode 743
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
A network has `n` machines labelled `1` to `n`. Each entry `[u, v, w]` in `times` is a one-way link: a message sent from machine `u` arrives at machine `v` after `w` milliseconds.
|
|
8
|
+
|
|
9
|
+
At time `0`, machine `k` sends out a signal, and every machine passes it on along all of its outgoing links as soon as it first receives it. Return how many milliseconds pass until **every** machine has received the signal. If some machine can never receive it, return `-1`.
|
|
10
|
+
|
|
11
|
+
## Examples
|
|
12
|
+
|
|
13
|
+
| `times` | `n` | `k` | Output | Why |
|
|
14
|
+
|---|---|---|---|---|
|
|
15
|
+
| `[[1, 2, 4], [1, 3, 1], [3, 2, 2], [2, 4, 1]]` | `4` | `1` | `4` | 2 hears it at 3 (via 3, not directly at 4), so 4 hears it at 4 |
|
|
16
|
+
| `[[2, 1, 5]]` | `2` | `1` | `-1` | the only link points the wrong way |
|
|
17
|
+
| `[]` | `1` | `1` | `0` | the only machine already has it |
|
|
18
|
+
|
|
19
|
+
## Constraints
|
|
20
|
+
|
|
21
|
+
- `1 <= k <= n <= 6,000` (the performance test uses 6,000 machines and 66,000 links)
|
|
22
|
+
- `0 <= times.length <= 70,000`
|
|
23
|
+
- `1 <= u, v <= n`, `u !== v`, and no `(u, v)` pair appears twice
|
|
24
|
+
- `0 <= w <= 1,000`
|
|
25
|
+
|
|
26
|
+
## Run it
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pnpm watch 224
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
33
|
+
|
|
34
|
+
Time O(E log V) with a binary heap, or O(V² + E) scanning an array for the closest unfinished machine · Space O(V + E). Relaxing every link once per round until nothing changes (Bellman-Ford) is O(V · E) when the network is one long line, which the performance test rejects.
|
|
35
|
+
|
|
36
|
+
TypeScript has no built-in priority queue. You can write a small binary heap yourself, or scan an array for the smallest value each time. Both are fine here.
|
|
37
|
+
|
|
38
|
+
</details>
|
|
39
|
+
|
|
40
|
+
## Follow-ups an interviewer might ask
|
|
41
|
+
|
|
42
|
+
- Why does your approach break if a link could take a *negative* time? What would you use instead?
|
|
43
|
+
- Why is it safe to treat a machine as finished the first time you take it off the heap? What do you do with stale heap entries?
|
|
44
|
+
- Return the order in which the machines first receive the signal, or the route to the machine that hears it last.
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { timeMs } from '../../lib/perf'
|
|
3
|
+
import { networkDelayTime } from './solution'
|
|
4
|
+
|
|
5
|
+
type Link = [number, number, number]
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Machines 1..n in a line, each link 1 ms, listed from the far end back to the start. Every machine
|
|
9
|
+
* also has slower shortcuts: i -> i + d taking d + 1 ms, so the quickest route is always the line.
|
|
10
|
+
*/
|
|
11
|
+
function lineWithShortcuts(n: number, steps: readonly number[]): Link[] {
|
|
12
|
+
const line = Array.from({ length: n - 1 }, (_, i): Link => [n - 1 - i, n - i, 1])
|
|
13
|
+
const shortcuts: Link[] = []
|
|
14
|
+
for (let i = 1; i <= n; i++) for (const d of steps) if (i + d <= n) shortcuts.push([i, i + d, d + 1])
|
|
15
|
+
return [...line, ...shortcuts]
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
describe('224 network delay time', () => {
|
|
19
|
+
it('takes the quicker route even when it has more links', () => {
|
|
20
|
+
expect(networkDelayTime([[1, 2, 4], [1, 3, 1], [3, 2, 2], [2, 4, 1]], 4, 1)).toBe(4)
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
it('returns -1 when a machine cannot be reached', () => {
|
|
24
|
+
expect(networkDelayTime([[2, 1, 5]], 2, 1)).toBe(-1)
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
it('returns 0 for a single machine', () => {
|
|
28
|
+
expect(networkDelayTime([], 1, 1)).toBe(0)
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('returns -1 when the source has no links but there are other machines', () => {
|
|
32
|
+
expect(networkDelayTime([[2, 3, 1], [3, 2, 1]], 3, 1)).toBe(-1)
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
it('starts from a machine in the middle', () => {
|
|
36
|
+
expect(networkDelayTime([[3, 1, 2], [3, 5, 7], [1, 2, 1], [2, 4, 3], [5, 4, 1]], 5, 3)).toBe(7)
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
it('handles links that take 0 ms', () => {
|
|
40
|
+
expect(networkDelayTime([[1, 2, 0], [2, 3, 0], [1, 3, 5]], 3, 1)).toBe(0)
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
it('handles loops in the network', () => {
|
|
44
|
+
expect(networkDelayTime([[1, 2, 2], [2, 3, 2], [3, 1, 2], [3, 4, 10], [2, 4, 20]], 4, 1)).toBe(14)
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
it('returns the slowest machine, not the last one found', () => {
|
|
48
|
+
// Machine 2 is found first, through a slow link, but finishes last.
|
|
49
|
+
expect(networkDelayTime([[1, 2, 50], [1, 3, 1], [3, 4, 1], [4, 5, 1]], 5, 1)).toBe(50)
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
it('updates a machine when a quicker route turns up later', () => {
|
|
53
|
+
// A route with more links that is found later beats the direct link.
|
|
54
|
+
expect(networkDelayTime([[1, 4, 10], [1, 2, 1], [2, 3, 1], [3, 4, 1], [4, 5, 1]], 5, 1)).toBe(4)
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
it('handles a 1,000-machine line', () => {
|
|
58
|
+
expect(networkDelayTime(lineWithShortcuts(1_000, [2, 3]), 1_000, 1)).toBe(999)
|
|
59
|
+
expect(networkDelayTime(lineWithShortcuts(1_000, [2, 3]), 1_000, 2)).toBe(-1)
|
|
60
|
+
})
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
describe('224 performance', () => {
|
|
64
|
+
it('handles 6,000 machines and 66,000 links in under 200 ms (Bellman-Ford, O(V · E), is too slow here)', () => {
|
|
65
|
+
const n = 6_000
|
|
66
|
+
const times = lineWithShortcuts(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29])
|
|
67
|
+
const ms = timeMs(() => expect(networkDelayTime(times, n, 1)).toBe(n - 1))
|
|
68
|
+
expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(200)
|
|
69
|
+
})
|
|
70
|
+
})
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# 225 · Cheapest Flights Within K Stops
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: graphs (Bellman-Ford / BFS by number of stops) · Target: 30 min · NeetCode 150 · LeetCode 787
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
There are `n` cities numbered `0` to `n - 1`. Each entry `[from, to, price]` in `flights` is a one-way flight from city `from` to city `to` costing `price`.
|
|
8
|
+
|
|
9
|
+
Return the cheapest total price to get from city `src` to city `dst` with **at most `k` stops** in between (so at most `k + 1` flights). If no such trip exists, return `-1`.
|
|
10
|
+
|
|
11
|
+
A stop is any city you land in on the way, other than `src` and `dst`. A trip may pass through the same city more than once, though a cheapest one never needs to.
|
|
12
|
+
|
|
13
|
+
## Examples
|
|
14
|
+
|
|
15
|
+
| `n` | `flights` | `src` | `dst` | `k` | Output | Why |
|
|
16
|
+
|---|---|---|---|---|---|---|
|
|
17
|
+
| `4` | `[[0, 1, 50], [1, 3, 50], [0, 2, 20], [2, 1, 10], [0, 3, 200]]` | `0` | `3` | `1` | `100` | 0 → 1 → 3; the cheaper 0 → 2 → 1 → 3 needs 2 stops |
|
|
18
|
+
| same | same | `0` | `3` | `2` | `80` | now 0 → 2 → 1 → 3 is allowed |
|
|
19
|
+
| same | same | `0` | `3` | `0` | `200` | only the direct flight |
|
|
20
|
+
| `3` | `[[0, 1, 5]]` | `0` | `2` | `1` | `-1` | no flight reaches city 2 |
|
|
21
|
+
|
|
22
|
+
## Constraints
|
|
23
|
+
|
|
24
|
+
- `2 <= n <= 100` (the performance test uses 74 cities)
|
|
25
|
+
- `0 <= flights.length <= n · (n - 1)`, with no self-loops and no `(from, to)` pair twice
|
|
26
|
+
- `1 <= price <= 10^4`
|
|
27
|
+
- `0 <= k < n`, and `src !== dst`
|
|
28
|
+
|
|
29
|
+
## Run it
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pnpm watch 225
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
36
|
+
|
|
37
|
+
Time O(k · E) · Space O(n) for `k + 1` rounds of relaxing every flight, where E is `flights.length`. (A heap-based search over `(city, stops)` states is also fine.) Trying every route with up to `k` stops is exponential, which the performance test rejects.
|
|
38
|
+
|
|
39
|
+
</details>
|
|
40
|
+
|
|
41
|
+
## Follow-ups an interviewer might ask
|
|
42
|
+
|
|
43
|
+
- Why does ordinary Dijkstra (one best price per city) give wrong answers here? Find a small example.
|
|
44
|
+
- In your rounds, why must each round read prices from a copy of the previous round, and not from the array it is updating?
|
|
45
|
+
- Return the route itself, not just its price.
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { timeMs } from '../../lib/perf'
|
|
3
|
+
import { findCheapestPrice } from './solution'
|
|
4
|
+
|
|
5
|
+
type Flight = [number, number, number]
|
|
6
|
+
|
|
7
|
+
const example: Flight[] = [[0, 1, 50], [1, 3, 50], [0, 2, 20], [2, 1, 10], [0, 3, 200]]
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* City 0 flies to every city in layer 1; every city in each layer flies to every city in the next;
|
|
11
|
+
* every city in the last layer flies to the destination (city 1 + width · layers). All prices are 10.
|
|
12
|
+
* There are width^layers different routes, each with `layers` stops.
|
|
13
|
+
*/
|
|
14
|
+
function layered(width: number, layers: number): { n: number; flights: Flight[]; dst: number } {
|
|
15
|
+
const city = (layer: number, i: number): number => 1 + (layer - 1) * width + i
|
|
16
|
+
const dst = 1 + width * layers
|
|
17
|
+
const flights: Flight[] = []
|
|
18
|
+
for (let i = 0; i < width; i++) flights.push([0, city(1, i), 10], [city(layers, i), dst, 10])
|
|
19
|
+
for (let layer = 1; layer < layers; layer++) {
|
|
20
|
+
for (let i = 0; i < width; i++) for (let j = 0; j < width; j++) flights.push([city(layer, i), city(layer + 1, j), 10])
|
|
21
|
+
}
|
|
22
|
+
return { n: dst + 1, flights, dst }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
describe('225 cheapest flights within k stops', () => {
|
|
26
|
+
it('picks the cheapest route that fits the stop limit', () => {
|
|
27
|
+
expect(findCheapestPrice(4, example, 0, 3, 1)).toBe(100)
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
it('takes a cheaper route with more stops when the limit allows it', () => {
|
|
31
|
+
expect(findCheapestPrice(4, example, 0, 3, 2)).toBe(80)
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
it('allows only a direct flight when k is 0', () => {
|
|
35
|
+
expect(findCheapestPrice(4, example, 0, 3, 0)).toBe(200)
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
it('returns -1 when no flight reaches the destination', () => {
|
|
39
|
+
expect(findCheapestPrice(3, [[0, 1, 5]], 0, 2, 1)).toBe(-1)
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
it('returns -1 when every route needs too many stops', () => {
|
|
43
|
+
expect(findCheapestPrice(4, [[0, 1, 1], [1, 2, 1], [2, 3, 1]], 0, 3, 1)).toBe(-1)
|
|
44
|
+
expect(findCheapestPrice(4, [[0, 1, 1], [1, 2, 1], [2, 3, 1]], 0, 3, 2)).toBe(3)
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
it('does not chain two flights in one round', () => {
|
|
48
|
+
// Flights are listed in route order, so updating prices in place would let 0 -> 1 -> 2 -> 3 count as 0 stops.
|
|
49
|
+
const flights: Flight[] = [[0, 1, 1], [1, 2, 1], [2, 3, 1], [0, 3, 100]]
|
|
50
|
+
expect(findCheapestPrice(4, flights, 0, 3, 0)).toBe(100)
|
|
51
|
+
expect(findCheapestPrice(4, flights, 0, 3, 1)).toBe(100)
|
|
52
|
+
expect(findCheapestPrice(4, flights, 0, 3, 2)).toBe(3)
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
it('does not lock in the cheapest price to a stop that has no stops left', () => {
|
|
56
|
+
// City 2 is cheapest through 1 (price 2, one stop used) but the 2 -> 4 leg then needs a second stop at 3.
|
|
57
|
+
// The pricier 0 -> 2 direct flight leaves room for it.
|
|
58
|
+
const flights: Flight[] = [[0, 1, 1], [1, 2, 1], [0, 2, 5], [2, 3, 1], [3, 4, 1]]
|
|
59
|
+
expect(findCheapestPrice(5, flights, 0, 4, 2)).toBe(7)
|
|
60
|
+
expect(findCheapestPrice(5, flights, 0, 4, 3)).toBe(4)
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
it('handles loops among the cities', () => {
|
|
64
|
+
const flights: Flight[] = [[0, 1, 3], [1, 0, 1], [1, 2, 4], [2, 1, 1], [2, 3, 6], [0, 3, 20]]
|
|
65
|
+
expect(findCheapestPrice(4, flights, 0, 3, 2)).toBe(13)
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
it('handles a source with no outgoing flights', () => {
|
|
69
|
+
expect(findCheapestPrice(3, [[1, 0, 2], [1, 2, 2]], 0, 2, 2)).toBe(-1)
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
it('handles a large k', () => {
|
|
73
|
+
const flights = Array.from({ length: 99 }, (_, i): Flight => [i, i + 1, 7])
|
|
74
|
+
expect(findCheapestPrice(100, flights, 0, 99, 99)).toBe(99 * 7)
|
|
75
|
+
expect(findCheapestPrice(100, flights, 0, 99, 97)).toBe(-1)
|
|
76
|
+
})
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
describe('225 performance', () => {
|
|
80
|
+
it('handles 9 layers of 8 cities in under 100 ms (trying every route, 8^9 of them, is too slow here)', () => {
|
|
81
|
+
const { n, flights, dst } = layered(8, 9)
|
|
82
|
+
const ms = timeMs(() => expect(findCheapestPrice(n, flights, 0, dst, 9)).toBe(100))
|
|
83
|
+
expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(100)
|
|
84
|
+
})
|
|
85
|
+
})
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# 226 · House Robber II
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: 1-D dynamic programming · Target: 25 min · NeetCode 150 · LeetCode 213
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
The houses on a street are built in a **ring**: house `i` sits next to houses `i - 1` and `i + 1`, and the last house sits next to the first one. `nums[i]` is the cash in house `i`.
|
|
8
|
+
|
|
9
|
+
You may collect from any set of houses, as long as no two of them are next to each other around the ring. Return the largest total you can collect.
|
|
10
|
+
|
|
11
|
+
## Examples
|
|
12
|
+
|
|
13
|
+
| `nums` | Output | Why |
|
|
14
|
+
|---|---|---|
|
|
15
|
+
| `[3, 5, 4]` | `5` | with three houses in a ring, every pair is neighbours, so take one |
|
|
16
|
+
| `[4, 1, 2, 7]` | `8` | houses 1 and 3: `1 + 7`; houses 0 and 3 would be `11`, but they are neighbours |
|
|
17
|
+
| `[6, 2, 3, 6]` | `9` | houses 0 and 2: `6 + 3` |
|
|
18
|
+
| `[10, 1, 1, 1, 10]` | `11` | in a straight row `10 + 1 + 10` would work; in a ring the two 10s touch |
|
|
19
|
+
|
|
20
|
+
## Constraints
|
|
21
|
+
|
|
22
|
+
- `1 <= nums.length <= 100` (the performance test uses 40 houses)
|
|
23
|
+
- `0 <= nums[i] <= 1000`
|
|
24
|
+
|
|
25
|
+
## Run it
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pnpm watch 226
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
32
|
+
|
|
33
|
+
Time O(n) · Space O(1). Plain "take it or skip it" recursion is O(2^n) and fails the performance test; memoising it gives O(n) time and O(n) space, which passes.
|
|
34
|
+
|
|
35
|
+
</details>
|
|
36
|
+
|
|
37
|
+
## Follow-ups an interviewer might ask
|
|
38
|
+
|
|
39
|
+
- Why is it safe to split the ring into two straight rows? What does each row leave out?
|
|
40
|
+
- Return which houses to take, not just the total.
|
|
41
|
+
- What if the houses form a binary tree instead? (LeetCode 337)
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { timeMs } from '../../lib/perf'
|
|
3
|
+
import { rob } from './solution'
|
|
4
|
+
|
|
5
|
+
describe('226 house robber ii', () => {
|
|
6
|
+
it('runs the README examples', () => {
|
|
7
|
+
expect(rob([3, 5, 4])).toBe(5)
|
|
8
|
+
expect(rob([4, 1, 2, 7])).toBe(8)
|
|
9
|
+
expect(rob([6, 2, 3, 6])).toBe(9)
|
|
10
|
+
expect(rob([10, 1, 1, 1, 10])).toBe(11)
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
it('never takes both the first and the last house', () => {
|
|
14
|
+
expect(rob([10, 1, 1, 10])).toBe(11)
|
|
15
|
+
expect(rob([9, 0, 0, 0, 0, 9])).toBe(9)
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
it('handles one house', () => {
|
|
19
|
+
expect(rob([7])).toBe(7)
|
|
20
|
+
expect(rob([0])).toBe(0)
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
it('handles two houses, which are neighbours', () => {
|
|
24
|
+
expect(rob([3, 8])).toBe(8)
|
|
25
|
+
expect(rob([8, 3])).toBe(8)
|
|
26
|
+
expect(rob([5, 5])).toBe(5)
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
it('handles zeros', () => {
|
|
30
|
+
expect(rob([0, 0, 0])).toBe(0)
|
|
31
|
+
expect(rob([0, 4, 0, 4, 0])).toBe(8)
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
it('handles equal values with an even and an odd number of houses', () => {
|
|
35
|
+
expect(rob([5, 5, 5, 5, 5, 5])).toBe(15)
|
|
36
|
+
expect(rob([5, 5, 5, 5, 5])).toBe(10)
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
it('handles a longer ring', () => {
|
|
40
|
+
expect(rob([8, 2, 9, 4, 7, 3, 6, 5, 1, 9, 2, 8])).toBe(39)
|
|
41
|
+
})
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
describe('226 performance', () => {
|
|
45
|
+
it('handles 40 houses in under 50 ms (plain recursion takes seconds)', () => {
|
|
46
|
+
// Even positions hold 2 and odd positions hold 1. House 39 is odd, so all 20 even houses fit.
|
|
47
|
+
const nums = Array.from({ length: 40 }, (_, i) => (i % 2 === 0 ? 2 : 1))
|
|
48
|
+
const ms = timeMs(() => expect(rob(nums)).toBe(40))
|
|
49
|
+
expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(50)
|
|
50
|
+
})
|
|
51
|
+
})
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# 227 · Longest Palindromic Substring
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: expand around centres (or 2-D dynamic programming) · Target: 25 min · NeetCode 150 · LeetCode 5
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
Return the longest **contiguous** piece of `s` that reads the same from left to right and from right to left.
|
|
8
|
+
|
|
9
|
+
If several pieces tie for the longest, return any one of them. A single character always counts, so the answer is never empty.
|
|
10
|
+
|
|
11
|
+
## Examples
|
|
12
|
+
|
|
13
|
+
| `s` | Output | Why |
|
|
14
|
+
|---|---|---|
|
|
15
|
+
| `"racecars"` | `"racecar"` | the first seven letters |
|
|
16
|
+
| `"xyyz"` | `"yy"` | an even-length answer |
|
|
17
|
+
| `"noonmadam"` | `"madam"` | `"noon"` has 4 letters, `"madam"` has 5 |
|
|
18
|
+
| `"abc"` | `"a"`, `"b"` or `"c"` | every single letter ties |
|
|
19
|
+
|
|
20
|
+
## Constraints
|
|
21
|
+
|
|
22
|
+
- `1 <= s.length <= 2000` (the performance test uses 1,802 characters)
|
|
23
|
+
- `s` contains lowercase English letters and digits.
|
|
24
|
+
|
|
25
|
+
## Run it
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pnpm watch 227
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
32
|
+
|
|
33
|
+
Time O(n²) · Space O(1) by growing outwards from every possible middle. A table of "is `s[i..j]` a palindrome?" is also O(n²) time, with O(n²) space, and passes. Checking every substring separately is O(n³) and fails the performance test.
|
|
34
|
+
|
|
35
|
+
</details>
|
|
36
|
+
|
|
37
|
+
## Follow-ups an interviewer might ask
|
|
38
|
+
|
|
39
|
+
- How many centres are there in a string of length `n`, and why isn't it just `n`?
|
|
40
|
+
- Count every palindromic substring instead of finding the longest. (LeetCode 647)
|
|
41
|
+
- Can you do it in O(n)? (Manacher's algorithm)
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { timeMs } from '../../lib/perf'
|
|
3
|
+
import { longestPalindrome } from './solution'
|
|
4
|
+
|
|
5
|
+
function isPalindrome(text: string): boolean {
|
|
6
|
+
return text === [...text].reverse().join('')
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** Ties are allowed, so check the shape of the answer rather than one exact string. */
|
|
10
|
+
function expectLongest(s: string, length: number): void {
|
|
11
|
+
const result = longestPalindrome(s)
|
|
12
|
+
expect(result, `"${result}" should come from "${s.slice(0, 40)}"`).toHaveLength(length)
|
|
13
|
+
expect(s.includes(result), `"${result.slice(0, 40)}" is not a substring`).toBe(true)
|
|
14
|
+
expect(isPalindrome(result), `"${result.slice(0, 40)}" is not a palindrome`).toBe(true)
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
describe('227 longest palindromic substring', () => {
|
|
18
|
+
it('runs the README examples', () => {
|
|
19
|
+
expect(longestPalindrome('racecars')).toBe('racecar')
|
|
20
|
+
expect(longestPalindrome('xyyz')).toBe('yy')
|
|
21
|
+
expect(longestPalindrome('noonmadam')).toBe('madam')
|
|
22
|
+
expectLongest('abc', 1)
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
it('handles a single character', () => {
|
|
26
|
+
expect(longestPalindrome('q')).toBe('q')
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
it('returns the whole string when it is a palindrome', () => {
|
|
30
|
+
expect(longestPalindrome('abcba')).toBe('abcba')
|
|
31
|
+
expect(longestPalindrome('abba')).toBe('abba')
|
|
32
|
+
expect(longestPalindrome('zz')).toBe('zz')
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
it('finds even-length answers', () => {
|
|
36
|
+
expect(longestPalindrome('abccbx')).toBe('bccb')
|
|
37
|
+
expect(longestPalindrome('xyzzy')).toBe('yzzy')
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
it('finds answers at either end', () => {
|
|
41
|
+
expect(longestPalindrome('levelup')).toBe('level')
|
|
42
|
+
expect(longestPalindrome('upsideddedis')).toBe('sideddedis')
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
it('handles runs of one letter', () => {
|
|
46
|
+
expect(longestPalindrome('aaaa')).toBe('aaaa')
|
|
47
|
+
expect(longestPalindrome('baaab')).toBe('baaab')
|
|
48
|
+
expect(longestPalindrome('baaac')).toBe('aaa')
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
it('accepts any of several tied answers', () => {
|
|
52
|
+
expectLongest('abaxcdc', 3)
|
|
53
|
+
expectLongest('ab', 1)
|
|
54
|
+
expectLongest('xyyxzwwz', 4)
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
it('handles digits', () => {
|
|
58
|
+
expect(longestPalindrome('9123217')).toBe('12321')
|
|
59
|
+
})
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
describe('227 performance', () => {
|
|
63
|
+
it('handles 1,802 characters in under 100 ms (checking every substring is O(n³), too slow here)', () => {
|
|
64
|
+
// 900 a's, then "bc", then 900 more a's: either run of a's is a longest answer.
|
|
65
|
+
const s = 'a'.repeat(900) + 'bc' + 'a'.repeat(900)
|
|
66
|
+
const ms = timeMs(() => expectLongest(s, 900))
|
|
67
|
+
expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(100)
|
|
68
|
+
})
|
|
69
|
+
})
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# 228 · Decode Ways
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: 1-D dynamic programming · Target: 25 min · NeetCode 150 · LeetCode 91
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
A message made of capital letters is turned into digits by replacing each letter with its position in the alphabet (`A` → `"1"`, `B` → `"2"`, …, `Z` → `"26"`) and gluing the codes together with no separators.
|
|
8
|
+
|
|
9
|
+
Given the digit string `s`, return how many **different messages** could have produced it.
|
|
10
|
+
|
|
11
|
+
A code never starts with `0`: `"5"` is `E`, but `"05"` is not. If no message can produce `s`, return `0`.
|
|
12
|
+
|
|
13
|
+
## Examples
|
|
14
|
+
|
|
15
|
+
| `s` | Output | Why |
|
|
16
|
+
|---|---|---|
|
|
17
|
+
| `"17"` | `2` | `1 7` → `AG`, or `17` → `Q` |
|
|
18
|
+
| `"2611"` | `4` | `2 6 1 1`, `26 1 1`, `2 6 11`, `26 11` |
|
|
19
|
+
| `"1201"` | `1` | only `1 20 1`; `12 01` uses an invalid code |
|
|
20
|
+
| `"301"` | `0` | `30` is too big and `0` alone is no letter |
|
|
21
|
+
|
|
22
|
+
## Constraints
|
|
23
|
+
|
|
24
|
+
- `1 <= s.length <= 100` (the performance test uses 38 digits)
|
|
25
|
+
- `s` contains only digits, and may start with `0`.
|
|
26
|
+
- The answer fits in a 32-bit integer.
|
|
27
|
+
|
|
28
|
+
## Run it
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pnpm watch 228
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
35
|
+
|
|
36
|
+
Time O(n) · Space O(1). Plain recursion ("take one digit or two?") is O(2^n) and fails the performance test; memoising it gives O(n) time and O(n) space, which passes.
|
|
37
|
+
|
|
38
|
+
</details>
|
|
39
|
+
|
|
40
|
+
## Follow-ups an interviewer might ask
|
|
41
|
+
|
|
42
|
+
- Which inputs give the most decodings for a given length? How fast does the count grow?
|
|
43
|
+
- What if `*` can stand for any digit from 1 to 9? (LeetCode 639)
|
|
44
|
+
- Return every decoded message, not just how many there are. How big can that output get?
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { timeMs } from '../../lib/perf'
|
|
3
|
+
import { numDecodings } from './solution'
|
|
4
|
+
|
|
5
|
+
describe('228 decode ways', () => {
|
|
6
|
+
it('runs the README examples', () => {
|
|
7
|
+
expect(numDecodings('17')).toBe(2)
|
|
8
|
+
expect(numDecodings('2611')).toBe(4)
|
|
9
|
+
expect(numDecodings('1201')).toBe(1)
|
|
10
|
+
expect(numDecodings('301')).toBe(0)
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
it('handles a single digit', () => {
|
|
14
|
+
expect(numDecodings('9')).toBe(1)
|
|
15
|
+
expect(numDecodings('0')).toBe(0)
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
it('returns 0 for a leading zero', () => {
|
|
19
|
+
expect(numDecodings('05')).toBe(0)
|
|
20
|
+
expect(numDecodings('011')).toBe(0)
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
it('only lets a zero follow a 1 or a 2', () => {
|
|
24
|
+
expect(numDecodings('10')).toBe(1)
|
|
25
|
+
expect(numDecodings('20')).toBe(1)
|
|
26
|
+
expect(numDecodings('30')).toBe(0)
|
|
27
|
+
expect(numDecodings('100')).toBe(0)
|
|
28
|
+
expect(numDecodings('101')).toBe(1)
|
|
29
|
+
expect(numDecodings('110')).toBe(1)
|
|
30
|
+
expect(numDecodings('2101')).toBe(1)
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
it('treats 26 as a letter and 27 as two', () => {
|
|
34
|
+
expect(numDecodings('26')).toBe(2)
|
|
35
|
+
expect(numDecodings('27')).toBe(1)
|
|
36
|
+
expect(numDecodings('2626')).toBe(4)
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
it('counts every split of a longer string', () => {
|
|
40
|
+
expect(numDecodings('1226')).toBe(5)
|
|
41
|
+
expect(numDecodings('1111111111')).toBe(89)
|
|
42
|
+
})
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
describe('228 performance', () => {
|
|
46
|
+
it('handles 38 digits in under 50 ms (plain recursion takes seconds)', () => {
|
|
47
|
+
const ms = timeMs(() => expect(numDecodings('12'.repeat(19))).toBe(63_245_986))
|
|
48
|
+
expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(50)
|
|
49
|
+
})
|
|
50
|
+
})
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# 229 · Maximum Product Subarray
|
|
2
|
+
|
|
3
|
+
**Level 2 · Medium** · Pattern: 1-D dynamic programming (running max and min) · Target: 25 min · NeetCode 150 · LeetCode 152
|
|
4
|
+
|
|
5
|
+
## Problem
|
|
6
|
+
|
|
7
|
+
Pick a **non-empty, contiguous** run of elements from `nums` and multiply them together. Return the largest product any run can give.
|
|
8
|
+
|
|
9
|
+
## Examples
|
|
10
|
+
|
|
11
|
+
| `nums` | Output | Why |
|
|
12
|
+
|---|---|---|
|
|
13
|
+
| `[3, -1, 4]` | `4` | the run `[4]`; any run with `-1` in it is negative |
|
|
14
|
+
| `[-2, -3, 5]` | `30` | two negatives cancel out |
|
|
15
|
+
| `[-4, 0, -2]` | `0` | the run `[0]` beats either negative |
|
|
16
|
+
| `[2, -5, -2, -4, 3]` | `24` | `-2 · -4 · 3` |
|
|
17
|
+
|
|
18
|
+
## Constraints
|
|
19
|
+
|
|
20
|
+
- `1 <= nums.length <= 2 · 10^4` (the performance test uses 60,000)
|
|
21
|
+
- `-10 <= nums[i] <= 10`
|
|
22
|
+
- The product of every run fits in a 32-bit integer.
|
|
23
|
+
|
|
24
|
+
## Run it
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pnpm watch 229
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
<details><summary>Target complexity (open after your first attempt)</summary>
|
|
31
|
+
|
|
32
|
+
Time O(n) · Space O(1). Multiplying out every run is O(n²) and fails the performance test.
|
|
33
|
+
|
|
34
|
+
</details>
|
|
35
|
+
|
|
36
|
+
## Follow-ups an interviewer might ask
|
|
37
|
+
|
|
38
|
+
- Why isn't the best product ending at `i` enough on its own, the way the best sum is for maximum subarray *sum*?
|
|
39
|
+
- How do zeros change things? Could you split the array at the zeros and solve each piece?
|
|
40
|
+
- Return the start and end of the best run, not just its product.
|