Recursion & backtracking
Solve a problem by solving smaller versions of itself; backtracking builds solutions one choice at a time and undoes choices that lead to dead ends.
Description
A recursive function solves a problem by calling itself on smaller inputs, until it reaches a base case simple enough to answer directly. Summing a list is the first element plus the sum of the rest; the sum of an empty list is 0. Trees, nested data and divide-and-conquer algorithms are naturally recursive.
Backtracking uses recursion to search through choices. Build a solution one decision at a time; after each decision, check whether it can still lead to a valid solution. If it can't, undo the decision and try the next option. It's a depth-first search over the tree of all possible partial solutions, cutting off branches early.
The classic example is N-Queens: place n queens on an n × n board so none attack each other. Place one queen per row; if every column in a row is attacked, back up and move the previous queen. The same approach solves Sudoku, generates permutations and subsets, finds paths in mazes and powers constraint solvers.
Backtracking is exponential in the worst case. Its power comes from pruning: the earlier a partial solution can be rejected, the more of the search tree is never explored.
How it works
One solution to 4-Queens: no two queens share a row, column or diagonal
- row 0: , ♛, ,
- row 1: , , , ♛
- row 2: ♛, , ,
- row 3: , , ♛,
Step through: backtracking on 4-Queens
Step 1 of 32Place 4 queens so that none attack each other: one per row, trying columns left to right.
Complexity
| Operation | Average | Worst |
|---|---|---|
| Backtracking in generalPruning decides how much of the tree is explored. | exponential | exponential |
| N-Queens (naive) | O(n!) | O(n!) |
| Generate all subsets | O(2ⁿ · n) | O(2ⁿ · n) |
| Generate all permutations | O(n! · n) | O(n! · n) |
Space: O(depth) for the recursion stack
Recursion depth is limited: JavaScript engines allow roughly 10 000 frames. Deep recursion needs an explicit stack.
TypeScript implementation
N-Queens and subset generation with backtracking, counting how many partial placements pruning skips.
// Backtracking: build a solution one choice at a time, undo dead ends.
/** All solutions to N-Queens, plus how many placements were tried. */
export function nQueens(n: number): { solutions: number[][]; tried: number } {
const cols = new Set<number>(), diag1 = new Set<number>(), diag2 = new Set<number>();
const queens: number[] = [];
const solutions: number[][] = [];
let tried = 0;
const place = (row: number) => {
if (row === n) return void solutions.push([...queens]); // base case: all rows filled
for (let c = 0; c < n; c++) {
tried++;
if (cols.has(c) || diag1.has(row - c) || diag2.has(row + c)) continue; // prune
queens.push(c); cols.add(c); diag1.add(row - c); diag2.add(row + c); // choose
place(row + 1); // explore
queens.pop(); cols.delete(c); diag1.delete(row - c); diag2.delete(row + c); // undo
}
};
place(0);
return { solutions, tried };
}
/** All subsets of items that add up to target. */
export function subsetsWithSum(items: number[], target: number): number[][] {
const out: number[][] = [];
const pick: number[] = [];
const go = (i: number, remaining: number) => {
if (remaining === 0) return void out.push([...pick]);
if (i === items.length || remaining < 0) return; // dead end
pick.push(items[i]);
go(i + 1, remaining - items[i]); // include items[i]
pick.pop();
go(i + 1, remaining); // skip items[i]
};
go(0, target);
return out;
}
export function demo(): string[] {
const q4 = nQueens(4), q8 = nQueens(8);
return [
`4-Queens: ${q4.solutions.length} solutions, first: columns [${q4.solutions[0].join(", ")}]`,
`8-Queens: ${q8.solutions.length} solutions after trying ${q8.tried.toLocaleString("en")} placements (8⁸ = 16,777,216 without pruning)`,
`subsets of [3, 34, 4, 12, 5, 2] summing to 9: ${subsetsWithSum([3, 34, 4, 12, 5, 2], 9).map((s) => `[${s.join(", ")}]`).join(", ")}`,
];
}When to use it
Use it when
- Problems defined recursively: trees, nested structures, divide and conquer.
- Searching for one or all combinations that satisfy constraints: puzzles, scheduling, configuration.
- Generating permutations, subsets or combinations.
Avoid it when
- Subproblems repeat: add memoization, which is dynamic programming.
- A greedy choice is provably optimal: it's much faster.
- Recursion depth could reach the thousands: use an explicit stack.
Pitfalls
- Missing or wrong base cases, leading to infinite recursion.
- Forgetting to undo a choice when backtracking, so state leaks into the next branch.
- Stack overflow on deep inputs.
- Recomputing the same subproblems many times: memoize.
Alternatives
Dynamic programming
Choose it when the same subproblems recur.
Greedy algorithms
Choose it when a locally best choice is always safe.
Constraint or SAT solvers
Choose it when the problem is large: solvers use far smarter pruning than hand-written backtracking.