interview-reps 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (285) hide show
  1. package/README.md +59 -2
  2. package/content/CLAUDE.md +131 -0
  3. package/content/LADDER.md +166 -0
  4. package/content/behavioral/QUESTIONS.md +93 -0
  5. package/content/behavioral/REVIEW.md +86 -0
  6. package/content/design/D01-short-links/README.md +20 -0
  7. package/content/design/D02-rate-limiter/README.md +21 -0
  8. package/content/design/D03-news-feed/README.md +20 -0
  9. package/content/design/D04-chat-messaging/README.md +20 -0
  10. package/content/design/D05-notification-service/README.md +20 -0
  11. package/content/design/D06-typeahead-search/README.md +20 -0
  12. package/content/design/D07-web-crawler/README.md +20 -0
  13. package/content/design/D08-file-sync/README.md +20 -0
  14. package/content/design/D09-ride-matching/README.md +20 -0
  15. package/content/design/D10-job-scheduler/README.md +20 -0
  16. package/content/design/D11-metrics-alerting/README.md +20 -0
  17. package/content/design/D12-payments-ledger/README.md +20 -0
  18. package/content/design/REVIEW.md +94 -0
  19. package/content/lib/binary-tree.ts +69 -0
  20. package/content/lib/graph.ts +50 -0
  21. package/content/lib/linked-list.ts +37 -0
  22. package/content/lib/perf.ts +9 -0
  23. package/content/problems/001-contains-duplicate/README.md +37 -0
  24. package/content/problems/001-contains-duplicate/solution.test.ts +38 -0
  25. package/content/problems/002-valid-anagram/README.md +36 -0
  26. package/content/problems/002-valid-anagram/solution.test.ts +38 -0
  27. package/content/problems/003-two-sum/README.md +40 -0
  28. package/content/problems/003-two-sum/solution.test.ts +40 -0
  29. package/content/problems/004-valid-palindrome/README.md +39 -0
  30. package/content/problems/004-valid-palindrome/solution.test.ts +38 -0
  31. package/content/problems/005-best-time-to-buy-and-sell-stock/README.md +38 -0
  32. package/content/problems/005-best-time-to-buy-and-sell-stock/solution.test.ts +39 -0
  33. package/content/problems/006-valid-parentheses/README.md +42 -0
  34. package/content/problems/006-valid-parentheses/solution.test.ts +41 -0
  35. package/content/problems/007-binary-search/README.md +39 -0
  36. package/content/problems/007-binary-search/solution.test.ts +56 -0
  37. package/content/problems/008-reverse-linked-list/README.md +39 -0
  38. package/content/problems/008-reverse-linked-list/solution.test.ts +41 -0
  39. package/content/problems/009-merge-two-sorted-lists/README.md +36 -0
  40. package/content/problems/009-merge-two-sorted-lists/solution.test.ts +43 -0
  41. package/content/problems/010-linked-list-cycle/README.md +37 -0
  42. package/content/problems/010-linked-list-cycle/solution.test.ts +39 -0
  43. package/content/problems/011-invert-binary-tree/README.md +39 -0
  44. package/content/problems/011-invert-binary-tree/solution.test.ts +32 -0
  45. package/content/problems/012-maximum-depth-of-binary-tree/README.md +37 -0
  46. package/content/problems/012-maximum-depth-of-binary-tree/solution.test.ts +29 -0
  47. package/content/problems/013-same-tree/README.md +37 -0
  48. package/content/problems/013-same-tree/solution.test.ts +38 -0
  49. package/content/problems/014-balanced-binary-tree/README.md +37 -0
  50. package/content/problems/014-balanced-binary-tree/solution.test.ts +38 -0
  51. package/content/problems/015-climbing-stairs/README.md +35 -0
  52. package/content/problems/015-climbing-stairs/solution.test.ts +27 -0
  53. package/content/problems/016-diameter-of-binary-tree/README.md +38 -0
  54. package/content/problems/016-diameter-of-binary-tree/solution.test.ts +63 -0
  55. package/content/problems/017-subtree-of-another-tree/README.md +42 -0
  56. package/content/problems/017-subtree-of-another-tree/solution.test.ts +61 -0
  57. package/content/problems/018-kth-largest-element-in-a-stream/README.md +49 -0
  58. package/content/problems/018-kth-largest-element-in-a-stream/solution.test.ts +104 -0
  59. package/content/problems/019-last-stone-weight/README.md +44 -0
  60. package/content/problems/019-last-stone-weight/solution.test.ts +67 -0
  61. package/content/problems/020-min-cost-climbing-stairs/README.md +40 -0
  62. package/content/problems/020-min-cost-climbing-stairs/solution.test.ts +44 -0
  63. package/content/problems/021-single-number/README.md +41 -0
  64. package/content/problems/021-single-number/solution.test.ts +46 -0
  65. package/content/problems/022-missing-number/README.md +40 -0
  66. package/content/problems/022-missing-number/solution.test.ts +44 -0
  67. package/content/problems/101-group-anagrams/README.md +41 -0
  68. package/content/problems/101-group-anagrams/solution.test.ts +83 -0
  69. package/content/problems/102-top-k-frequent-elements/README.md +44 -0
  70. package/content/problems/102-top-k-frequent-elements/solution.test.ts +59 -0
  71. package/content/problems/103-product-of-array-except-self/README.md +43 -0
  72. package/content/problems/103-product-of-array-except-self/solution.test.ts +59 -0
  73. package/content/problems/104-longest-consecutive-sequence/README.md +40 -0
  74. package/content/problems/104-longest-consecutive-sequence/solution.test.ts +62 -0
  75. package/content/problems/105-encode-and-decode-strings/README.md +47 -0
  76. package/content/problems/105-encode-and-decode-strings/solution.test.ts +50 -0
  77. package/content/problems/106-two-sum-ii-input-array-is-sorted/README.md +43 -0
  78. package/content/problems/106-two-sum-ii-input-array-is-sorted/solution.test.ts +47 -0
  79. package/content/problems/107-three-sum/README.md +42 -0
  80. package/content/problems/107-three-sum/solution.test.ts +79 -0
  81. package/content/problems/108-container-with-most-water/README.md +40 -0
  82. package/content/problems/108-container-with-most-water/solution.test.ts +53 -0
  83. package/content/problems/109-longest-substring-without-repeating-characters/README.md +40 -0
  84. package/content/problems/109-longest-substring-without-repeating-characters/solution.test.ts +56 -0
  85. package/content/problems/110-longest-repeating-character-replacement/README.md +41 -0
  86. package/content/problems/110-longest-repeating-character-replacement/solution.test.ts +51 -0
  87. package/content/problems/111-permutation-in-string/README.md +38 -0
  88. package/content/problems/111-permutation-in-string/solution.test.ts +54 -0
  89. package/content/problems/112-min-stack/README.md +51 -0
  90. package/content/problems/112-min-stack/solution.test.ts +123 -0
  91. package/content/problems/113-daily-temperatures/README.md +40 -0
  92. package/content/problems/113-daily-temperatures/solution.test.ts +56 -0
  93. package/content/problems/114-evaluate-reverse-polish-notation/README.md +44 -0
  94. package/content/problems/114-evaluate-reverse-polish-notation/solution.test.ts +56 -0
  95. package/content/problems/115-generate-parentheses/README.md +38 -0
  96. package/content/problems/115-generate-parentheses/solution.test.ts +59 -0
  97. package/content/problems/116-koko-eating-bananas/README.md +41 -0
  98. package/content/problems/116-koko-eating-bananas/solution.test.ts +53 -0
  99. package/content/problems/117-find-minimum-in-rotated-sorted-array/README.md +41 -0
  100. package/content/problems/117-find-minimum-in-rotated-sorted-array/solution.test.ts +69 -0
  101. package/content/problems/118-search-in-rotated-sorted-array/README.md +41 -0
  102. package/content/problems/118-search-in-rotated-sorted-array/solution.test.ts +95 -0
  103. package/content/problems/119-time-based-key-value-store/README.md +50 -0
  104. package/content/problems/119-time-based-key-value-store/solution.test.ts +107 -0
  105. package/content/problems/120-reorder-list/README.md +43 -0
  106. package/content/problems/120-reorder-list/solution.test.ts +83 -0
  107. package/content/problems/121-remove-nth-node-from-end-of-list/README.md +40 -0
  108. package/content/problems/121-remove-nth-node-from-end-of-list/solution.test.ts +55 -0
  109. package/content/problems/122-lru-cache/README.md +55 -0
  110. package/content/problems/122-lru-cache/solution.test.ts +152 -0
  111. package/content/problems/123-binary-tree-level-order-traversal/README.md +40 -0
  112. package/content/problems/123-binary-tree-level-order-traversal/solution.test.ts +42 -0
  113. package/content/problems/124-binary-tree-right-side-view/README.md +40 -0
  114. package/content/problems/124-binary-tree-right-side-view/solution.test.ts +56 -0
  115. package/content/problems/125-validate-binary-search-tree/README.md +46 -0
  116. package/content/problems/125-validate-binary-search-tree/solution.test.ts +78 -0
  117. package/content/problems/126-kth-smallest-element-in-a-bst/README.md +39 -0
  118. package/content/problems/126-kth-smallest-element-in-a-bst/solution.test.ts +61 -0
  119. package/content/problems/127-lowest-common-ancestor-of-a-bst/README.md +46 -0
  120. package/content/problems/127-lowest-common-ancestor-of-a-bst/solution.test.ts +106 -0
  121. package/content/problems/128-kth-largest-element-in-an-array/README.md +42 -0
  122. package/content/problems/128-kth-largest-element-in-an-array/solution.test.ts +67 -0
  123. package/content/problems/129-k-closest-points-to-origin/README.md +43 -0
  124. package/content/problems/129-k-closest-points-to-origin/solution.test.ts +74 -0
  125. package/content/problems/130-number-of-islands/README.md +44 -0
  126. package/content/problems/130-number-of-islands/solution.test.ts +69 -0
  127. package/content/problems/131-course-schedule/README.md +42 -0
  128. package/content/problems/131-course-schedule/solution.test.ts +82 -0
  129. package/content/problems/132-rotting-oranges/README.md +46 -0
  130. package/content/problems/132-rotting-oranges/solution.test.ts +74 -0
  131. package/content/problems/133-clone-graph/README.md +42 -0
  132. package/content/problems/133-clone-graph/solution.test.ts +58 -0
  133. package/content/problems/134-house-robber/README.md +38 -0
  134. package/content/problems/134-house-robber/solution.test.ts +45 -0
  135. package/content/problems/135-coin-change/README.md +40 -0
  136. package/content/problems/135-coin-change/solution.test.ts +45 -0
  137. package/content/problems/136-longest-increasing-subsequence/README.md +41 -0
  138. package/content/problems/136-longest-increasing-subsequence/solution.test.ts +53 -0
  139. package/content/problems/137-word-break/README.md +39 -0
  140. package/content/problems/137-word-break/solution.test.ts +49 -0
  141. package/content/problems/138-merge-intervals/README.md +40 -0
  142. package/content/problems/138-merge-intervals/solution.test.ts +84 -0
  143. package/content/problems/139-insert-interval/README.md +40 -0
  144. package/content/problems/139-insert-interval/solution.test.ts +75 -0
  145. package/content/problems/201-valid-sudoku/README.md +63 -0
  146. package/content/problems/201-valid-sudoku/solution.test.ts +104 -0
  147. package/content/problems/202-car-fleet/README.md +46 -0
  148. package/content/problems/202-car-fleet/solution.test.ts +85 -0
  149. package/content/problems/203-search-a-2d-matrix/README.md +47 -0
  150. package/content/problems/203-search-a-2d-matrix/solution.test.ts +108 -0
  151. package/content/problems/204-copy-list-with-random-pointer/README.md +46 -0
  152. package/content/problems/204-copy-list-with-random-pointer/solution.test.ts +120 -0
  153. package/content/problems/205-add-two-numbers/README.md +45 -0
  154. package/content/problems/205-add-two-numbers/solution.test.ts +74 -0
  155. package/content/problems/206-find-the-duplicate-number/README.md +47 -0
  156. package/content/problems/206-find-the-duplicate-number/solution.test.ts +72 -0
  157. package/content/problems/207-count-good-nodes/README.md +44 -0
  158. package/content/problems/207-count-good-nodes/solution.test.ts +63 -0
  159. package/content/problems/208-construct-tree-from-preorder-and-inorder/README.md +52 -0
  160. package/content/problems/208-construct-tree-from-preorder-and-inorder/solution.test.ts +126 -0
  161. package/content/problems/209-implement-trie/README.md +52 -0
  162. package/content/problems/209-implement-trie/solution.test.ts +138 -0
  163. package/content/problems/210-design-add-and-search-words/README.md +50 -0
  164. package/content/problems/210-design-add-and-search-words/solution.test.ts +127 -0
  165. package/content/problems/211-task-scheduler/README.md +47 -0
  166. package/content/problems/211-task-scheduler/solution.test.ts +64 -0
  167. package/content/problems/212-design-twitter/README.md +63 -0
  168. package/content/problems/212-design-twitter/solution.test.ts +137 -0
  169. package/content/problems/213-subsets/README.md +42 -0
  170. package/content/problems/213-subsets/solution.test.ts +63 -0
  171. package/content/problems/214-combination-sum/README.md +44 -0
  172. package/content/problems/214-combination-sum/solution.test.ts +75 -0
  173. package/content/problems/215-permutations/README.md +42 -0
  174. package/content/problems/215-permutations/solution.test.ts +70 -0
  175. package/content/problems/216-word-search/README.md +50 -0
  176. package/content/problems/216-word-search/solution.test.ts +86 -0
  177. package/content/problems/217-letter-combinations-of-a-phone-number/README.md +53 -0
  178. package/content/problems/217-letter-combinations-of-a-phone-number/solution.test.ts +57 -0
  179. package/content/problems/218-palindrome-partitioning/README.md +42 -0
  180. package/content/problems/218-palindrome-partitioning/solution.test.ts +77 -0
  181. package/content/problems/219-max-area-of-island/README.md +43 -0
  182. package/content/problems/219-max-area-of-island/solution.test.ts +78 -0
  183. package/content/problems/220-pacific-atlantic-water-flow/README.md +43 -0
  184. package/content/problems/220-pacific-atlantic-water-flow/solution.test.ts +86 -0
  185. package/content/problems/221-course-schedule-ii/README.md +42 -0
  186. package/content/problems/221-course-schedule-ii/solution.test.ts +107 -0
  187. package/content/problems/222-graph-valid-tree/README.md +42 -0
  188. package/content/problems/222-graph-valid-tree/solution.test.ts +75 -0
  189. package/content/problems/223-redundant-connection/README.md +42 -0
  190. package/content/problems/223-redundant-connection/solution.test.ts +68 -0
  191. package/content/problems/224-network-delay-time/README.md +44 -0
  192. package/content/problems/224-network-delay-time/solution.test.ts +70 -0
  193. package/content/problems/225-cheapest-flights-within-k-stops/README.md +45 -0
  194. package/content/problems/225-cheapest-flights-within-k-stops/solution.test.ts +85 -0
  195. package/content/problems/226-house-robber-ii/README.md +41 -0
  196. package/content/problems/226-house-robber-ii/solution.test.ts +51 -0
  197. package/content/problems/227-longest-palindromic-substring/README.md +41 -0
  198. package/content/problems/227-longest-palindromic-substring/solution.test.ts +69 -0
  199. package/content/problems/228-decode-ways/README.md +44 -0
  200. package/content/problems/228-decode-ways/solution.test.ts +50 -0
  201. package/content/problems/229-maximum-product-subarray/README.md +40 -0
  202. package/content/problems/229-maximum-product-subarray/solution.test.ts +55 -0
  203. package/content/problems/230-partition-equal-subset-sum/README.md +39 -0
  204. package/content/problems/230-partition-equal-subset-sum/solution.test.ts +54 -0
  205. package/content/problems/231-unique-paths/README.md +41 -0
  206. package/content/problems/231-unique-paths/solution.test.ts +45 -0
  207. package/content/problems/232-longest-common-subsequence/README.md +41 -0
  208. package/content/problems/232-longest-common-subsequence/solution.test.ts +48 -0
  209. package/content/problems/233-coin-change-ii/README.md +44 -0
  210. package/content/problems/233-coin-change-ii/solution.test.ts +45 -0
  211. package/content/problems/234-edit-distance/README.md +45 -0
  212. package/content/problems/234-edit-distance/solution.test.ts +48 -0
  213. package/content/problems/235-maximum-subarray/README.md +40 -0
  214. package/content/problems/235-maximum-subarray/solution.test.ts +63 -0
  215. package/content/problems/236-jump-game/README.md +40 -0
  216. package/content/problems/236-jump-game/solution.test.ts +68 -0
  217. package/content/problems/237-gas-station/README.md +42 -0
  218. package/content/problems/237-gas-station/solution.test.ts +56 -0
  219. package/content/problems/238-partition-labels/README.md +40 -0
  220. package/content/problems/238-partition-labels/solution.test.ts +54 -0
  221. package/content/problems/239-non-overlapping-intervals/README.md +40 -0
  222. package/content/problems/239-non-overlapping-intervals/solution.test.ts +61 -0
  223. package/content/problems/240-meeting-rooms-ii/README.md +42 -0
  224. package/content/problems/240-meeting-rooms-ii/solution.test.ts +65 -0
  225. package/content/problems/241-rotate-image/README.md +41 -0
  226. package/content/problems/241-rotate-image/solution.test.ts +72 -0
  227. package/content/problems/242-spiral-matrix/README.md +40 -0
  228. package/content/problems/242-spiral-matrix/solution.test.ts +90 -0
  229. package/content/problems/243-set-matrix-zeroes/README.md +44 -0
  230. package/content/problems/243-set-matrix-zeroes/solution.test.ts +153 -0
  231. package/content/problems/301-trapping-rain-water/README.md +42 -0
  232. package/content/problems/301-trapping-rain-water/solution.test.ts +63 -0
  233. package/content/problems/302-minimum-window-substring/README.md +43 -0
  234. package/content/problems/302-minimum-window-substring/solution.test.ts +56 -0
  235. package/content/problems/303-sliding-window-maximum/README.md +42 -0
  236. package/content/problems/303-sliding-window-maximum/solution.test.ts +63 -0
  237. package/content/problems/304-largest-rectangle-in-histogram/README.md +42 -0
  238. package/content/problems/304-largest-rectangle-in-histogram/solution.test.ts +57 -0
  239. package/content/problems/305-median-of-two-sorted-arrays/README.md +42 -0
  240. package/content/problems/305-median-of-two-sorted-arrays/solution.test.ts +84 -0
  241. package/content/problems/306-merge-k-sorted-lists/README.md +42 -0
  242. package/content/problems/306-merge-k-sorted-lists/solution.test.ts +72 -0
  243. package/content/problems/307-reverse-nodes-in-k-group/README.md +42 -0
  244. package/content/problems/307-reverse-nodes-in-k-group/solution.test.ts +86 -0
  245. package/content/problems/308-binary-tree-maximum-path-sum/README.md +44 -0
  246. package/content/problems/308-binary-tree-maximum-path-sum/solution.test.ts +91 -0
  247. package/content/problems/309-serialize-and-deserialize-binary-tree/README.md +50 -0
  248. package/content/problems/309-serialize-and-deserialize-binary-tree/solution.test.ts +120 -0
  249. package/content/problems/310-find-median-from-data-stream/README.md +47 -0
  250. package/content/problems/310-find-median-from-data-stream/solution.test.ts +102 -0
  251. package/content/problems/311-word-search-ii/README.md +51 -0
  252. package/content/problems/311-word-search-ii/solution.test.ts +144 -0
  253. package/content/problems/312-n-queens/README.md +41 -0
  254. package/content/problems/312-n-queens/solution.test.ts +91 -0
  255. package/content/problems/313-word-ladder/README.md +42 -0
  256. package/content/problems/313-word-ladder/solution.test.ts +85 -0
  257. package/content/problems/314-alien-dictionary/README.md +43 -0
  258. package/content/problems/314-alien-dictionary/solution.test.ts +127 -0
  259. package/content/problems/315-longest-increasing-path-in-a-matrix/README.md +42 -0
  260. package/content/problems/315-longest-increasing-path-in-a-matrix/solution.test.ts +118 -0
  261. package/content/problems/316-swim-in-rising-water/README.md +44 -0
  262. package/content/problems/316-swim-in-rising-water/solution.test.ts +138 -0
  263. package/content/product/P01-tool-lending/README.md +28 -0
  264. package/content/product/P02-city-bike-share/README.md +28 -0
  265. package/content/product/P03-caring-from-afar/README.md +29 -0
  266. package/content/product/P04-first-garden/README.md +28 -0
  267. package/content/product/P05-save-for-later/README.md +28 -0
  268. package/content/product/P06-ship-or-hold/README.md +28 -0
  269. package/content/product/P07-photo-backup-goals/README.md +28 -0
  270. package/content/product/P08-quarter-roadmap/README.md +28 -0
  271. package/content/product/P09-grocer-delivery/README.md +29 -0
  272. package/content/product/P10-notes-for-work/README.md +28 -0
  273. package/content/product/P11-fitness-coaching/README.md +28 -0
  274. package/content/product/P12-low-price-rival/README.md +28 -0
  275. package/content/product/P13-coffee-cups/README.md +28 -0
  276. package/content/product/P14-bike-repair-market/README.md +27 -0
  277. package/content/product/P15-scooter-rides/README.md +27 -0
  278. package/content/product/P16-school-lunch-boxes/README.md +28 -0
  279. package/content/product/P17-weekly-users-drop/README.md +28 -0
  280. package/content/product/P18-ride-cancellations/README.md +28 -0
  281. package/content/product/P19-signups-up-revenue-flat/README.md +28 -0
  282. package/content/product/P20-longer-sessions/README.md +28 -0
  283. package/content/product/REVIEW.md +107 -0
  284. package/dist/cli.mjs +4462 -0
  285. package/package.json +38 -4
