Backtracking
Build a solution one choice at a time, and undo choices that can’t work.
- current
- not reached yet
- visited / done
- result
Record the empty set
Every call first saves a copy of the current path.
VARIABLES
- path
- []
- results so far
- 1
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
Backtracking explores a tree of decisions with recursion: choose, recurse, then un-choose. Pruning skips branches that can’t lead to a valid answer.
Why it matters
Problems that ask for all combinations, permutations or valid arrangements need a systematic search.
Think of it like this
Solving a maze by always taking a path and walking back to the last junction at a dead end.
Use it when
- Generating all subsets, permutations or combinations
- Constraint puzzles such as N-Queens or Sudoku
- Small inputs where exponential work is acceptable
Avoid it when
- You only need a count or best value and subproblems repeat - use DP
- Large n (beyond about 20) without strong pruning
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| Subsets of n items | O(n × 2ⁿ) | O(n) stack |
| Permutations of n items | O(n × n!) | O(n) stack |
| With good pruning | often far less | O(n) |
Often confused with: dynamic programming - it also explores choices, but reuses results when subproblems repeat.
How to recognize it
Clues in interview prompts that point straight to this pattern.
- n ≤ 10 to 20 often signals that exponential search is expected
- “Return all” means the output itself can be exponential
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- Appending path instead of a copy - every result ends up as the same list
- Forgetting to undo the choice with path.pop()
- Not skipping duplicates for inputs like [1, 2, 2]
Edge cases to test
- Empty input - one subset, the empty one
- Duplicate values
- A target that can’t be reached in combination-sum problems
Knowledge check
Quick check to lock in the intuition.
Why append path[:] instead of path?
Practice
Apply what you just watched on real interview problems.