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,52 @@
1
+ # 209 · Implement Trie
2
+
3
+ **Level 2 · Medium** · Pattern: tries (prefix tree) · Target: 25 min · NeetCode 150 · LeetCode 208
4
+
5
+ ## Problem
6
+
7
+ Build a word store that can answer two kinds of question quickly: "was this exact word added?" and "was any word added that begins with these letters?". Export a class `Trie` with:
8
+
9
+ - `constructor()`: an empty store.
10
+ - `insert(word)`: add `word`. Adding the same word again changes nothing.
11
+ - `search(word)`: `true` if `word` itself was added, `false` otherwise. A word that only appears as the beginning of a longer added word doesn't count.
12
+ - `startsWith(prefix)`: `true` if at least one added word begins with `prefix`. A word counts as beginning with itself.
13
+
14
+ Each call should cost time proportional to the length of its argument, not to how many words are stored.
15
+
16
+ ## Examples
17
+
18
+ | Call | Returns | Why |
19
+ |---|---|---|
20
+ | `insert("card")` | | |
21
+ | `search("car")` | `false` | `car` was never added on its own |
22
+ | `startsWith("car")` | `true` | `card` begins with `car` |
23
+ | `insert("car")` | | |
24
+ | `search("car")` | `true` | now it was added |
25
+ | `search("cards")` | `false` | longer than anything stored |
26
+ | `startsWith("cards")` | `false` | |
27
+ | `startsWith("d")` | `false` | no word begins with `d` |
28
+
29
+ ## Constraints
30
+
31
+ - `1 <= word.length, prefix.length <= 2000`; only lowercase letters `a`–`z`.
32
+ - Up to `3 × 10^4` calls in total on LeetCode. The performance tests use 20,000 short words with 60,000 lookups, and 300 words of 2,000 letters each.
33
+
34
+ ## Run it
35
+
36
+ ```bash
37
+ pnpm watch 209
38
+ ```
39
+
40
+ <details><summary>Target complexity (open after your first attempt)</summary>
41
+
42
+ O(L) per call, where `L` is the length of the argument · Space O(total letters inserted) in the worst case, less when words share beginnings.
43
+
44
+ Two shortcuts fail the performance tests: keeping a `Set` of words and checking every one on each `startsWith` is O(number of words × L) per call, and adding every prefix of every word to a `Set` is O(L²) per `insert` (about 2 million characters for one 2,000-letter word).
45
+
46
+ </details>
47
+
48
+ ## Follow-ups an interviewer might ask
49
+
50
+ - Children as a `Map`, a plain object, or a fixed array of 26: what are the trade-offs in memory and speed?
51
+ - Add `countWordsStartingWith(prefix)` and `erase(word)` (LeetCode 1804). What extra field does each node need?
52
+ - How would you return every stored word that begins with a prefix, say for autocomplete? In sorted order?
@@ -0,0 +1,138 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { timeMs } from '../../lib/perf'
3
+ import { Trie } from './solution'
4
+
5
+ /** Word number i: `length` letters from a–t, distinct for distinct i (7,919 shares no factor with 20). */
6
+ function wordFor(i: number, length: number): string {
7
+ let n = (i * 7_919) % 20 ** length
8
+ let word = ''
9
+ for (let d = 0; d < length; d++) {
10
+ word = String.fromCharCode(97 + (n % 20)) + word
11
+ n = Math.floor(n / 20)
12
+ }
13
+ return word
14
+ }
15
+
16
+ describe('209 implement trie', () => {
17
+ it('runs the README example', () => {
18
+ const trie = new Trie()
19
+ trie.insert('card')
20
+ expect(trie.search('car')).toBe(false)
21
+ expect(trie.startsWith('car')).toBe(true)
22
+ trie.insert('car')
23
+ expect(trie.search('car')).toBe(true)
24
+ expect(trie.search('cards')).toBe(false)
25
+ expect(trie.startsWith('cards')).toBe(false)
26
+ expect(trie.startsWith('d')).toBe(false)
27
+ })
28
+
29
+ it('finds nothing in an empty trie', () => {
30
+ const trie = new Trie()
31
+ expect(trie.search('a')).toBe(false)
32
+ expect(trie.startsWith('a')).toBe(false)
33
+ })
34
+
35
+ it('treats a whole word as a prefix of itself', () => {
36
+ const trie = new Trie()
37
+ trie.insert('maple')
38
+ expect(trie.startsWith('maple')).toBe(true)
39
+ expect(trie.search('maple')).toBe(true)
40
+ expect(trie.search('mapl')).toBe(false)
41
+ })
42
+
43
+ it('keeps a short word after a longer word that starts with it is added', () => {
44
+ const trie = new Trie()
45
+ trie.insert('in')
46
+ trie.insert('inner')
47
+ expect(trie.search('in')).toBe(true)
48
+ expect(trie.search('inn')).toBe(false)
49
+ expect(trie.search('inner')).toBe(true)
50
+ })
51
+
52
+ it('handles single-letter words', () => {
53
+ const trie = new Trie()
54
+ trie.insert('q')
55
+ expect(trie.search('q')).toBe(true)
56
+ expect(trie.startsWith('q')).toBe(true)
57
+ expect(trie.search('qq')).toBe(false)
58
+ expect(trie.startsWith('r')).toBe(false)
59
+ })
60
+
61
+ it('handles the same word inserted twice', () => {
62
+ const trie = new Trie()
63
+ trie.insert('echo')
64
+ trie.insert('echo')
65
+ expect(trie.search('echo')).toBe(true)
66
+ expect(trie.search('ech')).toBe(false)
67
+ })
68
+
69
+ it('separates words that share a prefix but branch apart', () => {
70
+ const trie = new Trie()
71
+ for (const w of ['tea', 'ten', 'tent', 'to']) trie.insert(w)
72
+ expect(trie.search('te')).toBe(false)
73
+ expect(trie.startsWith('te')).toBe(true)
74
+ expect(trie.search('tent')).toBe(true)
75
+ expect(trie.search('tents')).toBe(false)
76
+ expect(trie.startsWith('tex')).toBe(false)
77
+ expect(trie.search('to')).toBe(true)
78
+ })
79
+
80
+ it('keeps separate tries independent', () => {
81
+ const a = new Trie()
82
+ const b = new Trie()
83
+ a.insert('apple')
84
+ b.insert('berry')
85
+ expect(a.search('apple')).toBe(true)
86
+ expect(a.startsWith('b')).toBe(false)
87
+ expect(b.search('berry')).toBe(true)
88
+ expect(b.startsWith('a')).toBe(false)
89
+ })
90
+
91
+ it('handles a 2,000-letter word', () => {
92
+ const trie = new Trie()
93
+ const long = 'xy'.repeat(1_000)
94
+ trie.insert(long)
95
+ expect(trie.search(long)).toBe(true)
96
+ expect(trie.search(long.slice(0, -1))).toBe(false)
97
+ expect(trie.startsWith(long.slice(0, 1_500))).toBe(true)
98
+ expect(trie.startsWith(`${long}x`)).toBe(false)
99
+ })
100
+ })
101
+
102
+ describe('209 performance', () => {
103
+ it('handles 20,000 words and 60,000 lookups in under 150 ms (checking every stored word on each lookup is too slow here)', () => {
104
+ const count = 20_000
105
+ const words = Array.from({ length: count }, (_, i) => wordFor(i, 6))
106
+ let found = 0
107
+ let prefixHits = 0
108
+ let prefixMisses = 0
109
+ const ms = timeMs(() => {
110
+ const trie = new Trie()
111
+ for (const w of words) trie.insert(w)
112
+ for (const w of words) {
113
+ if (trie.search(w)) found++
114
+ // The first four letters of a stored word are always a prefix; adding a 'u' (never used) makes a miss.
115
+ if (trie.startsWith(w.slice(0, 4))) prefixHits++
116
+ if (!trie.startsWith(`${w.slice(0, 4)}u`)) prefixMisses++
117
+ }
118
+ })
119
+ expect([found, prefixHits, prefixMisses]).toEqual([count, count, count])
120
+ expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(150)
121
+ })
122
+
123
+ it('handles 300 words of 2,000 letters in under 150 ms (storing every prefix of every word is too slow here)', () => {
124
+ // Each word is a shared 1,900-letter stem plus 100 letters that are different for each word.
125
+ const stem = 'ab'.repeat(950)
126
+ const words = Array.from({ length: 300 }, (_, i) => stem + wordFor(i, 4).repeat(25))
127
+ const results: boolean[] = []
128
+ const ms = timeMs(() => {
129
+ const trie = new Trie()
130
+ for (const w of words) trie.insert(w)
131
+ for (const w of words) {
132
+ results.push(trie.search(w), trie.startsWith(w.slice(0, 1_950)), !trie.search(w.slice(0, 1_999)))
133
+ }
134
+ })
135
+ expect(results.every(Boolean)).toBe(true)
136
+ expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(150)
137
+ })
138
+ })
@@ -0,0 +1,50 @@
1
+ # 210 · Design Add and Search Words
2
+
3
+ **Level 2 · Medium** · Pattern: tries (with backtracking on wildcards) · Target: 30 min · NeetCode 150 · LeetCode 211
4
+
5
+ ## Problem
6
+
7
+ Build a dictionary you can add words to and then query with simple patterns. Export a class `WordDictionary` with:
8
+
9
+ - `constructor()`: an empty dictionary.
10
+ - `addWord(word)`: add `word`. Adding it again changes nothing.
11
+ - `search(word)`: return `true` if some added word matches the pattern `word`, and `false` otherwise. The pattern is made of lowercase letters and dots `.`. A letter must match the same letter; a dot matches **exactly one** letter, whatever it is. So a match always has the same length as the pattern, and a pattern with no dots only matches that exact word.
12
+
13
+ ## Examples
14
+
15
+ After `addWord("lamp")`, `addWord("limp")` and `addWord("lump")`:
16
+
17
+ | Call | Returns | Why |
18
+ |---|---|---|
19
+ | `search("l.mp")` | `true` | all three words match |
20
+ | `search("..mp")` | `true` | |
21
+ | `search("lam")` | `false` | no three-letter word was added |
22
+ | `search("lamp.")` | `false` | the dot needs a fifth letter |
23
+ | `search("l..p")` | `true` | |
24
+ | `search("x...")` | `false` | no word starts with `x` |
25
+
26
+ ## Constraints
27
+
28
+ - `1 <= word.length <= 25`. Added words are lowercase letters `a`–`z`; search patterns are lowercase letters and `.`.
29
+ - A search pattern can contain several dots (LeetCode allows at most 2; these tests use up to 4, and each performance-test search has exactly one).
30
+ - Up to `10^4` calls on LeetCode. The performance test adds 20,000 eight-letter words, then runs 15,000 searches that each contain a dot; 10,000 of them match nothing.
31
+
32
+ ## Run it
33
+
34
+ ```bash
35
+ pnpm watch 210
36
+ ```
37
+
38
+ <details><summary>Target complexity (open after your first attempt)</summary>
39
+
40
+ `addWord`: O(L). `search`: O(L) without dots; each dot can branch into up to 26 letters, so the worst case is O(26^d · L) for `d` dots, which stays small for the few dots used here. Space O(total letters added).
41
+
42
+ Comparing the pattern against every stored word (even only the ones of the right length, or with a regular expression) is O(number of words × L) per search, which the performance test rejects.
43
+
44
+ </details>
45
+
46
+ ## Follow-ups an interviewer might ask
47
+
48
+ - What does a pattern like `"........"` cost? How would you speed up searches with many dots?
49
+ - Support `*`, matching any run of letters (including none). What changes in the search?
50
+ - Return how many words match, or the matching words themselves, instead of `true`/`false`.
@@ -0,0 +1,127 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { timeMs } from '../../lib/perf'
3
+ import { WordDictionary } from './solution'
4
+
5
+ /** Word number i: `length` letters from a–t, distinct for distinct i (7,919 shares no factor with 20). */
6
+ function wordFor(i: number, length: number): string {
7
+ let n = (i * 7_919) % 20 ** length
8
+ let word = ''
9
+ for (let d = 0; d < length; d++) {
10
+ word = String.fromCharCode(97 + (n % 20)) + word
11
+ n = Math.floor(n / 20)
12
+ }
13
+ return word
14
+ }
15
+
16
+ const withChar = (word: string, at: number, ch: string): string => word.slice(0, at) + ch + word.slice(at + 1)
17
+
18
+ describe('210 design add and search words', () => {
19
+ it('runs the README example', () => {
20
+ const dict = new WordDictionary()
21
+ dict.addWord('lamp')
22
+ dict.addWord('limp')
23
+ dict.addWord('lump')
24
+ expect(dict.search('l.mp')).toBe(true)
25
+ expect(dict.search('..mp')).toBe(true)
26
+ expect(dict.search('lam')).toBe(false)
27
+ expect(dict.search('lamp.')).toBe(false)
28
+ expect(dict.search('l..p')).toBe(true)
29
+ expect(dict.search('x...')).toBe(false)
30
+ })
31
+
32
+ it('finds nothing in an empty dictionary', () => {
33
+ const dict = new WordDictionary()
34
+ expect(dict.search('a')).toBe(false)
35
+ expect(dict.search('.')).toBe(false)
36
+ })
37
+
38
+ it('matches exact words without dots', () => {
39
+ const dict = new WordDictionary()
40
+ dict.addWord('seat')
41
+ expect(dict.search('seat')).toBe(true)
42
+ expect(dict.search('sea')).toBe(false)
43
+ expect(dict.search('seats')).toBe(false)
44
+ })
45
+
46
+ it('makes each dot match exactly one letter', () => {
47
+ const dict = new WordDictionary()
48
+ dict.addWord('go')
49
+ dict.addWord('abc')
50
+ expect(dict.search('..')).toBe(true)
51
+ expect(dict.search('.')).toBe(false)
52
+ expect(dict.search('...')).toBe(true)
53
+ expect(dict.search('....')).toBe(false)
54
+ expect(dict.search('ab.')).toBe(true)
55
+ expect(dict.search('g.o')).toBe(false)
56
+ expect(dict.search('go.')).toBe(false)
57
+ })
58
+
59
+ it('tries every letter for a dot, not just the first one it sees', () => {
60
+ const dict = new WordDictionary()
61
+ dict.addWord('ax')
62
+ dict.addWord('by')
63
+ dict.addWord('cz')
64
+ expect(dict.search('.y')).toBe(true)
65
+ expect(dict.search('.z')).toBe(true)
66
+ expect(dict.search('.w')).toBe(false)
67
+ })
68
+
69
+ it('does not match the start of a longer word', () => {
70
+ const dict = new WordDictionary()
71
+ dict.addWord('trial')
72
+ expect(dict.search('tri.')).toBe(false)
73
+ expect(dict.search('tri..')).toBe(true)
74
+ })
75
+
76
+ it('handles dots at the start, middle and end together', () => {
77
+ const dict = new WordDictionary()
78
+ for (const w of ['stone', 'store', 'shore', 'stove']) dict.addWord(w)
79
+ expect(dict.search('.to.e')).toBe(true)
80
+ expect(dict.search('s.o.e')).toBe(true)
81
+ expect(dict.search('.h..e')).toBe(true)
82
+ expect(dict.search('.h..s')).toBe(false)
83
+ })
84
+
85
+ it('handles the same word added twice', () => {
86
+ const dict = new WordDictionary()
87
+ dict.addWord('mint')
88
+ dict.addWord('mint')
89
+ expect(dict.search('m.nt')).toBe(true)
90
+ expect(dict.search('min')).toBe(false)
91
+ })
92
+
93
+ it('keeps separate dictionaries independent', () => {
94
+ const a = new WordDictionary()
95
+ const b = new WordDictionary()
96
+ a.addWord('one')
97
+ b.addWord('two')
98
+ expect(a.search('...')).toBe(true)
99
+ expect(a.search('t..')).toBe(false)
100
+ expect(b.search('t..')).toBe(true)
101
+ })
102
+ })
103
+
104
+ describe('210 performance', () => {
105
+ it('handles 20,000 words and 15,000 searches with a dot in under 200 ms (comparing the pattern with every stored word is too slow here)', () => {
106
+ const count = 20_000
107
+ const length = 8
108
+ const words = Array.from({ length: count }, (_, i) => wordFor(i, length))
109
+ let hits = 0
110
+ let misses = 0
111
+ const ms = timeMs(() => {
112
+ const dict = new WordDictionary()
113
+ for (const w of words) dict.addWord(w)
114
+ for (let i = 0; i < 5_000; i++) {
115
+ // A stored word with one letter swapped for a dot: always found.
116
+ if (dict.search(withChar(words[i * 4]!, i % length, '.'))) hits++
117
+ }
118
+ for (let i = 0; i < 10_000; i++) {
119
+ // A dot plus a 'u', a letter no stored word uses: never found.
120
+ const w = withChar(words[i * 2]!, i % length, '.')
121
+ if (!dict.search(withChar(w, (i + 3) % length, 'u'))) misses++
122
+ }
123
+ })
124
+ expect([hits, misses]).toEqual([5_000, 10_000])
125
+ expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(200)
126
+ })
127
+ })
@@ -0,0 +1,47 @@
1
+ # 211 · Task Scheduler
2
+
3
+ **Level 2 · Medium** · Pattern: heap / greedy (simulation or counting) · Target: 30 min · NeetCode 150 · LeetCode 621
4
+
5
+ ## Problem
6
+
7
+ A machine works in time units. In each unit it either runs exactly one task or sits idle. You get the tasks to run as `tasks`, a list of labels (single capital letters `A`–`Z`); labels can repeat, and every copy has to run once. Each task takes one unit.
8
+
9
+ There's a cooldown: after running a task with some label, the machine must wait at least `n` units before running that same label again. Those units can go to other labels or be idle. Different labels don't block each other.
10
+
11
+ You may run the tasks in any order. Return the smallest number of units needed to finish them all, idle units included. Don't modify `tasks`.
12
+
13
+ ## Examples
14
+
15
+ | `tasks` | `n` | Output | One best order (`_` is idle) |
16
+ |---|---|---|---|
17
+ | `["X", "X", "X", "Y", "Y", "Z"]` | `2` | `7` | `X Y Z X Y _ X` |
18
+ | `["P", "P", "Q", "Q"]` | `0` | `4` | `P P Q Q` |
19
+ | `["K", "K", "K", "K"]` | `3` | `13` | `K _ _ _ K _ _ _ K _ _ _ K` |
20
+ | `["A", "B", "C", "D", "A", "B"]` | `1` | `6` | `A B C D A B` |
21
+
22
+ ## Constraints
23
+
24
+ - `1 <= tasks.length <= 10^4`; each label is one of `A`–`Z`.
25
+ - `0 <= n <= 100`
26
+ - One test uses 10,000 tasks. There's no timed test: within these limits, anything that doesn't try every possible order is fast enough.
27
+
28
+ ## Run it
29
+
30
+ ```bash
31
+ pnpm watch 211
32
+ ```
33
+
34
+ <details><summary>Target complexity (open after your first attempt)</summary>
35
+
36
+ Time O(T), where `T` is the number of tasks · Space O(1) (at most 26 counts).
37
+
38
+ Two good answers: simulate the schedule with a max-heap of remaining counts plus a queue of labels cooling down (O(T log 26), or O(answer) if you step through idle units one by one), or work it out directly from the largest count and how many labels share it. A brute-force search over orders is exponential.
39
+
40
+ </details>
41
+
42
+ ## Follow-ups an interviewer might ask
43
+
44
+ - Can you get the answer without simulating, from the counts alone? Explain why it's correct, including when the result is just `tasks.length`.
45
+ - Return an actual schedule, not just its length.
46
+ - The tasks must run in the order given (LeetCode 2365). What changes?
47
+ - What if `n` could be 10^9? Which approaches still work?
@@ -0,0 +1,64 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { leastInterval } from './solution'
3
+
4
+ const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
5
+ const repeat = (label: string, times: number): string[] => Array.from({ length: times }, () => label)
6
+
7
+ describe('211 task scheduler', () => {
8
+ it('runs the README examples', () => {
9
+ expect(leastInterval(['X', 'X', 'X', 'Y', 'Y', 'Z'], 2)).toBe(7)
10
+ expect(leastInterval(['P', 'P', 'Q', 'Q'], 0)).toBe(4)
11
+ expect(leastInterval(['K', 'K', 'K', 'K'], 3)).toBe(13)
12
+ expect(leastInterval(['A', 'B', 'C', 'D', 'A', 'B'], 1)).toBe(6)
13
+ })
14
+
15
+ it('handles a single task, whatever the gap', () => {
16
+ expect(leastInterval(['M'], 0)).toBe(1)
17
+ expect(leastInterval(['M'], 100)).toBe(1)
18
+ })
19
+
20
+ it('never idles when the gap is 0', () => {
21
+ expect(leastInterval(['A', 'A', 'A', 'A', 'B'], 0)).toBe(5)
22
+ })
23
+
24
+ it('counts every label tied for the most copies', () => {
25
+ // A B _ A B _ A B
26
+ expect(leastInterval(['A', 'A', 'A', 'B', 'B', 'B'], 2)).toBe(8)
27
+ // A B C D A B C D: three-way tie plus one, and no idle needed.
28
+ expect(leastInterval(['A', 'B', 'C', 'D', 'A', 'B', 'C', 'D'], 3)).toBe(8)
29
+ // A B C _ A B C
30
+ expect(leastInterval(['C', 'B', 'A', 'C', 'B', 'A'], 3)).toBe(7)
31
+ })
32
+
33
+ it('needs no idle time when there are enough different tasks', () => {
34
+ expect(leastInterval(['A', 'A', 'A', 'B', 'C', 'D', 'E', 'F', 'G'], 2)).toBe(9)
35
+ expect(leastInterval(letters, 25)).toBe(26)
36
+ expect(leastInterval(letters, 40)).toBe(26)
37
+ })
38
+
39
+ it('handles tasks given in any order', () => {
40
+ expect(leastInterval(['B', 'A', 'B', 'C', 'B'], 2)).toBe(7)
41
+ expect(leastInterval(['B', 'B', 'B', 'A', 'C'], 2)).toBe(7)
42
+ })
43
+
44
+ it('handles a gap of 100', () => {
45
+ // E, then 100 units, then E again: two copies need 102 units.
46
+ expect(leastInterval(['E', 'E'], 100)).toBe(102)
47
+ expect(leastInterval(['E', 'E', 'F'], 100)).toBe(102)
48
+ })
49
+
50
+ it('handles 10,000 tasks', () => {
51
+ // 5,000 A and 5,000 B, gap 100: 4,999 blocks of 101 units, then A B.
52
+ expect(leastInterval([...repeat('A', 5_000), ...repeat('B', 5_000)], 100)).toBe(4_999 * 101 + 2)
53
+ // 384 of each letter, gap 25: the 26 letters fill each block exactly.
54
+ expect(leastInterval(letters.flatMap((l) => repeat(l, 384)), 25)).toBe(26 * 384)
55
+ // Gap 0: just the count.
56
+ expect(leastInterval(repeat('Z', 10_000), 0)).toBe(10_000)
57
+ })
58
+
59
+ it('does not modify the input', () => {
60
+ const tasks = ['B', 'A', 'B']
61
+ leastInterval(tasks, 1)
62
+ expect(tasks).toEqual(['B', 'A', 'B'])
63
+ })
64
+ })
@@ -0,0 +1,63 @@
1
+ # 212 · Design Twitter
2
+
3
+ **Level 2 · Medium** · Pattern: heap (merging k sorted lists) + hash maps · Target: 30 min · NeetCode 150 · LeetCode 355
4
+
5
+ ## Problem
6
+
7
+ Build the core of a small social feed. People post short messages, follow each other, and read a feed. Export a class `Twitter` with:
8
+
9
+ - `constructor()`: no users, no tweets.
10
+ - `postTweet(userId, tweetId)`: user `userId` posts a tweet with id `tweetId`. Every tweet id is different.
11
+ - `getNewsFeed(userId)`: return the ids of the **10 most recent** tweets posted by `userId` or by anyone `userId` currently follows, **newest first**. Return fewer if there are fewer than 10, and `[]` if there are none (including for a user you've never seen).
12
+ - `follow(followerId, followeeId)`: `followerId` starts following `followeeId`. Following is one-way, and following someone you already follow changes nothing.
13
+ - `unfollow(followerId, followeeId)`: `followerId` stops following `followeeId`. Unfollowing someone you don't follow changes nothing.
14
+
15
+ Details that matter:
16
+
17
+ - "Recent" means the order the `postTweet` calls happened in. Tweet ids say nothing about time: a later tweet can have a smaller id.
18
+ - A feed is worked out when it's asked for. After a follow, all of that person's earlier tweets can appear; after an unfollow, none of them do.
19
+ - Your own tweets are always in your feed. `follow(u, u)` and `unfollow(u, u)` have no effect.
20
+ - Ids are non-negative integers; `0` is a valid tweet id.
21
+
22
+ ## Examples
23
+
24
+ | Call | Returns |
25
+ |---|---|
26
+ | `postTweet(1, 50)` | |
27
+ | `getNewsFeed(1)` | `[50]` |
28
+ | `follow(1, 2)` | |
29
+ | `postTweet(2, 7)` | |
30
+ | `getNewsFeed(1)` | `[7, 50]` |
31
+ | `postTweet(1, 30)` | |
32
+ | `getNewsFeed(1)` | `[30, 7, 50]` |
33
+ | `unfollow(1, 2)` | |
34
+ | `getNewsFeed(1)` | `[30, 50]` |
35
+ | `getNewsFeed(2)` | `[7]` |
36
+
37
+ ## Constraints
38
+
39
+ - Up to `3 × 10^4` calls on LeetCode, with user ids up to 500.
40
+ - The performance test stores 210,000 tweets from 12,000 users, then builds 2,000 feeds for users who each follow 6 people. Their newest tweets are far back in time, so anything that walks through all recent tweets for each feed is too slow.
41
+
42
+ ## Run it
43
+
44
+ ```bash
45
+ pnpm watch 212
46
+ ```
47
+
48
+ <details><summary>Target complexity (open after your first attempt)</summary>
49
+
50
+ `postTweet`, `follow`, `unfollow`: O(1). `getNewsFeed`: O(f + 10 log f) for `f` people in the feed, using a max-heap seeded with each person's newest tweet and refilled from the same person's list as you pop (a k-way merge). Taking the last 10 tweets of each person and sorting those (O(f log f)) also passes. Space O(users + follows + tweets).
51
+
52
+ Keeping one global list of tweets and scanning it from the newest end costs O(total tweets) per feed when the people you follow haven't posted lately, which the performance test rejects.
53
+
54
+ TypeScript has no built-in priority queue. A small binary heap is about 30 lines; sorting the candidates is fine too.
55
+
56
+ </details>
57
+
58
+ ## Follow-ups an interviewer might ask
59
+
60
+ - Why seed the heap with only each person's newest tweet instead of all their tweets?
61
+ - Make the feed size `k` a parameter. How does the cost change?
62
+ - At real scale, would you build feeds when they're read (pull) or push each tweet into followers' feeds when it's posted? What about accounts with millions of followers?
63
+ - Add `deleteTweet(tweetId)`.
@@ -0,0 +1,137 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { timeMs } from '../../lib/perf'
3
+ import { Twitter } from './solution'
4
+
5
+ describe('212 design twitter', () => {
6
+ it('runs the README example', () => {
7
+ const t = new Twitter()
8
+ t.postTweet(1, 50)
9
+ expect(t.getNewsFeed(1)).toEqual([50])
10
+ t.follow(1, 2)
11
+ t.postTweet(2, 7)
12
+ expect(t.getNewsFeed(1)).toEqual([7, 50])
13
+ t.postTweet(1, 30)
14
+ expect(t.getNewsFeed(1)).toEqual([30, 7, 50])
15
+ t.unfollow(1, 2)
16
+ expect(t.getNewsFeed(1)).toEqual([30, 50])
17
+ expect(t.getNewsFeed(2)).toEqual([7])
18
+ })
19
+
20
+ it('returns an empty feed for a user with no tweets and no follows', () => {
21
+ const t = new Twitter()
22
+ expect(t.getNewsFeed(9)).toEqual([])
23
+ t.follow(9, 4)
24
+ expect(t.getNewsFeed(9)).toEqual([])
25
+ })
26
+
27
+ it('orders by when tweets were posted, not by their ids', () => {
28
+ const t = new Twitter()
29
+ for (const id of [5, 900, 0, 42, 17]) t.postTweet(3, id)
30
+ expect(t.getNewsFeed(3)).toEqual([17, 42, 0, 900, 5])
31
+ })
32
+
33
+ it('returns only the 10 most recent tweets', () => {
34
+ const t = new Twitter()
35
+ for (let i = 0; i < 12; i++) t.postTweet(1, 100 + i)
36
+ expect(t.getNewsFeed(1)).toEqual([111, 110, 109, 108, 107, 106, 105, 104, 103, 102])
37
+ })
38
+
39
+ it('merges tweets from several people by time', () => {
40
+ const t = new Twitter()
41
+ t.follow(1, 2)
42
+ t.follow(1, 3)
43
+ // Posting order: 2, 3, 1, 3, 2, 1, 3, 2, 2, 3, 1, 3 (ids are the post order, scrambled).
44
+ const posts: [number, number][] = [
45
+ [2, 71], [3, 12], [1, 88], [3, 40], [2, 9], [1, 63], [3, 25], [2, 77], [2, 3], [3, 56], [1, 14], [3, 30],
46
+ ]
47
+ for (const [user, id] of posts) t.postTweet(user, id)
48
+ expect(t.getNewsFeed(1)).toEqual([30, 14, 56, 3, 77, 25, 63, 9, 40, 88])
49
+ expect(t.getNewsFeed(2)).toEqual([3, 77, 9, 71])
50
+ })
51
+
52
+ it('shows tweets posted before the follow, and drops them all after an unfollow', () => {
53
+ const t = new Twitter()
54
+ t.postTweet(2, 11)
55
+ t.follow(1, 2)
56
+ t.postTweet(2, 22)
57
+ expect(t.getNewsFeed(1)).toEqual([22, 11])
58
+ t.unfollow(1, 2)
59
+ expect(t.getNewsFeed(1)).toEqual([])
60
+ t.follow(1, 2)
61
+ expect(t.getNewsFeed(1)).toEqual([22, 11])
62
+ })
63
+
64
+ it('ignores following or unfollowing yourself', () => {
65
+ const t = new Twitter()
66
+ t.postTweet(4, 1)
67
+ t.follow(4, 4)
68
+ expect(t.getNewsFeed(4)).toEqual([1])
69
+ t.unfollow(4, 4)
70
+ expect(t.getNewsFeed(4)).toEqual([1])
71
+ })
72
+
73
+ it('treats a repeated follow as one, and ignores unfollowing a stranger', () => {
74
+ const t = new Twitter()
75
+ t.postTweet(2, 8)
76
+ t.follow(1, 2)
77
+ t.follow(1, 2)
78
+ expect(t.getNewsFeed(1)).toEqual([8])
79
+ t.unfollow(1, 2)
80
+ expect(t.getNewsFeed(1)).toEqual([])
81
+ t.unfollow(1, 5)
82
+ t.unfollow(6, 7)
83
+ expect(t.getNewsFeed(1)).toEqual([])
84
+ })
85
+
86
+ it('makes following one-way', () => {
87
+ const t = new Twitter()
88
+ t.follow(1, 2)
89
+ t.postTweet(1, 10)
90
+ t.postTweet(2, 20)
91
+ expect(t.getNewsFeed(1)).toEqual([20, 10])
92
+ expect(t.getNewsFeed(2)).toEqual([20])
93
+ })
94
+
95
+ it('keeps separate instances independent', () => {
96
+ const a = new Twitter()
97
+ const b = new Twitter()
98
+ a.postTweet(1, 1)
99
+ b.postTweet(1, 2)
100
+ expect(a.getNewsFeed(1)).toEqual([1])
101
+ expect(b.getNewsFeed(1)).toEqual([2])
102
+ })
103
+ })
104
+
105
+ describe('212 performance', () => {
106
+ it('builds a feed 2,000 times with 210,000 tweets stored in under 300 ms (scanning every tweet for each feed is too slow here)', () => {
107
+ const quietUsers = 2_000 // ids 1..2000, 5 tweets each, posted first
108
+ const rounds = 5
109
+ const noiseUsers = 10_000 // ids 100,001..110,000, 20 tweets each, posted after; nobody below follows them
110
+ const readers = 2_000 // ids 50,001..52,000, each follows 6 quiet users
111
+ const quietTweet = (round: number, user: number): number => 1_000_000 - (round * quietUsers + user)
112
+ const followsOf = (r: number): number[] => Array.from({ length: 6 }, (_, j) => ((r * 7 + j * 101) % quietUsers) + 1)
113
+
114
+ // The 10 newest tweets among a reader's 6 quiet users: all 6 from the last round, then 4 from the one before.
115
+ const expectedFeed = (r: number): number[] => {
116
+ const users = followsOf(r).sort((a, b) => b - a)
117
+ return [...users.map((u) => quietTweet(rounds - 1, u)), ...users.map((u) => quietTweet(rounds - 2, u))].slice(0, 10)
118
+ }
119
+
120
+ const feeds: number[][] = []
121
+ const ms = timeMs(() => {
122
+ const t = new Twitter()
123
+ for (let round = 0; round < rounds; round++) {
124
+ for (let u = 1; u <= quietUsers; u++) t.postTweet(u, quietTweet(round, u))
125
+ }
126
+ for (let i = 0; i < 20 * noiseUsers; i++) t.postTweet(100_001 + (i % noiseUsers), 2_000_000 + i)
127
+ for (let r = 0; r < readers; r++) for (const u of followsOf(r)) t.follow(50_001 + r, u)
128
+ for (let r = 0; r < readers; r++) feeds.push(t.getNewsFeed(50_001 + r))
129
+ })
130
+ const mismatches = feeds
131
+ .map((feed, r) => (feed.join() === expectedFeed(r).join() ? '' : `reader ${50_001 + r}: got [${feed.join(', ')}]`))
132
+ .filter(Boolean)
133
+ .slice(0, 5)
134
+ expect(mismatches).toEqual([])
135
+ expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(300)
136
+ })
137
+ })