Here is a first answer to 212. Word Search II: for each word in the list, run the Word Search from problem 79 on the grid, and keep the words it finds.
import { exist } from "../0079-word-search/solution.ts";
// Run Word Search once per word.
// Time O(W * m * n * 4 * 3^(L-1)) worst case: the whole grid search, W times. Memory O(L) besides the output.
export function findWordsEach(board: string[][], words: string[]): string[] {
return words.filter((word) => exist(board, word));
}
LeetCode allows up to 3 × 10⁴ words on a 12 × 12 grid. On random grids this answer passes: it took 182.51 ms for 30,000 words in the measurement at the end of this page. But the limits also allow a grid where every word shares a long start and none is there, and on one we built, it took 7,044.5 ms. One grid search that follows a trie of the words took 10.1 ms on the same input.
This module works six problems. Three list every subset, combination or ordering of a small list; two search a grid for words; one builds the trie that the last problem needs. Each one follows the nine steps from Module 1.
After this module, you can:
- list every subset, combination or ordering with one shared path that you change, explore and change back, copying it only when you record an answer
- build each answer in one order only, by starting each level at
start, and cut a branch early by sorting and stopping at the first choice that’s too large - search a grid for a word by marking cells in place and restoring them, and skip hopeless searches with a letter count and the rarer end of the word
- build a trie with a
Mapper node, and say what it costs in memory - search a grid once for many words by following a trie, and shrink the trie as words are found
The code for this module is in module-10/ of the course repository, and node --test "module-10/**/*.test.ts" from its root runs every test. atlimit.ts in the module folder calls each solution once on a hard input at its problem’s limit, so its times are rough, and yours will differ. Every number on this page comes from Node.js 24.22.1 on an Apple M2 laptop with macOS.
The pattern: choose, explore, undo
Backtracking builds an answer one choice at a time, and when a choice can’t lead any further, it takes the choice back and tries the next one. The choices form a search tree, where each node is a partial answer and each child adds one more choice. The search walks this tree depth first, as Module 7’s DFS walked a binary tree. DSA Module 10 teaches backtracking and counts how big these trees get.
The walk keeps one path, the list of choices from the root to the node it’s at. It doesn’t build a new list for each node. It adds a choice, calls itself, and removes the choice when the call returns. Figure 1 shows the shape every problem in this module shares.
explore(state):
if path is an answer: record a COPY of path the path keeps changing
for each choice still allowed from state:
choose: path.push(choice) (or mark a cell)
explore: explore(the state after choice)
undo: path.pop() (or restore the cell)
Figure 1: one path is shared by the whole search, so each choice is undone on the way back, and an answer is copied when it’s recorded.
To prune is to stop a branch before you walk it, because no answer can be under it. Every speedup in the first four problems is a prune, or a rule that stops the search from building the same answer twice.
The second structure in this module is the trie. It’s a tree with one node per distinct prefix of the stored words, and each node maps the next letter to a child node. Problem 208 builds one, and 212 uses it to steer a grid search. DSA Module 12 has a short tour of tries.
Signs that point to backtracking:
- “every”, “all”, “list each”: subsets, combinations, orderings, ways to reach a total
- small limits: n up to 10, 6 or 30, words up to 15 letters, where the answer itself can be 2ⁿ or n! long
- a path through a grid that may not use a cell twice
Signs that point to a trie:
- many words, and questions about prefixes (“starts with”)
- one walk that must check many words at each step
The cost of backtracking is the size of the tree: 2ⁿ nodes for subsets, about e · n! for orderings. A trie costs memory: one object per node.
Rule: Keep one path and undo every choice on the way back. Copy the path only to record it, and prune a branch as soon as no answer can be under it.
78. Subsets
78. Subsets is rated Medium. You get a list of different integers. Return every subset of it, from the empty one to the whole list, each exactly once. The order of the subsets, and of the numbers inside each, doesn’t matter.
1 ≤ n ≤ 10-10 ≤ nums[i] ≤ 10- the numbers are all different
The signature is function subsets(nums: number[]): number[][]. Try it on LeetCode first.
Hint
If each subset is built in increasing index order, it’s built once. At each step, which numbers may still be added?
Interviewer: Return every subset of this list.
Candidate: So every way to pick some of the numbers, including none and all of them. Can a number appear twice in the input?
Interviewer: No, they’re all different.
Candidate: Is the empty subset part of the answer? And does the order matter?
Interviewer: Yes, include it. Any order is fine, for the subsets and inside each.
The interviewer and the candidate are invented. The problems, limits and timings are real.
Candidate: Here’s my example and three edge cases.
nums expected
[-4, 7] [], [-4], [7], [-4, 7]
[5] [], [5]
[5, -10, 0] 8 subsets; 0 and negatives are ordinary values
n = 10 1,024 different subsets
Candidate: The first answer that comes to mind: start with only the empty subset. For each number, copy every subset I have so far and add the number to the copy. So each number doubles the list.
// Start from the empty subset; each number doubles the list (every old subset, without and with it).
// Time O(2^n * n): 2^n subsets, each copied once at up to n items. Memory O(2^n * n), the output.
export function subsetsByDoubling(nums: number[]): number[][] {
let out: number[][] = [[]];
for (const x of nums) out = out.concat(out.map((subset) => [...subset, x]));
return out;
}
Candidate: There are 2ⁿ subsets, and each is copied once with up to n numbers, so it’s O(2ⁿ · n) time and memory. At n = 10 that’s 1,024 subsets, which is nothing.
In atlimit.ts it took 0.5 ms at n = 10.
Interviewer: It fits. Can you do better?
Candidate: Not in time. The answer itself is 2ⁿ subsets of n / 2 numbers on average, so any solution is O(2ⁿ · n). But I’d still write it as a backtracking search. It needs only O(n) memory besides the answer, and the same shape solves the next problems.
Candidate: Every node of the search tree is one subset, so I record a copy of the path at each call. Then, for each index from start on, I choose that number, explore from the next index, and undo. Because the index only goes up, each subset is built in one order only.
// Backtracking: every node of the search is one subset; choose nums[i], explore from i + 1, undo.
// Time O(2^n * n): 2^n nodes, each copies its path of up to n items. Memory O(n) besides the output (path, stack).
function subsets(nums: number[]): number[][] {
const out: number[][] = [];
const path: number[] = [];
const explore = (start: number): void => {
out.push([...path]); // copy: path keeps changing after this
for (let i = start; i < nums.length; i++) {
path.push(nums[i]);
explore(i + 1);
path.pop();
}
};
explore(0);
return out;
}
export { subsets };
Pause and predict. For n numbers, how many times does explore run?
Each call records exactly one subset, and each subset is recorded once, so explore runs 2ⁿ times: 1,024 at n = 10. DSA Module 10 counted the same nodes in a run.
Interviewer: Trace your example.
Figure 2 lists the calls for [-4, 7] in the order they run. Each line is one node of the search tree.
call path records then chooses
explore(0) [] [] -4 (i = 0), later 7 (i = 1)
explore(1) [-4] [-4] 7 (i = 1)
explore(2) [-4, 7] [-4, 7] nothing: start = 2 = n
explore(2) [7] [7] nothing
out = [[], [-4], [-4, 7], [7]]
Figure 2: every call records the path it was given, and since the index only moves up, [7, -4] is never built.
Candidate: After explore(2) returns from [-4, 7], pop takes 7 off, then the loop ends and pop takes -4 off. So the path is empty again when the first call chooses 7. For [5], the first call records [], chooses 5, and the second records [5].
Interviewer: Final cost?
Candidate: O(2ⁿ · n) time: 2ⁿ calls, each copying a path of up to n numbers. O(n) memory besides the output, for the path and up to n + 1 waiting calls. At n = 10 the recursion is 11 calls deep at most.
In atlimit.ts it took 0.2 ms at n = 10.
Interviewer: What if the input can repeat numbers?
The Candidate’s answer
Candidate: Then two branches can build equal subsets. I’d sort first. Then, inside one call, I’d skip a number equal to the one before it in the loop: i > start && nums[i] === nums[i - 1] means “already tried at this level”. The cost stays O(2ⁿ · n).
That’s LeetCode’s 90. Subsets II, which this course doesn’t cover. This version isn’t in the lab.
Interviewer: Can you do it without recursion?
The Candidate’s answer (stretch)
Candidate: The doubling version is already a plain loop. Another way: each integer from 0 to 2ⁿ − 1 has n bits, and bit i says whether nums[i] is in the subset. That uses bit operators, which Module 12 covers.
Interviewer: And if I only want the number of subsets?
The Candidate’s answer
Candidate: It’s 2ⁿ, with no search at all: each number is either in or out.
Two mistakes are common here. mistakes.ts in the module folder prints the wrong output of every mistake in this module that has one.
- Recording the path itself.
out.push(path)stores the same array eight times, and the undo steps empty it by the end. For[1, 2, 3]it returns[[],[],[],[],[],[],[],[]]. Record a copy,[...path]. - Looping from 0 instead of
start. Every subset is then built in every order. A version that loops from 0 and skips numbers already in the path returns 16 results for[1, 2, 3], with both[1,3]and[1,3,2], instead of 8. Start each loop atstart.
Lab folder: module-10/0078-subsets/ in the course repository.
39. Combination Sum
39. Combination Sum is rated Medium. You get a list of different positive integers and a target. Return every way to reach the target exactly by adding numbers from the list, where each number may be used as many times as you like. Two answers that differ only in order count as one.
1 ≤ candidates.length ≤ 302 ≤ candidates[i] ≤ 40, all different1 ≤ target ≤ 40- the page promises fewer than 150 answers for its test inputs; any order is accepted
The signature is function combinationSum(candidates: number[], target: number): number[][]. Try it on LeetCode first.
Hint
Subsets avoided repeats by never going back to a smaller index. What should the next call’s start be when a number may be used again?
Interviewer: Find every combination of these numbers that adds up to the target.
Candidate: So I may use a number more than once, and [4, 9] and [9, 4] are the same answer. Is that right?
Interviewer: Yes. Only how many of each number counts.
Candidate: Can a number be 0 or negative? And is the list sorted?
Interviewer: Every number is at least 2. The list isn’t sorted.
Candidate: Then every choice lowers what’s left by at least 2, so the search ends. A path is at most 40 / 2 = 20 numbers long.
Candidate: Here’s my example, coin sizes and a total, and three edge cases.
candidates, target expected
[9, 4, 5], 13 [4, 9], [4, 4, 5]
[40, 39], 2 [] nothing fits
[3], 3 [[3]] one number is the whole answer
[40, 2], 40 [40] and twenty 2s: a path 20 deep
Candidate: The naive answer: at each step, try every number that still fits. When I reach 0, I sort the path and keep it under a string key, so each combination is kept once.
// Try every candidate at every step (ordered sequences), then keep one copy of each sorted sequence.
// Time O(N^(T/M) * T/M): N choices at each of up to T/M levels (M = smallest candidate), and every order of a
// combination is built. Memory O(N^(T/M) * T/M) in the worst case for the set of keys.
export function combinationSumOrdered(candidates: number[], target: number): number[][] {
const seen = new Map<string, number[]>();
const path: number[] = [];
const explore = (left: number): void => {
if (left === 0) {
const combo = [...path].sort((a, b) => a - b);
seen.set(combo.join(","), combo);
return;
}
for (const x of candidates) {
if (x > left) continue;
path.push(x);
explore(left - x);
path.pop();
}
};
explore(target);
return [...seen.values()];
}
Candidate: With N numbers, a target T and a smallest number M, the tree has up to T / M levels and N branches at each. So it’s O(N^(T/M) · T/M) time in the worst case.
Interviewer: Is that too slow when the page promises fewer than 150 answers?
Candidate: The promise counts answers, not orders. With [2, 3, 4, 5] and 40, there are 145 answers, but 9,098,878 ordered sequences add up to 40, and this version builds every one.
atlimit.ts ran exactly that input. It took 5,516.4 ms, so it’s too slow even inside the page’s promise.
Interviewer: What does it repeat?
Candidate: It builds each combination once per order: [4, 9] and [9, 4] are two separate walks. I’ll do what Subsets did: never choose a smaller index than the last one, so each combination is built in one order only. The difference is that I explore from i, not i + 1, because the same number may come again.
// Loop from `start`: a combination is built in one order only (index never goes down), so no duplicates.
// Time O(N^(T/M) * T/M) worst case, but each combination is reached once. Memory O(T/M) besides the output.
export function combinationSumFromStart(candidates: number[], target: number): number[][] {
const out: number[][] = [];
const path: number[] = [];
const explore = (start: number, left: number): void => {
if (left === 0) {
out.push([...path]);
return;
}
for (let i = start; i < candidates.length; i++) {
if (candidates[i] > left) continue;
path.push(candidates[i]);
explore(i, left - candidates[i]); // i, not i + 1: the same number may be used again
path.pop();
}
};
explore(0, target);
return out;
}
Candidate: No key set is needed now, because no combination is built twice. On the same input it took 0.3 ms.
Candidate: One more prune. If I sort the numbers first, the first number larger than what’s left ends the loop, because every later number is larger too. So continue becomes break.
// Sort first, then `break` at the first candidate larger than what is left: every later one is larger too.
// Time O(N log N) for the sort plus O(N^(T/M) * T/M) worst case for the search. Memory O(T/M) besides the output.
function combinationSum(candidates: number[], target: number): number[][] {
const sorted = [...candidates].sort((a, b) => a - b);
const out: number[][] = [];
const path: number[] = [];
const explore = (start: number, left: number): void => {
if (left === 0) {
out.push([...path]);
return;
}
for (let i = start; i < sorted.length; i++) {
if (sorted[i] > left) break;
path.push(sorted[i]);
explore(i, left - sorted[i]);
path.pop();
}
};
explore(0, target);
return out;
}
export { combinationSum };
Candidate: I sort a copy, so the caller’s list doesn’t change.
In atlimit.ts, combinationSum also took 0.3 ms on [2, 3, 4, 5] and 40. The break saves the most when many numbers are larger than what’s left, because it skips them all at once instead of checking each one.
Interviewer: Trace your example.
Figure 3 shows the search for [9, 4, 5] and 13. The sorted copy is [4, 5, 9], and each line is one call with its path and what’s left.
[] left 13
[4] left 9
[4,4] left 5
[4,4,4] left 1
4 > 1: break
[4,4,5] left 0: record
9 > 5: break
[4,5] left 4
5 > 4: break
[4,9] left 0: record
[5] left 8
[5,5] left 3
5 > 3: break
9 > 8: break
[9] left 4
9 > 4: break
Figure 3: under [5] the search never goes back to 4, so [5, 4, 4] is never built, and each break skips every larger number.
Candidate: It returns [[4,4,5],[4,9]]. For [40, 39] and 2, the sorted copy is [39, 40], 39 is larger than 2, the first loop breaks, and the answer is [].
Interviewer: Final cost?
Candidate: O(N log N) for the sort, plus O(N^(T/M) · T/M) in the worst case for the search, where each combination is reached once. O(T/M) memory besides the output: the path and the waiting calls, at most 20 deep here.
Interviewer: What if each number may be used at most once, and the list can repeat numbers?
The Candidate’s answer
Candidate: I’d explore from i + 1 instead of i. To avoid equal answers from equal numbers, I’d sort and skip a number equal to the one before it in the same loop, as in the repeated-numbers version of Subsets.
That’s LeetCode’s 40. Combination Sum II, which this course doesn’t cover. This version isn’t in the lab.
Interviewer: What if I only want the number of combinations?
The Candidate’s answer (stretch)
Candidate: Then I don’t need the combinations themselves. I’d count the ways to reach each total from 0 to the target, taking the numbers one at a time, which is O(N · T). That’s dynamic programming, the topic of Module 11, where Coin Change asks a close question.
This version isn’t in the lab.
Three mistakes are common here, each shown on [9, 4, 5] and 13, which should give [4, 4, 5] and [4, 9]:
- Looping from 0. Every order is built:
[[9,4],[4,9],[4,4,5],[4,5,4],[5,4,4]]. Passias the nextstart. breakwithout sorting. The loop stops at 9 before it sees 4, so it returns[[4,4,5]]and misses[4, 9]. Sort first, or usecontinue.- Exploring from
i + 1. No number can be used twice, so it returns[[9,4]]. Passi.
Lab folder: module-10/0039-combination-sum/ in the course repository.
46. Permutations
46. Permutations is rated Medium. You get a list of different integers. Return every ordering of all of them, each once, in any order.
1 ≤ n ≤ 6-10 ≤ nums[i] ≤ 10- the numbers are all different
The signature is function permute(nums: number[]): number[][]. Try it on LeetCode first.
Hint
Now every number appears in every answer, so a start index doesn’t help. How do you know which numbers are still free?
Interviewer: Return every ordering of these numbers.
Candidate: So every way to line up all of them. Can numbers repeat?
Interviewer: No, they’re all different.
Candidate: Must the orderings come out in sorted order?
Interviewer: No, any order.
Candidate: Here’s my example, three deploy steps numbered [4, -2, 9], and two edge cases.
nums expected
[4, -2, 9] 6 orderings, from [4,-2,9] to [9,-2,4]
[7] [[7]]
n = 6 720 different orderings
Candidate: The naive answer: build every sequence of n picks, allowing repeats, and keep the ones with no number twice.
// Build every sequence of n picks (repeats allowed), keep those with no number twice.
// Time O(n^n * n): n^n sequences, each checked and copied in O(n). Memory O(n! * n), the output.
export function permuteAllSequences(nums: number[]): number[][] {
const out: number[][] = [];
const path: number[] = [];
const explore = (): void => {
if (path.length === nums.length) {
if (new Set(path).size === nums.length) out.push([...path]);
return;
}
for (const x of nums) {
path.push(x);
explore();
path.pop();
}
};
explore();
return out;
}
Candidate: There are nⁿ sequences, each checked in O(n), so O(nⁿ · n) time. At n = 6 that’s 46,656 sequences for 720 answers, which fits.
In atlimit.ts it took 4.8 ms at n = 6.
Interviewer: It fits. What if n were 10?
Candidate: Then it’s 10¹⁰ sequences for 3,628,800 orderings, far over the budget. The waste is that a sequence with a repeat is finished before it’s thrown away. I should check at each choice instead: try only numbers that aren’t in the path yet.
Candidate: I keep one flag per position. Choose means set the flag and push; undo means pop and clear the flag.
// Backtracking with a used flag per position: only numbers not yet in the path are tried.
// Time O(n * n!): about e * n! nodes, each scanning n flags; each of the n! leaves copies n items.
// Memory O(n) besides the output (path, flags, stack).
function permute(nums: number[]): number[][] {
const out: number[][] = [];
const path: number[] = [];
const used = new Array<boolean>(nums.length).fill(false);
const explore = (): void => {
if (path.length === nums.length) {
out.push([...path]);
return;
}
for (let i = 0; i < nums.length; i++) {
if (used[i]) continue;
used[i] = true;
path.push(nums[i]);
explore();
path.pop();
used[i] = false; // undo both
}
};
explore();
return out;
}
export { permute };
Candidate: Each level picks one unused number, so every leaf is an ordering and every ordering has one path.
Interviewer: Trace your example.
Figure 4 shows the search for [4, -2, 9]. The flags are written as three digits, one per position, with 1 for used.
[] used 000
[4] used 100
[4,-2] used 110
[4,-2,9] record
[4,9] used 101
[4,9,-2] record
[-2] used 010
[-2,4] used 110
[-2,4,9] record
[-2,9] used 011
[-2,9,4] record
[9] used 001
[9,4] used 101
[9,4,-2] record
[9,-2] used 011
[9,-2,4] record
Figure 4: the flags go back to 000 before each first choice, so all six orderings are built and no sequence with a repeat is started.
Candidate: For [7], the first call chooses 7, the next call sees a full path and records [7].
Interviewer: Final cost?
Candidate: The tree has about e · n! nodes, and each scans n flags, so O(n · n!) time. Each of the n! leaves also copies n numbers, which is the same bound. O(n) memory besides the output.
DSA Module 10 shows where e · n! comes from: the tree for 10 items has 9,864,101 nodes, 2.7183 times its 10! leaves. In atlimit.ts, permute took 0.3 ms at n = 6.
Interviewer: What if the input can repeat numbers?
The Candidate’s answer
Candidate: I’d sort, and skip nums[i] when it equals nums[i - 1] and nums[i - 1] isn’t used. That way equal numbers are always taken in the same order, so equal orderings aren’t built twice.
That’s LeetCode’s 47. Permutations II, which this course doesn’t cover. This version isn’t in the lab.
Interviewer: Can you do it without the used array?
The Candidate’s answer
Candidate: Yes. I keep the numbers chosen so far at the front of nums. At position start, I swap each nums[i] with i ≥ start into place, explore from start + 1, and swap back. When start reaches n, I record a copy of nums. The cost is the same, O(n · n!).
This version isn’t in the lab.
Two mistakes are common here:
- Setting the flag but never clearing it. After the first ordering, every flag stays set, so
[4, -2, 9]returns[[4,-2,9]], one ordering instead of six. Clear the flag when you pop. - Recording the path itself. As in 78, every entry ends up as the same emptied array. Record
[...path]. This one isn’t inmistakes.tsfor 46.
Lab folder: module-10/0046-permutations/ in the course repository.
79. Word Search
79. Word Search is rated Medium. You get a grid of letters and a word. Say whether the word can be spelled by starting on some cell and stepping up, down, left or right from cell to cell, using each cell at most once.
mrows andncolumns,1 ≤ m, n ≤ 61 ≤ word.length ≤ 15- the grid and the word use only English letters, upper and lower case
- the page’s follow-up: can pruning make the search faster on a larger grid?
The signature is function exist(board: string[][], word: string): boolean. Try it on LeetCode first.
Hint
The path is the cells used so far. How can a cell say “I’m on the path” without a separate array, and what must happen when the search backs out of it?
Interviewer: Is the word in the grid?
Candidate: So I start anywhere and step to a side neighbor each time, spelling the word in order. Are diagonal steps allowed?
Interviewer: No, only up, down, left and right.
Candidate: Can one cell be used twice in the word? And are upper and lower case the same letter?
Interviewer: No to both. A and a are different letters.
Candidate: May I change the board while I search, if it’s the same when I return?
Interviewer: Yes, as long as it’s the same afterwards.
Candidate: Here’s my example and three edge cases. I write each row as a string.
grid word expected
CODE AXYS TPIN CAT true down, down from C
CODE AXYS TPIN CODY true right, right, down
CODE AXYS TPIN COAT false no A is next to the O
a a true one cell
a aa false a cell can't be used twice
AAB AAC AAA AAAAAAC true a dead end must not block it
aA AA false only one A
Figure 5 draws the example with the cells’ positions.
c=0 c=1 c=2 c=3
r=0 C O D E CAT: (0,0) -> (1,0) -> (2,0)
r=1 A X Y S CODY: (0,0) -> (0,1) -> (0,2) -> (1,2)
r=2 T P I N COAT: the O at (0,1) has no A beside it
Figure 5: a word is a path of side steps through the grid, and no path through the O reaches an A.
Candidate: The naive answer: from every cell, walk every path of word.length cells, never reusing a cell, and compare the letters at the end.
// Walk every path of word.length cells from every cell, and compare the letters only at the end.
// Time O(m * n * 4 * 3^(L-1) * L): up to 4 * 3^(L-1) paths per start, each string built letter by letter.
// Memory O(m * n + L): the used marks, the stack and the string.
export function existAllPaths(board: string[][], word: string): boolean {
const rows = board.length, cols = board[0].length;
const used = board.map((row) => row.map(() => false));
const walk = (r: number, c: number, spelled: string): boolean => {
if (r < 0 || c < 0 || r >= rows || c >= cols || used[r][c]) return false;
spelled += board[r][c];
if (spelled.length === word.length) return spelled === word;
used[r][c] = true;
const found = walk(r + 1, c, spelled) || walk(r - 1, c, spelled) || walk(r, c + 1, spelled) || walk(r, c - 1, spelled);
used[r][c] = false;
return found;
};
for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) if (walk(r, c, "")) return true;
return false;
}
Candidate: With L letters, a path has 4 choices at the first step and at most 3 after, since it can’t go back. So each of the m·n cells starts up to 4 · 3^(L−1) paths. Each path builds a string of L letters, so it’s O(m·n · 4 · 3^(L−1) · L) time.
Candidate: At the limit that bound is 36 · 4 · 3¹⁴, about 6.9 × 10⁸ paths. That’s over the budget on paper.
On a 6 × 6 grid the bound is loose, because most of those paths leave the grid or run into themselves. atlimit.ts tried a hard case: 6 × 6 of A with one B in a corner, and a word of 14 As and a C. Every path of As is walked before the answer is false. It took 152.2 ms, so this answer fits the limits.
Interviewer: It fits. The page asks how pruning would help on a larger grid. Where would you start?
Candidate: It builds a whole path before it compares anything. A path that starts C, A can’t spell CODY, but it’s extended to four cells anyway. So I compare each cell as I step on it, and stop at the first wrong letter. That cuts the whole branch below it.
Candidate: I also don’t need the used array. I write # into the cell while it’s on the path, since no letter matches #, and I write the letter back when I leave.
// Backtracking: stop a path at the first letter that does not match; mark the cell in the board, undo after.
// Time O(m * n * 4 * 3^(L-1)) worst case: the first step has 4 neighbours, later steps 3 (not the one we came from).
// Memory O(L): the call stack; the board itself holds the marks.
export function existBacktrack(board: string[][], word: string): boolean {
const rows = board.length, cols = board[0].length;
const step = (r: number, c: number, k: number): boolean => {
if (r < 0 || c < 0 || r >= rows || c >= cols || board[r][c] !== word[k]) return false;
if (k === word.length - 1) return true;
const letter = board[r][c];
board[r][c] = "#"; // choose: no letter matches "#", so the path cannot come back here
const found = step(r + 1, c, k + 1) || step(r - 1, c, k + 1) || step(r, c + 1, k + 1) || step(r, c - 1, k + 1);
board[r][c] = letter; // undo, even when found, so the caller gets its board back
return found;
};
for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) if (step(r, c, 0)) return true;
return false;
}
Candidate: step(r, c, k) asks whether the word from letter k on can start at (r, c). The worst case is the same, because a grid where every letter matches gives no early stop. But on most grids a wrong letter ends a path after one or two steps.
On the all-A grid it took 51.1 ms in atlimit.ts. Every letter but the last matches there, so the early stop helps least.
The lab names this function existBacktrack. The version to paste into LeetCode is exist, below.
Interviewer: Can you avoid the search entirely on that grid?
Candidate: Two checks before the search. First, count the letters: if the grid has fewer of some letter than the word needs, the answer is false. The C isn’t on the grid, so that returns at once. Second, a path read backwards spells the reversed word. So if the word’s first letter is more common on the grid than its last, I search for the reversed word, which has fewer starting cells.
// The page's follow-up: two prunes before the same search.
// 1. Count letters: if the board has fewer of some letter than the word needs, answer false in O(m * n + L).
// 2. Search from the rarer end: a path read backwards spells the reversed word, so the answer is the same,
// and fewer starting cells match. Worst case still O(m * n * 4 * 3^(L-1)); memory O(L) plus the counts.
function exist(board: string[][], word: string): boolean {
const rows = board.length, cols = board[0].length;
const have = new Map<string, number>();
for (const row of board) for (const letter of row) have.set(letter, (have.get(letter) ?? 0) + 1);
const need = new Map<string, number>();
for (const letter of word) need.set(letter, (need.get(letter) ?? 0) + 1);
for (const [letter, count] of need) if ((have.get(letter) ?? 0) < count) return false;
if (have.get(word[0])! > have.get(word[word.length - 1])!) word = [...word].reverse().join("");
const step = (r: number, c: number, k: number): boolean => {
if (r < 0 || c < 0 || r >= rows || c >= cols || board[r][c] !== word[k]) return false;
if (k === word.length - 1) return true;
const letter = board[r][c];
board[r][c] = "#";
const found = step(r + 1, c, k + 1) || step(r - 1, c, k + 1) || step(r, c + 1, k + 1) || step(r, c - 1, k + 1);
board[r][c] = letter;
return found;
};
for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) if (step(r, c, 0)) return true;
return false;
}
export { exist };
Candidate: After the count check passes, every letter of the word is on the grid, so the two ! reads are safe.
In atlimit.ts, exist answered the all-A case in 0.1 ms. We also built a word that passes both checks and still isn’t there: B in two opposite corners, and B, twelve As, B. The corners are an even number of steps apart, and that word needs 13 steps, so no path spells it. The search starts only from the two B cells, and it took 1.8 ms.
Interviewer: Trace COAT on your example.
Figure 6 follows step for COAT. Both checks pass: each letter appears once on the grid, so the word isn’t reversed. The neighbors are tried down, up, right, left; cells that don’t hold a C fail at once and aren’t shown.
step at letter k result
(0,0) C 0 matches, write #
(1,0) A 1 A != O
(-1,0) - 1 off the grid
(0,1) O 1 matches, write #
(1,1) X 2 X != A
(-1,1) - 2 off the grid
(0,2) D 2 D != A
(0,0) # 2 # != A: C is on the path
(0,1) restore O, return false
(0,-1) - 1 off the grid
(0,0) restore C, return false
Figure 6: the # stops the path from turning back onto C, and each cell gets its letter back before its call returns.
Candidate: No other cell holds a C, so the answer is false and the board is unchanged. For CAT, (0,0) matches, the step down to (1,0) matches A, and the step down to (2,0) is the last letter, so it’s true after three calls.
Candidate: The dead-end case needs the restore. In AAB AAC AAA, a path of As can wander into a corner and fail. If its cells stayed #, the path that does reach C would find them blocked.
Interviewer: Final cost?
Candidate: O(m·n + L) for the checks. The search is still O(m·n · 4 · 3^(L−1)) in the worst case, but the checks and the early stop cut most of it. O(L) memory for the waiting calls, at most 15 deep, plus the letter counts.
Interviewer: What if you may not change the board at all?
The Candidate’s answer
Candidate: I’d keep a separate m × n array of flags, as existAllPaths does, and set and clear a flag instead of writing #. That’s O(m·n) more memory and the same time.
Interviewer: What if I give you many words for the same grid?
The Candidate’s answer
Candidate: Running this once per word repeats the same walks for words that start alike. I’d put the words in a trie and walk the grid once. That’s problem 212, at the end of this module.
Two mistakes are common here:
- Not restoring the cell. A failed path leaves its
#marks behind. OnAAB AAC AAA,AAAAAACreturns false instead of true.mistakes.tstried all 24 orders of the four directions, on every turn and mirror image of two dead-end grids, and the missing restore failed in every order. Write the letter back before you return, even after a find. - Reading the cell before the bounds check.
board[-1]isundefinedin JavaScript, soboard[-1][c]throwsTypeError: Cannot read properties of undefined (reading '1'). A bad column only givesundefined, so the bug shows up only at the top and bottom rows. Check the bounds first.
Lab folder: module-10/0079-word-search/ in the course repository.
208. Implement Trie (Prefix Tree)
208. Implement Trie (Prefix Tree) is rated Medium. Build a store of words with three operations: add a word, say whether an exact word was added, and say whether any added word starts with a given prefix.
1 ≤ word.length, prefix.length ≤ 2000- only lowercase English letters
- at most 3 × 10⁴ calls in all to
insert,searchandstartsWith
LeetCode’s TypeScript template is a class Trie with a constructor, insert(word: string): void, search(word: string): boolean and startsWith(prefix: string): boolean. Try it on LeetCode first.
Hint
Words that start the same could share their first letters. How do you find, from one letter, the nodes for every word that continues it?
Interviewer: Implement this class.
Candidate: So search is an exact match, and startsWith asks whether any stored word begins with the prefix. Which characters can appear?
Interviewer: Lowercase a to z only.
Candidate: Can the same word be inserted twice? Can a word be empty?
Interviewer: Nothing forbids inserting twice. Every word and prefix has at least one letter.
Candidate: Here’s my example, three shell commands, and three edge cases.
calls expected
insert git, gist, grep
startsWith("gi") true
startsWith("go") false
search("gis") false only a prefix
search("gist") true
insert abc; search("ab") false
then insert ab; search("ab") true now a word too
empty trie: search("a") false
after abc and ab: startsWith("abcd") false longer than every word
Candidate: The naive answer is a Set of the words. insert and search are a Set add and lookup, and startsWith checks every word.
// A Set of the words. insert and search: O(L) to hash the word. startsWith: O(W * P), it checks every word.
// Memory O(total characters inserted).
export class TrieSet {
words = new Set<string>();
insert(word: string): void {
this.words.add(word);
}
search(word: string): boolean {
return this.words.has(word);
}
startsWith(prefix: string): boolean {
for (const word of this.words) if (word.startsWith(prefix)) return true;
return false;
}
}
Candidate: insert and search hash the word, O(L) for L letters. startsWith compares the prefix with every one of W words, O(W · P) for a prefix of P letters.
Candidate: In the worst case at the limits, 15,000 inserts come first, then 15,000 prefix checks that each compare up to 2,000 letters with 15,000 words. That’s 4.5 × 10¹¹ letter compares, far over the budget.
atlimit.ts built that case: words that share their first 1,990 letters, and a prefix that matches all 1,990 and fails at the next one. It took 5,698.6 ms at 1,000 calls of each kind and 21,188.8 ms at 2,000. That’s 3.7 times longer for twice the calls, close to the 4 times of a quadratic cost. At 15,000 of each, the same growth gives 15 to 20 minutes, so we didn’t run it.
Interviewer: What does startsWith repeat?
Candidate: It compares the same shared letters again for every word that has them. If words that share a start also share the nodes for it, a prefix check walks one node per letter of the prefix, however many words there are. That’s a trie.
Figure 7 draws the trie after inserting git, gist and grep. A node is [letter], -> is a child link, and * marks a node where a word ends.
[root] -> [g] -+-> [i] -+-> [t]* * isWord = true
| +-> [s] -> [t]*
+-> [r] -> [e] -> [p]*
Figure 7: git and gist share the nodes for gi, and only the * says that git is a word and gis isn’t.
class TrieNode {
children = new Map<string, TrieNode>();
isWord = false;
}
// A trie: one node per distinct prefix, a child per next letter. Every call walks one node per letter:
// insert O(L), search O(L), startsWith O(P). Memory O(total characters inserted) nodes at most.
class Trie {
root = new TrieNode();
insert(word: string): void {
let node = this.root;
for (const letter of word) {
let next = node.children.get(letter);
if (next === undefined) {
next = new TrieNode();
node.children.set(letter, next);
}
node = next;
}
node.isWord = true;
}
search(word: string): boolean {
const node = this.walk(word);
return node !== null && node.isWord; // the path existing is not enough: it may be only a prefix
}
startsWith(prefix: string): boolean {
return this.walk(prefix) !== null;
}
// The node reached by spelling `letters` from the root, or null if the path stops.
walk(letters: string): TrieNode | null {
let node = this.root;
for (const letter of letters) {
const next = node.children.get(letter);
if (next === undefined) return null;
node = next;
}
return node;
}
}
export { Trie };
Candidate: insert reuses a child when there is one and makes it only when there isn’t. search and startsWith share walk; the only difference is that search also needs the isWord mark. To paste this into LeetCode, I paste TrieNode with it.
Interviewer: Trace your example.
Figure 8 follows walk for two of the queries on the trie in Figure 7.
query walk node at the end answer
search("gis") root -> g -> i -> s [s], isWord false false
startsWith("go") root -> g, no child "o" null false
search("gist") root -> g -> i -> s -> t [t], isWord true true
Figure 8: walk stops at the first missing letter, and search needs the end mark, so a prefix that exists isn’t a word.
Candidate: For the edge case, inserting abc makes the node for ab but doesn’t mark it, so search("ab") is false. Inserting ab later walks the same nodes and only sets the mark.
Interviewer: Final cost?
Candidate: O(L) for insert and search, O(P) for startsWith: one Map lookup per letter. Memory is one node per distinct prefix, at most the total number of letters inserted.
In atlimit.ts, the same hard case at the full 15,000 inserts and 15,000 prefix checks took 793.0 ms. That’s 3 × 10⁴ walks of about 2,000 letters each, 6 × 10⁷ Map lookups.
Pause and predict. At the limits, how many nodes can the trie hold, and about how much memory is that?
Interviewer: How much memory can it take at the limits?
The Candidate’s answer
Candidate: If 3 × 10⁴ inserted words of 2,000 letters share nothing, that’s up to 6 × 10⁷ nodes. Each node is an object with its own Map, so the nodes are the cost.
measure.ts built a trie of 500 random words of 2,000 letters: 999,378 nodes held 223.9 MB, 224.0 bytes per node. At that rate, 6 × 10⁷ nodes would be about 13 GB. During research, a first version of the lab’s limit test inserted 10,000 random 2,000-letter words, about 2 × 10⁷ nodes. Node.js stopped with a heap out-of-memory error past 4 GB. We can’t tell whether LeetCode’s tests reach that size without submitting.
Candidate: To use less, I’d give each node an array of 26 children, indexed by letter.charCodeAt(0) - 97, instead of a Map. Or I’d store a string on each edge, so a run of nodes with one child each becomes one edge. That’s a compressed trie.
Neither version is in the lab, and we didn’t measure them.
Interviewer: How would you delete a word?
The Candidate’s answer
Candidate: The simple way is to walk to its node and clear isWord. That doesn’t free any nodes. To free them, I’d keep in each node the number of stored words that pass through it. On delete, I’d lower it along the path and drop a child whose count reaches 0.
This version isn’t in the lab.
Interviewer: What if search can contain . for any one letter?
The Candidate’s answer
Candidate: At a ., I’d try every child of the current node, and go on with the rest of the word under each. That’s backtracking over the trie. The worst case is every node in the trie, but a normal letter still follows one child.
That’s LeetCode’s 211. Design Add and Search Words Data Structure, which this course doesn’t cover. This version isn’t in the lab.
Two mistakes are common here:
searchthat only checks the path. It returns true when the walk reaches the last letter, without the end mark. After insertinggist,search("gis")returns true instead of false. Returnnode.isWord.- Making a new child even when one exists.
insert("gist")would replace thegnode thatgitmade, sosearch("git")returns false after it. Make a child only whengetreturnsundefined. This one isn’t inmistakes.ts.
Lab folder: module-10/0208-implement-trie-prefix-tree/ in the course repository.
212. Word Search II
212. Word Search II is rated Hard. It has the grid and the step rules of Word Search, but you get a list of words. Return every word from the list that can be spelled on the grid, each once, in any order.
mrows andncolumns,1 ≤ m, n ≤ 12- the grid holds lowercase English letters
1 ≤ words.length ≤ 3 × 10⁴, and1 ≤ words[i].length ≤ 10- the words are lowercase and all different
The signature is function findWords(board: string[][], words: string[]): string[]. Try it on LeetCode first.
Hint
Instead of asking “is this word here?” for each word, walk the grid once. At each cell, ask “is what I’ve spelled so far the start of any word?” Which structure from 208 answers that one letter at a time?
Interviewer: Find every word from this list in the grid.
Candidate: Can the list repeat a word? And should a word that the grid spells in two ways be returned twice?
Interviewer: The words are all different, and each found word is returned once.
Candidate: How many words, and how long?
Interviewer: Up to 3 × 10⁴ words of up to 10 letters, on up to 144 cells.
Candidate: Here’s my example, the grid from 79 in lowercase, and three edge cases.
grid words expected
code axys tpin cat cody coat spin nip dog cat, cody, nip
aaa aaa aa aa, once
ab ab abc ab
aab aac aaa aaaaaac aaaaaac (dead end)
Candidate: nip reads right to left along the bottom row. spin fails because no p is next to the s, and dog because no g is next to the o.
Candidate: The naive answer is findWordsEach, the function at the top of this page: run exist from 79 once per word.
Candidate: Each call can walk O(m·n · 4 · 3^(L−1)) paths, and there are W words. At the limits that bound is 3 × 10⁴ · 144 · 4 · 3⁹, about 3.4 × 10¹¹.
The bound is loose on random grids. In the measurement at the end of this page, on random 12 × 12 grids of four letters, 30,000 words took 182.51 ms. exist‘s letter count and rarer end stop most of those searches within a few letters.
atlimit.ts built a grid that defeats both checks: 12 × 12 of a, with the letters b to z once each, no two side by side. Each of the 30,000 words is aaaaa, four different rare letters, then a. Every letter is on the grid, and both ends are a, so each word walks every path of five a cells from every a cell, and none is found. It took 7,044.5 ms.
Interviewer: What does it repeat?
Candidate: All 30,000 words start with aaaaa, and each one walks those same paths again. If the words were in a trie, one walk over the grid could follow the trie instead. A path goes on only while what it spells is the start of some word, and a node with a word on it means a find.
Candidate: I build the trie with the whole word stored on its last node. That saves rebuilding the word from the path.
class WordNode {
children = new Map<string, WordNode>();
word: string | null = null; // set on the node where a word ends
}
function buildTrie(words: string[]): WordNode {
const root = new WordNode();
for (const word of words) {
let node = root;
for (const letter of word) {
let next = node.children.get(letter);
if (next === undefined) {
next = new WordNode();
node.children.set(letter, next);
}
node = next;
}
node.word = word;
}
return root;
}
// Put the words in a trie and search the grid once: a path continues only while it spells a prefix of some word.
// Time O(S + m * n * 4 * 3^(L-1)), S = total letters of the words; the grid search no longer depends on W.
// Memory O(S) for the trie, O(L) for the stack.
export function findWordsTrie(board: string[][], words: string[]): string[] {
const root = buildTrie(words);
const rows = board.length, cols = board[0].length;
const found = new Set<string>(); // a word reached by two paths is reported once
const step = (r: number, c: number, parent: WordNode): void => {
if (r < 0 || c < 0 || r >= rows || c >= cols) return;
const letter = board[r][c];
const node = parent.children.get(letter); // "#" (a used cell) is never a child
if (node === undefined) return;
if (node.word !== null) found.add(node.word);
board[r][c] = "#";
step(r + 1, c, node);
step(r - 1, c, node);
step(r, c + 1, node);
step(r, c - 1, node);
board[r][c] = letter;
};
for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) step(r, c, root);
return [...found];
}
Candidate: step gets the trie node for the letters before (r, c). If the cell’s letter isn’t one of its children, no word continues this way, and the branch ends. That’s the prune, and it works for all words at once. A Set keeps a word found by two paths from being returned twice.
Candidate: Building the trie is O(S), where S is the total number of letters in the words. The grid search is O(m·n · 4 · 3^(L−1)), with no W in it.
On the built grid, findWordsTrie took 9.9 ms in atlimit.ts. The lab names this function findWordsTrie. The version to paste into LeetCode is findWords, below.
Interviewer: Once a word is found, does the search still walk its branch?
Candidate: Yes, and it can find it again. I’d clear the word from its node when I find it, so it’s returned once without the Set. And on the way back, if a node has no word and no children left, I delete it from its parent. Then no later path walks a branch whose words are all found.
// The same search, and it shrinks the trie as it goes: a found word is cleared from its node, and a node with
// no word and no children left is cut from its parent, so no later path walks a finished branch again.
// Same worst-case bound, O(S + m * n * 4 * 3^(L-1)) time and O(S) memory; much less work once words are found.
function findWords(board: string[][], words: string[]): string[] {
const root = buildTrie(words);
const rows = board.length, cols = board[0].length;
const found: string[] = [];
const step = (r: number, c: number, parent: WordNode): void => {
if (r < 0 || c < 0 || r >= rows || c >= cols) return;
const letter = board[r][c];
const node = parent.children.get(letter);
if (node === undefined) return;
if (node.word !== null) {
found.push(node.word);
node.word = null; // report it once
}
board[r][c] = "#";
step(r + 1, c, node);
step(r - 1, c, node);
step(r, c + 1, node);
step(r, c - 1, node);
board[r][c] = letter;
if (node.children.size === 0 && node.word === null) parent.children.delete(letter);
};
for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) step(r, c, root);
return found;
}
export { findWords };
Candidate: To paste this into LeetCode, I paste WordNode and buildTrie with it.
On the built grid nothing is found, so nothing is cut, and findWords took 10.1 ms, the same as findWordsTrie. The cut pays off when many words are found; the measurement at the end of this page shows it.
Interviewer: Trace your example.
Figure 9 follows findWords on code axys tpin. The scan goes row by row; a cell whose letter isn’t a child of the root returns at once and isn’t shown. Each line is a call that found its letter in the trie.
cell letter spelled then
(0,0) c c
(1,0) a ca
(2,0) t cat found cat; cut "cat", then "ca"
(0,1) o co
(0,2) d cod
(1,2) y cody found cody; cut "cody", then "cod"
(0,2) d d start of dog
(0,1) o do no g beside it
(1,3) s s start of spin: no p beside it
(2,3) n n start of nip
(2,2) i ni
(2,1) p nip found nip; cut "nip", "ni", then "n"
Figure 9: co stays because coat still hangs below it, and each found word’s branch is cut on the way back, so no later start can walk it again.
Candidate: The answer is cat, cody, nip. From co, the step down meets x, which isn’t a child, so coat is never spelled.
Pause and predict. On the grid aaa aaa with the one word aa, how many times would a version that never clears node.word report aa?
Fourteen times. The grid has seven pairs of side neighbors, and each pair spells aa in two directions. With node.word = null, the first find clears it, and aa is reported once.
Interviewer: Final cost?
Candidate: O(S + m·n · 4 · 3^(L−1)) time: building the trie, then a grid search bounded by the 144 cells and 10 letters, not by W. At the limits that’s S ≤ 3 × 10⁵ and about 1.1 × 10⁷ paths. O(S) memory for the trie, and O(L) for the waiting calls.
Interviewer: Why a trie, and not a Set of the words plus a Set of every prefix?
The Candidate’s answer
Candidate: That works too. But each step would build the spelled string and hash it, up to 10 letters per lookup. The trie moves one node per letter and never builds a string. The prefix set also can’t shrink as words are found.
This version isn’t in the lab.
Interviewer: How much memory does the trie take here?
The Candidate’s answer
Candidate: At most one node per letter of the words, so at most 3 × 10⁵ nodes. If a node costs about what 208’s nodes cost, 224 bytes, that’s about 67 MB in the worst case, and less when words share prefixes.
Two mistakes are common here:
- Not clearing a found word. A trie search that pushes every word it reaches, and never clears it, returns
aa14 times foraaa aaaand["aa"]. Setnode.word = nullafter a find, or collect into aSet. - Not restoring the cell. As in 79, a dead end blocks a later path. The lab runs the dead-end grids of 79 in every turn and mirror image for all three versions, and checks after every call that the board is unchanged.
Lab folder: module-10/0212-word-search-ii/ in the course repository.
Measured: Word Search II, once per word against a trie
Word Search II, the problem at the top of this page, is the one this module measures, with bench.ts from DSA Module 1. Each input is a new 12 × 12 grid, the limit, over four letters, with W words of 10 letters. Half of the words are read along a random path on the grid, and half are random. The script also measures 208’s trie nodes.
// measure.ts: Module 10's measurement. 212. Word Search II, Word Search once per word against one search with a trie.
// Run from the repository root: node --expose-gc module-10/measure.ts (without --expose-gc the memory part is skipped)
import { bench } from "../shared/bench.ts";
import { findWordsEach, findWordsTrie, findWords } from "./0212-word-search-ii/solution.ts";
import { Trie } from "./0208-implement-trie-prefix-tree/solution.ts";
import { toBoard, randomGrid } from "./grids.ts";
let sink = 0;
const randomLetters = (length: number, letters: number) =>
Array.from({ length }, () => String.fromCharCode(97 + Math.floor(Math.random() * letters))).join("");
// A word read along a random path of `length` cells that never reuses a cell (so it is on the board).
function wordOnBoard(g: string[], length: number): string {
for (;;) {
let r = Math.floor(Math.random() * g.length), c = Math.floor(Math.random() * g[0].length);
const used = new Set([r * g[0].length + c]);
let word = g[r][c];
while (word.length < length) {
const next = [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]].filter(
([y, x]) => y >= 0 && x >= 0 && y < g.length && x < g[0].length && !used.has(y * g[0].length + x),
);
if (next.length === 0) break; // stuck: start again
[r, c] = next[Math.floor(Math.random() * next.length)];
used.add(r * g[0].length + c);
word += g[r][c];
}
if (word.length === length) return word;
}
}
// A 12 x 12 board (the limit) over 4 letters, and W words of 10 letters (the limit): half read from the board,
// half random (most of those are not on it). Duplicates are dropped, as the page promises unique words.
function makeInput(w: number): { board: string[][]; words: string[] } {
const g = randomGrid(12, 12, 4);
const words = new Set<string>();
for (let i = 0; i < w; i++) words.add(i % 2 === 0 ? wordOnBoard(g, 10) : randomLetters(10, 4));
return { board: toBoard(g), words: [...words] };
}
const sample = makeInput(30_000);
const a = [...findWordsEach(sample.board, sample.words)].sort();
const b = [...findWords(sample.board, sample.words)].sort();
console.log(`W = 30,000 asked: ${sample.words.length} unique words, ${a.length} found; same answer: ${JSON.stringify(a) === JSON.stringify(b)}`);
const sizes = [1_000, 10_000, 30_000];
bench("Word Search once per word (findWordsEach)", sizes, makeInput, ({ board, words }) => (sink += findWordsEach(board, words).length));
bench("trie, one grid search (findWordsTrie)", sizes, makeInput, ({ board, words }) => (sink += findWordsTrie(board, words).length));
bench("trie that drops found words (findWords)", sizes, makeInput, ({ board, words }) => (sink += findWords(board, words).length));
// Memory: heap per trie node (208's Trie, a Map per node), after gc. 500 random words of 2,000 letters over 26
// letters share almost nothing past their first letters, so the trie has about 10^6 nodes.
const gc = (globalThis as { gc?: () => void }).gc;
if (gc) {
const words = Array.from({ length: 500 }, () => randomLetters(2000, 26));
gc();
const before = process.memoryUsage().heapUsed;
const trie = new Trie();
for (const w of words) trie.insert(w);
gc();
const after = process.memoryUsage().heapUsed;
let nodes = 0;
const stack = [trie.root];
while (stack.length > 0) {
const node = stack.pop()!;
nodes++;
for (const child of node.children.values()) stack.push(child);
}
sink += nodes;
console.log(`\ntrie of 500 words x 2,000 letters: ${nodes.toLocaleString("en-US")} nodes, ${((after - before) / 1e6).toFixed(1)} MB, ${((after - before) / nodes).toFixed(1)} bytes per node`);
}
console.log(`\nsink ${sink}`);
bench runs each size once to warm up, then five times on fresh inputs, and prints the median and how many times slower each size is than the one before. The n column is W, the number of words asked for; dropping repeats leaves a few percent fewer. Making the inputs isn’t timed. --expose-gc lets the script run the garbage collector before it reads the heap size, so the memory line counts only the trie.
Pause and predict. When W grows 10 times, from 1,000 to 10,000 words, by how much should each version’s time grow?
Here is what node --expose-gc module-10/measure.ts printed:
W = 30,000 asked: 28385 unique words, 17562 found; same answer: true
Word Search once per word (findWordsEach)
n median ms x prev
1,000 6.34
10,000 61.96 9.8
30,000 182.51 2.9
trie, one grid search (findWordsTrie)
n median ms x prev
1,000 3.57
10,000 18.72 5.2
30,000 43.94 2.3
trie that drops found words (findWords)
n median ms x prev
1,000 1.93
10,000 10.32 5.4
30,000 25.11 2.4
trie of 500 words x 2,000 letters: 999,378 nodes, 223.9 MB, 224.0 bytes per node
sink 1430075
These numbers come from one run on an Apple M2 laptop with macOS and Node.js 24.22.1. Your numbers will differ, but the ratios should look alike.
Once per word grew 9.8 times for 10 times the words, and 2.9 times for 3 times. Each word pays for its own grid search, here about 6 µs, because exist‘s checks and wrong letters end most searches early.
Both trie versions grew less than W: 5.2 and 5.4 times for 10 times the words. The grid search is bounded by the 144 cells and 10 letters. What still grows with W is building the trie, O(S), and the walks that reach more real words. At 30,000 words, the trie that drops found words took 25.11 ms against 182.51 ms, about 7 times faster.
On these random grids, all three versions pass. The gap is much larger on the built grid in atlimit.ts, 7,044.5 ms against 10.1 ms, because there every word walks every path of five a cells. So once per word is an answer that can pass, and the trie is the answer whose cost the limits can’t push up with W. sink adds up the counts, so V8 can’t skip the calls.
Underneath: recursion, copies and Map nodes in JavaScript
Every search in this module is recursive, and its depth is the length of the path. That’s at most 10 for Subsets, 20 for Combination Sum, 6 for Permutations, 15 for Word Search and 10 for Word Search II. V8 limits the call stack by bytes, 984 KB by default on this build (node --v8-options), which allows a few thousand calls. So unlike Module 9’s grids, the depth is never the problem here. The number of nodes is, and it runs out of time long before the depth runs out of stack. DSA Module 10 shows this with its tree sizes.
Every recorded answer is a new array, so copying only when you record matters. DSA Module 10 timed the subsets walk at 20 items: counting with a shared path took 9.21 ms, and copying every subset 173.46 ms. A version that built a new array on every call with concat took 377.96 ms. The shared path with push and pop makes only the copies the answer needs.
A trie node here is an object with its own Map. On this machine, measure.ts found 224.0 bytes per node. DSA Module 12 measured about 235 bytes per node on another machine, and a trie 24 times the size of a Set of the same random words. So a trie pays off when many prefix questions hit the same words, as in 212. For exact lookups only, a Set is as fast and much smaller.
Cheat sheet
Figure 10 maps each problem in this module to the sign that pointed to its solution.
sign no. the move cost
every subset 78 record at each node, i + 1 O(2^n · n)
totals, numbers reused 39 sort, start at i, break O(N^(T/M) · T/M)
every ordering 46 used flags, undo both O(n · n!)
a word as a grid path 79 mark #, restore, 2 checks O(m·n·4·3^(L-1))
prefix questions 208 trie, a Map per node O(L) per call
many words, one grid 212 grid walk along a trie O(S + m·n·4·3^(L-1))
Figure 10: each problem is a search tree; a start index, a flag or a trie decides which branches exist, and a prune cuts the rest.
- Shape: choose, explore, undo on one shared path; record
[...path], neverpath. - No repeats: start each level at
start(i + 1for each item once,ifor reuse); sort first if youbreak. - Grid paths: write
#into the cell, check bounds before reading it, and restore it before every return. - Trie: a
Mapper node plus an end mark (isWord, or the word itself); about 224 bytes per node on this build. - Size: 2ⁿ subsets, about e · n! orderings; the limits are small because the answers are large.
- Next: Module 11 works dynamic programming, starting from Coin Change by plain recursion, which never finishes on a large amount.
Sources
- LeetCode problem pages, checked on 2026-11-20: 78, 39, 46, 79, 208, 212, and 90, 40, 47 and 211 for follow-ups.
- NIST Dictionary of Algorithms and Data Structures: backtracking and trie.
- ECMAScript specification: section 24.1,
Map. - Node.js documentation: TypeScript, test runner.