Lesson 20 · Core algorithms

Backtracking Algorithms

Backtracking builds a solution one decision at a time and abandons a partial solution, undoing its last choice, as soon as it is clear it cannot be completed.

Backtracking Algorithms concept diagramA visual explanation of the layout and operations shown in this lesson.[ ][1][2][1,2]✕✕ marks a branch pruned before it is exploreddashed = undo and backtrack
1

Searching a Tree of Partial Solutions

Backtracking builds a solution step by step, one decision at a time, and gives up on a partial solution the moment it is clear it cannot be completed. It still finds every valid answer, but it skips most of the possibilities by never extending one that is already dead.

The picture to keep in mind is a state space tree. The root is the empty solution, each edge is one decision, and each node is the partial solution made by the decisions above it. Backtracking is a depth-first walk of this tree that never builds the whole thing: only the current path exists at any time.

Compare it with brute force, which builds every complete candidate and tests each one at the end. Placing 8 queens on any 8 of the 64 squares gives 4,426,165,368 boards to test. Backtracking places one queen per row and rejects a square the moment it is attacked: it tests 15,720 squares, and only 2,057 partial boards survive to be extended, while still finding all 92 solutions.

Backtracking and dynamic programming are both recursive, but they suit different problems. Dynamic programming applies when the same subproblem comes up again and its answer can be stored and reused. Backtracking applies when every branch is a different configuration with nothing to reuse, such as listing all arrangements, so the only saving is not exploring branches that cannot work.

  • Build one decision at a time; drop a branch as soon as it cannot work
  • The state space tree is walked depth-first and never stored
  • Finds every answer, like brute force, at a fraction of the work
  • No repeated subproblems to cache, so pruning is the only saving
2

Choose, Explore, Un-choose

  1. Choose: add one option to the partial solution
  2. Explore: recurse to make the next decision on top of it
  3. Un-choose: remove the option, so the state is exactly as it was before

Every backtracking function has the same three-part body, and the third part gives the technique its name.

Recursion and backtracking go together because the call stack remembers where each decision was made. When a call returns, the caller undoes its own choice and tries the next option, which is the backtrack. The rule to hold on to: a call must leave the state exactly as it found it, so every change on the way down has a matching undo on the way up.

The undo must mirror the choice exactly. If choosing appended to a list, undoing pops; if it set used[i] = true, undoing sets it back to false; if it wrote a board cell, undoing restores the old value. Forgetting one undo is the most common bug: the first branch comes out right and every later one is polluted. On [1, 2], a missing pop() turns the answer into [[], [1], [1, 2], [1, 2, 2]].

The other common bug is storing the working list itself. res.append(path) stores a reference, and later changes to path rewrite every stored entry, so subsets of [1, 2] come out as [[], [], [], []]. Store a copy: path[:] in Python, new ArrayList<>(path) in Java; C++'s push_back(path) copies already.

One alternative avoids the undo entirely: pass a new copy of the state into each call instead of changing a shared one. It is harder to get wrong but costs O(depth) copying per node, so the change-and-undo form is the usual one.

  • Every change on the way down needs an undo on the way up
  • A missing undo leaks one branch's choices into the next
  • Store a copy of a finished solution, not the live list
  • Passing copies removes the undo, at O(depth) per call
3

Pruning Is Where the Speed Is

Without pruning, backtracking is brute force with extra steps. All of its advantage comes from cutting branches before exploring them, so the design question is: what is the earliest point at which this branch is certain to fail?

A feasibility check rejects a choice that breaks a rule, before recursing. In N-Queens a square is rejected the moment it shares a column or diagonal with a placed queen, not after a full board is built.

A bound check rejects a branch that cannot beat the best answer so far, or cannot reach a target: if the running sum already exceeds the target and every remaining value is positive, stop. Pushed further, with a best-so-far that improves as the search goes, this becomes branch and bound.

Order the choices so failures show up early. Trying the most constrained option first, such as the Sudoku cell with the fewest legal digits, makes dead ends appear near the root. Sorting the input often has the same effect for less effort.

The reason is size. In a tree with branching factor b and depth n, a cut at depth d removes about b^(n − d) nodes. A cut near the root is worth exponentially more than one near the leaves, so effort spent checking early pays off far more than speeding up the final test.

  • Ask what makes a branch hopeless, and test it before recursing
  • Feasibility rejects broken states; bounds reject unwinnable ones
  • Try the most constrained choice first to fail near the root
  • A cut high in the tree removes exponentially more work
Key reference

Terms, operations, and practical uses

Core vocabulary

  • State space treeEvery partial solution as a node, every decision as an edge; walked depth-first, never stored.
  • CandidateA partial or complete solution currently being built.
  • PruningStopping a branch as soon as it is known it cannot lead to a valid solution.

Mechanics

  • ChooseAdd one option to the partial solution.
  • Un-chooseUndo that option after the recursive call returns, restoring the state exactly.
  • Base caseThe point where a candidate is complete and copied into the results.

Common patterns

  • SubsetsRecord every node; pass a start index so each element is used once.
  • PermutationsChoose any unused element; track use with a boolean array.
  • CombinationsSubsets that record only paths of length k.
