Lesson 21 · Core algorithms

Backtracking Foundations

Every backtracking solution is the same short function: if the partial answer is complete, record it; otherwise try each option that does not break a rule, recurse, and undo the option before trying the next. This lesson builds that function from scratch and shows how to estimate what it costs.

Backtracking Foundations concept diagramA line chart of recursion depth over time for listing binary strings of length 3 with no two 1s together. The line steps down one level for each choice and climbs back up, dashed, for each undo. It reaches depth 3 five times, recording 000, 001, 010, 100 and 101. Two short red stubs mark the 1s rejected after a 1, where no call is made. The run uses 11 calls and never goes deeper than 3 levels.depth 0path emptydepth 11 bitdepth 22 bitsdepth 33 bits000000100111 ✕001011 ✕001001101choose: append, callunchoose: pop, returnpruned: no call made11 calls · 2 pruned · 5 strings · never deeper than n = 3
1

Three Questions Before Writing Code

Backtracking solves problems where an answer is built from a sequence of small decisions and some sequences break a rule. The running example here: list every binary string of length n with no two 1s next to each other. For n = 3 the answers are 000, 001, 010, 100 and 101.

Before any code, answer three questions. What is a partial answer? The bits chosen so far, kept in one list called the path. What can go next? A 0 or a 1. When is it finished? When the path holds n bits. A fourth question turns a slow search into a fast one: when is a partial answer already hopeless? Here, as soon as it ends in 11.

Each call of the function is responsible for one decision, the next slot. It makes a choice and hands the rest to a deeper call, so the depth of the recursion equals the number of slots filled. The recursion lesson covers how those calls stack up.

  • State: the path, the choices made so far
  • Options: what may be added next
  • Goal: the test for a complete answer
  • Dead end: the earliest sign that no completion can work
2

The Template

  1. If the path is complete, save a copy and return
  2. Loop over every option for the next slot
  3. Skip an option that breaks a rule
  4. Choose: add the option to the path
  5. Explore: call the function again for the next slot
  6. Unchoose: remove the option, so the path is back to how it was

This backtracking template fits almost every listing problem: subsets, permutations, combinations, parentheses, word search. Only the three answers change. In Python the body for the running example is five lines: if len(path) == n: save; for bit in "01": if bit == "1" and path and path[-1] == "1": continue; path.append(bit); solve(); path.pop().

Choose explore unchoose is the heart of it. One path list is shared by every call, which keeps memory small, but it also means a call must leave the list exactly as it found it. The pop after the call is what returns the path to its earlier state, so the next option can sit in the same slot.

The base case goes before the loop. That ordering is what makes n = 0 work: the first call sees a complete, empty path and records it, giving one answer, the empty string, without entering the loop.

  • Only the answers to the three questions change between problems
  • One shared path keeps memory at O(n), but every change needs an undo
  • Passing a fresh copy into each call removes the undo, at O(n) extra work per call
3

Pruning in Backtracking

Pruning in backtracking means rejecting an option before the recursive call, not after a full answer is built. In the example the check previous bit is 1 sits inside the loop. When it fires, no call is made, and every string that would have started with that prefix disappears in one test.

The saving is large because a rejected prefix carries a whole subtree with it. For n = 20 there are 17,711 valid strings. With the check in the loop the search makes 46,366 calls. Building all 2²⁰ strings and filtering at the end makes 2,097,151 calls, about 45 times as many, for the same answers.

Two kinds of check cover most problems. A rule check rejects an option that breaks a constraint now, like a 1 after a 1 or a queen on an attacked square. A reachability check rejects a path that can no longer reach the goal, like a running sum that already passes the target when every remaining number is positive. The backtracking lesson shows both on N-Queens.

  • Check in the loop, before the call: a skipped call skips its whole subtree
  • A cut near the root removes far more work than one near the leaves
  • Pruning never changes the answers, only how many calls it takes to find them
Key reference

Terms, operations, and practical uses

Key terms

  • PathThe single shared list holding the choices made so far.
  • Base caseThe check that the path is a complete answer; it records a copy and returns.
  • UnchooseUndoing the last choice after its call returns, so the path is as it was.
  • PruningSkipping an option before the call because it cannot lead to an answer.
Implementation

Code in Python, C++ and Java

def strings_without_11(n, prune=True):
    results, path, calls = [], [], 0

    def solve():
        nonlocal calls
        calls += 1
        if len(path) == n:
            results.append("".join(path))
            return
        for bit in "01":
            if prune and bit == "1" and path and path[-1] == "1":
                continue
            path.append(bit)
            solve()
            path.pop()

    solve()
    if not prune:
        results = [s for s in results if "11" not in s]
    return results, calls


