Backtracking

Systematically build candidates choice by choice, undo choices that fail, and prune early to generate subsets, permutations and constrained solutions.

Intermediate · about 8 hours · difficulty 3/5

Learn first: Recursion and Divide and Conquer

Backtracking is recursion over choices. At each step you pick an option, recurse, then undo the pick and try the next one. It enumerates all subsets, permutations or combinations, and with pruning it solves constraint puzzles like N-Queens and Sudoku.

The template

solve(state):
  if state is complete: record answer; return
  for each choice valid in state:
    make choice
    solve(next state)
    undo choice

The undo step is what keeps a single shared path correct across branches.

Three shapes to know

  • Subsets: for each element, include or exclude (2^n results).
  • Permutations: choose any unused element for the next position (n! results), tracked with a used array.
  • Combinations / combination sum: pass a start index so you never go backwards, which avoids duplicate orderings.

Handling duplicates

Sort the input, then skip an element if it equals the previous one at the same recursion level (i > start && a[i] == a[i-1]).

Pruning

Stop early when the partial state cannot lead to a valid answer: sum already exceeds target, a queen is attacked, a word does not match the grid. Good pruning is the difference between TLE and AC.

Backtracking is exponential by nature. If you notice the same subproblem recurring, that is your cue to switch to dynamic programming.

Key concepts

  • Choose, explore, unchoose template
  • Subsets
  • Permutations
  • Combinations and combination sum
  • Skipping duplicates
  • Pruning
  • Grid search (Word Search)
  • N-Queens and Sudoku

Mini project

Solve 8 problems: Subsets, Subsets II, Permutations, Combination Sum, Combination Sum II, Letter Combinations of a Phone Number, Word Search, and N-Queens.

Check yourself

In Subsets II, why does the duplicate-skip condition check i > start rather than i > 0?

Free resources