Implementation

Code in Python, C++ and Java

def subsets(nums):
    res = []
    def backtrack(start, path):
        res.append(path[:])
        for i in range(start, len(nums)):
            path.append(nums[i])
            backtrack(i + 1, path)
            path.pop()
    backtrack(0, [])
    return res
print(subsets([1, 2]))
#include <iostream>
#include <vector>
using namespace std;

void backtrack(int start, vector<int>& path, vector<int>& nums, vector<vector<int>>& res) {
    res.push_back(path);
    for (int i = start; i < nums.size(); i++) {
        path.push_back(nums[i]);
        backtrack(i + 1, path, nums, res);
        path.pop_back();
    }
}
vector<vector<int>> subsets(vector<int>& nums) {
    vector<vector<int>> res;
    vector<int> path;
    backtrack(0, path, nums, res);
    return res;
}

int main() {
    vector<int> nums = {1, 2};
    vector<vector<int>> res = subsets(nums);
    cout << '[';
    for (size_t i = 0; i < res.size(); i++) {
        if (i) cout << ", ";
        cout << '[';
        for (size_t j = 0; j < res[i].size(); j++) {
            if (j) cout << ", ";
            cout << res[i][j];
        }
        cout << ']';
    }
    cout << "]\n";
}
import java.util.*;

public class Main {
    static void backtrack(int start, List<Integer> path, int[] nums, List<List<Integer>> res) {
        res.add(new ArrayList<>(path));
        for (int i = start; i < nums.length; i++) {
            path.add(nums[i]);
            backtrack(i + 1, path, nums, res);
            path.remove(path.size() - 1);
        }
    }
    static List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        backtrack(0, new ArrayList<>(), nums, res);
        return res;
    }

    public static void main(String[] args) {
        System.out.println(subsets(new int[]{1, 2}));
    }
}
Watch it run

Step through it

Running on nums = [1, 2]

backtrack(0, [])[ ]path (one shared list)emptyres[]call stack: backtrack(0, [])
Step 1

Visit the root: record []

backtrack(0, []) runs. The first thing every call does is record the current path, so the empty subset goes into res before any choice is made.

Output
1 / 15
4

One Template, Four Classic Problems

Subsets. Each call records the current path, then tries adding each remaining element, starting after the last one used. That is the code below. Every node of the tree is a subset, so all 2ⁿ are recorded and nothing can be pruned when all of them are wanted. Cost: O(n · 2ⁿ), since each subset takes O(n) to copy.

Permutations. At each position, choose any element not used yet. The branching starts at n and drops by one per level, giving n! leaves and O(n · n!) work. A boolean used array tracks what is taken; swapping elements into place and swapping back avoids the extra array. Generating permutations adds repeated values and Heap's algorithm.

Combinations. Like subsets, but only paths of length k are recorded, and a branch can stop once too few elements remain to reach k. Subsets and combinations works through that bound and the bitmask version.

N-Queens. Place one queen per row and try each column. A column is legal if no earlier queen shares it or either diagonal. Keeping three sets, of columns, of row − col and of row + col, makes that check O(1) instead of a scan over the placed queens. There is no neat formula for the number of nodes, which is exactly why pruning matters here: 4 queens need only 17 nodes and 60 square tests, against 4⁴ = 256 full boards with one queen per row.

Duplicates. When the input has repeated values, sort it, then skip an element equal to the one before it at the same level: if i > start and nums[i] == nums[i - 1]: continue. Comparing with the previous sibling stops two identical branches at one level, while the value can still be used again deeper down.

What changes between the four problems
ProblemChoice at each stepResultsKey detail
SubsetsAny element after the last one used2ⁿRecord every node, not just leaves
PermutationsAny unused elementn!used array, or swap and swap back
CombinationsAny element after the last one usedC(n, k)Record only paths of length k
N-QueensA column in this row92 for n = 8Sets for columns and both diagonals
  • Subsets and combinations pass a start index so no element repeats
  • Permutations track what is used
  • N-Queens checks column, row − col and row + col in O(1)
  • Sort, then skip nums[i] == nums[i - 1] when i > start
5

Where Backtracking Is Used

Backtracking fits any problem that asks for all solutions, or for one solution under constraints, where choices are made one at a time and a partial choice can be checked early. Sudoku, crossword filling, graph colouring and the Hamiltonian cycle are classic exam examples.

Its worst case stays exponential, because some inputs prune almost nothing. When the question asks for a count or a best value and subproblems repeat, dynamic programming is usually the better tool; when it asks for a best value and a good bound is available, branch and bound is.

Practise the template in this order: Subsets, Subsets II, Permutations, Permutations II, Combinations, Combination Sum, Palindrome Partitioning, Word Search, N-Queens and Sudoku Solver. The recursion lesson covers the call stack the template relies on, backtracking foundations builds the template step by step, and constraint-based backtracking adds forward checking and fewest-options-first ordering for Sudoku-style puzzles.

  • Use it to list all solutions, or find one under constraints
  • Worst case stays exponential; pruning changes the typical case
  • Repeated subproblems with a count or best value: use DP instead