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,120 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { rightSpine, TreeNode, treeFrom, treeToArray } from '../../lib/binary-tree'
3
+ import { timeMs } from '../../lib/perf'
4
+ import { Codec } from './solution'
5
+
6
+ /** Serializes with one Codec and deserializes with a fresh one, so nothing can be kept in memory between the calls. */
7
+ function roundTrip(root: TreeNode | null): TreeNode | null {
8
+ const data = new Codec().serialize(root)
9
+ expect(typeof data).toBe('string')
10
+ return new Codec().deserialize(data)
11
+ }
12
+
13
+ /** Collects every node of a tree (iteratively, so deep trees are fine). */
14
+ function allNodes(root: TreeNode | null): TreeNode[] {
15
+ const out: TreeNode[] = []
16
+ const stack: (TreeNode | null)[] = [root]
17
+ while (stack.length > 0) {
18
+ const node = stack.pop()
19
+ if (node) {
20
+ out.push(node)
21
+ stack.push(node.right, node.left)
22
+ }
23
+ }
24
+ return out
25
+ }
26
+
27
+ /** A complete binary tree with n nodes and scrambled values in -1000..1000. */
28
+ function completeTree(n: number): (number | null)[] {
29
+ return Array.from({ length: n }, (_, i) => ((i * 7_919) % 2_001) - 1_000)
30
+ }
31
+
32
+ describe('309 serialize and deserialize binary tree', () => {
33
+ it('round-trips the README examples', () => {
34
+ for (const levelOrder of [
35
+ [4, -7, 12, null, 3, 3],
36
+ [0, null, 0, null, 0],
37
+ ]) {
38
+ expect(treeToArray(roundTrip(treeFrom(levelOrder)))).toEqual(levelOrder)
39
+ }
40
+ })
41
+
42
+ it('round-trips an empty tree', () => {
43
+ expect(roundTrip(null)).toBeNull()
44
+ })
45
+
46
+ it('round-trips a single node, including 0 and negative values', () => {
47
+ for (const v of [0, 7, -1000, 1000]) expect(treeToArray(roundTrip(new TreeNode(v)))).toEqual([v])
48
+ })
49
+
50
+ it('tells apart trees with the same values but different shapes', () => {
51
+ const leftChild = [5, 6]
52
+ const rightChild = [5, null, 6]
53
+ expect(treeToArray(roundTrip(treeFrom(leftChild)))).toEqual(leftChild)
54
+ expect(treeToArray(roundTrip(treeFrom(rightChild)))).toEqual(rightChild)
55
+ const codec = new Codec()
56
+ expect(codec.serialize(treeFrom(leftChild))).not.toBe(codec.serialize(treeFrom(rightChild)))
57
+ })
58
+
59
+ it('round-trips gaps, uneven depths and repeated values', () => {
60
+ for (const levelOrder of [
61
+ [1, 2, 3, 4, null, null, 5, 6, null, null, 7],
62
+ [-3, -3, -3, null, -3, -3],
63
+ [10, 20, null, 30, null, 40, null, 50],
64
+ [8, null, -2, -9, 14, null, null, 0],
65
+ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
66
+ ]) {
67
+ expect(treeToArray(roundTrip(treeFrom(levelOrder)))).toEqual(levelOrder)
68
+ }
69
+ })
70
+
71
+ it('handles multi-digit and negative values that share digits', () => {
72
+ const levelOrder = [-1, 11, -11, 111, null, -111, 1]
73
+ expect(treeToArray(roundTrip(treeFrom(levelOrder)))).toEqual(levelOrder)
74
+ })
75
+
76
+ it('builds new nodes, unaffected by later changes to the original', () => {
77
+ const original = treeFrom([2, 1, 3])!
78
+ const data = new Codec().serialize(original)
79
+ const before = new Set(allNodes(original))
80
+ original.val = 99
81
+ original.left = null
82
+ const rebuilt = new Codec().deserialize(data)
83
+ expect(treeToArray(rebuilt)).toEqual([2, 1, 3])
84
+ expect(allNodes(rebuilt).some((node) => before.has(node))).toBe(false)
85
+ })
86
+
87
+ it('can deserialize the same string more than once', () => {
88
+ const codec = new Codec()
89
+ const data = codec.serialize(treeFrom([6, 2, 8, null, 4]))
90
+ const first = codec.deserialize(data)
91
+ const second = codec.deserialize(data)
92
+ expect(first).not.toBe(second)
93
+ expect(treeToArray(first)).toEqual([6, 2, 8, null, 4])
94
+ expect(treeToArray(second)).toEqual([6, 2, 8, null, 4])
95
+ })
96
+
97
+ it('round-trips a 3,000-node chain', () => {
98
+ const rebuilt = roundTrip(rightSpine(3_000))
99
+ const values = allNodes(rebuilt).map((node) => node.val)
100
+ expect(values).toEqual(Array.from({ length: 3_000 }, (_, i) => i + 1))
101
+ expect(allNodes(rebuilt).every((node) => node.left === null)).toBe(true)
102
+ })
103
+ })
104
+
105
+ describe('309 performance', () => {
106
+ it('round-trips a 50,000-node tree in under 300 ms (re-slicing the string or token list per node, O(n²), is too slow here)', () => {
107
+ const levelOrder = completeTree(50_000)
108
+ const root = treeFrom(levelOrder)
109
+ let rebuilt: TreeNode | null = null
110
+ const ms = timeMs(() => {
111
+ const data = new Codec().serialize(root)
112
+ rebuilt = new Codec().deserialize(data)
113
+ })
114
+ const actual = treeToArray(rebuilt)
115
+ // Compare without a giant diff: the length, then the first position that differs.
116
+ expect(actual.length).toBe(levelOrder.length)
117
+ expect(actual.findIndex((v, i) => v !== levelOrder[i])).toBe(-1)
118
+ expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(300)
119
+ })
120
+ })
@@ -0,0 +1,47 @@
1
+ # 310 · Find Median from Data Stream
2
+
3
+ **Level 3 · Hard** · Pattern: two heaps · Target: 40 min · NeetCode 150 · LeetCode 295
4
+
5
+ ## Problem
6
+
7
+ Numbers arrive one at a time, and at any moment you may be asked for the median of everything seen so far. Export a class `MedianFinder` with:
8
+
9
+ - `constructor()`: starts with no numbers.
10
+ - `addNum(num)`: records one more number. Repeats are allowed and each one counts.
11
+ - `findMedian()`: returns the median of all numbers recorded so far. With an odd count, that's the middle value once they're sorted. With an even count, it's the average of the two middle values, which can be a fraction such as `2.5`.
12
+
13
+ `findMedian` is only called after at least one `addNum`. Calls to the two methods can be mixed in any order, and the tests ask for the median after every single `addNum`.
14
+
15
+ ## Examples
16
+
17
+ | Calls | Returns |
18
+ |---|---|
19
+ | `addNum(8)`, `findMedian()` | `8` |
20
+ | then `addNum(-4)`, `findMedian()` | `2` (average of -4 and 8) |
21
+ | then `addNum(5)`, `findMedian()` | `5` (sorted: -4, 5, 8) |
22
+ | then `addNum(6)`, `findMedian()` | `5.5` (sorted: -4, 5, 6, 8) |
23
+
24
+ ## Constraints
25
+
26
+ - `-10^5 <= num <= 10^5`.
27
+ - Up to `5 · 10^4` calls on LeetCode. The performance test adds 250,000 numbers and asks for the median after each one.
28
+
29
+ ## Run it
30
+
31
+ ```bash
32
+ pnpm watch 310
33
+ ```
34
+
35
+ <details><summary>Target complexity (open after your first attempt)</summary>
36
+
37
+ `addNum` O(log n) · `findMedian` O(1) · Space O(n). Sorting on every `findMedian` (O(n log n) per call) is far too slow for the performance test. Keeping one sorted array and inserting into it with `splice` costs O(n) per `addNum`, which is also rejected at this size.
38
+
39
+ TypeScript has no built-in priority queue, so if you use one, write a small binary heap yourself.
40
+
41
+ </details>
42
+
43
+ ## Follow-ups an interviewer might ask
44
+
45
+ - If every number is between 0 and 100, can you do better? What if 99% of them are?
46
+ - How would you support removing a number, for example a median over a sliding window (LeetCode 480)?
47
+ - How would you find an approximate median of a stream too large to keep in memory?
@@ -0,0 +1,102 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { timeMs } from '../../lib/perf'
3
+ import { MedianFinder } from './solution'
4
+
5
+ /** Adds each number and records the median after every add (`+ 0` turns a -0 into 0, so either is accepted). */
6
+ function mediansAfterEachAdd(nums: readonly number[]): number[] {
7
+ const finder = new MedianFinder()
8
+ return nums.map((num) => {
9
+ finder.addNum(num)
10
+ return finder.findMedian() + 0
11
+ })
12
+ }
13
+
14
+ /** The median of a list, by sorting a copy (only used to check answers). */
15
+ function sortedMedian(nums: readonly number[]): number {
16
+ const sorted = [...nums].sort((a, b) => a - b)
17
+ const mid = Math.floor(sorted.length / 2)
18
+ return sorted.length % 2 === 1 ? sorted[mid]! : (sorted[mid - 1]! + sorted[mid]!) / 2
19
+ }
20
+
21
+ /** Deterministic pseudo-random integers in [-100,000, 100,000]. */
22
+ function scrambled(n: number, seed: number): number[] {
23
+ let state = seed
24
+ return Array.from({ length: n }, () => {
25
+ state = (state * 48_271) % 2_147_483_647
26
+ return (state % 200_001) - 100_000
27
+ })
28
+ }
29
+
30
+ describe('310 find median from data stream', () => {
31
+ it('runs the README example', () => {
32
+ expect(mediansAfterEachAdd([8, -4, 5, 6])).toEqual([8, 2, 5, 5.5])
33
+ })
34
+
35
+ it('returns the only number after one add', () => {
36
+ expect(mediansAfterEachAdd([-17])).toEqual([-17])
37
+ expect(mediansAfterEachAdd([0])).toEqual([0])
38
+ })
39
+
40
+ it('averages the two middle values, which can be a fraction', () => {
41
+ expect(mediansAfterEachAdd([1, 2])).toEqual([1, 1.5])
42
+ expect(mediansAfterEachAdd([-3, -6])).toEqual([-3, -4.5])
43
+ })
44
+
45
+ it('counts repeated numbers separately', () => {
46
+ expect(mediansAfterEachAdd([4, 4, 9, 4, 9, 9, 9])).toEqual([4, 4, 4, 4, 4, 6.5, 9])
47
+ })
48
+
49
+ it('handles numbers arriving in increasing and in decreasing order', () => {
50
+ expect(mediansAfterEachAdd([10, 20, 30, 40, 50])).toEqual([10, 15, 20, 25, 30])
51
+ expect(mediansAfterEachAdd([50, 40, 30, 20, 10])).toEqual([50, 45, 40, 35, 30])
52
+ })
53
+
54
+ it('handles negatives, zero and the extreme values', () => {
55
+ expect(mediansAfterEachAdd([100_000, -100_000, 0, -100_000, 100_000, 7])).toEqual([
56
+ 100_000, 0, 0, -50_000, 0, 3.5,
57
+ ])
58
+ })
59
+
60
+ it('lets findMedian be called several times in a row without changing anything', () => {
61
+ const finder = new MedianFinder()
62
+ finder.addNum(3)
63
+ finder.addNum(11)
64
+ expect(finder.findMedian()).toBe(7)
65
+ expect(finder.findMedian()).toBe(7)
66
+ finder.addNum(1)
67
+ expect(finder.findMedian()).toBe(3)
68
+ expect(finder.findMedian()).toBe(3)
69
+ })
70
+
71
+ it('matches a sorted copy after every add on a mixed sequence', () => {
72
+ const nums = scrambled(300, 7)
73
+ const expected = nums.map((_, i) => sortedMedian(nums.slice(0, i + 1)))
74
+ expect(mediansAfterEachAdd(nums)).toEqual(expected)
75
+ })
76
+
77
+ it('keeps separate finders independent', () => {
78
+ const a = new MedianFinder()
79
+ const b = new MedianFinder()
80
+ a.addNum(1)
81
+ b.addNum(100)
82
+ a.addNum(3)
83
+ expect(a.findMedian()).toBe(2)
84
+ expect(b.findMedian()).toBe(100)
85
+ })
86
+ })
87
+
88
+ describe('310 performance', () => {
89
+ it('adds 250,000 numbers with a median after each in under 500 ms (sorting, or splicing into a sorted array, per add is too slow here)', () => {
90
+ const n = 250_000
91
+ const nums = scrambled(n, 42)
92
+ let medians: number[] = []
93
+ const ms = timeMs(() => {
94
+ medians = mediansAfterEachAdd(nums)
95
+ })
96
+ const checkpoints = [0, 1, 2, 999, 10_000, 33_333, 77_776, 180_001, n - 2, n - 1]
97
+ for (const i of checkpoints) {
98
+ expect(medians[i], `median after ${i + 1} numbers`).toBe(sortedMedian(nums.slice(0, i + 1)))
99
+ }
100
+ expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(500)
101
+ })
102
+ })
@@ -0,0 +1,51 @@
1
+ # 311 · Word Search II
2
+
3
+ **Level 3 · Hard** · Pattern: trie + backtracking · Target: 40 min · NeetCode 150 · LeetCode 212
4
+
5
+ ## Problem
6
+
7
+ `board` is a grid of lowercase letters, given as an array of rows with one letter per cell. `words` is a list of distinct lowercase words. Return every word from `words` that can be traced on the board.
8
+
9
+ To trace a word, start on any cell holding its first letter and step to a cell directly above, below, left or right for each next letter. One word can't use the same cell twice, but different words may share cells.
10
+
11
+ Each word that can be traced appears once in the answer, even if there are several ways to trace it. The order doesn't matter; the tests sort your answer. Don't modify `board`.
12
+
13
+ ## Examples
14
+
15
+ `board` for the first two examples:
16
+
17
+ ```
18
+ m o p
19
+ a t e
20
+ r s n
21
+ ```
22
+
23
+ | `board` | `words` | Output |
24
+ |---|---|---|
25
+ | grid above | `["mat", "top", "pets", "stem", "mast", "rat"]` | `["mat", "pets", "rat", "top"]` (any order) |
26
+ | grid above | `["ten", "note", "tot"]` | `["ten"]` (`tot` would reuse the `t`) |
27
+ | `[["q"]]` | `["q", "qq"]` | `["q"]` |
28
+
29
+ ## Constraints
30
+
31
+ - `1 <= rows, cols <= 12`, every cell is a lowercase letter.
32
+ - `1 <= words.length <= 3 · 10^4`, `1 <= words[i].length <= 10`, all words distinct.
33
+ - The performance test uses a 12 × 12 board where most cells hold the same letter, with 4,000 words, many of them sharing long prefixes.
34
+
35
+ ## Run it
36
+
37
+ ```bash
38
+ pnpm watch 311
39
+ ```
40
+
41
+ <details><summary>Target complexity (open after your first attempt)</summary>
42
+
43
+ Time O(R · C · 3^L) in the worst case, where `L` is the longest word, but every word is searched **together**, so the cost no longer multiplies by the number of words. Space O(total letters in `words`). Running a separate grid search for each word (O(W · R · C · 3^L)) is what the performance test rejects.
44
+
45
+ </details>
46
+
47
+ ## Follow-ups an interviewer might ask
48
+
49
+ - How do you stop the search from revisiting paths for words you've already found? Can you prune those branches away as you go?
50
+ - How would you solve the single-word version (LeetCode 79), and why doesn't repeating it scale?
51
+ - What changes if a cell may be reused within one word?
@@ -0,0 +1,144 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { timeMs } from '../../lib/perf'
3
+ import { findWords } from './solution'
4
+
5
+ const grid = (rows: readonly string[]): string[][] => rows.map((row) => [...row])
6
+ const sorted = (words: readonly string[]): string[] => [...words].sort()
7
+
8
+ const EXAMPLE = grid(['mop', 'ate', 'rsn'])
9
+
10
+ /** Deterministic pseudo-random generator (MINSTD). */
11
+ function makeRandom(seed: number): (limit: number) => number {
12
+ let state = seed
13
+ return (limit) => {
14
+ state = (state * 48_271) % 2_147_483_647
15
+ return state % limit
16
+ }
17
+ }
18
+
19
+ const OFF_BOARD = 'efghijklmnopqrstuvwxy'
20
+
21
+ /**
22
+ * A board that is mostly 'a' (the rest 'b', 'c' or 'd'), plus words that can be traced on it (made by
23
+ * self-avoiding random walks) and words that can't: a run of 'a's followed by two letters that are not
24
+ * on the board. Those share long prefixes, which is what makes one search per word slow.
25
+ */
26
+ function buildCase(size: number, wordCount: number, seed: number) {
27
+ const random = makeRandom(seed)
28
+ const board = Array.from({ length: size }, () =>
29
+ Array.from({ length: size }, () => (random(100) < 85 ? 'a' : 'bcd'[random(3)]!)),
30
+ )
31
+ const traceable = new Set<string>()
32
+ for (let attempt = 0; traceable.size < wordCount / 2 && attempt < wordCount * 50; attempt++) {
33
+ const length = 5 + random(6)
34
+ let r = random(size)
35
+ let c = random(size)
36
+ const used = new Set<number>([r * size + c])
37
+ let word = board[r]![c]!
38
+ while (word.length < length) {
39
+ const steps = [
40
+ [r - 1, c],
41
+ [r + 1, c],
42
+ [r, c - 1],
43
+ [r, c + 1],
44
+ ].filter(([nr, nc]) => nr! >= 0 && nr! < size && nc! >= 0 && nc! < size && !used.has(nr! * size + nc!))
45
+ if (steps.length === 0) break
46
+ ;[r, c] = steps[random(steps.length)]! as [number, number]
47
+ used.add(r * size + c)
48
+ word += board[r]![c]!
49
+ }
50
+ traceable.add(word)
51
+ }
52
+ const untraceable = new Set<string>()
53
+ while (untraceable.size < wordCount / 2) {
54
+ const prefix = 'a'.repeat(4 + random(6))
55
+ untraceable.add(prefix + OFF_BOARD[random(OFF_BOARD.length)]! + OFF_BOARD[random(OFF_BOARD.length)]!)
56
+ }
57
+ const words = [...traceable, ...untraceable].sort((a, b) => a.length - b.length || (a < b ? 1 : -1))
58
+ return { board, words, expected: sorted([...traceable]) }
59
+ }
60
+
61
+ describe('311 word search ii', () => {
62
+ it('runs the first README example', () => {
63
+ expect(sorted(findWords(EXAMPLE, ['mat', 'top', 'pets', 'stem', 'mast', 'rat']))).toEqual([
64
+ 'mat',
65
+ 'pets',
66
+ 'rat',
67
+ 'top',
68
+ ])
69
+ })
70
+
71
+ it('does not reuse a cell within one word', () => {
72
+ expect(findWords(EXAMPLE, ['ten', 'note', 'tot'])).toEqual(['ten'])
73
+ })
74
+
75
+ it('handles a one-cell board', () => {
76
+ expect(findWords([['q']], ['q', 'qq'])).toEqual(['q'])
77
+ })
78
+
79
+ it('returns an empty list when nothing can be traced', () => {
80
+ expect(findWords(EXAMPLE, ['xyz', 'mn', 'ms'])).toEqual([])
81
+ })
82
+
83
+ it('does not move diagonally', () => {
84
+ expect(sorted(findWords(grid(['ab', 'cd']), ['ad', 'bc', 'ab', 'ca']))).toEqual(['ab', 'ca'])
85
+ })
86
+
87
+ it('lists a word once even when it can be traced in several ways', () => {
88
+ expect(findWords(grid(['aaa', 'aaa']), ['aa', 'aaa'])).toHaveLength(2)
89
+ expect(sorted(findWords(grid(['aaa', 'aaa']), ['aa', 'aaa']))).toEqual(['aa', 'aaa'])
90
+ })
91
+
92
+ it('needs as many distinct cells as the word has letters', () => {
93
+ expect(sorted(findWords(grid(['aa', 'aa']), ['a', 'aaaa', 'aaaaa']))).toEqual(['a', 'aaaa'])
94
+ })
95
+
96
+ it('finds words that are prefixes of each other', () => {
97
+ expect(sorted(findWords(grid(['ston', 'xxxe']), ['st', 'sto', 'ston', 'stone', 'stones']))).toEqual([
98
+ 'st',
99
+ 'sto',
100
+ 'ston',
101
+ 'stone',
102
+ ])
103
+ })
104
+
105
+ it('finds a word that only works after backing out of a dead end', () => {
106
+ // From the middle 'a', going up to 'b' first leads nowhere; the word needs the path down and around.
107
+ const board = grid(['xbx', 'cab', 'dcb'])
108
+ expect(sorted(findWords(board, ['abcd', 'acdcb', 'abbc']))).toEqual(['abbc', 'acdcb'])
109
+ })
110
+
111
+ it('finds words along the edges and through the corners of a non-square board', () => {
112
+ const board = grid(['abcde', 'fghij'])
113
+ expect(sorted(findWords(board, ['abcdejihgf', 'edcba', 'fa', 'jed', 'aj']))).toEqual([
114
+ 'abcdejihgf',
115
+ 'edcba',
116
+ 'fa',
117
+ 'jed',
118
+ ])
119
+ })
120
+
121
+ it('matches the expected words on a small random board', () => {
122
+ const { board, words, expected } = buildCase(5, 60, 11)
123
+ expect(sorted(findWords(board, words))).toEqual(expected)
124
+ })
125
+
126
+ it('does not modify the board', () => {
127
+ const board = grid(['mop', 'ate', 'rsn'])
128
+ findWords(board, ['mat', 'top', 'pets'])
129
+ expect(board).toEqual(grid(['mop', 'ate', 'rsn']))
130
+ })
131
+ })
132
+
133
+ describe('311 performance', () => {
134
+ it('searches a 12 × 12 board for 4,000 words in under 400 ms (one grid search per word is too slow here)', () => {
135
+ const { board, words, expected } = buildCase(12, 4_000, 42)
136
+ let found: string[] = []
137
+ const ms = timeMs(() => {
138
+ found = findWords(board, words)
139
+ })
140
+ expect(found.length, 'number of words found (each word once)').toBe(expected.length)
141
+ expect(sorted(found)).toEqual(expected)
142
+ expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(400)
143
+ })
144
+ })
@@ -0,0 +1,41 @@
1
+ # 312 · N-Queens
2
+
3
+ **Level 3 · Hard** · Pattern: backtracking · Target: 40 min · NeetCode 150 · LeetCode 51
4
+
5
+ ## Problem
6
+
7
+ On an `n` × `n` chessboard, place `n` queens so that no two of them attack each other: no two share a row, a column or a diagonal (in either direction). Return **every** such arrangement.
8
+
9
+ Describe each arrangement as an array of `n` strings, one per row from top to bottom. In each string, `'Q'` marks the queen and `'.'` marks an empty square. For example, `".Q.."` is a row of a 4 × 4 board with the queen in the second column.
10
+
11
+ Return the arrangements in any order; the tests sort them before comparing. If there are none, return `[]`.
12
+
13
+ ## Examples
14
+
15
+ | `n` | Output |
16
+ |---|---|
17
+ | `4` | `[[".Q..", "...Q", "Q...", "..Q."], ["..Q.", "Q...", "...Q", ".Q.."]]` (any order) |
18
+ | `1` | `[["Q"]]` |
19
+ | `3` | `[]` |
20
+
21
+ ## Constraints
22
+
23
+ - `1 <= n <= 9` on LeetCode. The tests go up to `n = 10` (724 arrangements), and the performance test uses `n = 11` (2,680 arrangements).
24
+
25
+ ## Run it
26
+
27
+ ```bash
28
+ pnpm watch 312
29
+ ```
30
+
31
+ <details><summary>Target complexity (open after your first attempt)</summary>
32
+
33
+ Time O(n!) in the worst case, though pruning keeps the real count far lower · Space O(n) for the search, plus the output. The performance test rejects generating every placement (or every column ordering) first and checking it afterwards; the tree must be cut off as soon as a queen is attacked. Checking a square in O(1) with sets for columns and both diagonals is the usual way, but scanning earlier rows also passes.
34
+
35
+ </details>
36
+
37
+ ## Follow-ups an interviewer might ask
38
+
39
+ - Return only the number of arrangements (LeetCode 52). What can you stop storing?
40
+ - How can you use symmetry to do about half the work?
41
+ - How would bit masks replace the sets, and why is that faster?
@@ -0,0 +1,91 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { timeMs } from '../../lib/perf'
3
+ import { solveNQueens } from './solution'
4
+
5
+ /** Known number of arrangements for each board size. */
6
+ const COUNTS: Record<number, number> = { 1: 1, 2: 0, 3: 0, 4: 2, 5: 10, 6: 4, 7: 40, 8: 92, 9: 352, 10: 724, 11: 2_680 }
7
+
8
+ const sortBoards = (boards: readonly (readonly string[])[]): string[] => boards.map((b) => b.join('/')).sort()
9
+
10
+ /** Returns a description of the first problem with a board, or null if it is a valid arrangement. */
11
+ function boardProblem(board: readonly string[], n: number): string | null {
12
+ if (board.length !== n) return `has ${board.length} rows`
13
+ const cols: number[] = []
14
+ for (const row of board) {
15
+ if (row.length !== n || !/^\.*Q\.*$/.test(row)) return `row "${row}" is not ${n} squares with one Q`
16
+ cols.push(row.indexOf('Q'))
17
+ }
18
+ for (let r1 = 0; r1 < n; r1++) {
19
+ for (let r2 = r1 + 1; r2 < n; r2++) {
20
+ const c1 = cols[r1]!
21
+ const c2 = cols[r2]!
22
+ if (c1 === c2 || Math.abs(c1 - c2) === r2 - r1) return `queens in rows ${r1} and ${r2} attack each other`
23
+ }
24
+ }
25
+ return null
26
+ }
27
+
28
+ /** Checks the count, that every board is valid, and that no board repeats. */
29
+ function expectAllArrangements(boards: readonly (readonly string[])[], n: number): void {
30
+ expect(boards).toHaveLength(COUNTS[n]!)
31
+ const problems = boards.map((board) => boardProblem(board, n)).filter((p) => p !== null)
32
+ expect(problems).toEqual([])
33
+ expect(new Set(sortBoards(boards)).size).toBe(boards.length)
34
+ }
35
+
36
+ describe('312 n-queens', () => {
37
+ it('finds both arrangements for n = 4', () => {
38
+ expect(sortBoards(solveNQueens(4))).toEqual(
39
+ sortBoards([
40
+ ['.Q..', '...Q', 'Q...', '..Q.'],
41
+ ['..Q.', 'Q...', '...Q', '.Q..'],
42
+ ]),
43
+ )
44
+ })
45
+
46
+ it('handles a 1 × 1 board', () => {
47
+ expect(solveNQueens(1)).toEqual([['Q']])
48
+ })
49
+
50
+ it('returns an empty list when there is no arrangement', () => {
51
+ expect(solveNQueens(2)).toEqual([])
52
+ expect(solveNQueens(3)).toEqual([])
53
+ })
54
+
55
+ it('finds all 10 arrangements for n = 5', () => {
56
+ const boards = solveNQueens(5)
57
+ expectAllArrangements(boards, 5)
58
+ expect(sortBoards(boards)).toContain('Q..../..Q../....Q/.Q.../...Q.')
59
+ })
60
+
61
+ it('finds exactly 4 arrangements for n = 6 (fewer than for n = 5)', () => {
62
+ expect(sortBoards(solveNQueens(6))).toEqual(
63
+ sortBoards([
64
+ ['.Q....', '...Q..', '.....Q', 'Q.....', '..Q...', '....Q.'],
65
+ ['..Q...', '.....Q', '.Q....', '....Q.', 'Q.....', '...Q..'],
66
+ ['...Q..', 'Q.....', '....Q.', '.Q....', '.....Q', '..Q...'],
67
+ ['....Q.', '..Q...', 'Q.....', '.....Q', '...Q..', '.Q....'],
68
+ ]),
69
+ )
70
+ })
71
+
72
+ it('finds every arrangement for n = 7 to 10', () => {
73
+ for (const n of [7, 8, 9, 10]) expectAllArrangements(solveNQueens(n), n)
74
+ })
75
+
76
+ it('returns separate row arrays for each board', () => {
77
+ const boards = solveNQueens(4)
78
+ expect(boards[0]).not.toBe(boards[1])
79
+ })
80
+ })
81
+
82
+ describe('312 performance', () => {
83
+ it('finds all 2,680 arrangements for n = 11 in under 300 ms (trying every column ordering and checking afterwards is too slow here)', () => {
84
+ let boards: string[][] = []
85
+ const ms = timeMs(() => {
86
+ boards = solveNQueens(11)
87
+ })
88
+ expectAllArrangements(boards, 11)
89
+ expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(300)
90
+ })
91
+ })
@@ -0,0 +1,42 @@
1
+ # 313 · Word Ladder
2
+
3
+ **Level 3 · Hard** · Pattern: graphs (BFS over implicit neighbours) · Target: 40 min · NeetCode 150 · LeetCode 127
4
+
5
+ ## Problem
6
+
7
+ You want to turn `beginWord` into `endWord` one letter at a time. Each step changes exactly one letter (in place: no adding, removing or reordering), and the word you get after every step must appear in `wordList`. `beginWord` itself doesn't need to be in `wordList`.
8
+
9
+ Return the number of words in the **shortest** such chain, counting both `beginWord` and `endWord`. If `endWord` can't be reached at all (including when it isn't in `wordList`), return `0`.
10
+
11
+ All words are lowercase and the same length, `beginWord` differs from `endWord`, and `wordList` has no repeats. Don't modify `wordList`.
12
+
13
+ ## Examples
14
+
15
+ | `beginWord` | `endWord` | `wordList` | Output |
16
+ |---|---|---|---|
17
+ | `"cold"` | `"warm"` | `["cord", "card", "ward", "warm", "worm", "word"]` | `5` (`cold → cord → word → worm → warm`) |
18
+ | `"lamp"` | `"lime"` | `["limp", "lame", "lamb"]` | `0` (`lime` isn't in the list) |
19
+ | `"ab"` | `"cb"` | `["cb"]` | `2` |
20
+
21
+ ## Constraints
22
+
23
+ - `1 <= beginWord.length <= 10`, and every word has that length.
24
+ - `1 <= wordList.length <= 5000` on LeetCode. The performance test uses 15,630 six-letter words, almost all of which the search has to visit.
25
+
26
+ ## Run it
27
+
28
+ ```bash
29
+ pnpm watch 313
30
+ ```
31
+
32
+ <details><summary>Target complexity (open after your first attempt)</summary>
33
+
34
+ Time O(n · L² · 26) with letter-by-letter substitution and a `Set` (each of the `n · L · 26` candidates costs O(L) to build and hash), or O(n · L²) with wildcard patterns · Space O(n · L). Finding each word's neighbours by comparing it with every other word in the list costs O(n² · L) and is too slow for the performance test.
35
+
36
+ </details>
37
+
38
+ ## Follow-ups an interviewer might ask
39
+
40
+ - Search from both ends at once. Why does that explore far fewer words?
41
+ - Return every shortest chain, not just its length (LeetCode 126).
42
+ - What if each letter change had a different cost?