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,57 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { timeMs } from '../../lib/perf'
3
+ import { largestRectangleArea } from './solution'
4
+
5
+ describe('304 largest rectangle in histogram', () => {
6
+ it('spans several bars at the height of the shortest', () => {
7
+ expect(largestRectangleArea([3, 1, 3, 2, 2])).toBe(6)
8
+ })
9
+
10
+ it('uses two equal tall bars together', () => {
11
+ expect(largestRectangleArea([2, 4, 4, 1])).toBe(8)
12
+ })
13
+
14
+ it('handles a single bar', () => {
15
+ expect(largestRectangleArea([5])).toBe(5)
16
+ expect(largestRectangleArea([0])).toBe(0)
17
+ })
18
+
19
+ it('handles rising and falling bars', () => {
20
+ expect(largestRectangleArea([1, 2, 3, 4, 5])).toBe(9)
21
+ expect(largestRectangleArea([5, 4, 3, 2, 1])).toBe(9)
22
+ })
23
+
24
+ it('handles all-equal bars', () => {
25
+ expect(largestRectangleArea([4, 4, 4])).toBe(12)
26
+ })
27
+
28
+ it('can not span a zero-height bar', () => {
29
+ expect(largestRectangleArea([6, 0, 6])).toBe(6)
30
+ expect(largestRectangleArea([0, 0, 0])).toBe(0)
31
+ expect(largestRectangleArea([3, 3, 0, 2, 2, 2])).toBe(6)
32
+ })
33
+
34
+ it('prefers a wide short rectangle over a narrow tall one', () => {
35
+ expect(largestRectangleArea([2, 1, 2])).toBe(3)
36
+ expect(largestRectangleArea([1, 9, 1, 1, 1, 1, 1, 1, 1, 1, 1])).toBe(11)
37
+ })
38
+
39
+ it('prefers a narrow tall rectangle over a wide short one', () => {
40
+ expect(largestRectangleArea([1, 1, 1, 10, 9, 1])).toBe(18)
41
+ })
42
+
43
+ it('handles a valley and repeated heights', () => {
44
+ expect(largestRectangleArea([5, 5, 1, 7, 1, 1, 5, 2, 7, 6])).toBe(12)
45
+ })
46
+ })
47
+
48
+ describe('304 performance', () => {
49
+ it('handles 70,000 rising bars in under 200 ms (spreading out from every bar, O(n²), is too slow here)', () => {
50
+ const n = 70_000
51
+ const heights = Array.from({ length: n }, (_, i) => i + 1)
52
+ // A rectangle of height h spans the last n - h + 1 bars; the best h is the middle one.
53
+ const h = Math.floor((n + 1) / 2)
54
+ const ms = timeMs(() => expect(largestRectangleArea(heights)).toBe(h * (n - h + 1)))
55
+ expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(200)
56
+ })
57
+ })
@@ -0,0 +1,42 @@
1
+ # 305 · Median of Two Sorted Arrays
2
+
3
+ **Level 3 · Hard** · Pattern: binary search · Target: 40 min · NeetCode 150 · LeetCode 4
4
+
5
+ ## Problem
6
+
7
+ `nums1` and `nums2` are each sorted in ascending order (repeats allowed). Return the median of all their values taken together.
8
+
9
+ The median is the middle value once everything is in one sorted list. When the combined count is even, it is the average of the two middle values, which may end in `.5`.
10
+
11
+ Your solution must read O(log(m + n)) elements, where `m` and `n` are the two lengths. The test counts every element you read from either array, so merging the arrays (or copying, spreading or concatenating them) won't pass.
12
+
13
+ ## Examples
14
+
15
+ | `nums1` | `nums2` | Output |
16
+ |---|---|---|
17
+ | `[1, 4, 9]` | `[2, 3]` | `3` |
18
+ | `[5, 6]` | `[1, 2, 7, 8]` | `5.5` |
19
+ | `[]` | `[4]` | `4` |
20
+
21
+ ## Constraints
22
+
23
+ - `0 <= nums1.length, nums2.length <= 10^6`, and at least one of them is non-empty (the read-count test uses up to 2,000,000 values in all and allows up to 5,000 reads)
24
+ - `-10^6 <= nums[i] <= 10^6` in the examples; the read-count test uses values up to about 2 · 10^7.
25
+
26
+ ## Run it
27
+
28
+ ```bash
29
+ pnpm watch 305
30
+ ```
31
+
32
+ <details><summary>Target complexity (open after your first attempt)</summary>
33
+
34
+ Time O(log(min(m, n))) · Space O(1), by searching for where to split the shorter array. Repeatedly discarding about half of the values that are certainly below the `k`-th smallest is O(log(m + n)) and passes too. Merging until the middle is O(m + n), which the read-count test rejects.
35
+
36
+ </details>
37
+
38
+ ## Follow-ups an interviewer might ask
39
+
40
+ - Why search over the shorter array? What breaks if you search over the longer one?
41
+ - Generalise it: return the `k`-th smallest value across both arrays.
42
+ - How would you find the median of `k` sorted arrays, or of a stream of numbers? (LeetCode 295)
@@ -0,0 +1,84 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { findMedianSortedArrays } from './solution'
3
+
4
+ /** Wraps an array so every element read is counted. */
5
+ function counted(values: readonly number[]): { nums: readonly number[]; reads: () => number } {
6
+ let reads = 0
7
+ const nums = new Proxy(values, {
8
+ get(target, prop, receiver) {
9
+ if (typeof prop === 'string' && /^\d+$/.test(prop)) reads++
10
+ return Reflect.get(target, prop, receiver)
11
+ },
12
+ })
13
+ return { nums, reads: () => reads }
14
+ }
15
+
16
+ const range = (start: number, length: number, step = 1): number[] =>
17
+ Array.from({ length }, (_, i) => start + i * step)
18
+
19
+ describe('305 median of two sorted arrays', () => {
20
+ it('finds the middle of an odd total', () => {
21
+ expect(findMedianSortedArrays([1, 4, 9], [2, 3])).toBe(3)
22
+ })
23
+
24
+ it('averages the two middle values of an even total', () => {
25
+ expect(findMedianSortedArrays([5, 6], [1, 2, 7, 8])).toBe(5.5)
26
+ })
27
+
28
+ it('handles one empty array', () => {
29
+ expect(findMedianSortedArrays([], [4])).toBe(4)
30
+ expect(findMedianSortedArrays([1, 2, 3, 4], [])).toBe(2.5)
31
+ expect(findMedianSortedArrays([-7], [])).toBe(-7)
32
+ })
33
+
34
+ it('handles one value in each array', () => {
35
+ expect(findMedianSortedArrays([10], [3])).toBe(6.5)
36
+ })
37
+
38
+ it('handles arrays whose ranges do not overlap, in either order', () => {
39
+ expect(findMedianSortedArrays([1, 2, 3], [10, 11, 12, 13])).toBe(10)
40
+ expect(findMedianSortedArrays([10, 11, 12, 13], [1, 2, 3])).toBe(10)
41
+ expect(findMedianSortedArrays([1, 2], [3, 4])).toBe(2.5)
42
+ })
43
+
44
+ it('handles very different lengths', () => {
45
+ expect(findMedianSortedArrays([50], [1, 2, 3, 4, 5, 6, 7])).toBe(4.5)
46
+ expect(findMedianSortedArrays([1, 2, 3, 4, 5, 6, 7, 8], [0])).toBe(4)
47
+ })
48
+
49
+ it('handles repeated values within and across the arrays', () => {
50
+ expect(findMedianSortedArrays([3, 3], [3])).toBe(3)
51
+ expect(findMedianSortedArrays([1, 1, 1], [1, 1, 5])).toBe(1)
52
+ expect(findMedianSortedArrays([2, 2, 4, 4], [2, 4])).toBe(3)
53
+ })
54
+
55
+ it('handles negative values', () => {
56
+ expect(findMedianSortedArrays([-9, -4, -1], [-6, -3])).toBe(-4)
57
+ expect(findMedianSortedArrays([-1_000_000], [1_000_000])).toBe(0)
58
+ })
59
+
60
+ it('handles interleaved values', () => {
61
+ expect(findMedianSortedArrays([1, 3, 5, 7, 9], [2, 4, 6, 8, 10])).toBe(5.5)
62
+ })
63
+ })
64
+
65
+ describe('305 read count', () => {
66
+ const n = 1_000_000
67
+ const cases: { name: string; a: number[]; b: number[]; median: number }[] = [
68
+ { name: 'interleaved evens and odds', a: range(0, n, 2), b: range(1, n, 2), median: n - 0.5 },
69
+ { name: 'a short array after a long one', a: range(0, n), b: [n, n + 1, n + 2], median: 500_001 },
70
+ { name: 'a short array before a long one', a: range(20_000_000, n), b: [-3, -2, -1], median: 20_499_998 },
71
+ { name: 'an empty first array', a: [], b: range(0, n), median: 499_999.5 },
72
+ { name: 'a single value', a: range(0, n), b: [-5], median: 499_999 },
73
+ ]
74
+
75
+ it('reads at most 5,000 elements of up to 2,000,000 (merging reads about a million)', () => {
76
+ for (const { name, a, b, median } of cases) {
77
+ const first = counted(a)
78
+ const second = counted(b)
79
+ expect(findMedianSortedArrays(first.nums, second.nums), name).toBe(median)
80
+ const reads = first.reads() + second.reads()
81
+ expect(reads, `read ${reads} elements for ${name}`).toBeLessThanOrEqual(5_000)
82
+ }
83
+ })
84
+ })
@@ -0,0 +1,42 @@
1
+ # 306 · Merge k Sorted Lists
2
+
3
+ **Level 3 · Hard** · Pattern: heap / priority queue · Target: 40 min · NeetCode 150 · LeetCode 23
4
+
5
+ ## Problem
6
+
7
+ `lists` holds the heads of `k` singly linked lists. Each list is sorted in ascending order (repeats allowed), and any of them may be empty (`null`). `lists` itself may be empty.
8
+
9
+ Combine all of their nodes into one list sorted in ascending order and return its head, or `null` if there are no nodes at all.
10
+
11
+ You may relink the existing nodes or build new ones; the tests only read the values of the list you return. Don't modify `lists` itself (it's `readonly`).
12
+
13
+ ## Examples
14
+
15
+ | `lists` | Output |
16
+ |---|---|
17
+ | `[1 → 5 → 9, 2 → 6, 0 → 7 → 8]` | `0 → 1 → 2 → 5 → 6 → 7 → 8 → 9` |
18
+ | `[null, 3 → 3]` | `3 → 3` |
19
+ | `[]` | `null` |
20
+
21
+ ## Constraints
22
+
23
+ - `0 <= k <= 10^4`, and at most `10^5` nodes in all (the performance test uses 10,000 lists of 10 nodes each)
24
+ - `-10^4 <= val <= 10^4` in the examples; the performance test uses values up to 100,000.
25
+
26
+ ## Run it
27
+
28
+ ```bash
29
+ pnpm watch 306
30
+ ```
31
+
32
+ <details><summary>Target complexity (open after your first attempt)</summary>
33
+
34
+ Time O(N log k) for `N` nodes in all · Space O(k). TypeScript has no built-in priority queue, so the heap version means writing a small binary heap; merging the lists in pairs, round after round, gets the same bound without one. Copying every value into an array and sorting it is O(N log N) and passes too, but misses the point. Scanning all `k` heads for the smallest at every step, or merging the lists into the result one at a time, is O(N·k), which the performance test rejects.
35
+
36
+ </details>
37
+
38
+ ## Follow-ups an interviewer might ask
39
+
40
+ - Why is merging the lists into one result list one after another O(N·k), while merging them in pairs is O(N log k)?
41
+ - What do you keep in the heap: nodes, values, or list indices? What ties do you need to break?
42
+ - The lists are huge files on disk and only a little of each fits in memory. What changes?
@@ -0,0 +1,72 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { listFrom, listToArray } from '../../lib/linked-list'
3
+ import { timeMs } from '../../lib/perf'
4
+ import { mergeKLists } from './solution'
5
+
6
+ /** Builds each list, merges them and returns the merged values. */
7
+ const merged = (values: number[][]): number[] => {
8
+ const total = values.reduce((sum, list) => sum + list.length, 0)
9
+ return listToArray(mergeKLists(values.map((v) => listFrom(v))), total + 1)
10
+ }
11
+
12
+ describe('306 merge k sorted lists', () => {
13
+ it('merges three lists', () => {
14
+ expect(merged([[1, 5, 9], [2, 6], [0, 7, 8]])).toEqual([0, 1, 2, 5, 6, 7, 8, 9])
15
+ })
16
+
17
+ it('skips empty lists', () => {
18
+ expect(merged([[], [3, 3]])).toEqual([3, 3])
19
+ expect(merged([[4], [], [1, 2], []])).toEqual([1, 2, 4])
20
+ })
21
+
22
+ it('returns null when there are no nodes', () => {
23
+ expect(mergeKLists([])).toBeNull()
24
+ expect(mergeKLists([null, null, null])).toBeNull()
25
+ })
26
+
27
+ it('returns a single list unchanged', () => {
28
+ expect(merged([[-3, 0, 0, 12]])).toEqual([-3, 0, 0, 12])
29
+ })
30
+
31
+ it('keeps repeats from different lists', () => {
32
+ expect(merged([[1, 1, 2], [1, 2, 2], [2]])).toEqual([1, 1, 1, 2, 2, 2, 2])
33
+ expect(merged([[5], [5], [5], [5]])).toEqual([5, 5, 5, 5])
34
+ })
35
+
36
+ it('handles negative values', () => {
37
+ expect(merged([[-10, -2, 4], [-7, -6], [-8, 9]])).toEqual([-10, -8, -7, -6, -2, 4, 9])
38
+ })
39
+
40
+ it('handles lists that do not overlap', () => {
41
+ expect(merged([[20, 21], [10, 11, 12], [1, 2]])).toEqual([1, 2, 10, 11, 12, 20, 21])
42
+ })
43
+
44
+ it('handles many single-node lists', () => {
45
+ const values = [9, 4, 7, 1, 8, 2, 6, 3, 5, 0]
46
+ expect(merged(values.map((v) => [v]))).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
47
+ })
48
+
49
+ it('does not modify the lists array', () => {
50
+ const lists = [listFrom([2, 4]), null, listFrom([1, 3])]
51
+ const before = [...lists]
52
+ mergeKLists(lists)
53
+ expect(lists).toEqual(before)
54
+ expect(lists.every((head, i) => head === before[i])).toBe(true)
55
+ })
56
+ })
57
+
58
+ describe('306 performance', () => {
59
+ it('merges 10,000 lists of 10 nodes in under 200 ms (scanning every head per node, or merging one list at a time, is O(N·k) and too slow here)', () => {
60
+ const k = 10_000
61
+ const length = 10
62
+ // List j holds j, j + k, j + 2k, …, so the merged values are 0 … N - 1, fully interleaved.
63
+ const lists = Array.from({ length: k }, (_, j) => listFrom(Array.from({ length }, (_, i) => j + i * k)))
64
+ let head: ReturnType<typeof mergeKLists> = null
65
+ const ms = timeMs(() => {
66
+ head = mergeKLists(lists)
67
+ })
68
+ const values = listToArray(head, k * length + 1)
69
+ expect(values).toEqual(Array.from({ length: k * length }, (_, i) => i))
70
+ expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(200)
71
+ })
72
+ })
@@ -0,0 +1,42 @@
1
+ # 307 · Reverse Nodes in k-Group
2
+
3
+ **Level 3 · Hard** · Pattern: linked list (in-place reversal) · Target: 40 min · NeetCode 150 · LeetCode 25
4
+
5
+ ## Problem
6
+
7
+ You get the head of a singly linked list and a positive integer `k`. Split the list into consecutive groups of `k` nodes, starting from the head, and reverse the order of the nodes inside each full group. If the last group has fewer than `k` nodes, leave it as it is.
8
+
9
+ Return the head of the resulting list.
10
+
11
+ Do it by relinking the existing nodes: don't change any `val` and don't create new nodes. The tests check that each position holds the exact original node that belongs there, so swapping values between nodes fails.
12
+
13
+ ## Examples
14
+
15
+ | List | `k` | Output |
16
+ |---|---|---|
17
+ | `10 → 20 → 30 → 40 → 50` | `2` | `20 → 10 → 40 → 30 → 50` |
18
+ | `1 → 2 → 3 → 4 → 5 → 6 → 7 → 8` | `3` | `3 → 2 → 1 → 6 → 5 → 4 → 7 → 8` |
19
+ | `4 → 5 → 6` | `4` | `4 → 5 → 6` |
20
+
21
+ ## Constraints
22
+
23
+ - `0 <= nodes <= 5000` (an empty list is `null`), `1 <= k`; `k` may be larger than the list
24
+ - `0 <= val <= 1000`
25
+
26
+ ## Run it
27
+
28
+ ```bash
29
+ pnpm watch 307
30
+ ```
31
+
32
+ <details><summary>Target complexity (open after your first attempt)</summary>
33
+
34
+ Time O(n) · Space O(1), relinking with a few pointers. A recursive version (reverse one group, recurse on the rest) is also O(n) time but uses O(n / k) stack. Copying the nodes into an array and relinking them by index is O(n) extra space. The tests don't time this one: every reasonable approach is linear, so judge the space yourself.
35
+
36
+ </details>
37
+
38
+ ## Follow-ups an interviewer might ask
39
+
40
+ - Can you do it with O(1) extra space, without recursion?
41
+ - Change it so the leftover group at the end is reversed too.
42
+ - Reverse the groups counting from the tail end instead, so the short group sits at the front.
@@ -0,0 +1,86 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { ListNode, listFrom, listToArray } from '../../lib/linked-list'
3
+ import { reverseKGroup } from './solution'
4
+
5
+ function nodesOf(head: ListNode | null, maxLength: number): ListNode[] {
6
+ const nodes: ListNode[] = []
7
+ for (let n = head; n; n = n.next) {
8
+ if (nodes.length >= maxLength) throw new Error('List is longer than expected — is there a cycle?')
9
+ nodes.push(n)
10
+ }
11
+ return nodes
12
+ }
13
+
14
+ /** Reverses a list built from `values` in groups of k and returns the resulting values. */
15
+ const reversed = (values: number[], k: number): number[] =>
16
+ listToArray(reverseKGroup(listFrom(values), k), values.length + 1)
17
+
18
+ /** The original positions, in the order the nodes should end up. */
19
+ function expectedPositions(n: number, k: number): number[] {
20
+ const out: number[] = []
21
+ for (let start = 0; start < n; start += k) {
22
+ const end = Math.min(start + k, n)
23
+ for (let i = 0; i < end - start; i++) out.push(end - start === k ? end - 1 - i : start + i)
24
+ }
25
+ return out
26
+ }
27
+
28
+ describe('307 reverse nodes in k-group', () => {
29
+ it('reverses pairs and leaves the last node alone', () => {
30
+ expect(reversed([10, 20, 30, 40, 50], 2)).toEqual([20, 10, 40, 30, 50])
31
+ })
32
+
33
+ it('leaves a short final group in its original order', () => {
34
+ expect(reversed([1, 2, 3, 4, 5, 6, 7, 8], 3)).toEqual([3, 2, 1, 6, 5, 4, 7, 8])
35
+ })
36
+
37
+ it('changes nothing when k is larger than the list', () => {
38
+ expect(reversed([4, 5, 6], 4)).toEqual([4, 5, 6])
39
+ })
40
+
41
+ it('changes nothing when k is 1', () => {
42
+ expect(reversed([1, 2, 3], 1)).toEqual([1, 2, 3])
43
+ })
44
+
45
+ it('reverses the whole list when k equals its length', () => {
46
+ expect(reversed([1, 2, 3, 4], 4)).toEqual([4, 3, 2, 1])
47
+ })
48
+
49
+ it('reverses every group when the length is a multiple of k', () => {
50
+ expect(reversed([1, 2, 3, 4, 5, 6], 3)).toEqual([3, 2, 1, 6, 5, 4])
51
+ expect(reversed([1, 2, 3, 4, 5, 6], 2)).toEqual([2, 1, 4, 3, 6, 5])
52
+ })
53
+
54
+ it('handles an empty list and a single node', () => {
55
+ expect(reverseKGroup(null, 2)).toBeNull()
56
+ expect(reversed([9], 1)).toEqual([9])
57
+ expect(reversed([9], 3)).toEqual([9])
58
+ })
59
+
60
+ it('handles repeated values', () => {
61
+ expect(reversed([0, 0, 1, 1, 0], 2)).toEqual([0, 0, 1, 1, 0])
62
+ expect(reversed([5, 5, 2, 7, 7, 2, 5], 3)).toEqual([2, 5, 5, 2, 7, 7, 5])
63
+ })
64
+
65
+ it('relinks the original nodes instead of swapping values', () => {
66
+ for (let n = 1; n <= 9; n++) {
67
+ for (let k = 1; k <= n + 1; k++) {
68
+ const head = listFrom(Array.from({ length: n }, (_, i) => i + 1))
69
+ const original = nodesOf(head, n)
70
+ const position = new Map(original.map((node, i) => [node, i]))
71
+ const result = nodesOf(reverseKGroup(head, k), n + 1)
72
+ expect(result.map((node) => position.get(node)), `n = ${n}, k = ${k}`).toEqual(expectedPositions(n, k))
73
+ original.forEach((node, i) => expect(node.val).toBe(i + 1))
74
+ }
75
+ }
76
+ })
77
+
78
+ it('handles 3,000 nodes', () => {
79
+ const n = 3_000
80
+ const values = Array.from({ length: n }, (_, i) => i % 1_000)
81
+ for (const k of [2, 7, 1_000]) {
82
+ const result = reversed(values, k)
83
+ expect(result, `k = ${k}`).toEqual(expectedPositions(n, k).map((i) => values[i]))
84
+ }
85
+ })
86
+ })
@@ -0,0 +1,44 @@
1
+ # 308 · Binary Tree Maximum Path Sum
2
+
3
+ **Level 3 · Hard** · Pattern: trees (DFS) · Target: 40 min · NeetCode 150 · LeetCode 124
4
+
5
+ ## Problem
6
+
7
+ A **path** in a binary tree is a sequence of nodes where each neighbouring pair is joined by an edge (parent to child or child to parent) and no node appears twice. A path has at least one node, and it doesn't have to pass through `root` or end at a leaf.
8
+
9
+ The sum of a path is the total of its nodes' values. Given the `root` of a non-empty tree, return the largest sum of any path.
10
+
11
+ Values can be negative, so the answer can be negative too.
12
+
13
+ The tests build trees from level-order arrays, where `null` marks a missing child (see `lib/binary-tree.ts`).
14
+
15
+ ## Examples
16
+
17
+ | Tree (level order) | Output |
18
+ |---|---|
19
+ | `[2, -1, 3]` | `5` (the path 2 → 3) |
20
+ | `[-10, 6, 5, null, null, 4, 8]` | `17` (the path 4 → 5 → 8, which avoids the root) |
21
+ | `[-3, -7, -1]` | `-1` (the single node -1) |
22
+
23
+ ## Constraints
24
+
25
+ - `1 <= nodes <= 3 · 10^5` (the performance test uses 256,000 nodes, about 2,000 levels deep)
26
+ - `-1000 <= val <= 1000`
27
+
28
+ ## Run it
29
+
30
+ ```bash
31
+ pnpm watch 308
32
+ ```
33
+
34
+ <details><summary>Target complexity (open after your first attempt)</summary>
35
+
36
+ Time O(n) · Space O(h) for the recursion, where `h` is the height. Recomputing the best downward path below every node from scratch is O(n·h), which on the deep tree in the performance test is too slow.
37
+
38
+ </details>
39
+
40
+ ## Follow-ups an interviewer might ask
41
+
42
+ - Return the path itself (its nodes in order), not just the sum.
43
+ - What changes if every path must start at the root? Or must run from one leaf to another?
44
+ - The tree is a long chain 10^5 levels deep and recursion overflows the stack. How do you do it without recursion?
@@ -0,0 +1,91 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { TreeNode, rightSpine, treeFrom } from '../../lib/binary-tree'
3
+ import { timeMs } from '../../lib/perf'
4
+ import { maxPathSum } from './solution'
5
+
6
+ /** Builds a non-empty tree from level order and returns its best path sum. */
7
+ function best(levelOrder: (number | null)[]): number {
8
+ const root = treeFrom(levelOrder)
9
+ if (!root) throw new Error('Test trees must have at least one node')
10
+ return maxPathSum(root)
11
+ }
12
+
13
+ /** A complete tree with `levels` levels, every node holding `val`. */
14
+ function complete(levels: number, val: number): TreeNode {
15
+ const node = new TreeNode(val)
16
+ if (levels > 1) {
17
+ node.left = complete(levels - 1, val)
18
+ node.right = complete(levels - 1, val)
19
+ }
20
+ return node
21
+ }
22
+
23
+ describe('308 binary tree maximum path sum', () => {
24
+ it('joins both children through their parent', () => {
25
+ expect(best([2, -1, 3])).toBe(5)
26
+ })
27
+
28
+ it('finds a path that avoids the root', () => {
29
+ expect(best([-10, 6, 5, null, null, 4, 8])).toBe(17)
30
+ })
31
+
32
+ it('returns the largest single node when every value is negative', () => {
33
+ expect(best([-3, -7, -1])).toBe(-1)
34
+ expect(best([-8, -2, -9, -4])).toBe(-2)
35
+ })
36
+
37
+ it('handles a single node', () => {
38
+ expect(best([-5])).toBe(-5)
39
+ expect(best([7])).toBe(7)
40
+ expect(best([0])).toBe(0)
41
+ })
42
+
43
+ it('bends at the best node, going up then down', () => {
44
+ expect(best([1, 2, 3, 4, 5])).toBe(11)
45
+ })
46
+
47
+ it('leaves out a negative branch', () => {
48
+ expect(best([5, -20, 4, null, null, -1, 3])).toBe(12)
49
+ })
50
+
51
+ it('passes through a negative node when both sides make up for it', () => {
52
+ expect(best([-2, 6, 7])).toBe(11)
53
+ expect(best([1, -5, null, 8, 9])).toBe(12)
54
+ })
55
+
56
+ it('takes only one branch below the bend on each side', () => {
57
+ // The path can't use both 10 and 20 below the left child and also go up to the root.
58
+ expect(best([1, 2, 3, 10, 20])).toBe(32)
59
+ })
60
+
61
+ it('handles zeros and a long path of small values', () => {
62
+ expect(best([0, 0, 0, 0, null, null, 0])).toBe(0)
63
+ expect(best([1, 1, 1, 1, null, null, 1, 1, null, null, 1])).toBe(7)
64
+ })
65
+
66
+ it('handles a 2,000-node chain', () => {
67
+ const root = rightSpine(2_000)
68
+ if (!root) throw new Error('unreachable')
69
+ expect(maxPathSum(root)).toBe((2_000 * 2_001) / 2)
70
+ })
71
+
72
+ it('handles a wide complete tree', () => {
73
+ // 10 levels: the longest path runs leaf to leaf through the root, 19 nodes.
74
+ expect(maxPathSum(complete(10, 1))).toBe(19)
75
+ expect(maxPathSum(complete(10, -1))).toBe(-1)
76
+ })
77
+ })
78
+
79
+ describe('308 performance', () => {
80
+ it('handles 256,000 nodes, 2,000 levels deep, in under 200 ms (recomputing every downward path, O(n·h), is too slow here)', () => {
81
+ // A right-going spine of 2,000 nodes worth 1, each with a 7-level subtree of -1s hanging to the left.
82
+ const spineLength = 2_000
83
+ let root: TreeNode | null = null
84
+ for (let i = 0; i < spineLength; i++) root = new TreeNode(1, complete(7, -1), root)
85
+ if (!root) throw new Error('unreachable')
86
+ const tree = root
87
+ // The best path is the whole spine.
88
+ const ms = timeMs(() => expect(maxPathSum(tree)).toBe(spineLength))
89
+ expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(200)
90
+ })
91
+ })
@@ -0,0 +1,50 @@
1
+ # 309 · Serialize and Deserialize Binary Tree
2
+
3
+ **Level 3 · Hard** · Pattern: trees (pre-order DFS or BFS with null markers) · Target: 40 min · NeetCode 150 · LeetCode 297
4
+
5
+ ## Problem
6
+
7
+ Write a class `Codec` that can turn a binary tree into a string and back again.
8
+
9
+ - `serialize(root)`: return a string that describes the tree rooted at `root` (which may be `null`).
10
+ - `deserialize(data)`: take a string produced by `serialize` and rebuild the tree from it, returning its root.
11
+
12
+ You choose the string format. The only requirement is that `deserialize(serialize(root))` gives a tree with exactly the same shape and the same value at every position as `root`. The tests never look inside your string, so any format works, as long as it doesn't depend on anything outside the string:
13
+
14
+ - `deserialize` may be called on a **different** `Codec` instance than the one that serialized the tree.
15
+ - The rebuilt tree must be made of **new** nodes, and changing the original tree after serializing must not change what `deserialize` returns.
16
+ - Values can be negative, zero or repeated, so a value alone doesn't identify a node.
17
+
18
+ The tests build and compare trees with `TreeNode`, `treeFrom` and `treeToArray` from `lib/binary-tree.ts`. Trees are written in level order, with `null` for a missing child.
19
+
20
+ ## Examples
21
+
22
+ | Tree (level order) | `deserialize(serialize(root))` |
23
+ |---|---|
24
+ | `[4, -7, 12, null, 3, 3]` | a new tree equal to `[4, -7, 12, null, 3, 3]` |
25
+ | `[0, null, 0, null, 0]` | a new tree equal to `[0, null, 0, null, 0]` |
26
+ | `[]` (`root` is `null`) | `null` |
27
+
28
+ ## Constraints
29
+
30
+ - `0 <= nodes <= 10^4` on LeetCode (the performance test uses a 50,000-node complete tree).
31
+ - `-1000 <= val <= 1000`.
32
+ - One test is a 3,000-node chain, so a recursive solution must handle that depth.
33
+
34
+ ## Run it
35
+
36
+ ```bash
37
+ pnpm watch 309
38
+ ```
39
+
40
+ <details><summary>Target complexity (open after your first attempt)</summary>
41
+
42
+ Time O(n) for each of `serialize` and `deserialize` · Space O(n) for the string, plus O(h) recursion (or an O(w) queue for a level-order version). The performance test rejects O(n²) parsing, for example cutting a fresh copy of the remaining string or token list (`slice`, `substring`) for every node.
43
+
44
+ </details>
45
+
46
+ ## Follow-ups an interviewer might ask
47
+
48
+ - Does your format work without `null` markers if the tree is a binary **search** tree (LeetCode 449)? How much shorter does it get?
49
+ - How would you serialize an N-ary tree (LeetCode 428)?
50
+ - Can you make the recursive version iterative, so a very deep tree can't overflow the call stack?