interview-reps 0.0.0-stage → 0.3.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 +4418 -0
  285. package/package.json +38 -4
@@ -0,0 +1,42 @@
1
+ # 213 · Subsets
2
+
3
+ **Level 2 · Medium** · Pattern: backtracking · Target: 25 min · NeetCode 150 · LeetCode 78
4
+
5
+ ## Problem
6
+
7
+ `nums` holds distinct integers. Return every subset of `nums`: every group you can make by keeping some of its elements (possibly none, possibly all) and dropping the rest.
8
+
9
+ Each subset must appear exactly once. The subsets can come back in any order, and so can the elements inside each one, so `[3, 1]` and `[1, 3]` count as the same subset and only one of them may appear.
10
+
11
+ ## Examples
12
+
13
+ | `nums` | Output |
14
+ |---|---|
15
+ | `[4, 8]` | `[[], [4], [8], [4, 8]]` |
16
+ | `[-1, 5, 0]` | `[[], [-1], [5], [0], [-1, 5], [-1, 0], [5, 0], [-1, 5, 0]]` |
17
+ | `[]` | `[[]]` |
18
+
19
+ ## Constraints
20
+
21
+ - `0 <= nums.length <= 12` (one test uses 12, which has 4,096 subsets)
22
+ - `-100 <= nums[i] <= 100`
23
+ - All values in `nums` are distinct.
24
+ - Don't change `nums`.
25
+
26
+ ## Run it
27
+
28
+ ```bash
29
+ pnpm watch 213
30
+ ```
31
+
32
+ <details><summary>Target complexity (open after your first attempt)</summary>
33
+
34
+ Time O(n · 2^n) · Space O(n) besides the output (the current subset plus the call stack). There are 2^n subsets and copying each costs up to n, so no approach can beat O(n · 2^n). That's why there is no performance test: any correct answer does about the same work.
35
+
36
+ </details>
37
+
38
+ ## Follow-ups an interviewer might ask
39
+
40
+ - Solve it again without recursion: once by growing the answer one element at a time, once by counting from 0 to 2^n − 1 and reading the bits.
41
+ - What changes if `nums` may contain repeated values and each distinct subset must still appear only once?
42
+ - Return only the subsets of exactly size `k`. How much work can you skip?
@@ -0,0 +1,63 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { subsets } from './solution'
3
+
4
+ // Subsets can come back in any order, and so can the values inside each one.
5
+ // Sorting both levels lets any valid answer compare equal, while still catching repeats.
6
+ function compareLists(a: readonly number[], b: readonly number[]): number {
7
+ for (let i = 0; i < Math.min(a.length, b.length); i++) {
8
+ if (a[i] !== b[i]) return a[i]! - b[i]!
9
+ }
10
+ return a.length - b.length
11
+ }
12
+
13
+ function normalise(sets: readonly (readonly number[])[]): number[][] {
14
+ return sets.map((set) => [...set].sort((a, b) => a - b)).sort(compareLists)
15
+ }
16
+
17
+ describe('213 subsets', () => {
18
+ it('lists every subset of two values', () => {
19
+ expect(normalise(subsets([4, 8]))).toEqual(normalise([[], [4], [8], [4, 8]]))
20
+ })
21
+
22
+ it('lists every subset of three values, including negatives and zero', () => {
23
+ expect(normalise(subsets([-1, 5, 0]))).toEqual(
24
+ normalise([[], [-1], [5], [0], [-1, 5], [-1, 0], [5, 0], [-1, 5, 0]]),
25
+ )
26
+ })
27
+
28
+ it('returns just the empty subset for an empty input', () => {
29
+ expect(subsets([])).toEqual([[]])
30
+ })
31
+
32
+ it('handles a single value', () => {
33
+ expect(normalise(subsets([-100]))).toEqual(normalise([[], [-100]]))
34
+ })
35
+
36
+ it('handles four values', () => {
37
+ const expected = [
38
+ [], [9], [2], [7], [3],
39
+ [9, 2], [9, 7], [9, 3], [2, 7], [2, 3], [7, 3],
40
+ [9, 2, 7], [9, 2, 3], [9, 7, 3], [2, 7, 3],
41
+ [9, 2, 7, 3],
42
+ ]
43
+ expect(normalise(subsets([9, 2, 7, 3]))).toEqual(normalise(expected))
44
+ })
45
+
46
+ it('returns 4,096 different subsets of 12 values, each built from the input', () => {
47
+ const nums = [12, -7, 30, 0, 5, -100, 44, 1, 99, -3, 8, 61]
48
+ const result = subsets(nums)
49
+ expect(result).toHaveLength(4096)
50
+ const keys = new Set(normalise(result).map((set) => set.join(',')))
51
+ expect(keys.size).toBe(4096)
52
+ for (const set of result) {
53
+ expect(new Set(set).size).toBe(set.length)
54
+ for (const value of set) expect(nums).toContain(value)
55
+ }
56
+ })
57
+
58
+ it('does not change the input', () => {
59
+ const nums = [6, 1, 4]
60
+ subsets(nums)
61
+ expect(nums).toEqual([6, 1, 4])
62
+ })
63
+ })
@@ -0,0 +1,44 @@
1
+ # 214 · Combination Sum
2
+
3
+ **Level 2 · Medium** · Pattern: backtracking · Target: 25 min · NeetCode 150 · LeetCode 39
4
+
5
+ ## Problem
6
+
7
+ `candidates` holds distinct positive integers, in no particular order, and `target` is a positive integer. Find every way to reach exactly `target` by adding up values from `candidates`, where each value may be used **as many times as you like** (including not at all).
8
+
9
+ Two ways count as the same if they use the same values the same number of times, whatever the order: `[2, 2, 6]` and `[6, 2, 2]` are one answer, and only one of them may appear.
10
+
11
+ Return the list of answers in any order, with the values inside each answer in any order. If `target` can't be reached, return `[]`.
12
+
13
+ ## Examples
14
+
15
+ | `candidates` | `target` | Output |
16
+ |---|---|---|
17
+ | `[5, 3, 4]` | `8` | `[[3, 5], [4, 4]]` |
18
+ | `[6, 2, 10]` | `10` | `[[10], [2, 2, 6], [2, 2, 2, 2, 2]]` |
19
+ | `[4, 9]` | `7` | `[]` |
20
+
21
+ ## Constraints
22
+
23
+ - `1 <= candidates.length <= 30`
24
+ - `1 <= candidates[i] <= 40`, all distinct
25
+ - `1 <= target <= 40` in most tests; the performance test uses `target = 44` with 7 candidates (472 answers).
26
+ - Don't change `candidates`.
27
+
28
+ ## Run it
29
+
30
+ ```bash
31
+ pnpm watch 214
32
+ ```
33
+
34
+ <details><summary>Target complexity (open after your first attempt)</summary>
35
+
36
+ Time roughly O(n^(t/m + 1)) in the worst case, where `t` is `target` and `m` the smallest candidate (the depth of the search is at most `t / m`) · Space O(t / m) besides the output. What matters in practice is generating each combination once: building every *ordering* of the values and removing repeats at the end is far slower, and the performance test rejects it.
37
+
38
+ </details>
39
+
40
+ ## Follow-ups an interviewer might ask
41
+
42
+ - How does sorting `candidates` first let you stop exploring early?
43
+ - What changes if each candidate may be used at most once, and `candidates` may contain repeats?
44
+ - If you only needed the **number** of combinations, how would you count them without listing them?
@@ -0,0 +1,75 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { timeMs } from '../../lib/perf'
3
+ import { combinationSum } from './solution'
4
+
5
+ // Answers can come back in any order, and so can the values inside each one.
6
+ function compareLists(a: readonly number[], b: readonly number[]): number {
7
+ for (let i = 0; i < Math.min(a.length, b.length); i++) {
8
+ if (a[i] !== b[i]) return a[i]! - b[i]!
9
+ }
10
+ return a.length - b.length
11
+ }
12
+
13
+ function normalise(combos: readonly (readonly number[])[]): number[][] {
14
+ return combos.map((combo) => [...combo].sort((a, b) => a - b)).sort(compareLists)
15
+ }
16
+
17
+ describe('214 combination sum', () => {
18
+ it('finds both ways to make 8', () => {
19
+ expect(normalise(combinationSum([5, 3, 4], 8))).toEqual(normalise([[3, 5], [4, 4]]))
20
+ })
21
+
22
+ it('reuses a value many times and includes a single-value answer', () => {
23
+ expect(normalise(combinationSum([6, 2, 10], 10))).toEqual(
24
+ normalise([[10], [2, 2, 6], [2, 2, 2, 2, 2]]),
25
+ )
26
+ })
27
+
28
+ it('returns an empty list when the target cannot be reached', () => {
29
+ expect(combinationSum([4, 9], 7)).toEqual([])
30
+ })
31
+
32
+ it('returns an empty list when every candidate is larger than the target', () => {
33
+ expect(combinationSum([12, 15, 31], 10)).toEqual([])
34
+ })
35
+
36
+ it('ignores candidates larger than the target', () => {
37
+ expect(normalise(combinationSum([13, 1], 1))).toEqual([[1]])
38
+ expect(normalise(combinationSum([40, 20, 9], 18))).toEqual([[9, 9]])
39
+ })
40
+
41
+ it('handles a single candidate', () => {
42
+ expect(normalise(combinationSum([3], 9))).toEqual([[3, 3, 3]])
43
+ })
44
+
45
+ it('lists each combination once, whatever order the candidates come in', () => {
46
+ const expected = normalise([[2, 3, 7], [3, 3, 3, 3], [2, 2, 2, 3, 3], [2, 2, 2, 2, 2, 2]])
47
+ expect(normalise(combinationSum([7, 3, 2], 12))).toEqual(expected)
48
+ expect(normalise(combinationSum([2, 7, 3], 12))).toEqual(expected)
49
+ })
50
+
51
+ it('does not change the input', () => {
52
+ const candidates = [7, 3, 2]
53
+ combinationSum(candidates, 12)
54
+ expect(candidates).toEqual([7, 3, 2])
55
+ })
56
+ })
57
+
58
+ describe('214 performance', () => {
59
+ it('finds all 472 ways to make 44 in under 150 ms (building every ordering is too slow here)', () => {
60
+ const candidates = [5, 3, 8, 4, 6, 11, 7]
61
+ let result: number[][] = []
62
+ const ms = timeMs(() => {
63
+ result = combinationSum(candidates, 44)
64
+ })
65
+ expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(150)
66
+
67
+ expect(result).toHaveLength(472)
68
+ const keys = new Set(normalise(result).map((combo) => combo.join(',')))
69
+ expect(keys.size).toBe(472)
70
+ for (const combo of result) {
71
+ expect(combo.reduce((sum, value) => sum + value, 0)).toBe(44)
72
+ for (const value of combo) expect(candidates).toContain(value)
73
+ }
74
+ })
75
+ })
@@ -0,0 +1,42 @@
1
+ # 215 · Permutations
2
+
3
+ **Level 2 · Medium** · Pattern: backtracking · Target: 25 min · NeetCode 150 · LeetCode 46
4
+
5
+ ## Problem
6
+
7
+ `nums` holds distinct integers. Return every possible ordering of all of its elements: each ordering uses every element of `nums` exactly once.
8
+
9
+ Each ordering must appear exactly once. The orderings themselves can come back in any order (but the order of values **inside** each one is the whole point, so `[5, 9]` and `[9, 5]` are two different answers).
10
+
11
+ ## Examples
12
+
13
+ | `nums` | Output |
14
+ |---|---|
15
+ | `[5, 9]` | `[[5, 9], [9, 5]]` |
16
+ | `[0, -3, 8]` | `[[0, -3, 8], [0, 8, -3], [-3, 0, 8], [-3, 8, 0], [8, 0, -3], [8, -3, 0]]` |
17
+ | `[11]` | `[[11]]` |
18
+
19
+ ## Constraints
20
+
21
+ - `1 <= nums.length <= 8` (the performance test uses 8, which has 40,320 orderings)
22
+ - `-10 <= nums[i] <= 10`
23
+ - All values in `nums` are distinct.
24
+ - Don't change `nums`.
25
+
26
+ ## Run it
27
+
28
+ ```bash
29
+ pnpm watch 215
30
+ ```
31
+
32
+ <details><summary>Target complexity (open after your first attempt)</summary>
33
+
34
+ Time O(n · n!) · Space O(n) besides the output (the current ordering, what's still unused, and the call stack). There are n! orderings and writing each one costs n. The performance test rejects building every length-n sequence with repeats allowed (n^n of them) and throwing away the ones that repeat a value.
35
+
36
+ </details>
37
+
38
+ ## Follow-ups an interviewer might ask
39
+
40
+ - What changes if `nums` may contain repeated values and each distinct ordering must appear only once?
41
+ - Can you produce the orderings by swapping elements in place in one working array? What do you have to undo, and when?
42
+ - Given one ordering, how would you compute the next one in sorted order without generating all of them?
@@ -0,0 +1,70 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { timeMs } from '../../lib/perf'
3
+ import { permute } from './solution'
4
+
5
+ // The orderings can come back in any order, but the values inside each one must stay as they are.
6
+ function compareLists(a: readonly number[], b: readonly number[]): number {
7
+ for (let i = 0; i < Math.min(a.length, b.length); i++) {
8
+ if (a[i] !== b[i]) return a[i]! - b[i]!
9
+ }
10
+ return a.length - b.length
11
+ }
12
+
13
+ function normalise(orderings: readonly (readonly number[])[]): number[][] {
14
+ return orderings.map((ordering) => [...ordering]).sort(compareLists)
15
+ }
16
+
17
+ // Checks that `orderings` holds `count` different orderings, each using every value of `nums` once.
18
+ function expectAllOrderings(
19
+ orderings: readonly (readonly number[])[],
20
+ nums: readonly number[],
21
+ count: number,
22
+ ): void {
23
+ expect(orderings).toHaveLength(count)
24
+ expect(new Set(orderings.map((ordering) => ordering.join(','))).size).toBe(count)
25
+ const sorted = [...nums].sort((a, b) => a - b)
26
+ for (const ordering of orderings) {
27
+ expect([...ordering].sort((a, b) => a - b)).toEqual(sorted)
28
+ }
29
+ }
30
+
31
+ describe('215 permutations', () => {
32
+ it('lists both orderings of two values', () => {
33
+ expect(normalise(permute([5, 9]))).toEqual(normalise([[5, 9], [9, 5]]))
34
+ })
35
+
36
+ it('lists all six orderings of three values, including negatives and zero', () => {
37
+ const expected = [[0, -3, 8], [0, 8, -3], [-3, 0, 8], [-3, 8, 0], [8, 0, -3], [8, -3, 0]]
38
+ expect(normalise(permute([0, -3, 8]))).toEqual(normalise(expected))
39
+ })
40
+
41
+ it('returns the single ordering of one value', () => {
42
+ expect(permute([11])).toEqual([[11]])
43
+ })
44
+
45
+ it('lists all 24 orderings of four values', () => {
46
+ expectAllOrderings(permute([4, -1, 10, 6]), [4, -1, 10, 6], 24)
47
+ })
48
+
49
+ it('lists all 720 orderings of six values', () => {
50
+ expectAllOrderings(permute([1, 2, 3, 4, 5, 6]), [1, 2, 3, 4, 5, 6], 720)
51
+ })
52
+
53
+ it('does not change the input', () => {
54
+ const nums = [3, -7, 2]
55
+ permute(nums)
56
+ expect(nums).toEqual([3, -7, 2])
57
+ })
58
+ })
59
+
60
+ describe('215 performance', () => {
61
+ it('lists all 40,320 orderings of 8 values in under 300 ms (trying all 8^8 sequences is too slow here)', () => {
62
+ const nums = [4, -2, 9, 0, 7, 1, -5, 3]
63
+ let result: number[][] = []
64
+ const ms = timeMs(() => {
65
+ result = permute(nums)
66
+ })
67
+ expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(300)
68
+ expectAllOrderings(result, nums, 40_320)
69
+ })
70
+ })
@@ -0,0 +1,50 @@
1
+ # 216 · Word Search
2
+
3
+ **Level 2 · Medium** · Pattern: backtracking · Target: 30 min · NeetCode 150 · LeetCode 79
4
+
5
+ ## Problem
6
+
7
+ `board` is a rectangular grid of single lowercase letters, and `word` is a lowercase string. Return `true` if you can spell `word` by starting on some cell and stepping from cell to cell, where each step goes up, down, left or right (never diagonally), and the letters you land on, in order, spell `word`. A single path may not use the same cell twice.
8
+
9
+ Return `false` otherwise. Don't change `board`.
10
+
11
+ ## Examples
12
+
13
+ For these examples `board` is:
14
+
15
+ ```
16
+ c a t
17
+ o r s
18
+ w e d
19
+ ```
20
+
21
+ | `board` | `word` | Output |
22
+ |---|---|---|
23
+ | the grid above | `"core"` | `true` |
24
+ | the grid above | `"cars"` | `true` |
25
+ | the grid above | `"tsar"` | `false` (from `s`, there's no `a` next to it) |
26
+ | the grid above | `"tat"` | `false` (it would need the `t` twice) |
27
+
28
+ ## Constraints
29
+
30
+ - `1 <= rows, columns <= 6` in most tests; the performance test uses an 8 × 8 board.
31
+ - `1 <= word.length <= 15` in most tests; the performance test uses a 16-letter word.
32
+ - Every cell holds one lowercase letter; `word` is lowercase letters only.
33
+
34
+ ## Run it
35
+
36
+ ```bash
37
+ pnpm watch 216
38
+ ```
39
+
40
+ <details><summary>Target complexity (open after your first attempt)</summary>
41
+
42
+ Time O(R · C · 3^L) in the worst case, where `L` is `word.length` (after the first step there are at most 3 new directions), but in practice far less, because a path is abandoned as soon as a letter doesn't match · Space O(L) for the path being explored (plus O(R · C) if you keep a separate visited grid). The performance test rejects walking every path of length `L` and only comparing the letters at the end.
43
+
44
+ </details>
45
+
46
+ ## Follow-ups an interviewer might ask
47
+
48
+ - Can you answer `false` right away for some inputs without exploring at all? (Think about letter counts, and which end of `word` to start from.)
49
+ - How would you avoid a separate visited grid, and what must you guarantee about the board when you return?
50
+ - Now you get a list of many words and must report which ones appear. How would you share work between words?
@@ -0,0 +1,86 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { timeMs } from '../../lib/perf'
3
+ import { exist } from './solution'
4
+
5
+ const grid = (rows: readonly string[]): string[][] => rows.map((row) => row.split(''))
6
+
7
+ // c a t
8
+ // o r s
9
+ // w e d
10
+ const sample = (): string[][] => grid(['cat', 'ors', 'wed'])
11
+
12
+ describe('216 word search', () => {
13
+ it('finds words that turn corners', () => {
14
+ expect(exist(sample(), 'core')).toBe(true)
15
+ expect(exist(sample(), 'cars')).toBe(true)
16
+ expect(exist(sample(), 'dew')).toBe(true)
17
+ })
18
+
19
+ it('rejects a word whose next letter is not next to the current cell', () => {
20
+ expect(exist(sample(), 'tsar')).toBe(false)
21
+ })
22
+
23
+ it('does not step diagonally', () => {
24
+ // c and r touch only at a corner.
25
+ expect(exist(sample(), 'cr')).toBe(false)
26
+ })
27
+
28
+ it('does not use the same cell twice', () => {
29
+ expect(exist(sample(), 'tat')).toBe(false)
30
+ expect(exist(sample(), 'rer')).toBe(false)
31
+ })
32
+
33
+ it('finds a word that uses every cell', () => {
34
+ expect(exist(sample(), 'catsdewor')).toBe(true)
35
+ })
36
+
37
+ it('rejects a word longer than the number of cells', () => {
38
+ expect(exist(sample(), 'catsdeworc')).toBe(false)
39
+ })
40
+
41
+ it('handles a single cell', () => {
42
+ expect(exist([['k']], 'k')).toBe(true)
43
+ expect(exist([['k']], 'j')).toBe(false)
44
+ expect(exist([['k']], 'kk')).toBe(false)
45
+ })
46
+
47
+ it('handles a single row and a single column', () => {
48
+ expect(exist(grid(['spool']), 'loop')).toBe(true)
49
+ expect(exist(grid(['s', 'p', 'o', 'o', 'l']), 'pool')).toBe(true)
50
+ expect(exist(grid(['spool']), 'pools')).toBe(false)
51
+ })
52
+
53
+ it('frees cells from a path that failed so a later path can use them', () => {
54
+ // q e e
55
+ // e e e
56
+ // Starting from the top-middle e always fails, and those attempts pass through cells
57
+ // that a path from a later start needs (for example top-right → bottom-right →
58
+ // bottom-middle → top-middle → q). A failed attempt must leave those cells free.
59
+ expect(exist(grid(['qee', 'eee']), 'eeeeq')).toBe(true)
60
+ })
61
+
62
+ it('handles repeated letters where only some paths work', () => {
63
+ expect(exist(grid(['aab', 'aba', 'baa']), 'aabaa')).toBe(true)
64
+ expect(exist(grid(['aab', 'aba', 'baa']), 'bbb')).toBe(false)
65
+ })
66
+
67
+ it('does not change the board', () => {
68
+ const board = sample()
69
+ exist(board, 'cars')
70
+ exist(board, 'tsar')
71
+ expect(board).toEqual(sample())
72
+ })
73
+ })
74
+
75
+ describe('216 performance', () => {
76
+ it('rejects a 16-letter word on an 8 × 8 board in under 150 ms (trying every path is too slow here)', () => {
77
+ const letters = 'abcdefgh'
78
+ const board = Array.from({ length: 8 }, (_, r) =>
79
+ Array.from({ length: 8 }, (_, c) => letters[(r * 3 + c * 5 + r * c) % letters.length]!),
80
+ )
81
+ // Fifteen letters that do occur on the board, then one that doesn't.
82
+ const word = 'abababababababaz'
83
+ const ms = timeMs(() => expect(exist(board, word)).toBe(false))
84
+ expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(150)
85
+ })
86
+ })
@@ -0,0 +1,53 @@
1
+ # 217 · Letter Combinations of a Phone Number
2
+
3
+ **Level 2 · Medium** · Pattern: backtracking · Target: 25 min · NeetCode 150 · LeetCode 17
4
+
5
+ ## Problem
6
+
7
+ On an old phone keypad, each digit from 2 to 9 stands for a few letters:
8
+
9
+ | Digit | Letters |
10
+ |---|---|
11
+ | 2 | `abc` |
12
+ | 3 | `def` |
13
+ | 4 | `ghi` |
14
+ | 5 | `jkl` |
15
+ | 6 | `mno` |
16
+ | 7 | `pqrs` |
17
+ | 8 | `tuv` |
18
+ | 9 | `wxyz` |
19
+
20
+ `digits` is a string made of the digits 2–9. Return every string you could get by replacing each digit with one of its letters, keeping the digits' order. For example, `"5"` followed by `"8"` can become `"jt"` but never `"tj"`.
21
+
22
+ Return the strings in any order. If `digits` is empty, return an empty list `[]` (not a list holding one empty string).
23
+
24
+ ## Examples
25
+
26
+ | `digits` | Output |
27
+ |---|---|
28
+ | `"58"` | `["jt", "ju", "jv", "kt", "ku", "kv", "lt", "lu", "lv"]` |
29
+ | `"9"` | `["w", "x", "y", "z"]` |
30
+ | `""` | `[]` |
31
+
32
+ ## Constraints
33
+
34
+ - `0 <= digits.length <= 4` (one test uses 4 digits, with 256 results)
35
+ - Every character of `digits` is between `'2'` and `'9'`.
36
+
37
+ ## Run it
38
+
39
+ ```bash
40
+ pnpm watch 217
41
+ ```
42
+
43
+ <details><summary>Target complexity (open after your first attempt)</summary>
44
+
45
+ Time O(n · 4^n) · Space O(n) besides the output, where `n` is `digits.length`: there are up to 4^n results and each has `n` letters. Every correct approach produces the same output, so there is no performance test.
46
+
47
+ </details>
48
+
49
+ ## Follow-ups an interviewer might ask
50
+
51
+ - Solve it both recursively and with a loop that grows the list of partial strings one digit at a time. Which is easier to read?
52
+ - How would you handle `0` and `1`, which have no letters, if they could appear?
53
+ - Given a dictionary of real words, how would you return only the results that are words, and skip work early?
@@ -0,0 +1,57 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { letterCombinations } from './solution'
3
+
4
+ // The results can come back in any order.
5
+ const sorted = (words: readonly string[]): string[] => [...words].sort()
6
+
7
+ describe('217 letter combinations of a phone number', () => {
8
+ it('combines two digits with three letters each', () => {
9
+ expect(sorted(letterCombinations('58'))).toEqual(['jt', 'ju', 'jv', 'kt', 'ku', 'kv', 'lt', 'lu', 'lv'])
10
+ })
11
+
12
+ it('handles a single four-letter digit', () => {
13
+ expect(sorted(letterCombinations('9'))).toEqual(['w', 'x', 'y', 'z'])
14
+ })
15
+
16
+ it('returns an empty list for no digits', () => {
17
+ expect(letterCombinations('')).toEqual([])
18
+ })
19
+
20
+ it('handles a single three-letter digit', () => {
21
+ expect(sorted(letterCombinations('2'))).toEqual(['a', 'b', 'c'])
22
+ })
23
+
24
+ it('keeps the digits in order and handles 7', () => {
25
+ expect(sorted(letterCombinations('73'))).toEqual(
26
+ sorted(['pd', 'pe', 'pf', 'qd', 'qe', 'qf', 'rd', 're', 'rf', 'sd', 'se', 'sf']),
27
+ )
28
+ })
29
+
30
+ it('handles a repeated digit', () => {
31
+ expect(sorted(letterCombinations('66'))).toEqual(['mm', 'mn', 'mo', 'nm', 'nn', 'no', 'om', 'on', 'oo'])
32
+ })
33
+
34
+ it('covers every digit from 2 to 9', () => {
35
+ const letters: Record<string, string> = {
36
+ '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl',
37
+ '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz',
38
+ }
39
+ for (const [digit, options] of Object.entries(letters)) {
40
+ expect(sorted(letterCombinations(digit))).toEqual(options.split(''))
41
+ }
42
+ })
43
+
44
+ it('returns 81 different strings for four three-letter digits', () => {
45
+ const result = letterCombinations('2345')
46
+ expect(result).toHaveLength(81)
47
+ expect(new Set(result).size).toBe(81)
48
+ for (const word of result) expect(word).toMatch(/^[abc][def][ghi][jkl]$/)
49
+ })
50
+
51
+ it('returns 256 different strings for four four-letter digits', () => {
52
+ const result = letterCombinations('7979')
53
+ expect(result).toHaveLength(256)
54
+ expect(new Set(result).size).toBe(256)
55
+ for (const word of result) expect(word).toMatch(/^[pqrs][wxyz][pqrs][wxyz]$/)
56
+ })
57
+ })
@@ -0,0 +1,42 @@
1
+ # 218 · Palindrome Partitioning
2
+
3
+ **Level 2 · Medium** · Pattern: backtracking · Target: 30 min · NeetCode 150 · LeetCode 131
4
+
5
+ ## Problem
6
+
7
+ A **palindrome** reads the same forwards and backwards, like `"level"` or `"oo"`. Every single letter is a palindrome.
8
+
9
+ `s` is a non-empty string. Cut it into consecutive pieces so that every piece is a palindrome, and return **every** way of doing that. Each way is a list of the pieces in their original left-to-right order; joining them back together gives `s`.
10
+
11
+ Each way must appear exactly once. The ways can come back in any order, but the pieces inside each way stay in the order they appear in `s`.
12
+
13
+ ## Examples
14
+
15
+ | `s` | Output |
16
+ |---|---|
17
+ | `"noon"` | `[["n", "o", "o", "n"], ["n", "oo", "n"], ["noon"]]` |
18
+ | `"xyx"` | `[["x", "y", "x"], ["xyx"]]` |
19
+ | `"abc"` | `[["a", "b", "c"]]` |
20
+
21
+ ## Constraints
22
+
23
+ - `1 <= s.length <= 16` in most tests; the performance test uses a 25-letter string.
24
+ - `s` holds lowercase English letters only.
25
+
26
+ ## Run it
27
+
28
+ ```bash
29
+ pnpm watch 218
30
+ ```
31
+
32
+ <details><summary>Target complexity (open after your first attempt)</summary>
33
+
34
+ Time O(n · 2^n) in the worst case (a string of one repeated letter, where every cut works) · Space O(n) besides the output for the current pieces and the call stack. On strings with few palindromes, a good answer does far less work, because it never extends a set of cuts whose last piece is not a palindrome. The performance test rejects trying all 2^(n−1) sets of cut positions and only then checking the pieces.
35
+
36
+ </details>
37
+
38
+ ## Follow-ups an interviewer might ask
39
+
40
+ - Checking a piece costs up to O(n) each time. How could you precompute, for every `i` and `j`, whether `s[i..j]` is a palindrome?
41
+ - Return only the **smallest number of cuts** needed instead of every way. How does the approach change?
42
+ - How many ways are there for a string of `n` identical letters, and why?