v9.1.1
Menu

Chapter 5: Backtracking

Week 5

Explore systematic search through decision spaces using backtracking. Learn how to enumerate subsets, combinations, and permutations by building partial solutions incrementally, pruning invalid branches early, and applying memoization when subproblems overlap.

Topics
8
Demos
5
Videos
3
Min read
34

Chapter Overview

Backtracking is a refined form of brute-force search. Instead of generating every possible solution and then checking validity, backtracking builds solutions incrementally---placing one element at a time---and abandons a partial solution as soon as it determines that it cannot possibly lead to a valid answer.

The key idea is a state-space tree: each node represents a partial solution, each edge represents a decision (include an element, pick a digit, place a queen), and each leaf is a complete candidate. DFS traverses this tree, and pruning cuts off entire subtrees when constraints are violated, dramatically reducing the search space.

Backtracking problems share a common template: choose a candidate, recurse with the updated state, then undo the choice (backtrack) before trying the next candidate. Mastering this template unlocks an entire class of interview problems---from generating subsets and permutations to solving constraint-satisfaction puzzles like N-queens and Sudoku.

This chapter covers:

  • State-space trees: Visualizing the decision tree and understanding how DFS explores it
  • Combinatorial generation: Subsets, combinations, and permutations using systematic enumeration
  • Pruning strategies: Cutting invalid branches early to avoid unnecessary work
  • Classic backtracking problems: Phone letter combinations, valid parentheses, and word break
  • Deduplication: Handling duplicate elements without producing duplicate results

Chapter Roadmap

Click any topic to jump in

Explainer videoInteractive demo
1
DFS with States

Every backtracking algorithm is a DFS over a state-space tree — nodes are partial solutions, edges are choices.

State-Space TreeBacktracking Template
From template to problem shapes

Combinations and permutations are the two fundamental shapes that map to the DFS template.

2
Combinations & Permutations

The two canonical shapes: choose $k$ from $n$ (order-free) and order $n$ items (order matters).

Combinations (Choose k from n)Permutations (All Orderings)
3
Pruning

Cut branches that cannot satisfy constraints — turns exponential search spaces into tractable ones.

Early Termination and Constraint CheckingN-Queens Constraint Propagation
Controlling the explosion
4
Letter Combinations

Generate the Cartesian product of digit-to-letter sets — a clean application of the combinatorial template.

Digit-to-Letter MappingIterative Cartesian Product Alternative
5
Generate Parentheses

Count of valid strings is the $n$-th Catalan number; the backtrack tree grows with constraint-guided pruning.

Open/Close Counting ConstraintCatalan Numbers and Counting
Applying the template

Each classic problem picks a different strategy — unrestricted product, constraint-driven, or choice-tracking.

6
Permutation Strategies

Two equivalent approaches — visited-array tracking versus in-place swap — with the same $\Theta(n \cdot n!)$ cost.

Visited-Array PermutationsSwap-Based In-Place Permutations
7
Memoization

When the backtrack tree has overlapping subproblems, caching collapses exponential work to polynomial.

Overlapping Subproblems in BacktrackingMemoized Word Break
From search to DP
8
Deduplication

Sort and skip — the standard way to avoid generating the same subset or permutation twice.

Sort and Skip PatternPermutations with Duplicates

Topics

8 topics in this chapter

A pizza shop offers three toppings, and you want to list every possible pizza, from plain cheese to all three toppings together. With three toppings you can write the eight options by hand, but with twenty toppings there are over a million, and you need a systematic way to produce each one exactly once without missing any.

The previous chapter, Depth First Search & Trees, walked real trees made of node objects. Backtracking walks a tree that is never stored: a state-space tree, where the root is an empty choice, each level decides one thing, such as whether topping i is on the pizza, and each root-to-leaf path is one complete candidate. The same DFS you used on binary trees explores it, carrying a partial solution down and undoing the last decision on the way back up.

We first draw the state-space tree for subsets and count its nodes and leaves, which explains why this kind of search is exponential. Then we distill the choose, explore, unchoose template that every later topic in this chapter reuses, and look at the two bugs that break it most often.

Definition

Backtracking is a depth-first search over a state-space tree whose nodes are partial solutions and whose edges extend a partial solution by one choice. At each node it chooses an option, recurses, and then undoes the choice before trying the next option, so a single mutable state is reused across the whole search. Leaves, or other accepted nodes, are recorded as solutions.

In this topic

  1. 1State-Space Tree
  2. 2Backtracking Template
1 of 2
State-Space Tree

A state-space tree is an abstract tree where each path from root to leaf represents a sequence of decisions that builds one complete candidate solution. The root is the empty state (no decisions made). At each level, you decide what to do with the next element---include it, exclude it, or choose from a set of options. DFS explores this tree, visiting every path. The total number of leaves equals the total number of candidate solutions.

Mathematical Intuition

A backtracking algorithm is a DFS over a state-space tree whose nodes are partial solutions and whose edges represent extending a partial solution by one choice. If each node has at most bb children (branching factor) and depth is at most dd, the tree has at most bdb^d leaves and Θ(bd)\Theta(b^d) nodes. Work per node is at least Ω(d)\Omega(d) to copy the state, so total time is Ω(d⋅bd)\Omega(d \cdot b^d) — inherently exponential without pruning.

Example:

Visualize the state-space tree for generating all subsets of [1, 2, 3].

2 of 2
Backtracking Template

Building a fresh copy of the partial solution at every node wastes time and memory, so backtracking keeps one shared list and edits it in place. Each node repeats three steps. Choose: append a candidate to the shared list. Explore: recurse, so the child sees the extended state. Unchoose: pop the candidate, restoring exactly the state the parent had, before trying the next option. This is the down-and-up flow from DFS on Trees, with state passed down by mutation. Two bugs dominate. Forgetting to unchoose leaks one branch's choices into its siblings, and recording the list without copying it stores a reference that later edits overwrite.

Mathematical Intuition

The template is: (1)(1) if state is a solution, record it and return; (2)(2) for each choice, apply it (mutate state), recurse, undo it (restore state). Undoing is what makes 'backtracking' — it reuses one mutable buffer across the entire traversal for O(d)O(d) extra memory. The total time remains Θ(∣tree∣⋅d)\Theta(|\text{tree}| \cdot d) but the constants are smaller than building new states.

Example:

Generate all subsets of a list using the backtracking template.