@@ -0,0 +1,40 @@
1
+ # 139 · Insert Interval
2
+
3
+ **Level 2 · Medium** · Pattern: intervals (single sweep) · Target: 25 min · NeetCode 150 · LeetCode 57
4
+
5
+ ## Problem
6
+
7
+ You get a list of closed intervals `[start, end]` that is already **sorted by start** and has **no overlaps**, plus one more interval `newInterval`. Add `newInterval` to the list, merging it with any intervals it overlaps, and return a list that is again sorted and overlap-free. Intervals that only touch, like `[1, 2]` and `[2, 3]`, count as overlapping.
8
+
9
+ Return a new array and **don't modify the input**: the tests check that `intervals` and `newInterval` are unchanged afterwards.
10
+
11
+ ## Examples
12
+
13
+ | `intervals` | `newInterval` | Output |
14
+ |---|---|---|
15
+ | `[[1, 3], [6, 9]]` | `[2, 5]` | `[[1, 5], [6, 9]]` |
16
+ | `[[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]]` | `[4, 8]` | `[[1, 2], [3, 10], [12, 16]]` |
17
+ | `[]` | `[5, 7]` | `[[5, 7]]` |
18
+
19
+ ## Constraints
20
+
21
+ - `0 <= intervals.length <= 10^4`
22
+ - `0 <= start <= end <= 10^5`
23
+ - `intervals` is sorted by start and no two of its intervals overlap or touch.
24
+
25
+ ## Run it
26
+
27
+ ```bash
28
+ pnpm watch 139
29
+ ```
30
+
31
+ <details><summary>Target complexity (open after your first attempt)</summary>
32
+
33
+ Time O(n) · Space O(n) for the output. Appending `newInterval`, sorting and running Merge Intervals (problem 138) works in O(n log n), but it ignores that the input is already sorted. The tests don't time this one, so judge yourself: aim for one left-to-right pass.
34
+
35
+ </details>
36
+
37
+ ## Follow-ups an interviewer might ask
38
+
39
+ - Can you find where the overlap starts and ends with binary search? Does that improve the overall complexity?
40
+ - What if you had to insert many intervals one after another? Which data structure would you keep them in?
@@ -0,0 +1,75 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { insert } from './solution'
3
+
4
+ type Interval = [number, number]
5
+
6
+ /** Inserts, and also checks that neither input was modified. */
7
+ function inserted(intervals: Interval[], newInterval: Interval): Interval[] {
8
+ const before = structuredClone(intervals)
9
+ const newBefore = structuredClone(newInterval)
10
+ const result = insert(intervals, newInterval)
11
+ expect(intervals, 'intervals was modified').toEqual(before)
12
+ expect(newInterval, 'newInterval was modified').toEqual(newBefore)
13
+ return result
14
+ }
15
+
16
+ describe('139 insert interval', () => {
17
+ it('runs the README examples', () => {
18
+ expect(inserted([[1, 3], [6, 9]], [2, 5])).toEqual([[1, 5], [6, 9]])
19
+ expect(inserted([[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]], [4, 8])).toEqual([[1, 2], [3, 10], [12, 16]])
20
+ })
21
+
22
+ it('inserts into an empty list', () => {
23
+ expect(inserted([], [5, 7])).toEqual([[5, 7]])
24
+ })
25
+
26
+ it('inserts at the start without overlap', () => {
27
+ expect(inserted([[3, 5], [8, 9]], [0, 1])).toEqual([[0, 1], [3, 5], [8, 9]])
28
+ })
29
+
30
+ it('inserts at the end without overlap', () => {
31
+ expect(inserted([[1, 2], [3, 5]], [7, 9])).toEqual([[1, 2], [3, 5], [7, 9]])
32
+ })
33
+
34
+ it('inserts into a gap in the middle', () => {
35
+ expect(inserted([[1, 2], [10, 12]], [5, 6])).toEqual([[1, 2], [5, 6], [10, 12]])
36
+ })
37
+
38
+ it('swallows every interval', () => {
39
+ expect(inserted([[2, 3], [5, 6], [8, 9]], [0, 10])).toEqual([[0, 10]])
40
+ })
41
+
42
+ it('is swallowed by an existing interval', () => {
43
+ expect(inserted([[1, 10], [20, 30]], [3, 4])).toEqual([[1, 10], [20, 30]])
44
+ })
45
+
46
+ it('merges with intervals it only touches', () => {
47
+ expect(inserted([[1, 2], [5, 6]], [2, 5])).toEqual([[1, 6]])
48
+ expect(inserted([[1, 2]], [2, 2])).toEqual([[1, 2]])
49
+ expect(inserted([[3, 4]], [1, 3])).toEqual([[1, 4]])
50
+ expect(inserted([[3, 4]], [4, 6])).toEqual([[3, 6]])
51
+ })
52
+
53
+ it('extends the first or last interval', () => {
54
+ expect(inserted([[1, 5], [8, 9]], [0, 3])).toEqual([[0, 5], [8, 9]])
55
+ expect(inserted([[1, 5], [8, 9]], [9, 12])).toEqual([[1, 5], [8, 12]])
56
+ })
57
+
58
+ it('handles a zero-length new interval', () => {
59
+ expect(inserted([[1, 3], [6, 9]], [4, 4])).toEqual([[1, 3], [4, 4], [6, 9]])
60
+ })
61
+
62
+ it('handles a single existing interval on either side', () => {
63
+ expect(inserted([[5, 7]], [1, 2])).toEqual([[1, 2], [5, 7]])
64
+ expect(inserted([[5, 7]], [8, 9])).toEqual([[5, 7], [8, 9]])
65
+ })
66
+
67
+ it('merges a long run in the middle and keeps both ends', () => {
68
+ const intervals: Interval[] = Array.from({ length: 1_000 }, (_, k) => [4 * k, 4 * k + 2])
69
+ const result = inserted(intervals, [101, 2_001])
70
+ expect(result).toHaveLength(1_000 - 476 + 1)
71
+ expect(result[24]).toEqual([96, 98])
72
+ expect(result[25]).toEqual([100, 2_002])
73
+ expect(result[26]).toEqual([2_004, 2_006])
74
+ })
75
+ })
@@ -0,0 +1,63 @@
1
+ # 201 · Valid Sudoku
2
+
3
+ **Level 2 · Medium** · Pattern: arrays & hashing (one seen-set per row, column and box) · Target: 25 min · NeetCode 150 · LeetCode 36
4
+
5
+ ## Problem
6
+
7
+ `board` is a 9 × 9 Sudoku grid that may be only partly filled. Each cell is a single character: a digit `'1'` to `'9'`, or `'.'` for an empty cell.
8
+
9
+ Return `true` if the digits placed so far break none of these rules, and `false` otherwise:
10
+
11
+ - no digit appears twice in the same row;
12
+ - no digit appears twice in the same column;
13
+ - no digit appears twice in the same 3 × 3 box (the nine boxes are the blocks of rows 0–2, 3–5, 6–8 crossed with columns 0–2, 3–5, 6–8).
14
+
15
+ Only the filled cells matter. You don't have to decide whether the puzzle can be finished: a board can follow every rule and still have no solution, and that board is valid.
16
+
17
+ ## Examples
18
+
19
+ Board A (each string is one row, top to bottom):
20
+
21
+ ```
22
+ "1..4...8."
23
+ ".5....1.3"
24
+ "7...2...."
25
+ "..4..7.9."
26
+ "....9...."
27
+ ".9.2...6."
28
+ "3.....9.."
29
+ ".7..1..4."
30
+ "..2...6.8"
31
+ ```
32
+
33
+ Board B is board A with a `'5'` added in row 0, column 2.
34
+
35
+ | `board` | Output | Why |
36
+ |---|---|---|
37
+ | Board A | `true` | No row, column or box repeats a digit. |
38
+ | Board B | `false` | The top-left box now holds two `5`s (row 0 column 2, and row 1 column 1). |
39
+ | All `'.'` | `true` | Nothing is filled in, so nothing repeats. |
40
+
41
+ ## Constraints
42
+
43
+ - `board.length == 9` and `board[i].length == 9`.
44
+ - Each `board[i][j]` is `'1'`–`'9'` or `'.'`.
45
+ - The board is always 9 × 9, so there is no performance test: the work is about getting all three rules right.
46
+
47
+ ## Run it
48
+
49
+ ```bash
50
+ pnpm watch 201
51
+ ```
52
+
53
+ <details><summary>Target complexity (open after your first attempt)</summary>
54
+
55
+ Time O(1) · Space O(1), because the board is a fixed 81 cells. In terms of a general n × n board, aim for one pass over the cells, O(n²) time and O(n²) space. Checking each filled cell against every other cell in its row, column and box also passes here (the board is tiny), but it is O(n³) on an n × n board, and an interviewer will ask for the single pass.
56
+
57
+ </details>
58
+
59
+ ## Follow-ups an interviewer might ask
60
+
61
+ - Can you check all three rules in a single pass over the cells? How do you number the nine boxes?
62
+ - Could you store what you've seen in bitmasks instead of sets? What does that save?
63
+ - How would you go from validating to actually solving the puzzle? (LeetCode 37, backtracking)
@@ -0,0 +1,104 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { isValidSudoku } from './solution'
3
+
4
+ /** Turns nine 9-character strings into a board of single characters. */
5
+ function board(rows: readonly string[]): string[][] {
6
+ if (rows.length !== 9 || rows.some((row) => row.length !== 9)) throw new Error('A board needs 9 rows of 9 cells')
7
+ return rows.map((row) => [...row])
8
+ }
9
+
10
+ const EMPTY_ROW = '.........'
11
+
12
+ /** An empty board with the given digits placed at [row, col]. */
13
+ function boardWith(cells: readonly [number, number, string][]): string[][] {
14
+ const grid = board(Array.from({ length: 9 }, () => EMPTY_ROW))
15
+ return grid.map((row, r) => row.map((cell, c) => cells.find(([cr, cc]) => cr === r && cc === c)?.[2] ?? cell))
16
+ }
17
+
18
+ const BOARD_A = [
19
+ '1..4...8.',
20
+ '.5....1.3',
21
+ '7...2....',
22
+ '..4..7.9.',
23
+ '....9....',
24
+ '.9.2...6.',
25
+ '3.....9..',
26
+ '.7..1..4.',
27
+ '..2...6.8',
28
+ ]
29
+
30
+ /** A completely filled, correct grid. */
31
+ const SOLVED = [
32
+ '123456789',
33
+ '456789123',
34
+ '789123456',
35
+ '234567891',
36
+ '567891234',
37
+ '891234567',
38
+ '345678912',
39
+ '678912345',
40
+ '912345678',
41
+ ]
42
+
43
+ describe('201 valid sudoku', () => {
44
+ it('accepts a partly filled board that follows every rule (board A)', () => {
45
+ expect(isValidSudoku(board(BOARD_A))).toBe(true)
46
+ })
47
+
48
+ it('rejects board A with a second 5 in the top-left box (board B)', () => {
49
+ const rows = [...BOARD_A]
50
+ rows[0] = '1.54...8.'
51
+ expect(isValidSudoku(board(rows))).toBe(false)
52
+ })
53
+
54
+ it('accepts an empty board', () => {
55
+ expect(isValidSudoku(board(Array.from({ length: 9 }, () => EMPTY_ROW)))).toBe(true)
56
+ })
57
+
58
+ it('accepts a completely solved board', () => {
59
+ expect(isValidSudoku(board(SOLVED))).toBe(true)
60
+ })
61
+
62
+ it('rejects a repeat that breaks only the row rule', () => {
63
+ expect(isValidSudoku(boardWith([[2, 0, '6'], [2, 8, '6']]))).toBe(false)
64
+ })
65
+
66
+ it('rejects a repeat that breaks only the column rule', () => {
67
+ expect(isValidSudoku(boardWith([[0, 4, '2'], [8, 4, '2']]))).toBe(false)
68
+ })
69
+
70
+ it('rejects a repeat that breaks only the box rule', () => {
71
+ // Different rows and different columns, same middle box.
72
+ expect(isValidSudoku(boardWith([[3, 3, '8'], [5, 5, '8']]))).toBe(false)
73
+ expect(isValidSudoku(boardWith([[6, 8, '1'], [8, 6, '1']]))).toBe(false)
74
+ })
75
+
76
+ it('keeps the nine boxes apart', () => {
77
+ // Top-middle box and middle-left box: different boxes, rows and columns.
78
+ expect(isValidSudoku(boardWith([[0, 4, '7'], [4, 0, '7']]))).toBe(true)
79
+ // The same digit once in every box, on different rows and columns.
80
+ const diagonalish: [number, number, string][] = [
81
+ [0, 0, '9'], [1, 3, '9'], [2, 6, '9'],
82
+ [3, 1, '9'], [4, 4, '9'], [5, 7, '9'],
83
+ [6, 2, '9'], [7, 5, '9'], [8, 8, '9'],
84
+ ]
85
+ expect(isValidSudoku(boardWith(diagonalish))).toBe(true)
86
+ })
87
+
88
+ it('accepts a board that follows the rules but cannot be finished', () => {
89
+ // Row 0's last cell can only be 9, but column 8 already has a 9.
90
+ expect(isValidSudoku(boardWith([...'12345678'].map((d, c): [number, number, string] => [0, c, d]).concat([[1, 8, '9']])))).toBe(true)
91
+ })
92
+
93
+ it('rejects a solved board with two cells swapped', () => {
94
+ const rows = [...SOLVED]
95
+ rows[4] = '657891234'
96
+ expect(isValidSudoku(board(rows))).toBe(false)
97
+ })
98
+
99
+ it('catches a repeat in the last row, column and box', () => {
100
+ expect(isValidSudoku(boardWith([[8, 0, '4'], [8, 7, '4']]))).toBe(false)
101
+ expect(isValidSudoku(boardWith([[1, 8, '3'], [7, 8, '3']]))).toBe(false)
102
+ expect(isValidSudoku(boardWith([[6, 6, '5'], [7, 7, '5']]))).toBe(false)
103
+ })
104
+ })
@@ -0,0 +1,46 @@
1
+ # 202 · Car Fleet
2
+
3
+ **Level 2 · Medium** · Pattern: monotonic stack (sort by position, then sweep from the front) · Target: 25 min · NeetCode 150 · LeetCode 853
4
+
5
+ ## Problem
6
+
7
+ Some cars drive along a single-lane road towards a finish line at mile `target`. Car `i` starts at mile `position[i]` and drives at `speed[i]` miles per hour.
8
+
9
+ A car can never overtake the car in front. When a faster car catches up with a slower one, it slows down and the two drive on together at the slower speed. A group of cars driving bumper to bumper like this is called a **fleet**; a single car on its own is a fleet too. If a car catches up exactly at the finish line, it still counts as part of that fleet.
10
+
11
+ Return how many fleets cross the finish line.
12
+
13
+ ## Examples
14
+
15
+ | `target` | `position` | `speed` | Output | Why |
16
+ |---|---|---|---|---|
17
+ | `20` | `[2, 10, 14, 18]` | `[4, 2, 1, 1]` | `2` | The car at 18 finishes alone. The car at 14 never catches it, and the cars at 10 and 2 both catch the car at 14 before the line. |
18
+ | `12` | `[0, 4, 8]` | `[1, 2, 4]` | `3` | Every car is faster than the one behind it, so nobody catches anybody. |
19
+ | `10` | `[4, 6]` | `[3, 2]` | `1` | Both cars would arrive at exactly the same moment, so they meet on the line. |
20
+ | `9` | `[5]` | `[1]` | `1` | One car is one fleet. |
21
+
22
+ ## Constraints
23
+
24
+ - `n == position.length == speed.length`, `1 <= n <= 10^5` (the performance test uses 40,000 cars)
25
+ - `0 < target <= 10^6`
26
+ - `0 <= position[i] < target`, and all positions are different.
27
+ - `0 < speed[i] <= 10^6`, all whole numbers.
28
+ - `position` is in no particular order.
29
+
30
+ ## Run it
31
+
32
+ ```bash
33
+ pnpm watch 202
34
+ ```
35
+
36
+ <details><summary>Target complexity (open after your first attempt)</summary>
37
+
38
+ Time O(n log n) for the sort, then O(n) · Space O(n). The performance test rejects comparing every car with every car ahead of it, which is O(n²).
39
+
40
+ </details>
41
+
42
+ ## Follow-ups an interviewer might ask
43
+
44
+ - Why is it enough to compare each car's arrival time with just one number, not with every car ahead?
45
+ - Can you avoid floating-point division when comparing arrival times?
46
+ - What changes if cars may overtake, or if you need the time at which each car finishes? (LeetCode 1776, Car Fleet II)
@@ -0,0 +1,85 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { timeMs } from '../../lib/perf'
3
+ import { carFleet } from './solution'
4
+
5
+ /** Deterministic shuffle (a small linear congruential generator), so runs are repeatable. */
6
+ function shuffled<T>(items: readonly T[], seed: number): T[] {
7
+ const out = [...items]
8
+ let state = seed
9
+ for (let i = out.length - 1; i > 0; i--) {
10
+ state = (state * 1_103_515_245 + 12_345) % 2_147_483_648
11
+ const j = state % (i + 1)
12
+ ;[out[i], out[j]] = [out[j]!, out[i]!]
13
+ }
14
+ return out
15
+ }
16
+
17
+ describe('202 car fleet', () => {
18
+ it('merges cars that catch a slower car before the line', () => {
19
+ expect(carFleet(20, [2, 10, 14, 18], [4, 2, 1, 1])).toBe(2)
20
+ })
21
+
22
+ it('counts every car when nobody catches up', () => {
23
+ expect(carFleet(12, [0, 4, 8], [1, 2, 4])).toBe(3)
24
+ })
25
+
26
+ it('merges two cars that meet exactly on the finish line', () => {
27
+ expect(carFleet(10, [4, 6], [3, 2])).toBe(1)
28
+ })
29
+
30
+ it('keeps two cars apart when the catch-up point is past the line', () => {
31
+ // The back car would catch up at mile 12, after the finish at 10.
32
+ expect(carFleet(10, [3, 6], [3, 2])).toBe(2)
33
+ })
34
+
35
+ it('handles a single car', () => {
36
+ expect(carFleet(9, [5], [1])).toBe(1)
37
+ expect(carFleet(9, [0], [100])).toBe(1)
38
+ })
39
+
40
+ it('does not depend on the order of the input', () => {
41
+ expect(carFleet(20, [14, 2, 18, 10], [1, 4, 1, 2])).toBe(2)
42
+ expect(carFleet(12, [8, 0, 4], [4, 1, 2])).toBe(3)
43
+ })
44
+
45
+ it('compares with the slowest fleet ahead, not just the car directly ahead', () => {
46
+ // Front car: 5 h. Middle car: 3 h, joins it. Back car: 4 h, slower than
47
+ // the middle car alone but still catches the 5 h fleet.
48
+ expect(carFleet(10, [5, 4, 2], [1, 2, 2])).toBe(1)
49
+ })
50
+
51
+ it('lets a slow car in the middle hold up everyone behind it', () => {
52
+ expect(carFleet(100, [0, 50, 90], [100, 1, 100])).toBe(2)
53
+ })
54
+
55
+ it('treats equal speeds as never catching up', () => {
56
+ expect(carFleet(50, [1, 10, 20, 30, 40], [7, 7, 7, 7, 7])).toBe(5)
57
+ })
58
+
59
+ it('handles a car that starts at mile 0 and the largest values', () => {
60
+ expect(carFleet(1_000_000, [0, 999_999], [1_000_000, 1])).toBe(1)
61
+ expect(carFleet(1_000_000, [0, 999_999], [999_999, 1])).toBe(2)
62
+ })
63
+
64
+ it('merges a whole chain of cars into one fleet', () => {
65
+ expect(carFleet(10, [0, 1, 2, 3, 4], [10, 8, 6, 4, 1])).toBe(1)
66
+ })
67
+ })
68
+
69
+ describe('202 performance', () => {
70
+ it('handles 40,000 cars in under 300 ms (comparing every pair is O(n²), too slow here)', () => {
71
+ // Cars stand at miles 0..n-1, in pairs. The front car of each pair (odd mile) drives at 1 mph
72
+ // and finishes after every car in front of it, so it leads its own fleet. The back car (even
73
+ // mile) drives at 2 mph and always catches it, so there are n / 2 fleets.
74
+ const n = 40_000
75
+ const target = n
76
+ const cars = shuffled(
77
+ Array.from({ length: n }, (_, mile) => ({ mile, mph: mile % 2 === 1 ? 1 : 2 })),
78
+ 2024,
79
+ )
80
+ const position = cars.map((car) => car.mile)
81
+ const speed = cars.map((car) => car.mph)
82
+ const ms = timeMs(() => expect(carFleet(target, position, speed)).toBe(n / 2))
83
+ expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(300)
84
+ })
85
+ })
@@ -0,0 +1,47 @@
1
+ # 203 · Search a 2D Matrix
2
+
3
+ **Level 2 · Medium** · Pattern: binary search (treat the grid as one sorted array) · Target: 25 min · NeetCode 150 · LeetCode 74
4
+
5
+ ## Problem
6
+
7
+ `matrix` has `m` rows and `n` columns of integers, arranged so that:
8
+
9
+ - each row is sorted in strictly increasing order, left to right;
10
+ - the first value of every row is greater than the last value of the row above it.
11
+
12
+ Return `true` if `target` appears anywhere in `matrix`, and `false` otherwise.
13
+
14
+ Your solution must read O(log(m · n)) cells. The test counts every cell you read, so scanning the cells one by one (or a row or a column at a time) won't pass.
15
+
16
+ ## Examples
17
+
18
+ | `matrix` | `target` | Output |
19
+ |---|---|---|
20
+ | `[[2, 4, 7, 9], [11, 13, 18, 20], [23, 29, 31, 40]]` | `18` | `true` |
21
+ | `[[2, 4, 7, 9], [11, 13, 18, 20], [23, 29, 31, 40]]` | `21` | `false` |
22
+ | `[[-6], [0], [8]]` | `8` | `true` |
23
+ | `[[5]]` | `4` | `false` |
24
+
25
+ ## Constraints
26
+
27
+ - `1 <= m, n <= 100` (the read-count test uses a 2,000 × 500 matrix, a million cells, and allows up to 100 reads)
28
+ - `-10^4 <= matrix[i][j], target <= 10^4` in the examples; the read-count test uses larger values.
29
+ - Reading `matrix.length` or a row's `length` doesn't count as a read.
30
+
31
+ ## Run it
32
+
33
+ ```bash
34
+ pnpm watch 203
35
+ ```
36
+
37
+ <details><summary>Target complexity (open after your first attempt)</summary>
38
+
39
+ Time O(log(m · n)) · Space O(1). Finding the row first and then searching inside it is O(log m + log n), the same thing. Starting in a corner and stepping one row or column at a time is O(m + n), and the read-count test rejects it, as it does a full scan (O(m · n)).
40
+
41
+ </details>
42
+
43
+ ## Follow-ups an interviewer might ask
44
+
45
+ - Your index `k` runs over all `m · n` cells. Which row and column is cell `k`? Why does swapping `m` and `n` there break non-square matrices?
46
+ - What if each row and each column is sorted, but a row's first value need not be bigger than the row above's last? (LeetCode 240)
47
+ - Return the position of `target`, or where it would go if it were inserted.
@@ -0,0 +1,108 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { searchMatrix } from './solution'
3
+
4
+ /** Wraps every row so each cell read is counted. Reading `length` is free. */
5
+ function counted(rows: readonly (readonly number[])[]): { matrix: readonly (readonly number[])[]; reads: () => number } {
6
+ let reads = 0
7
+ const handler: ProxyHandler<readonly number[]> = {
8
+ get(target, prop, receiver) {
9
+ if (typeof prop === 'string' && /^\d+$/.test(prop)) reads++
10
+ return Reflect.get(target, prop, receiver)
11
+ },
12
+ }
13
+ const matrix = rows.map((row) => new Proxy(row, handler))
14
+ return { matrix, reads: () => reads }
15
+ }
16
+
17
+ const WIDE = [
18
+ [2, 4, 7, 9],
19
+ [11, 13, 18, 20],
20
+ [23, 29, 31, 40],
21
+ ]
22
+
23
+ describe('203 search a 2d matrix', () => {
24
+ it('finds a value in the middle row', () => {
25
+ expect(searchMatrix(WIDE, 18)).toBe(true)
26
+ })
27
+
28
+ it('returns false for a value that falls between two rows', () => {
29
+ expect(searchMatrix(WIDE, 21)).toBe(false)
30
+ })
31
+
32
+ it('finds every value of a non-square matrix', () => {
33
+ for (const value of WIDE.flat()) expect(searchMatrix(WIDE, value), `looking for ${value}`).toBe(true)
34
+ })
35
+
36
+ it('returns false for values inside a row that are missing', () => {
37
+ for (const value of [3, 5, 10, 12, 19, 30, 39]) expect(searchMatrix(WIDE, value), `looking for ${value}`).toBe(false)
38
+ })
39
+
40
+ it('returns false below the smallest and above the largest value', () => {
41
+ expect(searchMatrix(WIDE, 1)).toBe(false)
42
+ expect(searchMatrix(WIDE, 41)).toBe(false)
43
+ })
44
+
45
+ it('handles a single column', () => {
46
+ const column = [[-6], [0], [8]]
47
+ expect(searchMatrix(column, 8)).toBe(true)
48
+ expect(searchMatrix(column, -6)).toBe(true)
49
+ expect(searchMatrix(column, 0)).toBe(true)
50
+ expect(searchMatrix(column, 1)).toBe(false)
51
+ expect(searchMatrix(column, -7)).toBe(false)
52
+ })
53
+
54
+ it('handles a single row', () => {
55
+ const row = [[-9, -4, 0, 6, 15]]
56
+ for (const value of row[0]!) expect(searchMatrix(row, value), `looking for ${value}`).toBe(true)
57
+ expect(searchMatrix(row, 1)).toBe(false)
58
+ expect(searchMatrix(row, 16)).toBe(false)
59
+ })
60
+
61
+ it('handles a single cell', () => {
62
+ expect(searchMatrix([[5]], 5)).toBe(true)
63
+ expect(searchMatrix([[5]], 4)).toBe(false)
64
+ expect(searchMatrix([[5]], 6)).toBe(false)
65
+ })
66
+
67
+ it('finds every value of a tall, narrow matrix', () => {
68
+ const tall = [
69
+ [1, 3],
70
+ [5, 8],
71
+ [12, 14],
72
+ [16, 21],
73
+ [30, 33],
74
+ ]
75
+ for (const value of tall.flat()) expect(searchMatrix(tall, value), `looking for ${value}`).toBe(true)
76
+ for (const value of [0, 2, 9, 15, 22, 34]) expect(searchMatrix(tall, value), `looking for ${value}`).toBe(false)
77
+ })
78
+ })
79
+
80
+ describe('203 read count', () => {
81
+ it('reads at most 100 cells of a 2,000 × 500 matrix (a scan, or walking from a corner, reads thousands)', () => {
82
+ const m = 2_000
83
+ const n = 500
84
+ // Row r holds r·10,000 + 0, 2, 4, …, 998, so there are gaps inside and between rows.
85
+ const rows = Array.from({ length: m }, (_, r) => Array.from({ length: n }, (_, c) => r * 10_000 + c * 2))
86
+ const isPresent = (t: number): boolean => {
87
+ const r = Math.floor(t / 10_000)
88
+ const rest = t - r * 10_000
89
+ return r >= 0 && r < m && rest % 2 === 0 && rest / 2 < n
90
+ }
91
+ const targets = [
92
+ (m - 1) * 10_000, // bottom-left corner
93
+ (m - 1) * 10_000 + 998, // bottom-right corner
94
+ (m - 1) * 10_000 + 501, // missing, inside the last row
95
+ 0, // top-left corner
96
+ 998, // top-right corner
97
+ 1_234 * 10_000 + 700, // somewhere in the middle
98
+ 1_234 * 10_000 + 5_000, // missing, in the gap after a row
99
+ -1, // below the smallest
100
+ m * 10_000, // above the largest
101
+ ]
102
+ for (const target of targets) {
103
+ const { matrix, reads } = counted(rows)
104
+ expect(searchMatrix(matrix, target), `looking for ${target}`).toBe(isPresent(target))
105
+ expect(reads(), `read ${reads()} cells looking for ${target}`).toBeLessThanOrEqual(100)
106
+ }
107
+ })
108
+ })
@@ -0,0 +1,46 @@
1
+ # 204 · Copy List with Random Pointer
2
+
3
+ **Level 2 · Medium** · Pattern: linked list (map each original node to its copy) · Target: 25 min · NeetCode 150 · LeetCode 138
4
+
5
+ ## Problem
6
+
7
+ You get `head`, the first node of a linked list of `RandomListNode`s (defined in `node.ts`, next to this file). Besides `val` and `next`, every node has a `random` pointer that points to some node of the same list (possibly itself) or is `null`.
8
+
9
+ Return the head of a **deep copy** of the list: brand-new nodes, one per original node, with the same values, where every copy's `next` and `random` point to the matching **copies**. No pointer in your copy may lead back to an original node.
10
+
11
+ When your function returns, the original list must be exactly as it was: same values, same `next` and same `random` pointers. (Changing it temporarily is fine, as long as you put it back.)
12
+
13
+ ## Examples
14
+
15
+ Each list is written as `[val, index of the node random points to]`, with `null` for no random pointer.
16
+
17
+ | `head` | Output |
18
+ |---|---|
19
+ | `[[3, 2], [8, null], [3, 0]]` | a new list `[[3, 2], [8, null], [3, 0]]` |
20
+ | `[[6, 0]]` | a new list `[[6, 0]]` (the copy's `random` points to the copy itself) |
21
+ | `[]` (`head` is `null`) | `null` |
22
+
23
+ ## Constraints
24
+
25
+ - `0 <= nodes <= 1000` (the performance test copies 30 lists of 5,000 nodes each)
26
+ - `-10^4 <= val <= 10^4`, and values can repeat.
27
+ - Every `random` is `null` or a node of the same list.
28
+ - The tests check node identity: every node of your copy must be new, and each copy's `random` must be the copy at the same position as the original's `random`, not just a node with the same value.
29
+
30
+ ## Run it
31
+
32
+ ```bash
33
+ pnpm watch 204
34
+ ```
35
+
36
+ <details><summary>Target complexity (open after your first attempt)</summary>
37
+
38
+ Time O(n) · Space O(n) for a lookup from original nodes to copies. There is also an O(1)-extra-space version that threads each copy in right after its original, then splits the two lists apart. The performance test rejects finding each `random` target by walking the list from the head, which is O(n²).
39
+
40
+ </details>
41
+
42
+ ## Follow-ups an interviewer might ask
43
+
44
+ - Can you do it with O(1) extra space (not counting the copy itself)?
45
+ - Why can't you look up copies by value?
46
+ - How would you deep-copy a general graph where each node has a list of neighbours? (LeetCode 133)