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,67 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { timeMs } from '../../lib/perf'
3
+ import { lastStoneWeight } from './solution'
4
+
5
+ /** Deterministic shuffle of 0..n-1 (Fisher-Yates with a seeded MINSTD generator), so test data is the same every run. */
6
+ function shuffledRange(n: number, seed: number): number[] {
7
+ const out = Array.from({ length: n }, (_, i) => i)
8
+ let state = seed
9
+ for (let i = n - 1; i > 0; i--) {
10
+ state = (state * 48_271) % 2_147_483_647
11
+ const j = state % (i + 1)
12
+ ;[out[i], out[j]] = [out[j]!, out[i]!]
13
+ }
14
+ return out
15
+ }
16
+
17
+ describe('019 last stone weight', () => {
18
+ it('smashes everything away', () => {
19
+ expect(lastStoneWeight([3, 9, 4, 2])).toBe(0)
20
+ })
21
+
22
+ it('leaves the difference of two rocks', () => {
23
+ expect(lastStoneWeight([10, 4])).toBe(6)
24
+ })
25
+
26
+ it('returns a single rock as it is', () => {
27
+ expect(lastStoneWeight([7])).toBe(7)
28
+ })
29
+
30
+ it('destroys two equal rocks', () => {
31
+ expect(lastStoneWeight([5, 5])).toBe(0)
32
+ expect(lastStoneWeight([1, 1, 1])).toBe(1)
33
+ })
34
+
35
+ it('puts the chipped rock back on the pile for later rounds', () => {
36
+ // 8 vs 6 → 2; 3 vs 2 → 1; 2 vs 1 → 1; 1 vs 1 → none.
37
+ expect(lastStoneWeight([2, 8, 1, 6, 3])).toBe(0)
38
+ // 12 vs 11 → 1; 10 vs 1 → 9; 9 vs 1 → 8.
39
+ expect(lastStoneWeight([1, 10, 12, 11])).toBe(8)
40
+ })
41
+
42
+ it('compares numbers, not strings', () => {
43
+ // 100 vs 25 → 75; 75 vs 9 → 66.
44
+ expect(lastStoneWeight([9, 100, 25])).toBe(66)
45
+ })
46
+
47
+ it('does not modify the input', () => {
48
+ const stones = [4, 2, 7]
49
+ lastStoneWeight(stones)
50
+ expect(stones).toEqual([4, 2, 7])
51
+ })
52
+ })
53
+
54
+ describe('019 performance', () => {
55
+ // Weights 1..n, shuffled: the big rocks pair off into 1s, then the 1s cancel out.
56
+ const pile = (n: number): number[] => shuffledRange(n, 11).map((v) => v + 1)
57
+
58
+ it('smashes 34,000 rocks twice in under 100 ms (scanning or shifting the whole pile every round, O(n²), is too slow here)', () => {
59
+ const even = pile(34_000)
60
+ const odd = pile(34_002)
61
+ const ms = timeMs(() => {
62
+ expect(lastStoneWeight(even)).toBe(0)
63
+ expect(lastStoneWeight(odd)).toBe(1)
64
+ })
65
+ expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(100)
66
+ })
67
+ })
@@ -0,0 +1,40 @@
1
+ # 020 · Min Cost Climbing Stairs
2
+
3
+ **Level 1 · Easy** · Pattern: 1-D dynamic programming · Target: 15 min · NeetCode 150 · LeetCode 746
4
+
5
+ ## Problem
6
+
7
+ A staircase has one step per entry of `cost`, and stepping on step `i` costs `cost[i]`. You may start on step `0` or step `1` (you pay for the step you start on). From any step you move up 1 or 2 steps, paying for each step you land on. The top is just past the last step, and reaching it is free.
8
+
9
+ Return the smallest total you can pay to reach the top.
10
+
11
+ ## Examples
12
+
13
+ | `cost` | Output | Cheapest climb |
14
+ |---|---|---|
15
+ | `[4, 7, 2]` | `6` | step 0 (4), step 2 (2), top |
16
+ | `[5, 1, 1, 9, 1]` | `3` | step 1, step 2, step 4, top |
17
+ | `[3, 8]` | `3` | step 0, top |
18
+
19
+ ## Constraints
20
+
21
+ - `2 <= cost.length <= 1000`, `0 <= cost[i] <= 999`
22
+ - The performance test uses 40 steps, which is already too many for a solution that tries every path.
23
+
24
+ ## Run it
25
+
26
+ ```bash
27
+ pnpm watch 020
28
+ ```
29
+
30
+ <details><summary>Target complexity (open after your first attempt)</summary>
31
+
32
+ Time O(n) · Space O(1), keeping only the best totals for the last two steps. Plain recursion that tries both moves from every step is O(2^n) and fails the performance test; memoisation gets you O(n) time and O(n) space.
33
+
34
+ </details>
35
+
36
+ ## Follow-ups an interviewer might ask
37
+
38
+ - Return the steps of the cheapest climb, not just its cost.
39
+ - What if you may also jump 3 steps? Or any distance up to `k`?
40
+ - How does this differ from 015 Climbing Stairs, which counts the ways instead?
@@ -0,0 +1,44 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { timeMs } from '../../lib/perf'
3
+ import { minCostClimbingStairs } from './solution'
4
+
5
+ describe('020 min cost climbing stairs', () => {
6
+ it('skips the expensive middle step', () => {
7
+ expect(minCostClimbingStairs([4, 7, 2])).toBe(6)
8
+ })
9
+
10
+ it('takes several single steps when they are cheap', () => {
11
+ expect(minCostClimbingStairs([5, 1, 1, 9, 1])).toBe(3)
12
+ })
13
+
14
+ it('handles two steps: start on the cheaper one and jump to the top', () => {
15
+ expect(minCostClimbingStairs([3, 8])).toBe(3)
16
+ expect(minCostClimbingStairs([8, 3])).toBe(3)
17
+ })
18
+
19
+ it('may start on step 1', () => {
20
+ expect(minCostClimbingStairs([10, 1, 10, 1, 10])).toBe(2)
21
+ })
22
+
23
+ it('may finish from the second-to-last step', () => {
24
+ expect(minCostClimbingStairs([1, 9, 1, 9, 1, 50])).toBe(3)
25
+ })
26
+
27
+ it('handles free steps', () => {
28
+ expect(minCostClimbingStairs([0, 0, 0, 0])).toBe(0)
29
+ expect(minCostClimbingStairs([0, 5, 5, 0])).toBe(5)
30
+ })
31
+
32
+ it('handles equal costs', () => {
33
+ expect(minCostClimbingStairs([2, 2, 2, 2, 2, 2])).toBe(6)
34
+ })
35
+ })
36
+
37
+ describe('020 performance', () => {
38
+ it('handles 40 steps in under 50 ms (trying every path takes seconds)', () => {
39
+ // Costs cycle 1, 2, 3. The cheapest climb starts on step 1 and never lands on a 3.
40
+ const cost = Array.from({ length: 40 }, (_, i) => (i % 3) + 1)
41
+ const ms = timeMs(() => expect(minCostClimbingStairs(cost)).toBe(39))
42
+ expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(50)
43
+ })
44
+ })
@@ -0,0 +1,41 @@
1
+ # 021 · Single Number
2
+
3
+ **Level 1 · Easy** · Pattern: bit manipulation (XOR) · Target: 10 min · NeetCode 150 · LeetCode 136
4
+
5
+ ## Problem
6
+
7
+ In the non-empty array `nums`, every value appears exactly twice except one, which appears once. Return that one value.
8
+
9
+ Aim for O(n) time and **O(1) extra space**.
10
+
11
+ ## Examples
12
+
13
+ | `nums` | Output |
14
+ |---|---|
15
+ | `[6, 3, 6]` | `3` |
16
+ | `[8, 2, 5, 2, 8]` | `5` |
17
+ | `[-4]` | `-4` |
18
+
19
+ ## Constraints
20
+
21
+ - `1 <= nums.length <= 3 · 10^4`, and the length is always odd.
22
+ - `-3 · 10^4 <= nums[i] <= 3 · 10^4`
23
+ - The performance test uses 60,001 numbers.
24
+
25
+ ## Run it
26
+
27
+ ```bash
28
+ pnpm watch 021
29
+ ```
30
+
31
+ <details><summary>Target complexity (open after your first attempt)</summary>
32
+
33
+ Time O(n) · Space **O(1)**. Counting with a `Map` or `Set` also runs in O(n) and will pass the tests, but it uses O(n) extra space; sorting first is O(n log n) and passes too. The tests can't measure memory, so this one is on your honour: get to O(1) space. Counting each value by scanning the whole array is O(n²) and fails the performance test.
34
+
35
+ </details>
36
+
37
+ ## Follow-ups an interviewer might ask
38
+
39
+ - Why does XOR work here? Which of its properties are you relying on?
40
+ - Now every value appears **three** times except one (LeetCode 137). What changes?
41
+ - Now **two** values appear once and the rest twice (LeetCode 260). How do you find both?
@@ -0,0 +1,46 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { timeMs } from '../../lib/perf'
3
+ import { singleNumber } from './solution'
4
+
5
+ describe('021 single number', () => {
6
+ it('finds the value in the middle', () => {
7
+ expect(singleNumber([6, 3, 6])).toBe(3)
8
+ })
9
+
10
+ it('finds it among several pairs', () => {
11
+ expect(singleNumber([8, 2, 5, 2, 8])).toBe(5)
12
+ })
13
+
14
+ it('handles a single element', () => {
15
+ expect(singleNumber([-4])).toBe(-4)
16
+ })
17
+
18
+ it('finds it at either end', () => {
19
+ expect(singleNumber([9, 1, 1])).toBe(9)
20
+ expect(singleNumber([1, 1, 9])).toBe(9)
21
+ })
22
+
23
+ it('handles zero and negatives', () => {
24
+ expect(singleNumber([0, 7, 7])).toBe(0)
25
+ expect(singleNumber([-2, -2, 0])).toBe(0)
26
+ expect(singleNumber([-30_000, 4, -1, 4, -1])).toBe(-30_000)
27
+ expect(singleNumber([30_000, -30_000, 30_000])).toBe(-30_000)
28
+ })
29
+
30
+ it('does not modify the input', () => {
31
+ const nums = [5, 3, 5]
32
+ singleNumber(nums)
33
+ expect(nums).toEqual([5, 3, 5])
34
+ })
35
+ })
36
+
37
+ describe('021 performance', () => {
38
+ it('handles 60,001 numbers in under 200 ms (counting each value by scanning the array is too slow here)', () => {
39
+ const pairs = 30_000
40
+ // Each value's twin is 30,000 places later; the lone value is last.
41
+ const half = Array.from({ length: pairs }, (_, i) => i - 15_000)
42
+ const nums = [...half, ...half, 29_999]
43
+ const ms = timeMs(() => expect(singleNumber(nums)).toBe(29_999))
44
+ expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(200)
45
+ })
46
+ })
@@ -0,0 +1,40 @@
1
+ # 022 · Missing Number
2
+
3
+ **Level 1 · Easy** · Pattern: bit manipulation (XOR) or arithmetic sum · Target: 10 min · NeetCode 150 · LeetCode 268
4
+
5
+ ## Problem
6
+
7
+ `nums` holds `n` different integers, all taken from the range `0` to `n` inclusive. That range has `n + 1` values, so exactly one of them is absent. Return it. `nums` is in no particular order.
8
+
9
+ Aim for O(n) time and O(1) extra space.
10
+
11
+ ## Examples
12
+
13
+ | `nums` | Output |
14
+ |---|---|
15
+ | `[1, 4, 0, 2]` | `3` |
16
+ | `[2, 0]` | `1` |
17
+ | `[0]` | `1` |
18
+
19
+ ## Constraints
20
+
21
+ - `1 <= n <= 10^4`, values distinct and in `[0, n]`.
22
+ - The performance test uses `n = 120,000`.
23
+
24
+ ## Run it
25
+
26
+ ```bash
27
+ pnpm watch 022
28
+ ```
29
+
30
+ <details><summary>Target complexity (open after your first attempt)</summary>
31
+
32
+ Time O(n) · Space **O(1)**, either by comparing the expected sum `0 + 1 + … + n` with the actual sum, or by XOR-ing every index and value together. A `Set` of the values is O(n) time but O(n) space, and sorting first is O(n log n); both pass the tests, which can't measure memory. Checking each candidate with `includes` is O(n²) and fails the performance test.
33
+
34
+ </details>
35
+
36
+ ## Follow-ups an interviewer might ask
37
+
38
+ - With the sum approach, could the total overflow in a language with 32-bit integers? How does XOR avoid that?
39
+ - What if two numbers were missing?
40
+ - What if `nums` were sorted? (A binary search finds the gap in O(log n).)
@@ -0,0 +1,44 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { timeMs } from '../../lib/perf'
3
+ import { missingNumber } from './solution'
4
+
5
+ describe('022 missing number', () => {
6
+ it('finds a value in the middle of the range', () => {
7
+ expect(missingNumber([1, 4, 0, 2])).toBe(3)
8
+ })
9
+
10
+ it('handles two values', () => {
11
+ expect(missingNumber([2, 0])).toBe(1)
12
+ })
13
+
14
+ it('finds n itself when 0..n-1 are all there', () => {
15
+ expect(missingNumber([0])).toBe(1)
16
+ expect(missingNumber([3, 0, 2, 1])).toBe(4)
17
+ })
18
+
19
+ it('finds 0', () => {
20
+ expect(missingNumber([1])).toBe(0)
21
+ expect(missingNumber([2, 3, 1])).toBe(0)
22
+ })
23
+
24
+ it('works on sorted and reverse-sorted input', () => {
25
+ expect(missingNumber([0, 1, 2, 3, 5, 6])).toBe(4)
26
+ expect(missingNumber([6, 5, 4, 3, 1, 0])).toBe(2)
27
+ })
28
+
29
+ it('does not modify the input', () => {
30
+ const nums = [2, 0, 3]
31
+ missingNumber(nums)
32
+ expect(nums).toEqual([2, 0, 3])
33
+ })
34
+ })
35
+
36
+ describe('022 performance', () => {
37
+ it('handles n = 120,000 in under 200 ms (checking each candidate with includes is too slow here)', () => {
38
+ const n = 120_000
39
+ // Every value but n, in a scrambled order (7 and 120,000 share no factor, so i·7 mod n hits each of 0..n-1 once).
40
+ const scrambled = Array.from({ length: n }, (_, i) => (i * 7) % n)
41
+ const ms = timeMs(() => expect(missingNumber(scrambled)).toBe(n))
42
+ expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(200)
43
+ })
44
+ })
@@ -0,0 +1,41 @@
1
+ # 101 · Group Anagrams
2
+
3
+ **Level 2 · Medium** · Pattern: arrays & hashing · Target: 25 min · NeetCode 150 · LeetCode 49
4
+
5
+ ## Problem
6
+
7
+ You get an array of lowercase words. Two words are anagrams when one is a rearrangement of the other's letters (same letters, same counts). Collect the words into groups so that every group holds words that are all anagrams of each other, and no two groups could be merged.
8
+
9
+ Return the groups in any order, and the words inside each group in any order. Keep duplicates: if a word appears twice, it appears twice in its group.
10
+
11
+ ## Examples
12
+
13
+ | `strs` | Output (any order) |
14
+ |---|---|
15
+ | `["eat", "tea", "tan", "ate", "nat", "bat"]` | `[["bat"], ["nat", "tan"], ["ate", "eat", "tea"]]` |
16
+ | `[""]` | `[[""]]` |
17
+ | `["a"]` | `[["a"]]` |
18
+
19
+ ## Constraints
20
+
21
+ - `1 <= strs.length <= 10^4` (the performance test uses 12,000 words in 6,000 groups)
22
+ - `0 <= strs[i].length <= 100`
23
+ - Every word uses only `a`–`z`.
24
+
25
+ ## Run it
26
+
27
+ ```bash
28
+ pnpm watch 101
29
+ ```
30
+
31
+ <details><summary>Target complexity (open after your first attempt)</summary>
32
+
33
+ Time O(n · k log k) with a sorted-letters key, or O(n · k) with a letter-count key, where `k` is the longest word · Space O(n · k).
34
+
35
+ </details>
36
+
37
+ ## Follow-ups an interviewer might ask
38
+
39
+ - How does your solution scale when the words get very long?
40
+ - How would you group words that arrive one at a time from a stream?
41
+ - What changes if the words can contain any Unicode characters?
@@ -0,0 +1,83 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { timeMs } from '../../lib/perf'
3
+ import { groupAnagrams } from './solution'
4
+
5
+ /** Sorts the words inside each group, then sorts the groups, so any valid order compares equal. */
6
+ function normalise(groups: readonly (readonly string[])[]): string[][] {
7
+ return groups
8
+ .map((group) => [...group].sort())
9
+ .sort((a, b) => (a.join(',') < b.join(',') ? -1 : a.join(',') > b.join(',') ? 1 : 0))
10
+ }
11
+
12
+ describe('101 group anagrams', () => {
13
+ it('groups the example words', () => {
14
+ expect(normalise(groupAnagrams(['eat', 'tea', 'tan', 'ate', 'nat', 'bat']))).toEqual(
15
+ normalise([['bat'], ['nat', 'tan'], ['ate', 'eat', 'tea']]),
16
+ )
17
+ })
18
+
19
+ it('handles a single empty string', () => {
20
+ expect(groupAnagrams([''])).toEqual([['']])
21
+ })
22
+
23
+ it('handles a single word', () => {
24
+ expect(groupAnagrams(['a'])).toEqual([['a']])
25
+ })
26
+
27
+ it('keeps duplicate words', () => {
28
+ expect(normalise(groupAnagrams(['ab', 'ba', 'ab', '', '']))).toEqual(
29
+ normalise([['ab', 'ab', 'ba'], ['', '']]),
30
+ )
31
+ })
32
+
33
+ it('separates words with the same letters but different counts', () => {
34
+ expect(normalise(groupAnagrams(['aab', 'abb', 'bab', 'aba']))).toEqual(
35
+ normalise([['aab', 'aba'], ['abb', 'bab']]),
36
+ )
37
+ })
38
+
39
+ it('separates words of different lengths', () => {
40
+ expect(normalise(groupAnagrams(['a', 'aa', 'aaa']))).toEqual(normalise([['a'], ['aa'], ['aaa']]))
41
+ })
42
+
43
+ it('does not merge groups whose letter counts only look alike', () => {
44
+ // A count key built without separators turns both of these into "11...".
45
+ const a = 'b'.repeat(11) + 'a'
46
+ const b = 'a'.repeat(11) + 'b'
47
+ expect(normalise(groupAnagrams([a, b]))).toEqual(normalise([[a], [b]]))
48
+ })
49
+
50
+ it('puts every word in one group when they are all anagrams', () => {
51
+ expect(normalise(groupAnagrams(['listen', 'silent', 'enlist', 'tinsel', 'inlets']))).toEqual(
52
+ normalise([['enlist', 'inlets', 'listen', 'silent', 'tinsel']]),
53
+ )
54
+ })
55
+ })
56
+
57
+ /** The first `count` distinct letter multisets of length `len`, each spelled in sorted order. */
58
+ function sortedWords(count: number, len: number): string[] {
59
+ const words: string[] = []
60
+ const letters = new Array<number>(len).fill(0)
61
+ while (words.length < count) {
62
+ words.push(letters.map((c) => String.fromCharCode(97 + c)).join(''))
63
+ let p = len - 1
64
+ while (letters[p] === 25) p--
65
+ letters[p]!++
66
+ for (let q = p + 1; q < len; q++) letters[q] = letters[p]!
67
+ }
68
+ return words
69
+ }
70
+
71
+ describe('101 performance', () => {
72
+ it('groups 12,000 words into 6,000 groups in under 200 ms (comparing each word against every group is too slow here)', () => {
73
+ const words = sortedWords(6_000, 5)
74
+ const strs = [...words.map((w) => [...w].reverse().join('')), ...words]
75
+ const expected = normalise(words.map((w) => [w, [...w].reverse().join('')]))
76
+ let result: string[][] = []
77
+ const ms = timeMs(() => {
78
+ result = groupAnagrams(strs)
79
+ })
80
+ expect(normalise(result)).toEqual(expected)
81
+ expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(200)
82
+ })
83
+ })
@@ -0,0 +1,44 @@
1
+ # 102 · Top K Frequent Elements
2
+
3
+ **Level 2 · Medium** · Pattern: arrays & hashing · Target: 25 min · NeetCode 150 · LeetCode 347
4
+
5
+ ## Problem
6
+
7
+ You get an integer array `nums` and an integer `k`. Return the `k` values that occur most often in `nums`.
8
+
9
+ The answer is guaranteed to be unique: there is never a tie between the `k`-th and the `(k+1)`-th most frequent values. Return the values in any order.
10
+
11
+ TypeScript has no built-in priority queue. If you want a heap, write a small one yourself; sorting or quickselect are fine alternatives.
12
+
13
+ ## Examples
14
+
15
+ | `nums` | `k` | Output (any order) |
16
+ |---|---|---|
17
+ | `[1, 1, 1, 2, 2, 3]` | `2` | `[1, 2]` |
18
+ | `[1]` | `1` | `[1]` |
19
+ | `[4, 4, -1, -1, -1, 7]` | `1` | `[-1]` |
20
+
21
+ ## Constraints
22
+
23
+ - `1 <= nums.length <= 10^5`
24
+ - `-10^5 <= nums[i] <= 10^5` (the performance test uses 40,000 distinct values with `k = 20,000`)
25
+ - `1 <= k <=` the number of distinct values
26
+ - The answer is unique.
27
+
28
+ ## Run it
29
+
30
+ ```bash
31
+ pnpm watch 102
32
+ ```
33
+
34
+ <details><summary>Target complexity (open after your first attempt)</summary>
35
+
36
+ Time O(n) with bucket sort (bucket `i` holds the values that occur `i` times) · Space O(n). A size-`k` min-heap gives O(n log k). Sorting the distinct values by count is O(n log n) and also passes, but say why it isn't optimal.
37
+
38
+ </details>
39
+
40
+ ## Follow-ups an interviewer might ask
41
+
42
+ - What is the best time complexity possible here, and why?
43
+ - Return the values ordered from most to least frequent.
44
+ - What if the numbers arrive as a stream and `k` is small?
@@ -0,0 +1,59 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { timeMs } from '../../lib/perf'
3
+ import { topKFrequent } from './solution'
4
+
5
+ const sorted = (values: readonly number[]): number[] => [...values].sort((a, b) => a - b)
6
+
7
+ describe('102 top k frequent elements', () => {
8
+ it('finds the two most frequent values', () => {
9
+ expect(sorted(topKFrequent([1, 1, 1, 2, 2, 3], 2))).toEqual([1, 2])
10
+ })
11
+
12
+ it('handles a single element', () => {
13
+ expect(topKFrequent([1], 1)).toEqual([1])
14
+ })
15
+
16
+ it('handles negatives', () => {
17
+ expect(topKFrequent([4, 4, -1, -1, -1, 7], 1)).toEqual([-1])
18
+ })
19
+
20
+ it('returns every distinct value when k equals the number of distinct values', () => {
21
+ expect(sorted(topKFrequent([5, 3, 5, 9, 3, 5], 3))).toEqual([3, 5, 9])
22
+ })
23
+
24
+ it('does not depend on where the values appear', () => {
25
+ // 7 shows up first but least often.
26
+ expect(sorted(topKFrequent([7, 2, 2, 3, 3, 3, 2, 3], 2))).toEqual([2, 3])
27
+ })
28
+
29
+ it('handles the case where every value is equally frequent and k takes them all', () => {
30
+ expect(sorted(topKFrequent([10, 20, 30], 3))).toEqual([10, 20, 30])
31
+ })
32
+
33
+ it('returns exactly k values', () => {
34
+ const result = topKFrequent([1, 1, 1, 1, 2, 2, 2, 3, 3, 4], 3)
35
+ expect(result).toHaveLength(3)
36
+ expect(sorted(result)).toEqual([1, 2, 3])
37
+ })
38
+ })
39
+
40
+ describe('102 performance', () => {
41
+ it('picks the top 20,000 of 40,000 distinct values in under 200 ms (picking the max k times is too slow here)', () => {
42
+ const distinct = 40_000
43
+ const k = 20_000
44
+ // Values below k appear twice, the rest once, interleaved so order gives nothing away.
45
+ const nums: number[] = []
46
+ for (let i = 0; i < distinct; i++) {
47
+ const v = (i * 7_919) % distinct
48
+ nums.push(v)
49
+ if (v < k) nums.push(v)
50
+ }
51
+ const expected = Array.from({ length: k }, (_, i) => i)
52
+ let result: number[] = []
53
+ const ms = timeMs(() => {
54
+ result = topKFrequent(nums, k)
55
+ })
56
+ expect(sorted(result)).toEqual(expected)
57
+ expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(200)
58
+ })
59
+ })
@@ -0,0 +1,43 @@
1
+ # 103 · Product of Array Except Self
2
+
3
+ **Level 2 · Medium** · Pattern: arrays & hashing · Target: 25 min · NeetCode 150 · LeetCode 238
4
+
5
+ ## Problem
6
+
7
+ You get an integer array `nums`. Return a new array `answer` of the same length, where `answer[i]` is the product of every element of `nums` **except** `nums[i]`.
8
+
9
+ **You may not use division.** That rule is the whole point of the problem. (It also matters in practice: the tests include zeros, which break the "multiply everything, then divide by `nums[i]`" trick.)
10
+
11
+ Return a new array; don't modify `nums`.
12
+
13
+ ## Examples
14
+
15
+ | `nums` | Output |
16
+ |---|---|
17
+ | `[1, 2, 3, 4]` | `[24, 12, 8, 6]` |
18
+ | `[-1, 1, 0, -3, 3]` | `[0, 0, 9, 0, 0]` |
19
+
20
+ ## Constraints
21
+
22
+ - `2 <= nums.length <= 10^5` (the performance test uses 50,000)
23
+ - `-30 <= nums[i] <= 30`
24
+ - Every product of any subset of `nums` fits in a safe integer.
25
+ - The tests treat `-0` and `0` as equal, so you don't need to worry about JavaScript's negative zero.
26
+
27
+ ## Run it
28
+
29
+ ```bash
30
+ pnpm watch 103
31
+ ```
32
+
33
+ <details><summary>Target complexity (open after your first attempt)</summary>
34
+
35
+ Time O(n) · Space O(1) extra, not counting the output array. Two separate prefix and suffix arrays (O(n) extra) is a fine first step; then fold one of them into the output.
36
+
37
+ </details>
38
+
39
+ ## Follow-ups an interviewer might ask
40
+
41
+ - Can you do it with only the output array as extra space?
42
+ - If division *were* allowed, how would you handle one zero? Two zeros?
43
+ - How would you handle overflow in a language with fixed-width integers?
@@ -0,0 +1,59 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { timeMs } from '../../lib/perf'
3
+ import { productExceptSelf } from './solution'
4
+
5
+ /** Turns -0 into 0, so a correct answer never fails on JavaScript's negative zero. */
6
+ const clean = (values: readonly number[]): number[] => values.map((v) => (v === 0 ? 0 : v))
7
+
8
+ describe('103 product of array except self', () => {
9
+ it('multiplies everything else', () => {
10
+ expect(clean(productExceptSelf([1, 2, 3, 4]))).toEqual([24, 12, 8, 6])
11
+ })
12
+
13
+ it('handles a single zero', () => {
14
+ expect(clean(productExceptSelf([-1, 1, 0, -3, 3]))).toEqual([0, 0, 9, 0, 0])
15
+ expect(clean(productExceptSelf([0, 4, 5]))).toEqual([20, 0, 0])
16
+ })
17
+
18
+ it('handles two zeros', () => {
19
+ expect(clean(productExceptSelf([0, 2, 0, 3]))).toEqual([0, 0, 0, 0])
20
+ })
21
+
22
+ it('handles the minimum length', () => {
23
+ expect(clean(productExceptSelf([3, 7]))).toEqual([7, 3])
24
+ expect(clean(productExceptSelf([0, 0]))).toEqual([0, 0])
25
+ })
26
+
27
+ it('handles negatives', () => {
28
+ expect(clean(productExceptSelf([-2, -3, 4]))).toEqual([-12, -8, 6])
29
+ expect(clean(productExceptSelf([-1, -1, -1, -1]))).toEqual([-1, -1, -1, -1])
30
+ })
31
+
32
+ it('handles ones and repeated values', () => {
33
+ expect(clean(productExceptSelf([1, 1, 1]))).toEqual([1, 1, 1])
34
+ expect(clean(productExceptSelf([2, 2, 2, 2]))).toEqual([8, 8, 8, 8])
35
+ })
36
+
37
+ it('does not modify the input', () => {
38
+ const nums = [1, 2, 3, 4]
39
+ productExceptSelf(nums)
40
+ expect(nums).toEqual([1, 2, 3, 4])
41
+ })
42
+ })
43
+
44
+ describe('103 performance', () => {
45
+ it('handles 50,000 numbers in under 200 ms (O(n²) is too slow here)', () => {
46
+ const n = 50_000
47
+ // Only 1s and -1s, so every product stays exact.
48
+ const nums = Array.from({ length: n }, (_, i) => (i % 3 === 0 ? -1 : 1))
49
+ const negatives = Math.ceil(n / 3)
50
+ const total = negatives % 2 === 0 ? 1 : -1
51
+ const expected = nums.map((v) => total * v)
52
+ let result: number[] = []
53
+ const ms = timeMs(() => {
54
+ result = productExceptSelf(nums)
55
+ })
56
+ expect(result).toEqual(expected)
57
+ expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(200)
58
+ })
59
+ })