Lesson 135 of 296
Backtracking
What you will learn
- The choose, explore, un-choose pattern
- Subsets
- Permutations
- Combination Sum
- Word Search
- N-Queens
On this page
The idea
Backtracking explores all possible choices by building a solution step by step. At each step:
- Choose: add an option to the current partial solution.
- Explore: recurse to make the next choice.
- Un-choose: remove the option (backtrack) and try the next one.
It is like walking a maze: go down a path, and when you hit a dead end, go back to the last junction and try another path.
Backtracking problems usually ask for all subsets, permutations or combinations, or ask whether any arrangement satisfies a rule. The time is often exponential (O(2ⁿ) or O(n!)), which is fine because inputs are small (n ≤ about 10 to 20).
The template
function backtrackTemplate(options: number[]): number[][] {
const results: number[][] = [];
const current: number[] = [];
function explore(start: number): void {
results.push([...current]);
for (let i = start; i < options.length; i++) {
current.push(options[i]!);
explore(i + 1);
current.pop();
}
}
explore(0);
return results;
}[...current] stores a copy. Pushing current itself would store the same array, which keeps changing (Lesson 48).
Subsets
Problem (LeetCode 78): all subsets of distinct numbers.[1, 2, 3] → [[], [1], [1,2], [1,2,3], [1,3], [2], [2,3], [3]].
Every number is either in or out: 2ⁿ subsets.
function subsets(nums: number[]): number[][] {
const result: number[][] = [];
const current: number[] = [];
function explore(start: number): void {
result.push([...current]);
for (let i = start; i < nums.length; i++) {
current.push(nums[i]!);
explore(i + 1);
current.pop();
}
}
explore(0);
return result;
}Starting the loop at start means we only add numbers after the last one chosen, so [1, 2] and [2, 1] are not both produced.
O(n × 2ⁿ) time (2ⁿ subsets, each copied in O(n)), O(n) recursion depth.
Permutations
Problem (LeetCode 46): all orderings of distinct numbers. [1, 2, 3] has 3! = 6.
Here order matters, so at each position we may use any unused number. Track which are used.
function permute(nums: number[]): number[][] {
const result: number[][] = [];
const current: number[] = [];
const used = new Array<boolean>(nums.length).fill(false);
function explore(): void {
if (current.length === nums.length) {
result.push([...current]);
return;
}
for (let i = 0; i < nums.length; i++) {
if (used[i]) continue;
used[i] = true;
current.push(nums[i]!);
explore();
current.pop();
used[i] = false;
}
}
explore();
return result;
}O(n × n!) time.
Combination Sum
Problem (LeetCode 39): distinct candidate numbers; find all unique combinations that add to target. Each number may be used any number of times.candidates = [2, 3, 6, 7], target = 7 → [[2, 2, 3], [7]].
function combinationSum(candidates: number[], target: number): number[][] {
const result: number[][] = [];
const current: number[] = [];
const sorted = [...candidates].sort((a, b) => a - b);
function explore(start: number, remaining: number): void {
if (remaining === 0) {
result.push([...current]);
return;
}
for (let i = start; i < sorted.length; i++) {
const value = sorted[i]!;
if (value > remaining) break;
current.push(value);
explore(i, remaining - value);
current.pop();
}
}
explore(0, target);
return result;
}explore(i, ...)(noti + 1) allows the same number again.- Sorting lets us
breakas soon as a number is too big: this pruning (cutting off branches that cannot succeed) makes backtracking much faster.
Word Search
Problem (LeetCode 79): can the word be formed by moving between adjacent cells (up, down, left, right) in a grid of letters, using each cell at most once?
function exist(board: string[][], word: string): boolean {
const rows = board.length;
const cols = board[0]?.length ?? 0;
function explore(r: number, c: number, index: number): boolean {
if (index === word.length) return true;
if (r < 0 || r >= rows || c < 0 || c >= cols) return false;
if (board[r]![c] !== word[index]) return false;
const saved = board[r]![c]!;
board[r]![c] = "#";
const found =
explore(r + 1, c, index + 1) ||
explore(r - 1, c, index + 1) ||
explore(r, c + 1, index + 1) ||
explore(r, c - 1, index + 1);
board[r]![c] = saved;
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;
}Marking the cell "#" means "used on this path" (choose), and restoring it is the un-choose step. Time O(rows × cols × 4^L) for word length L (in practice much less thanks to early failures).
N-Queens (stretch)
Problem (LeetCode 51): place n queens on an n × n chess board so no two attack each other (same row, column or diagonal).
Place one queen per row. Track used columns and both diagonal directions in Sets:
- Cells on the same "down-right" diagonal share
row - col. - Cells on the same "down-left" diagonal share
row + col.
function solveNQueens(n: number): string[][] {
const results: string[][] = [];
const queenCols: number[] = [];
const cols = new Set<number>();
const diag1 = new Set<number>();
const diag2 = new Set<number>();
function place(row: number): void {
if (row === n) {
results.push(queenCols.map((c) => ".".repeat(c) + "Q" + ".".repeat(n - c - 1)));
return;
}
for (let col = 0; col < n; col++) {
if (cols.has(col) || diag1.has(row - col) || diag2.has(row + col)) continue;
cols.add(col);
diag1.add(row - col);
diag2.add(row + col);
queenCols.push(col);
place(row + 1);
queenCols.pop();
cols.delete(col);
diag1.delete(row - col);
diag2.delete(row + col);
}
}
place(0);
return results;
}For n = 4 there are 2 solutions; for n = 8, 92.
How to say it in an interview
"Backtracking builds a solution step by step with choose, explore, un-choose, exploring every branch of the decision tree. I store copies of the current path when recording results, use a start index for subsets and combinations so order is not repeated, a used array for permutations, and prune early, for example by sorting candidates and breaking once they exceed the remaining target. Time is exponential, which fits the small inputs these problems use."
Key words
| Word | Meaning |
|---|---|
| Backtracking | Trying choices and undoing them to explore all options |
| Decision tree | The tree of all choices |
| Pruning | Skipping branches that cannot succeed |
| Subset | Any selection of items, order ignored |
| Permutation | An ordering of items |
| Combination | A selection where order does not matter |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.