Skip to lesson

What backtracking is

Plain recursion computes one answer from smaller answers, such as summing an array or finding a Fibonacci number. When a problem asks you to search through many possible combinations, arrangements, or paths—and abandon any path the moment it breaks a rule—you need backtracking.

Choices, constraints and goal

Backtracking builds a solution step by step, tries a choice, explores further and undoes the choice if it leads nowhere, until every valid solution is found.

Backtracking is systematic trial-and-error search built on recursion: you build a candidate solution one step at a time and step back (backtrack) as soon as the current partial candidate cannot possibly lead to a valid answer.

Java
static void build(StringBuilder path, int n) {    if (path.length() == n) {                     // goal: the candidate is complete        System.out.println(path);        return;    }    for (char c = '0'; c <= '1'; c++) {           // choices: append 0 or 1        boolean endsWithOne = path.length() > 0 && path.charAt(path.length() - 1) == '1';        if (c == '1' && endsWithOne) continue;    // constraint: no "11"        path.append(c);                           // choose        build(path, n);                           // explore        path.deleteCharAt(path.length() - 1);     // un-choose    }}

Picture walking through a maze with chalk in your hand: at each junction you pick one corridor, mark it, and walk forward; if you hit a dead end, you walk back to the junction, erase your mark, and try the next corridor.

Every backtracking problem is defined by three parts. Once you can state these three parts in plain English, the recursive method almost writes itself.

  • Choices: What options can I pick for the next step from my current state? (For example, which digit 0 or 1 to append next, or which unused number to place in the next slot.)
  • Constraints: Which choices are legal right now, and which partial states are already dead ends that we should abandon immediately?
  • Goal (base case): How do I know my partial candidate is complete so I can record it (or return true) and stop going deeper?

Choose, explore, un-choose

Why not create a brand-new ArrayList or String before every recursive call? Because creating a copy at every node of a tree with 2ⁿ or n! nodes wastes both time and heap memory.

  1. Check the goal: If the current state satisfies the goal, record a copy of it (new ArrayList<>(current)) into the results list and return.
  2. Loop over choices: For each candidate option available at this step, check the constraints; skip any option that violates a rule.
  3. 1. Choose: Apply the choice to the shared state (for example, current.add(choice) or used[i] = true).
  4. 2. Explore: Call backtrack(...) recursively to make the remaining decisions.
  5. 3. Un-choose (backtrack): Undo the exact change you made in step 1 (current.remove(current.size() - 1) or used[i] = false) before the next loop iteration runs.

Example 1 · Tracing Choose, Explore, Un-choose on Binary Strings

BinaryStringsTrace.javaJava
import java.util.ArrayList;import java.util.List;
public class BinaryStringsTrace {    public static void generate(int n, StringBuilder current, List<String> results) {        if (current.length() == n) {            System.out.println("  Goal reached -> record \"" + current + "\"");            results.add(current.toString());            return;        }        for (char bit : new char[]{'0', '1'}) {            current.append(bit); // 1. Choose            System.out.println("Choose '" + bit + "' -> state is \"" + current + "\"");            generate(n, current, results); // 2. Explore            current.deleteCharAt(current.length() - 1); // 3. Un-choose            System.out.println("Un-choose '" + bit + "' -> back to \"" + current + "\"");        }    }
    public static void main(String[] args) {        List<String> results = new ArrayList<>();        generate(2, new StringBuilder(), results);        System.out.println("All results: " + results);    }}
Output
Choose '0' -> state is "0"
Choose '0' -> state is "00"
  Goal reached -> record "00"
Un-choose '0' -> back to "0"
Choose '1' -> state is "01"
  Goal reached -> record "01"
Un-choose '1' -> back to "0"
Un-choose '0' -> back to ""
Choose '1' -> state is "1"
Choose '0' -> state is "10"
  Goal reached -> record "10"
Un-choose '0' -> back to "1"
Choose '1' -> state is "11"
  Goal reached -> record "11"
Un-choose '1' -> back to "1"
Un-choose '1' -> back to ""
All results: [00, 01, 10, 11]

What this code does

  • One StringBuilder (current) is shared across the entire recursion; it grows to length 2 on the way down and shrinks back to "" on the way up.
  • Notice how every Choose line is paired with a matching Un-choose line that restores current to its exact state before that choice.
  • At the base case (current.length() == n), current.toString() creates an independent String snapshot so later deleteCharAt calls do not affect saved answers.

Example 2 · Adding a Constraint: Binary Strings Without Consecutive Ones

NoConsecutiveOnes.javaJava
import java.util.ArrayList;import java.util.List;
public class NoConsecutiveOnes {    public static List<String> validBinaryStrings(int n) {        List<String> results = new ArrayList<>();        backtrack(n, new StringBuilder(), results);        return results;    }
    private static void backtrack(int n, StringBuilder path, List<String> results) {        if (path.length() == n) {            results.add(path.toString());            return;        }
        // Choice 1: '0' is always allowed        path.append('0');        backtrack(n, path, results);        path.deleteCharAt(path.length() - 1);
        // Choice 2: '1' is allowed ONLY if the previous char is not '1'        if (path.isEmpty() || path.charAt(path.length() - 1) != '1') {            path.append('1');            backtrack(n, path, results);            path.deleteCharAt(path.length() - 1);        }    }
    public static void main(String[] args) {        System.out.println("n = 3: " + validBinaryStrings(3));        System.out.println("n = 4: " + validBinaryStrings(4));    }}
Output
n = 3: [000, 001, 010, 100, 101]
n = 4: [0000, 0001, 0010, 0100, 0101, 1000, 1001, 1010]

What this code does

  • Instead of generating all 2ⁿ strings and filtering them at the end, the constraint path.isEmpty() || path.charAt(path.length() - 1) != '1' blocks '1' immediately after '1'.
  • When path is "11", we never even enter that branch—so for n = 4, the entire subtree starting with "11..." ("1100", "1101", "1110", "1111") is skipped in one check.

Example 3 · The Reference Trap vs Copying at the Base Case

SnapshotTrapDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class SnapshotTrapDemo {    public static void backtrackWrong(int n, List<Integer> current, List<List<Integer>> results) {        if (current.size() == n) {            results.add(current); // BUG: adds the shared mutable list reference!            return;        }        for (int val = 1; val <= 2; val++) {            current.add(val);            backtrackWrong(n, current, results);            current.remove(current.size() - 1);        }    }
    public static void backtrackRight(int n, List<Integer> current, List<List<Integer>> results) {        if (current.size() == n) {            results.add(new ArrayList<>(current)); // FIX: snapshot copy            return;        }        for (int val = 1; val <= 2; val++) {            current.add(val);            backtrackRight(n, current, results);            current.remove(current.size() - 1);        }    }
    public static void main(String[] args) {        List<List<Integer>> wrong = new ArrayList<>();        backtrackWrong(2, new ArrayList<>(), wrong);        System.out.println("Wrong (no copy): " + wrong);
        List<List<Integer>> right = new ArrayList<>();        backtrackRight(2, new ArrayList<>(), right);        System.out.println("Right (with copy): " + right);    }}
Output
Wrong (no copy): [[], [], [], []]
Right (with copy): [[1, 1], [1, 2], [2, 1], [2, 2]]

What this code does

  • backtrackWrong adds current directly to results four times. Because all four entries point to the exact same ArrayList object, and current.remove(...) empties that list as recursion unwinds, wrong ends up holding four references to the same empty list [].
  • backtrackRight calls new ArrayList<>(current) at the base case, freezing a snapshot of [1, 1], [1, 2], [2, 1], and [2, 2] before current is mutated further.

Instead, backtracking keeps one shared mutable state—such as a StringBuilder or List<Integer> current—and modifies it in place. Because every recursive call shares that same object, any change you make before calling backtrack(...) must be undone immediately after the call returns, so the parent frame sees the exact state it had before trying that branch. This three-line rhythm inside a loop is the heart of backtracking:

Order of execution

One step of backtracking

Tap the steps in the order one call runs them.

Always add new ArrayList<>(current)—never current itself—to your results list at the base case. If you add the shared current reference directly, the un-choose steps will empty it out on the way back up, leaving you with a list of empty lists!

The state space tree

If you draw every partial candidate as a node and every choice as a downward arrow, you get a state space tree (also called a decision tree). The root at the top is the empty starting state []. Each level d represents the d-th decision, and the leaves at the bottom are complete candidates.

For example, when generating all 2-character strings from 'A' and 'B', the root "" branches into "A" and "B". From "A", we branch into "AA" (leaf) and "AB" (leaf), undoing back to "A" between them, then undoing back to "" before exploring "B" → "BA", "BB". Backtracking is simply a depth-first traversal of this state space tree that builds and tears down the state as it walks down and up the edges.

When constraints reject a node halfway down the tree (say at depth 2 out of 10), backtracking never visits the subtree underneath it. Cutting off an entire branch early is called pruning, and it is what makes backtracking much faster than blind brute force.

State Space Tree for 2-Bit Binary Strings (Choose, Explore, Un-choose)

Step 1 of 4

"""0""1""00"goal!"01""10""11"
current
"00"
depth
2
results
  1. 00
From root "", choose '0' -> "0", then choose '0' -> leaf "00". Goal reached (length 2): record "00".

How to spot this pattern

Reach for backtracking when you must build an answer from a series of choices and some choices can be rejected early.

  • The problem says "list all", "every arrangement" or "is there any way to...".
  • The answer is built step by step: pick, place, include or skip one item at a time.
  • A rule lets you reject a partial answer early (the sum is already too big, two queens attack each other).
  • The input is small (n up to about 20, or a 9 × 9 board), because the candidates grow like 2ⁿ or n!.

Next step

Check your understanding

10 quick questions