Backtracking

Build candidate solutions step by step, undo choices on return, and prune early to solve subsets, permutations and constraint puzzles.

Intermediate · about 8 hours · difficulty 3/5

Learn first: Recursion Fundamentals

Backtracking is recursion that explores a tree of choices: make a choice, recurse, then undo the choice. It is the standard approach when you must list every valid configuration.

Template

  1. If the current state is a complete solution, record it and return.
  2. For each available choice: if it is valid, apply it, recurse, then undo it.

Families

  • Subsets: Subsets, Subsets II (sort and skip duplicates at the same level).
  • Combinations: Combination Sum (reuse allowed), Combination Sum II (no reuse, skip duplicates), Combinations.
  • Permutations: with a used[] array or by swapping in place; Permutations II for duplicates.
  • Partitioning: Palindrome Partitioning.
  • Grid search: Word Search, Rat in a Maze.
  • Constraint puzzles: N-Queens (track columns and both diagonals), Sudoku Solver, M-Coloring.

Pruning

Sort the input and break early when the remaining target goes negative. Check constraints before recursing, not after. Good pruning is the difference between TLE and accepted.

Pitfalls

  • Forgetting to undo state (pop from the path, unmark visited).
  • Adding a reference to the path instead of a copy to the answer list (Java and Python).
  • Duplicate handling: skip only when i > start and nums[i] == nums[i - 1].

You are ready to move on when you can solve N-Queens and Subsets II and explain how your duplicate-skip condition works.

Key concepts

  • Choose, explore, unchoose
  • Subsets and combinations
  • Permutations
  • Handling duplicates
  • Pruning
  • Grid backtracking
  • N-Queens and Sudoku

Mini project

Solve these 10 in 7 days, log time and pattern: Subsets, Subsets II, Combination Sum, Combination Sum II, Permutations, Permutations II, Letter Combinations of a Phone Number, Palindrome Partitioning, Word Search, N-Queens.

Check yourself

In Combination Sum II, why does the duplicate check use i > start rather than i > 0?

Free resources