Backtracking is a way to explore every possible sequence of choices, using recursion. You build an answer one choice at a time; when a choice leads nowhere (or you've finished exploring it), you undo it and try the next option. It's how you'd solve a maze by hand: walk forward, and when you hit a dead end, step back to the last fork and try another path.
The template
Almost every backtracking solution has this shape:
const result = []
const path = [] // the choices made so far
function backtrack(/* where we are */) {
if (/* path is a complete answer */) {
result.push([...path]) // save a COPY
return
}
for (const choice of /* the options from here */) {
if (/* choice is not allowed */) continue
path.push(choice) // 1. choose
backtrack(/* the next position */) // 2. explore
path.pop() // 3. undo
}
}Choose, explore, undo. The undo step is what lets one path array serve the whole search: after exploring a choice, the array is back to exactly how it was.
Picture it as a tree
Each call is a node; each choice is a branch. For "all subsets of [1, 2]":
The leaves are the 4 answers. Backtracking is just a depth-first walk over this tree of choices.
Two important ideas
Pruning: stop early
If a partial answer can't possibly lead to a valid one, return immediately instead of exploring further. In Combination Sum, once the sum goes over the target, adding more positive numbers can't help. Good pruning is the difference between instant and timing out.
Avoiding duplicate answers
If order doesn't matter (combinations, subsets), make sure each answer is built in only one order. The usual trick: pass a start index and only choose items at or after it. Then [2, 3] can be built but [3, 2] can't.
Backtracking on a grid
On a grid, the choices are the neighbors (up, down, left, right), and "not allowed" includes cells already on the current path. Mark a cell when you step on it and unmark it when you step back:
board[r][c] = '#' // choose: mark as used
// explore the 4 neighbors
board[r][c] = letter // undo: give it backUsed in Word Search and Word Search II.
How fast is it?
Usually exponential, because the number of possible choice sequences is. That's expected: if a problem asks for all combinations, permutations or subsets, there can be exponentially many answers, and listing them takes that long. Pruning makes the real cost much lower.
How to recognize this category
- "Return all combinations / permutations / subsets / arrangements".
- "Can this be built/traced/placed?" where you must try options and back out of dead ends (word search on a grid, Sudoku, N-Queens).
- The input is small (often
n <= 20or a 6×6 board): a hint that an exponential search is expected.
Common mistakes
- Saving
pathinstead of a copy. Every saved answer then points to the same array, which ends up empty. - Forgetting the undo step. Leftover choices leak into the next branch.
- Producing duplicates like
[2, 3]and[3, 2]when order doesn't matter. Use astartindex. - No pruning, so the search explores branches that can never work.