Backtracking

Build an answer one choice at a time, undo the last choice when it cannot lead anywhere, and try the next one. The tool for subsets, permutations, combinations and puzzles such as N-Queens and Sudoku.

Overview

Backtracking builds an answer one choice at a time. After each choice it asks: can this partial answer still become a valid one? If yes, it goes deeper. If no, it undoes the last choice and tries the next option. When all options at a level are used up, it returns to the level above.

Reach for it when a problem asks for all answers, or any answer under constraints. Most such problems are one of three shapes, subsets, combinations and permutations, and they differ only in when an answer is recorded and where the loop starts.

Each section below follows the same shape: the rule first, then the rule on a tiny input, then the trap to avoid.

Choose, explore, unchoose

The rule: every backtracking function has the same three moves. Add a choice to the current path, call the function again to extend it, then remove the choice so the path is clean for the next option.

A few words come up throughout this chapter.

  • Path (or state): the partial answer built so far.
  • Choice: one option you can add at this step.
  • Base case: the test that says the path is a complete answer.
  • Pruning: skipping an option early because it cannot lead to a valid answer.
  • Backtrack: undo the last choice and return to try another.

One call of the function runs this routine.

  • If the path is a full answer, save a copy of it.
  • Otherwise, take the options one at a time.
  • For each option, ask whether it can still lead to an answer. If it cannot, skip it. That is pruning.
  • If it can, choose it by adding it to the path, explore by recursing, then unchoose it by removing it again.
  • Move on to the next option. When there are none left, return to the level above.

The undo in step 4, after each recursive call, is what lets one shared path serve every branch.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio