Suppose you pick a project team from a list of candidates, each with a daily cost, and you want every team that fits a daily budget. Here is a first answer, an excerpt of opening-slow.ts from the lab:
// A candidate has a unique name and a daily cost.
export type Candidate = { name: string; cost: number };
// Teams of exactly three: one loop per member. O(n^3) time. A team of four needs a fourth loop.
export function teamsOfThree(cands: Candidate[], budget: number): string[][] {
const teams: string[][] = [];
for (let a = 0; a < cands.length; a++)
for (let b = a + 1; b < cands.length; b++)
for (let c = b + 1; c < cands.length; c++)
if (cands[a].cost + cands[b].cost + cands[c].cost <= budget)
teams.push([cands[a].name, cands[b].name, cands[c].name]);
return teams;
}
// Teams of any size: build every subset by doubling a list, then keep the ones that fit.
// O(2^n * n) time and memory: all 2^n subsets exist at once, even those far over budget.
export function allTeamsBrute(cands: Candidate[], budget: number): string[][] {
let subsets: Candidate[][] = [[]];
for (const c of cands) subsets = subsets.concat(subsets.map((s) => [...s, c])); // doubles each time
return subsets
.filter((s) => s.length > 0 && s.reduce((sum, c) => sum + c.cost, 0) <= budget)
.map((s) => s.map((c) => c.name));
}
teamsOfThree needs one loop per member, so it can’t list teams of any size. allTeamsBrute can: it builds every subset of the candidates (every selection, from no one to everyone) and keeps the ones that fit. In one run, it took about 340 ms for 20 candidates, and every two more candidates made it about four times slower.
This module builds only the teams that can still fit. It chooses a candidate, explores every team that includes it, and then undoes the choice.
After this module, you can:
- list every team under a budget by choosing, exploring and undoing, without building every subset first
- cut off a branch with a sort and a
break, and say what that costs - pick the subsets, orders or groups-of-k shape from the words of a problem
- count the nodes of a search before you run it, and tell whether it can finish
- keep the memory of a search small: share one path, copy only what you record, or hand each result to the caller
Measure building every subset
Make a folder for the module, as in Module 1, and copy bench.ts into it unchanged:
mkdir module-10 && cd module-10 && echo '{ "type": "module" }' > package.json
Then copy opening-slow.ts from the module-10 folder of the course repository. makeCandidates(n) gives n candidates with daily costs from 100 to 999. The benchmark’s budget is 1,500 a day.
Pause and predict. allTeamsBrute takes about 25 ms for 16 candidates. How long does it take for 18 and for 20?
Here is what node opening-slow.ts printed:
teamsOfThree, budget 1000: [["Ana","Bo","Cy"],["Ana","Bo","Di"]]
allTeamsBrute, budget 700: [["Ana"],["Bo"],["Ana","Bo"],["Cy"],["Bo","Cy"],["Di"],["Ana","Di"],["Bo","Di"]]
allTeamsBrute, budget 1500
n median ms x prev
16 25.05
18 83.66 3.3
20 344.29 4.1
Every table in this module comes from one run on an Intel Core i7-9750H laptop (x86_64, 6 cores, macOS) with Node.js 26.13.1. Your numbers will differ, but the ratios should look alike.
Each candidate doubles the list of subsets, so 20 candidates make 2²⁰ = 1,048,576 subsets. Each subset holds up to n candidates, so allTeamsBrute is O(2ⁿ · n) in time and in memory. A cost like 2ⁿ is exponential: each extra item multiplies the work, instead of adding to it. So two more candidates multiply the subsets by 4, and the rows grew 3.3 and 4.1 times.
The run at 20 candidates held all of those subsets in memory at once. It did that to return the few hundred or few thousand teams that fit.
Rule: When a search builds every possible answer before it checks one, count the possible answers first: 2ⁿ for the subsets of n items.
Choose, explore, undo
Think about how you would list the teams by hand. Sort the candidates by cost: Bo 200, Ana 300, Di 400 and Cy 500, with a budget of 700. Pick Bo, and 500 is left. Then pick a second member from the candidates after Bo: Ana, and 200 is left.
Di costs 400, more than 200, and every candidate after Di costs more still, so stop there. Take Ana back out, and try Di as the second member instead.
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: each node is a partial answer, and each child adds one more choice. Here every node is a team, and the root at the top is the empty team.
Figure 1 is the search tree for the four candidates, as trace-demo.ts in the lab prints it. Each line is one node, and “left” is the budget still left.
(start) left 700
+-- [Bo] left 500
+-- [Bo, Ana] left 200
+-- Di 400 > 200: break
+-- [Bo, Di] left 100
+-- Cy 500 > 100: break
+-- [Bo, Cy] left 0
+-- [Ana] left 400
+-- [Ana, Di] left 0
+-- Cy 500 > 0: break
+-- Cy 500 > 400: break
+-- [Di] left 300
+-- Cy 500 > 300: break
+-- [Cy] left 200
Figure 1: every node is a team that fits, and break ends a loop at the first candidate that costs too much, because every later candidate costs more.
The search walks this tree depth first: it goes down one branch as far as it can before it tries the next, as Module 6 walked folders. The path is the list of choices from the root to the current node, here the names in the current team. So the search keeps only one list, the path, and changes it as it moves.
Here is the search, an excerpt of opening-fast.ts (the full file also checks it against allTeamsBrute and times both):
// Choose a candidate, explore every team that includes it, undo the choice.
// O(n log n) to sort, then O(T * n) for T teams under budget: every node of the
// search tree is a team, copied once (up to n names). O(n) memory besides the output.
export function teamsUnderBudget(cands: Candidate[], budget: number): string[][] {
const sorted = cands.toSorted((a, b) => a.cost - b.cost);
const teams: string[][] = [];
const path: string[] = [];
function explore(start: number, left: number): void {
for (let i = start; i < sorted.length; i++) {
if (sorted[i].cost > left) break; // sorted: every later candidate costs more
path.push(sorted[i].name); // choose
teams.push([...path]); // record a copy: path keeps changing
explore(i + 1, left - sorted[i].cost); // explore
path.pop(); // undo
}
}
explore(0, budget);
return teams;
}
The lines marked choose, explore and undo are the whole pattern. path.push chooses a candidate, and the recursive call explores every team that starts with the path. Then path.pop undoes the choice, so the next candidate starts from the same team. Figure 2 traces the path array through the same walk, as trace-demo.ts prints it.
step action path left
1 choose Bo, record [Bo] 500
2 choose Ana, record [Bo, Ana] 200
3 Di too dear: break [Bo, Ana] 200
4 undo Ana [Bo] 500
5 choose Di, record [Bo, Di] 100
6 Cy too dear: break [Bo, Di] 100
7 undo Di [Bo] 500
8 choose Cy, record [Bo, Cy] 0
9 undo Cy [Bo] 500
10 undo Bo [] 700
11 choose Ana, record [Ana] 400
12 choose Di, record [Ana, Di] 0
13 Cy too dear: break [Ana, Di] 0
14 undo Di [Ana] 400
15 Cy too dear: break [Ana] 400
16 undo Ana [] 700
17 choose Di, record [Di] 300
18 Cy too dear: break [Di] 300
19 undo Di [] 700
20 choose Cy, record [Cy] 200
21 undo Cy [] 700
Figure 2: the path grows by one name at each choice and shrinks by one at each undo, so one array serves the whole walk.
Why does teams.push([...path]) copy the path instead of pushing path itself? Because the path keeps changing. Every entry would point to the same array, which is empty when the walk ends. “Common mistakes” shows that bug.
Rule: Push a choice, explore, pop it. Record a copy of the path, never the path itself.
What backtracking costs, measured
Each node is a team that fits, and recording it copies up to n names. Each loop also makes at most one failed check, the one that ends in break. So with T teams under the budget, teamsUnderBudget is O(T · n) time, plus O(n log n) for the sort.
A stack frame is the memory one function call holds while it runs: its arguments and its local variables. Besides the output, teamsUnderBudget uses O(n) memory for:
- the sorted copy of the candidates
- the path
- one stack frame per name in the path
Pause and predict. allTeamsBrute would need 2⁸⁰ subsets for 80 candidates. How long does teamsUnderBudget take for 80?
node opening-fast.ts checks both versions against each other on 50 random lists. Then it counts the teams in five lists of each size and times both versions:
teamsUnderBudget, budget 700: [["Bo"],["Bo","Ana"],["Bo","Di"],["Bo","Cy"],["Ana"],["Ana","Di"],["Di"],["Cy"]]
same teams as allTeamsBrute on 50 random lists: true
n = 20: teams under 1500 in 5 random lists: 1303, 301, 445, 2351, 686
n = 40: teams under 1500 in 5 random lists: 34968, 19191, 8754, 17927, 80824
n = 80: teams under 1500 in 5 random lists: 518117, 3313558, 250852, 1930258, 683579
allTeamsBrute, budget 1500
n median ms x prev
16 10.75
18 74.15 6.9
20 300.97 4.1
teamsUnderBudget, budget 1500
n median ms x prev
16 0.13
18 0.13 1.0
20 0.06 0.5
teamsUnderBudget, budget 1500, more candidates
n median ms x prev
20 0.09
40 1.86 21.1
80 77.55 41.8
teamsUnderBudget, no budget limit (every team fits)
n median ms x prev
16 3.56
18 35.11 9.8
20 195.96 5.6
Both versions found the same teams. At 20 candidates, building every subset took 300.97 ms and backtracking 0.06 ms. Figure 3 draws the rows they share.
median ms for every team under 1,500 (each # is about 7 ms)
n = 16 brute force ## 10.75
backtracking | 0.13
n = 18 brute force ########### 74.15
backtracking | 0.13
n = 20 brute force ############################################ 300.97
backtracking | 0.06
Figure 3: building every subset grew about 4 to 7 times per two candidates, while backtracking stayed under a millisecond, because it visits only teams that fit.
The backtracking rows for 16 to 20 candidates are too small to compare, because a random list of 20 held from 301 to 2,351 teams. So these rows mostly measure which lists came out.
The row for 80 candidates is the one that counts. It took 77.55 ms for lists with 250,852 to 3,313,558 teams. The brute force would build 2⁸⁰ ≈ 1.2 × 10²⁴ subsets. At the 1.8 × 10⁸ nodes per second that a counting walk reaches later in this module, that’s about 200 million years (not run).
The last table has no budget limit, so every subset is a team, and T = 2ⁿ. Then backtracking is as exponential as the brute force: 3.56, 35.11 and 195.96 ms. No search can list 2ⁿ answers in less than 2ⁿ steps.
Rule: A backtracking search costs about the number of nodes it visits, so it’s fast only when few partial answers can still work.
Cut off a branch before you walk it
The count of nodes is the cost, so the way to make backtracking faster is to visit fewer nodes. To prune is to stop exploring a branch as soon as you can tell that no answer lies under it.
pruning.ts in the lab lists the same teams three ways and counts how many candidates each one looks at:
- No prune: it walks every subset and checks the budget only to decide whether to count a team.
continue: it skips a candidate that doesn’t fit, but still looks at every later one.- Sort and
break: this isteamsUnderBudget, which stops at the first candidate that doesn’t fit.
node pruning.ts printed:
n budget teams no prune continue sort + break
16 1500 525 65,535 2,079 1,021
16 3000 9,238 65,535 18,412 15,267
20 1500 900 1,048,575 2,841 1,747
20 3000 26,615 1,048,575 56,931 45,885
Without pruning, the search looks at 2ⁿ − 1 candidates whatever the budget, because it walks the whole tree. With 20 candidates and a budget of 1,500, continue already cuts that from 1,048,575 looks to 2,841. A team that is over the budget never gets explored, and neither does anything below it.
If continue already skips teams over the budget, what does the sort add? A bound. With break, each loop makes at most one failed look, so the looks are at most the teams plus the nodes, 2T + 1. continue has no such bound, because its looks depend on the order of the list.
A prune has three costs:
- The sort is O(n log n), plus a copy of the list.
breakis correct only on sorted input. “Common mistakes” shows what it misses otherwise.- A prune runs its check at every node, so a check that costs more than the branches it saves makes the search slower.
Rule: Prune on the earliest sign that a branch can’t work. Sort the choices so that the first failure means every later choice fails too, then
break.
Three shapes: subsets, orders, groups of k
Most backtracking problems use one of three trees. shapes.ts in the lab writes each one, plus a second way to walk subsets. The subsections below show each function as an excerpt of that file.
Copy shapes.ts from the lab and run it. node shapes.ts printed:
subsets(abc): - a ab abc ac b bc c
subsetsByChoice(abc): abc ab ac a bc b c -
orderings(abc): abc acb bac bca cab cba
combinations(abcd, 2): ab ac ad bc bd cd
Subsets
subsets is the teams search without a budget:
// Every subset, "loop from start" shape: every node of the tree is one subset.
// 2^n nodes, each copied (up to n items): O(2^n * n) time. O(n) memory besides the output.
export function subsets<T>(items: T[]): T[][] {
const out: T[][] = [];
const path: T[] = [];
function explore(start: number): void {
out.push([...path]); // every node is a subset
for (let i = start; i < items.length; i++) {
path.push(items[i]); // choose
explore(i + 1); // explore
path.pop(); // undo
}
}
explore(0);
return out;
}
It loops from start, so a later item never comes before an earlier one, and each subset appears once. Every node is recorded, so it’s O(2ⁿ · n) time.
The second way to walk the subsets has one level per item, where each level either takes its item or skips it. A leaf is a node with no children, and in this tree only the leaves are full answers:
// Every subset, "one level per item" shape: at level i, either take items[i] or skip it.
// 2^(n+1) - 1 nodes, and the 2^n leaves are the subsets. O(2^n * n) time, O(n) memory besides the output.
export function subsetsByChoice<T>(items: T[]): T[][] {
const out: T[][] = [];
const path: T[] = [];
function explore(i: number): void {
if (i === items.length) {
out.push([...path]); // a leaf: every item has been decided
return;
}
path.push(items[i]); // choice 1: take items[i]
explore(i + 1);
path.pop();
explore(i + 1); // choice 2: skip it
}
explore(0);
return out;
}
Figure 4 shows both trees for the subsets of a, b and c, as trace-demo.ts prints them.
loop from start: 8 nodes, every node is a subset
{}
a
ab
abc
ac
b
bc
c
one level per item: 15 nodes, the leaves (*) are the subsets
{}
take a: a
take b: ab
take c: abc *
skip c: ab *
skip b: a
take c: ac *
skip c: a *
skip a: {}
take b: b
take c: bc *
skip c: b *
skip b: {}
take c: c *
skip c: {} *
Figure 4: both trees end with the same 8 subsets, but the first has a subset at every node, and the second only at its 8 leaves.
So the loop-from-start tree has 2ⁿ nodes, and the one-level-per-item tree has 2ⁿ⁺¹ − 1. Both are O(2ⁿ).
Use the one-level-per-item shape when each level has its own list of choices, such as one value for each setting. Then a loop over the choices replaces “take” and “skip”. The signs for subsets are “every combination of”, “any number of”, or a budget that a set of items must fit.
Orders
A permutation is one order of all n items. There are n! of them, read “n factorial”: n · (n − 1) · … · 2 · 1. So 3! = 6, and 10! = 3,628,800.
// Every order of the items (they are distinct). n! leaves, about e * n! nodes, and each node
// scans n flags: O(n * n!) time. O(n) memory besides the output.
export function orderings<T>(items: T[]): T[][] {
const out: T[][] = [];
const path: T[] = [];
const used = new Array<boolean>(items.length).fill(false);
function explore(): void {
if (path.length === items.length) {
out.push([...path]);
return;
}
for (let i = 0; i < items.length; i++) {
if (used[i]) continue; // already in this order
used[i] = true; // choose
path.push(items[i]);
explore(); // explore
path.pop(); // undo both changes
used[i] = false;
}
}
explore();
return out;
}
orderings loops from 0 at every level, because any unused item can come next. The used array marks the items already in the path, and the undo clears the mark. Figure 5 shows its tree for a, b and c, one depth per line, as trace-demo.ts prints it.
depth 0 1 node {}
depth 1 3 nodes a b c
depth 2 6 nodes ab ac ba bc ca cb
depth 3 6 nodes abc acb bac bca cab cba
Figure 5: each level has one choice fewer than the level above, so the 6 orders sit under 3 · 2 · 1 branches.
It’s O(n · n!) time, which the next section counts, and O(n) memory besides the output. The signs are “every order”, “every schedule” or “every arrangement”. When some orders aren’t allowed, prune at the choice that breaks the rule instead of filtering the n! orders afterward.
Groups of k
A combination is a group of k items where order doesn’t count. The number of groups of k from n items is written C(n, k), and it equals n! / (k! · (n − k)!). So C(4, 2) = 6: the pairs ab, ac, ad, bc, bd and cd above.
// Every group of exactly k items. C(n, k) leaves, each copied (k items): O(C(n, k) * k) for the output,
// and the prune keeps the tree close to that size. O(k) memory besides the output.
export function combinations<T>(items: T[], k: number): T[][] {
const out: T[][] = [];
const path: T[] = [];
function explore(start: number): void {
if (path.length === k) {
out.push([...path]);
return;
}
const need = k - path.length; // items still to choose
for (let i = start; i <= items.length - need; i++) { // prune: leave room for the rest
path.push(items[i]);
explore(i + 1);
path.pop();
}
}
explore(0);
return out;
}
combinations loops from start like subsets, but records only full groups. It also leaves room for the rest: with need items still to choose, the loop stops at items.length - need. Figure 6 shows what that saves for groups of 3 from a, b, c and d, as trace-demo.ts prints it.
no prune 15 nodes: {} a ab abc* abd* ac acd* adx b bc bcd* bdx cx cdx dx
prune 10 nodes: {} a ab abc* abd* ac acd* b bc bcd*
(* = a group of 3, x = a dead end: too few items left)
Figure 6: without the prune, the search walks 5 branches that run out of items before they reach 3, and the prune never enters them.
The output is O(C(n, k) · k), and the pruned tree is close to that size. The signs are “exactly k”, “every pair” or “every team of four”.
Count the nodes before you run
Before you run a backtracking search, count its nodes. That count, not the code, decides whether the search finishes.
Pause and predict. The tree of every order of 10 items has 10! = 3,628,800 leaves. How many nodes does it have in all?
node-count.ts in the lab counts the nodes of each tree with the walks of shapes.ts, and compares them with the formulas:
subsets n nodes (loop from start) nodes (one level per item) 2^n
3 8 15 8
10 1,024 2,047 1,024
20 1,048,576 2,097,151 1,048,576
orderings n nodes leaves n! nodes / n!
3 16 6 6 2.6667
8 109,601 40,320 40,320 2.7183
10 9,864,101 3,628,800 3,628,800 2.7183
combinations n k C(n, k) nodes, no prune nodes, prune
5 3 10 26 20
20 3 1,140 1,351 1,330
20 10 184,756 616,666 352,716
n 2^n n!
10 1,024 3.63e+6
15 32,768 1.31e+12
20 1,048,576 2.43e+18
25 33,554,432 1.55e+25
30 1,073,741,824 2.65e+32
The orders tree for 10 items has 9,864,101 nodes, 2.7183 times its leaves. That ratio is the number e ≈ 2.71828, a constant from mathematics, so the tree has about e · n! nodes. Each node also scans n items to find the unused ones. So listing every order is O(n · n!) time.
The groups-of-k tree has C(n, k) leaves. The “no prune” column also walks branches that can’t reach k items, such as a group that starts with the last item. For C(20, 10), the prune cut the nodes from 616,666 to 352,716, with the same 184,756 groups.
The last table is why exponential searches stop working so suddenly. Every extra item doubles 2ⁿ, while 30! has 33 digits.
Where an exponential search stops
limits.ts in the lab times the subsets walk and the orders walk with nothing recorded, so the time is the walk itself:
countSubsets (n items)
n median ms x prev
20 5.68
22 23.16 4.1
24 90.91 3.9
26 368.39 4.1
countOrderings (n items)
n median ms x prev
8 1.99
9 18.85 9.5
10 209.29 11.1
The subsets walk grew 4 times per two items. At 26 items it visited 2²⁶ = 67,108,864 nodes in 368.39 ms, about 1.8 × 10⁸ nodes per second. So 30 items would take about 6 seconds without any work per node (not run).
The orders walk grew 9.5 and 11.1 times per item. The model n · e · n! predicts 10.1 and 11.1. It predicts 12.1 for 11 items, about 2.5 seconds (not run).
With real work per node, such as a copy, the limit drops further: subsets to about 20 to 25 items, and orders to about 10.
Rule: Count the nodes before you run: 2ⁿ for subsets, about e · n! for orders, about C(n, k) for groups of k. Then divide by about 10⁸ per second.
Underneath: backtracking in JavaScript
The depth is small, and the tree is not
Module 6 measured the recursion limit in Node.js at about 5,000 to 14,000 stack frames. A backtracking search is recursive, but its depth is the length of the path: at most n, the number of items. A tree with n = 30 levels already has 2³⁰ nodes. So the search runs out of time long before it runs out of stack, and recursion is fine here.
What a result costs
Every recorded result is a new array. copy-vs-share.ts in the lab times the subsets walk three ways:
countSubsetsshares one path and only counts.subsetsshares one path and copies it at each node.subsetsConcathas no shared path and builds a new array withconcaton every call.
countSubsets is subsets with the copy replaced by count++. Here is subsetsConcat, an excerpt of that file:
// No shared path and no undo: concat builds a new array on every call. O(2^n * n) time and memory.
export function subsetsConcat(xs: number[]): number[][] {
const out: number[][] = [];
function explore(start: number, path: number[]): void {
out.push(path);
for (let i = start; i < xs.length; i++) explore(i + 1, path.concat(xs[i]));
}
explore(0, []);
return out;
}
node copy-vs-share.ts printed:
countSubsets (shared path, no output)
n median ms x prev
16 0.60
18 2.30 3.9
20 9.21 4.0
subsets (shared path, copy per node)
n median ms x prev
16 5.83
18 27.84 4.8
20 173.46 6.2
subsetsConcat (new array per call)
n median ms x prev
16 16.42
18 65.15 4.0
20 377.96 5.8
Counting took 9.21 ms at 20 items, and copying every subset 173.46 ms, 19 times as long. The concat version needs no undo, but it builds an array at every call, and it took 377.96 ms. The copying versions also grew faster than 2ⁿ · n predicts: 4.8 and 6.2 times per two items, against 4.4. “Going deeper” shows where that extra time goes.
So copy the path only when you record a result, and record only what the caller needs.
Hand each result to the caller
When the caller only needs to look at each result once, don’t build the list. Pass a callback: a function the search calls with each result. Here is eachSubset, an excerpt of streaming.ts in the lab:
// Calls visit(path) at every node. The path is shared: visit must copy it to keep it.
// O(2^n) time plus the work of visit, O(n) memory.
export function eachSubset(xs: number[], visit: (path: readonly number[]) => void): void {
const path: number[] = [];
function explore(start: number): void {
visit(path);
for (let i = start; i < xs.length; i++) {
path.push(xs[i]);
explore(i + 1);
path.pop();
}
}
explore(0);
}
In one run, adding up the subset sizes through eachSubset took 10.83 ms at 20 items, close to the 9.21 ms of the counting walk. The cost is that visit must copy the path if it wants to keep it. A generator can hand over results too, but in the same run it was 31 times slower (“Going deeper” shows why).
Other choices, and when they win
- A greedy rule (Module 9) makes each choice once and never undoes it. When a rule is safe, it replaces the whole search.
- Dynamic programming (Module 11) stores the answer to each smaller question once. It helps when the question is “how many” or “the best one”, and the same smaller question comes up under many branches. Counting the teams under a budget, without listing them, depends only on the next candidate and the money left.
- Branch and bound keeps the best answer found so far and prunes every branch that can’t beat it. This course doesn’t cover it.
Listing every answer can’t take fewer steps than there are answers. If the caller needs all of them and there are 2ⁿ, no other pattern beats backtracking.
What changed recently
Nothing changed in backtracking itself. The NIST Dictionary of Algorithms and Data Structures describes it as a depth-first search of a tree of partial solutions. It quotes Golomb and Baumert (1965), who credit D. H. Lehmer with the name “backtrack” (NIST).
JavaScript gained iterator helpers in ES2025, which “Going deeper” uses to stop a generator early.
Common mistakes
mistakes.ts in the lab writes six bugs that are easy to make in a backtracking search, and prints what each one returns.
Pause and predict. Mistake 2 records the shared path, out.push(path), with no copy. What does it return for a, b and c?
node mistakes.ts printed:
1. no pop: - a ab abc abcc abccb abccbc abccbcc
2. no copy: [[],[],[],[],[],[],[],[]]
3. flag not cleared: abc
4. loop from 0: - a ab abc ac acb b ba bac bc bca c ca cab cb cba (16 results, not 8)
5. break, [300, 500, 200], budget 500: [[300],[500],[200]]
break, [200, 300, 500], budget 500: [[200],[200,300],[300],[500]]
6. equal items, xxy: - x xx xxy xy x xy y
skip equal: - x xx xxy xy y
No undo. Without path.pop(), each branch starts with the items of the branch before it. The subsets of a, b and c came out as abcc, abccb and so on. Every push in a search needs a matching pop after the recursive call.
No copy. out.push(path) stores the same array eight times. The walk empties it at the end, so all eight entries are []. Record [...path].
A mark that is never cleared. orderings sets used[i] = true but never sets it back, so after the first order every item looks used. Only abc came out. Undo every change a choice makes: the path and the marks.
Looping from 0 where the shape needs start. A subsets search that loops from 0 lists every order of every subset: 16 results for three items instead of 8. Loop from start for subsets and groups, and from 0 only for orders.
break on a list that isn’t sorted. With costs 300, 500 and 200 and a budget of 500, the search took 300 and then stopped at 500, which didn’t fit. It never tried 200, so it missed the team of 300 and 200. Sort first, or use continue.
Equal items give repeated answers. For x, y and x, the subsets x and xy came out twice. Sort, then skip an item equal to the one before it at the same level, i > start && sorted[i] === sorted[i - 1]. The first equal item still gets its branch, and that branch includes the later ones.
Exercises
The exercises are in the module’s exercises folder, each with a test file, and the solutions are in solutions. Run all the tests with:
node --test "exercises/*.test.ts"
All 24 tests fail until you write the four answers. Each exercise ends with a test that a correct answer without pruning fails on time. The slow folder holds such answers, with a copy of each test.
Exercise 1: a test matrix with rules (easy)
You test a product on several settings, such as the operating system and the browser. A configuration picks one value for every setting, written as name=value. Some pairs of values can’t go together.
Write testMatrix(settings, forbidden): every allowed configuration, with the values in the order of the settings. Start from exercises/test-matrix.ts:
// Exercise 1: each setting has a name and its possible values. A configuration picks one value for
// every setting, in the order of the list, written as "name=value". `forbidden` lists pairs of
// "name=value" that must not appear in the same configuration. Returns every allowed configuration.
export type Setting = { name: string; values: string[] };
export function testMatrix(settings: Setting[], forbidden: [string, string][]): string[][] {
throw new Error("not implemented");
}
With os linux or mac, browser firefox, safari or chrome, and the pair linux and safari forbidden, there are 5 configurations. The tests also cover a forbidden pair written in either order, edge cases such as no settings, and 200 random cases against a brute force. The last test has 10 settings of 4 values and rules that allow 286 of the 4¹⁰ configurations, in under 100 ms.
Hint
Use the one-level-per-item shape of subsetsByChoice: level i picks a value for setting i. What is the earliest moment you can tell that a forbidden pair is in the path?
Solution
// Exercise 1: each setting has a name and its possible values. A configuration picks one value for
// every setting, in the order of the list, written as "name=value". `forbidden` lists pairs of
// "name=value" that must not appear in the same configuration. Returns every allowed configuration.
export type Setting = { name: string; values: string[] };
// One level per setting, one branch per value. A value that forms a forbidden pair with a value
// already chosen ends its branch. O(N * k * r) time for N nodes, k settings and r rules per value
// (N is at most the 1 + V + V^2 + ... + V^k of the full tree for V values per setting).
// O(k) memory besides the output and the rule map.
export function testMatrix(settings: Setting[], forbidden: [string, string][]): string[][] {
const clashes = new Map<string, string[]>(); // "name=value" -> the values it must not meet
for (const [a, b] of forbidden) {
clashes.set(a, [...(clashes.get(a) ?? []), b]);
clashes.set(b, [...(clashes.get(b) ?? []), a]);
}
const out: string[][] = [];
const path: string[] = [];
function explore(i: number): void {
if (i === settings.length) {
out.push([...path]);
return;
}
for (const v of settings[i].values) {
const choice = `${settings[i].name}=${v}`;
if ((clashes.get(choice) ?? []).some((c) => path.includes(c))) continue; // prune
path.push(choice); // choose
explore(i + 1); // explore
path.pop(); // undo
}
}
explore(0);
return out;
}
Cost: each node checks the rules of its value against the path. With N nodes in the pruned tree, k settings and r rules per value, that’s O(N · k · r) time. N is at most the full tree, 1 + V + V² + … + Vᵏ for V values per setting. Besides the output, it uses O(k) memory for the path and the recursion, plus the rule map.
Building all Vᵏ configurations first and then filtering them, as slow/test-matrix.ts does, took 1,631 ms on the last test.
Exercise 2: every deploy order (medium)
A deploy runs its steps one at a time. Each rule [a, b] says that step a must run before step b. Write deployOrders(steps, rules): every order of the steps that follows every rule, or [] if none does. Start from exercises/deploy-orders.ts:
// Exercise 2: every order in which the steps can run. Each rule [a, b] says that step a must run
// before step b, and rules name only steps in the list. Steps are distinct. Returns [] if no
// order follows every rule.
export function deployOrders(steps: string[], rules: [string, string][]): string[][] {
throw new Error("not implemented");
}
For the steps build, migrate, deploy and notify, where build and migrate must come before deploy, there are 8 orders. The tests also cover rules that form a cycle and 200 random cases against a brute force. The last test has 10 steps in two chains of 5, with 252 orders, in under 100 ms.
Hint
Start from orderings. A step is ready when every step it waits for is already in the path. What should the loop do with a step that isn’t ready yet?
Solution
// Exercise 2: every order in which the steps can run. Each rule [a, b] says that step a must run
// before step b, and rules name only steps in the list. Steps are distinct. Returns [] if no
// order follows every rule.
// Orderings with a prune: a step can be chosen only once every step it waits for is chosen.
// O(N * (n + r)) time for N nodes of the pruned tree, n steps and r rules (N is at most about
// e * n!). O(n + r) memory besides the output.
export function deployOrders(steps: string[], rules: [string, string][]): string[][] {
const index = new Map(steps.map((s, i) => [s, i]));
const waitsFor: number[][] = steps.map(() => []);
for (const [a, b] of rules) waitsFor[index.get(b)!].push(index.get(a)!);
const out: string[][] = [];
const path: string[] = [];
const used = new Array<boolean>(steps.length).fill(false);
function explore(): void {
if (path.length === steps.length) {
out.push([...path]);
return;
}
for (let i = 0; i < steps.length; i++) {
if (used[i] || waitsFor[i].some((j) => !used[j])) continue; // prune: not ready yet
used[i] = true; // choose
path.push(steps[i]);
explore(); // explore
path.pop(); // undo both changes
used[i] = false;
}
}
explore();
return out;
}
Cost: each node scans the n steps and checks their rules, so O(N · (n + r)) time for N nodes of the pruned tree and r rules. N is at most about e · n!, with no rules. Besides the output, it uses O(n + r) memory.
With rules that form a cycle, no step in the cycle is ever ready. So no branch reaches n steps, and the answer is []. Listing all n! orders and then filtering them, as slow/deploy-orders.ts does, took 2,123 ms on the last test.
Exercise 3: vouchers for an exact total (medium)
A customer has vouchers, and two vouchers can have the same amount. Write vouchersForTotal(values, target): every set of vouchers whose amounts add up to exactly the target. Each voucher is used at most once, each set is in ascending order, and each set appears once. Start from exercises/vouchers.ts:
// Exercise 3: values are positive voucher amounts, and two vouchers can have the same amount.
// Returns every set of vouchers (each voucher used at most once) whose amounts add up to exactly
// target, each set in ascending order and listed once.
export function vouchersForTotal(values: number[], target: number): number[][] {
throw new Error("not implemented");
}
For the amounts 20, 10, 30, 10 and 20 and a total of 40, the answer is [10, 30], [20, 20] and [10, 10, 20], each once. The tests also cover a total no set reaches and 200 random cases against a brute force. The last test finds the sets that add up to 60 in 22 vouchers, in under 100 ms.
Hint
The opening’s sort and break work here too, with the money left as the budget. Record a set only when nothing is left. Which of the common mistakes is about equal items?
Solution
// Exercise 3: values are positive voucher amounts, and two vouchers can have the same amount.
// Returns every set of vouchers (each voucher used at most once) whose amounts add up to exactly
// target, each set in ascending order and listed once.
// Sort, then prune with break: once an amount is too big, every later one is too. Skip an amount
// equal to the one before it at the same level, so a set never comes out twice.
// O(N * n) time for N nodes of the pruned tree (at most 2^n) and n vouchers; O(n) memory besides
// the output.
export function vouchersForTotal(values: number[], target: number): number[][] {
const sorted = values.toSorted((a, b) => a - b);
const out: number[][] = [];
const path: number[] = [];
function 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; // prune: sorted, so every later amount is too big too
if (i > start && sorted[i] === sorted[i - 1]) continue; // the same choice as the last branch
path.push(sorted[i]); // choose
explore(i + 1, left - sorted[i]); // explore
path.pop(); // undo
}
}
explore(0, target);
return out;
}
Cost: O(N · n) time for N nodes of the pruned tree, because recording a set copies up to n amounts. N is at most 2ⁿ, when every set fits. Besides the output, it uses O(n) memory for the sorted copy, the path and the recursion.
Walking all 2ⁿ subsets and dropping the repeats with a Map, as slow/vouchers.ts does, took 2,151 ms on the last test.
Exercise 4: find a code in a grid of letters (harder)
A grid of letters is a list of rows of equal length. A code can be spelled by starting at any cell and moving up, down, left or right, using each cell at most once. Write gridHasCode(grid, code). Start from exercises/grid-code.ts:
// Exercise 4: grid is a list of rows of letters, all the same length. Returns true if code can be
// spelled by starting at any cell and moving up, down, left or right, using each cell at most once.
export function gridHasCode(grid: string[], code: string): boolean {
throw new Error("not implemented");
}
In the grid CATS, ODEX, PINE, the code COPI turns a corner and is found. The code CD would need a diagonal step, so it isn’t. The tests also cover a code that needs a cell twice and 300 random small grids against a brute force. One test puts a dead end in the way of the right path, in all eight turns and mirror images of the grid.
The last test looks for 200 codes of 10 letters in a 6 × 6 grid in under 100 ms.
Hint
Each cell is a place to start, and each step chooses one of four neighbors, as in Module 7‘s grids. Mark a cell when the path enters it. Module 7’s visited set never cleared a mark, because it asked what a walk can reach. What does a path search need to do when it leaves a cell?
Solution
// Exercise 4: grid is a list of rows of letters, all the same length. Returns true if code can be
// spelled by starting at any cell and moving up, down, left or right, using each cell at most once.
// Start from every cell; a wrong letter ends a branch at once. Mark a cell when the path enters it
// and clear the mark when the path leaves it, so a later path can use it.
// O(R * C * 4 * 3^(L-1)) time in the worst case for an R x C grid and a code of length L: after the
// first step, at most 3 new directions (the fourth is the cell the path came from).
// O(R * C + L) memory for the marks and the recursion.
export function gridHasCode(grid: string[], code: string): boolean {
if (code.length === 0) return true;
const rows = grid.length, cols = rows ? grid[0].length : 0;
const used = grid.map((row) => new Array<boolean>(row.length).fill(false));
function explore(r: number, c: number, k: number): boolean {
if (r < 0 || c < 0 || r >= rows || c >= cols) return false;
if (used[r][c] || grid[r][c] !== code[k]) return false; // prune: used, or the wrong letter
if (k === code.length - 1) return true; // the last letter matched
used[r][c] = true; // choose
const found =
explore(r + 1, c, k + 1) || explore(r - 1, c, k + 1) || explore(r, c + 1, k + 1) || explore(r, c - 1, k + 1);
used[r][c] = false; // undo, even when found, so the marks are clean
return found;
}
for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) if (explore(r, c, 0)) return true;
return false;
}
Cost: each of the R · C cells can start a path. After the first step, each step has at most 3 new directions, because the fourth is the cell the path came from. So the worst case is O(R · C · 4 · 3ᴸ⁻¹) for a code of length L. A grid of all A and a code of As that ends in a missing letter comes close to it.
A wrong letter ends a branch at once, so a grid of mixed letters visits far fewer cells. Memory is O(R · C) for the marks and O(L) for the recursion.
Without the undo, a cell that a dead end marked stays marked, and a later path through it fails. Walking every path as long as the code and comparing the letters only at the end, as slow/grid-code.ts does, took 1,688 ms on the last test.
Going deeper
You can skip this section. It covers details the main path left out.
Why orders have about e · n! nodes. Depth d of the orders tree holds n! / (n − d)! nodes: the orders of d items picked from n. Added up over every depth, that sum comes to e · n!, rounded down, for n ≥ 1. That’s why node-count.ts printed 2.7183 for 8 and 10 items.
The stack size. The recursion limit that Module 6 measured is set by V8’s --stack-size option. On Node.js 26.13.1, node --v8-options lists its default as 984 KB.
Where the copying time goes
memory.ts in the lab measures how much the full list of subsets holds. Run it with node --expose-gc memory.ts:
n = 16: 65,536 subsets hold 7.6 MB, 121.3 bytes per subset
n = 18: 262,144 subsets hold 25.4 MB, 101.5 bytes per subset
n = 20: 1,048,576 subsets hold 105.0 MB, 105.0 bytes per subset
The million subsets of 20 items hold 105 MB, about 105 bytes per subset of 10 numbers on average. The garbage collector is the part of V8 that finds memory no longer in use, and it has to trace all of this while the walk runs. gc-share.ts in the lab timed one subsets call at n = 20, and about 107 ms of 172 ms went to garbage collection. That share rose with n, which explains the growth above 4.4 in “What a result costs”.
Generators and yield*
A generator is a function that hands over values one at a time with yield, and pauses between them. Inside a generator, yield* hands over every value of another generator, one at a time (MDN). Here is the subsets walk as a generator, an excerpt of streaming.ts:
// The same walk as a generator. Each yield* passes the value up through every level
// above it, so a subset found at depth d costs O(d) more to reach the caller.
export function* subsetGen(xs: number[], start = 0, path: number[] = []): Generator<readonly number[]> {
yield path;
for (let i = start; i < xs.length; i++) {
path.push(xs[i]);
yield* subsetGen(xs, i + 1, path);
path.pop();
}
}
node streaming.ts adds up the subset sizes both ways, so both do the same work per result. It printed:
first 5 of 2^40 subsets: - 0 0+1 0+1+2 0+1+2+3 (0.09 ms)
callback
n median ms x prev
16 0.67
18 2.70 4.0
20 10.83 4.0
generator with yield*
n median ms x prev
16 18.53
18 80.51 4.3
20 339.65 4.2
Both grew 4 times per two items, so both are O(2ⁿ) for this walk, but the generator took 339.65 ms at 20 items. It pays for every level of yield*. A subset at depth d leaves its own generator, then passes through the d generators above it before it reaches the caller’s for loop.
yield-depth.ts in the lab passed values through chains of yield* and measured about 20 ns per level on this machine. A value took 44 to 55 ns at depth 0 and about 850 ns at depth 40.
The generator has one strength: the caller can stop it. The first line took 5 subsets of a 40-item search, a tree of 2⁴⁰ nodes, in 0.09 ms. It used map, take and toArray, which are iterator helpers: methods that generators inherit from Iterator.prototype, and that pass values through one at a time as the caller asks. So use a callback when the caller walks everything, and a generator when the caller may stop after the first few results.
Iterator helpers are part of ES2025 (TC39 finished proposals). V8 shipped them in version 12.2, in Chrome 122 (V8 blog, March 2024).
Cheat sheet
Figure 7 sums up the module: which shape fits which sign in a problem.
sign in the problem shape nodes
"every combination", "any number of" subsets, from start 2^n
"one value for each setting" one level per item product
"every order", "every schedule" orders, used flags about e * n!
"exactly k", "every pair" groups of k, room left about C(n, k)
"total at most", "adds up to exactly" sort, then break what fits
"how many" or "the best one" only greedy (9) or DP (11) not 2^n
Figure 7: backtracking costs one step per node, so the shape tells you the size of the tree, and pruning decides how much of it you walk.
- Shape: choose (
push, set a mark), explore (recurse), undo (pop, clear the mark). Copy the path only when you record it. - Count first: 2ⁿ subsets, about e · n! nodes for orders, C(n, k) groups. About 10⁸ nodes per second, fewer with copies.
- Prune: stop a branch at the first sign it can’t work. Sort, then
break; skip an item equal to the one before it at the same level. - Loop from
startfor subsets and groups, from 0 withusedflags for orders. - Many results: hand each to a callback instead of keeping a list.
- Next: Module 11 handles the searches where the same smaller question comes up under many branches. It stores each answer once, with dynamic programming.
Sources
- NIST Dictionary of Algorithms and Data Structures, backtracking, Paul E. Black, modified May 17, 2021 (quotes S. W. Golomb and L. D. Baumert, “Backtrack Programming”, Journal of the ACM 12(4), 1965).
- MDN,
yield*. - V8 blog, Iterator helpers (March 27, 2024).
- TC39 finished proposals (Sync Iterator helpers, 2025; Iterator Sequencing, 2026), read November 2026.
- Node.js v26.13.1,
node --v8-options(--stack-size, default 984 KB).