found, calls = strings_without_11(3)
print("n = 3:", " ".join(found), "| calls:", calls)
for prune in (True, False):
    found, calls = strings_without_11(20, prune)
    print("n = 20, pruning" if prune else "n = 20, filter at end", "->", len(found), "strings,", calls, "calls")
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int n, calls;
bool prune;
string path;
vector<string> results;

void solve() {
    calls++;
    if ((int)path.size() == n) {
        if (prune || path.find("11") == string::npos) results.push_back(path);
        return;
    }
    for (char bit : {'0', '1'}) {
        if (prune && bit == '1' && !path.empty() && path.back() == '1') continue;
        path.push_back(bit);
        solve();
        path.pop_back();
    }
}

void run(int size, bool usePruning) {
    n = size; prune = usePruning; calls = 0; path.clear(); results.clear();
    solve();
}

int main() {
    run(3, true);
    cout << "n = 3:";
    for (auto& s : results) cout << " " << s;
    cout << " | calls: " << calls << "\n";
    for (bool p : {true, false}) {
        run(20, p);
        cout << (p ? "n = 20, pruning" : "n = 20, filter at end") << " -> " << results.size() << " strings, " << calls << " calls\n";
    }
}
import java.util.ArrayList;
import java.util.List;

public class Main {
    static int n, calls;
    static boolean prune;
    static StringBuilder path = new StringBuilder();
    static List<String> results = new ArrayList<>();

    static void solve() {
        calls++;
        if (path.length() == n) {
            String s = path.toString();
            if (prune || !s.contains("11")) results.add(s);
            return;
        }
        for (char bit : new char[] {'0', '1'}) {
            if (prune && bit == '1' && path.length() > 0 && path.charAt(path.length() - 1) == '1') continue;
            path.append(bit);
            solve();
            path.deleteCharAt(path.length() - 1);
        }
    }

    static void run(int size, boolean usePruning) {
        n = size; prune = usePruning; calls = 0; path.setLength(0); results.clear();
        solve();
    }

    public static void main(String[] args) {
        run(3, true);
        System.out.println("n = 3: " + String.join(" ", results) + " | calls: " + calls);
        for (boolean p : new boolean[] {true, false}) {
            run(20, p);
            System.out.println((p ? "n = 20, pruning" : "n = 20, filter at end") + " -> " + results.size() + " strings, " + calls + " calls");
        }
    }
}
Watch it run

Step through it

Running on n = 3, rule: never put a 1 right after a 1

rule: never put a 1 right after a 1PATH (shared list)slot 0slot 1slot 2CALL STACKsolve(0) slot 0: try 0, 1RESULTS(none yet)calls 1 · pruned 0state = path · choices = 0 or 1 · done = 3 bits
Step 1

Start with an empty path

The answer is built in one shared list, the path. solve(0) is asked to fill slot 0. Three questions set up any backtracking search: what is a partial answer (the path so far), what can go next (0 or 1), and when is it finished (three bits).

Output
1 / 16
4

Backtracking Time Complexity

The time complexity of backtracking is found by counting calls, then multiplying by the work done in one call. Each call loops over at most b options, and the depth is at most n, so the search makes at most about bⁿ calls. Pruning lowers the real count; it rarely lowers the worst case.

Work per call is usually the rule check plus, at the leaves, copying an answer of length n. That copy is why many listings cost O(n × number of answers). Subsets of n items give 2ⁿ answers and O(n · 2ⁿ) time. Permutations give n! answers and O(n · n!) time. The no-11 strings grow like the Fibonacci numbers, about 1.618ⁿ, so the search costs O(n · 1.618ⁿ) instead of O(n · 2ⁿ).

Space is the depth of the recursion plus the path, O(n), because only one path exists at a time. The output list is separate and can be far larger. If you only need to count answers or find the first one, skip storing them and the space stays O(n).

  • Time: calls × work per call
  • Calls are at most branching factor ^ depth; pruning lowers the typical count
  • Space: O(depth) for the stack and path, plus whatever output you keep
5

Three Slips That Break It

No undo. Drop the pop and the path keeps every old choice. In the example the path grows to 0001 after the first answer, its length never equals 3 again, and the calls go deeper until the recursion limit stops the program. The rule: one undo for every change, in reverse order.

Saving the live list. results.append(path) stores a reference to the one shared list. When the search ends that list is empty, so every saved entry reads []. Save path[:], a joined string, or new ArrayList<>(path) in Java.

Checking too late. Testing the rule only in the base case gives correct answers but makes the search visit every complete string, which is brute force. Move each check to the earliest point where it can be decided.

  • Print the path when a call starts and when it returns: the two must match
  • Test n = 0 and n = 1 before anything larger
  • On small inputs, compare the count with a brute-force version
6

Practice and Next Steps

These problems use the same function with different answers to the three questions. Work through them in this order.

Once the template is natural, constraint-based backtracking adds smarter ordering and look-ahead for puzzles like Sudoku, and branch and bound prunes on the best answer found so far.