Backtracking Basics

How a program can build every answer one choice at a time, undo each choice, and drop branches that cannot work.

Picture three coins on a table, worth 2, 3 and 5. Which handfuls of them pay exactly 5? By hand, you would pick up a coin, add another, and put the last one back when the total goes over 5. Then you would try a different coin in its place.

Backtracking is that habit written as a program. It builds an answer one choice at a time and undoes each choice once everything after it has been tried. It suits problems that ask for every selection, order or placement that follows some rules.

A tree of choices

Start with an easier question: which handfuls can you make at all from the coins [2, 3, 5]? Each coin is either in your hand or not, so there are 2 × 2 × 2 = 8 handfuls, counting the empty hand.

Tree of handfuls for coins 2, 3 and 5, with the visit order 1 to 8 and a dashed arrow backing up from [2, 3, 5] to [2].

Look at the box [ ] at the top of the picture: that is the empty hand. The three lines under it, labelled "add 2", "add 3" and "add 5", are the first choices you can make. Each one leads to a box holding the new handful. From [2] you can still add 3 or 5, and from [2, 3] only 5 is left. A drawing of all the choices like this is called a decision tree.

Why is there no "add 2" line under [3]? Because [3, 2] holds the same coins as [2, 3], which already sits under [2]. One rule keeps every handful to a single box: after a coin is picked, only coins to its right in [2, 3, 5] may follow.

The orange numbers give the order in which a search visits the boxes. It goes as deep as it can first: [ ], [2], [2, 3], [2, 3, 5]. Box 4, [2, 3, 5], has no choices left, so the search follows the dashed arrow labelled "back up: take out 5, then 3". Back at [2], it tries "add 5" and reaches box 5, [2, 5].

That step back is where the name comes from. Taking out the last coins to return to an earlier box, then trying the next choice from there, is called backtracking. Going down one branch to the bottom before starting the next one is called depth-first order.

Choose, explore, un-choose

How does a program walk that tree when it does not know how many coins it will get? Nested loops would need one loop per coin. The answer is a method that handles a single box and then calls itself for every box hanging below it. Here it is, named collect:

Java
static void collect(int[] coins, int start, List<Integer> hand, List<List<Integer>> result) {
    result.add(new ArrayList<>(hand));          // save a copy of this box
    for (int i = start; i < coins.length; i++) {
        hand.add(coins[i]);                     // choose
        collect(coins, i + 1, hand, result);    // explore
        hand.remove(hand.size() - 1);           // un-choose
    }
}

The parameter start is the index of the first coin this box may still add, and hand is a single list that the whole search shares and keeps changing. Each call first saves a copy of hand into result, since every box in the picture is a handful to report. Then the loop makes three moves for each coin it may add:

  1. Choose: hand.add(coins[i]) puts the coin in the hand, which moves down one line in the picture.
  2. Explore: collect(coins, i + 1, hand, result) visits every box below. Passing i + 1 as the new start lets only coins to the right follow.
  3. Un-choose: hand.remove(hand.size() - 1) takes the coin back out, so the next coin in the loop starts from the same hand.

The un-choose line is the dashed back-up arrow in the picture. Without it, the coins from one branch would still be in the hand when the next branch starts.

Cutting branches early

Now back to the first question: which handfuls pay exactly 5? The slow way is to let collect list all eight handfuls and then add up each one. That works, but it visits every box, even boxes whose total went over 5 several coins ago.

A better search keeps a running total and gives up on a branch as soon as it cannot work. In this picture each box shows its sum:

The same tree with sums for a target of 5: [2, 3] and [5] pay 5, [2, 5] and [3, 5] are cut, [2, 3, 5] is never tried.

The box [2] has sum 2, so 3 more are needed. Adding the 5 coin would make 7, so the box [2, 5] is never visited. It is drawn dashed, with the label "cut: 7 is over 5". The box [3, 5] is cut the same way. The teal box [2, 3] already pays 5, so it is saved and nothing more is added to it. That is why [2, 3, 5] is marked "never tried".

Dropping a branch early because it cannot lead to an answer is called pruning. The method pay does it with a parameter left, the amount still to pay. When left is 0, the hand is saved. Otherwise each coin is checked against left before it goes in:

Java
for (int i = start; i < coins.length; i++) {
    if (coins[i] > left) {
        break;                              // sorted: every later coin is too big too
    }
    hand.add(coins[i]);
    pay(coins, i + 1, left - coins[i], hand, result);
    hand.remove(hand.size() - 1);
}

The loop can break rather than skip just one coin because the method that starts the search, payExactly, sorts a copy of the coins first. Once one coin is too big, every coin to its right is bigger still.

With three coins the saving is small: the pruned search makes 5 calls, one per solid box, against 8 for the slow way. With more coins the gap is huge. For coins worth 1 to 20 and a target of 10, both ways find the same 10 handfuls. The slow way makes 1,048,576 calls, and the pruned search makes 43.

When order matters

What if the question changes to "in how many orders can the three coins be laid in a row?" Now [2, 3] and [3, 2] start different rows, so the rule "only coins to the right" no longer fits. Any coin may come next, as long as it is not in the row yet.

The method lay keeps a boolean array, used, with one entry per coin, saying which coins are already in the list row. Choosing a coin now changes two things, and un-choosing puts both back:

Java
for (int i = 0; i < coins.length; i++) {
    if (used[i]) {
        continue;                           // this coin is already in the row
    }
    used[i] = true;
    row.add(coins[i]);
    lay(coins, used, row, result);
    row.remove(row.size() - 1);
    used[i] = false;
}

Here a row is saved only when it holds all three coins, at the bottom of the tree. The tree of rows has 1 box at the top, 3 below it, 6 on the next level and 6 at the bottom. So lay is called 16 times to find 6 rows.

Equal values in the input

Swap the 5 for a second 3, so the coins are [2, 3, 3]. Run collect on them unchanged and it saves [2, 3] twice and [3] twice, once with each 3. As money, the two copies are the same handful, so each should appear once.

Tree for coins 2, 3, 3: the second 3 is skipped next to the first 3, but allowed one level deeper, giving [3, 3] and [2, 3, 3].

Two choices that leave the same box are called siblings. In the picture, "add 2", "add first 3" and "add second 3" are siblings under [ ]. Picking the second 3 right after its sibling, the first 3, leads to the same handfuls again. So that dashed line is marked "skipped", and under [2] the same thing happens.

The two orange lines are different. Under [3], the first 3 is already in the hand, and the second 3 is the first coin tried from that box. Adding it gives [3, 3], a handful nobody has made yet. The same goes for [2, 3, 3].

In code that takes two parts. The coins are sorted, so equal values sit side by side. Then the loop skips a coin that has the same value as the coin before it, but only when that coin was a sibling, which means i > start:

Java
for (int i = start; i < coins.length; i++) {
    if (i > start && coins[i] == coins[i - 1]) {
        continue;                           // same value as the sibling just tried
    }
    hand.add(coins[i]);
    collectNoRepeats(coins, i + 1, hand, result);
    hand.remove(hand.size() - 1);
}

The box [3] was made by adding the coin at index 1, so its call gets start = 2. The second 3 sits at index 2, so i > start is false and the coin is not skipped.

The complete program

The class below holds the four searches: subsets starts collect, payExactly starts pay, orders starts lay, and subsetsNoRepeats starts collectNoRepeats. A static counter, calls, goes up by one each time collect, pay or lay is entered, so it counts the boxes a search visits. The method payBySearchingAll is the slow way, kept for comparison.

Its main runs the coins [2, 3, 5] through the first three searches and the slow way. It also tries an empty coin list, an unsorted input, a target nothing can pay, the coins [2, 3, 3], and coins worth 1 to 20.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Backtracking {

    static int calls; // how many times a backtracking method was entered

    // Every handful of coins: each box of the tree is saved.
    static List<List<Integer>> subsets(int[] coins) {
        List<List<Integer>> result = new ArrayList<>();
        calls = 0;
        collect(coins, 0, new ArrayList<>(), result);
        return result;
    }

    static void collect(int[] coins, int start, List<Integer> hand, List<List<Integer>> result) {
        calls++;
        result.add(new ArrayList<>(hand));          // save a copy of this box
        for (int i = start; i < coins.length; i++) {
            hand.add(coins[i]);                     // choose
            collect(coins, i + 1, hand, result);    // explore
            hand.remove(hand.size() - 1);           // un-choose
        }
    }

    // Every handful that adds up to exactly target, cutting branches that go over it.
    static List<List<Integer>> payExactly(int[] coins, int target) {
        int[] sorted = coins.clone();
        Arrays.sort(sorted);
        List<List<Integer>> result = new ArrayList<>();
        calls = 0;
        pay(sorted, 0, target, new ArrayList<>(), result);
        return result;
    }

    static void pay(int[] coins, int start, int left, List<Integer> hand,
                    List<List<Integer>> result) {
        calls++;
        if (left == 0) {                            // the hand pays exactly the target
            result.add(new ArrayList<>(hand));
            return;
        }
        for (int i = start; i < coins.length; i++) {
            if (coins[i] > left) {
                break;                              // sorted: every later coin is too big too
            }
            hand.add(coins[i]);
            pay(coins, i + 1, left - coins[i], hand, result);
            hand.remove(hand.size() - 1);
        }
    }

    // The slow way: list every handful first, then keep the ones that add up to target.
    static List<List<Integer>> payBySearchingAll(int[] coins, int target) {
        List<List<Integer>> result = new ArrayList<>();
        for (List<Integer> hand : subsets(coins)) {
            int sum = 0;
            for (int c : hand) {
                sum += c;
            }
            if (sum == target) {
                result.add(hand);
            }
        }
        return result;
    }

    // Every order of laying all the coins in a row.
    static List<List<Integer>> orders(int[] coins) {
        List<List<Integer>> result = new ArrayList<>();
        calls = 0;
        lay(coins, new boolean[coins.length], new ArrayList<>(), result);
        return result;
    }

    static void lay(int[] coins, boolean[] used, List<Integer> row, List<List<Integer>> result) {
        calls++;
        if (row.size() == coins.length) {
            result.add(new ArrayList<>(row));
            return;
        }
        for (int i = 0; i < coins.length; i++) {
            if (used[i]) {
                continue;                           // this coin is already in the row
            }
            used[i] = true;
            row.add(coins[i]);
            lay(coins, used, row, result);
            row.remove(row.size() - 1);
            used[i] = false;
        }
    }

    // Every handful once, even when two coins have the same value.
    static List<List<Integer>> subsetsNoRepeats(int[] coins) {
        int[] sorted = coins.clone();
        Arrays.sort(sorted);
        List<List<Integer>> result = new ArrayList<>();
        collectNoRepeats(sorted, 0, new ArrayList<>(), result);
        return result;
    }

    static void collectNoRepeats(int[] coins, int start, List<Integer> hand,
                                 List<List<Integer>> result) {
        result.add(new ArrayList<>(hand));
        for (int i = start; i < coins.length; i++) {
            if (i > start && coins[i] == coins[i - 1]) {
                continue;                           // same value as the sibling just tried
            }
            hand.add(coins[i]);
            collectNoRepeats(coins, i + 1, hand, result);
            hand.remove(hand.size() - 1);
        }
    }

    public static void main(String[] args) {
        int[] coins = {2, 3, 5};
        System.out.println("subsets " + subsets(coins) + ", calls " + calls);
        System.out.println("subsets of [] " + subsets(new int[] {}));

        System.out.println("pay 5 " + payExactly(coins, 5) + ", calls " + calls);
        System.out.println("pay 5, slow way " + payBySearchingAll(coins, 5) + ", calls " + calls);
        System.out.println("pay 7 from [5, 3, 2] " + payExactly(new int[] {5, 3, 2}, 7));
        System.out.println("pay 1 " + payExactly(coins, 1) + ", calls " + calls);

        System.out.println("orders " + orders(coins) + ", calls " + calls);

        int[] twoThrees = {2, 3, 3};
        System.out.println("plain subsets of [2, 3, 3] " + subsets(twoThrees));
        System.out.println("no repeats " + subsetsNoRepeats(twoThrees));

        int[] oneToTwenty = new int[20];
        for (int i = 0; i < 20; i++) {
            oneToTwenty[i] = i + 1;
        }
        int found = payBySearchingAll(oneToTwenty, 10).size();
        System.out.println("1..20, pay 10, slow way: " + found + " handfuls, calls " + calls);
        found = payExactly(oneToTwenty, 10).size();
        System.out.println("1..20, pay 10, pruned:   " + found + " handfuls, calls " + calls);
    }
}

Running it prints:

Output
subsets [[], [2], [2, 3], [2, 3, 5], [2, 5], [3], [3, 5], [5]], calls 8
subsets of [] [[]]
pay 5 [[2, 3], [5]], calls 5
pay 5, slow way [[2, 3], [5]], calls 8
pay 7 from [5, 3, 2] [[2, 5]]
pay 1 [], calls 1
orders [[2, 3, 5], [2, 5, 3], [3, 2, 5], [3, 5, 2], [5, 2, 3], [5, 3, 2]], calls 16
plain subsets of [2, 3, 3] [[], [2], [2, 3], [2, 3, 3], [2, 3], [3], [3, 3], [3]]
no repeats [[], [2], [2, 3], [2, 3, 3], [3], [3, 3]]
1..20, pay 10, slow way: 10 handfuls, calls 1048576
1..20, pay 10, pruned:   10 handfuls, calls 43

The first line lists the eight handfuls in the order of the orange numbers in the first picture, from [] to [5], with 8 calls. For an empty coin list the answer is [[]], not []: the empty hand is still one handful.

The line pay 5 [[2, 3], [5]], calls 5 matches the five solid boxes of the second picture, and the slow way finds the same two handfuls with 8 calls. The coins [5, 3, 2] arrive unsorted, yet pay 7 still finds [[2, 5]], because payExactly sorts a copy first. For pay 1, the smallest coin, 2, is already over 1, so the loop breaks at once and only the first call is made.

The orders line shows the 6 rows from 16 calls. Next, the plain search on [2, 3, 3] saves eight lists with [2, 3] and [3] each appearing twice, while no repeats keeps the six handfuls drawn solid in the third picture.

The last two lines are the 1 to 20 comparison: the same 10 handfuls, from 1,048,576 calls the slow way and 43 calls with pruning.

Typical traps

What goes wrong when one line of the template is off? Each of the following mistakes compiles, runs and gives a wrong answer without any error message:

  • Saving hand itself with result.add(hand) instead of a copy made with new ArrayList<>(hand).
  • Leaving out the un-choose line, hand.remove(hand.size() - 1).
  • Writing the sibling check as i > 0 instead of i > start.
  • Using the right sibling check on coins that were never sorted.

This program has one method per mistake, each run on the coins used so far:

Java
import java.util.ArrayList;
import java.util.List;

public class BacktrackingTraps {

    // Trap 1: saves the shared list itself instead of a copy.
    static void noCopy(int[] coins, int start, List<Integer> hand, List<List<Integer>> result) {
        result.add(hand);
        for (int i = start; i < coins.length; i++) {
            hand.add(coins[i]);
            noCopy(coins, i + 1, hand, result);
            hand.remove(hand.size() - 1);
        }
    }

    // Trap 2: never takes the coin back out.
    static void noUnchoose(int[] coins, int start, List<Integer> hand,
                           List<List<Integer>> result) {
        result.add(new ArrayList<>(hand));
        for (int i = start; i < coins.length; i++) {
            hand.add(coins[i]);
            noUnchoose(coins, i + 1, hand, result);
        }
    }

    // Trap 3: compares with the previous coin even when it is not a sibling (i > 0).
    static void skipTooMuch(int[] coins, int start, List<Integer> hand,
                            List<List<Integer>> result) {
        result.add(new ArrayList<>(hand));
        for (int i = start; i < coins.length; i++) {
            if (i > 0 && coins[i] == coins[i - 1]) {
                continue;
            }
            hand.add(coins[i]);
            skipTooMuch(coins, i + 1, hand, result);
            hand.remove(hand.size() - 1);
        }
    }

    // Trap 4: the right skip check, but on input that was not sorted.
    static void unsortedSkip(int[] coins, int start, List<Integer> hand,
                             List<List<Integer>> result) {
        result.add(new ArrayList<>(hand));
        for (int i = start; i < coins.length; i++) {
            if (i > start && coins[i] == coins[i - 1]) {
                continue;
            }
            hand.add(coins[i]);
            unsortedSkip(coins, i + 1, hand, result);
            hand.remove(hand.size() - 1);
        }
    }

    public static void main(String[] args) {
        List<List<Integer>> result = new ArrayList<>();
        noCopy(new int[] {2, 3, 5}, 0, new ArrayList<>(), result);
        System.out.println("no copy:       " + result);

        result = new ArrayList<>();
        noUnchoose(new int[] {2, 3, 5}, 0, new ArrayList<>(), result);
        System.out.println("no un-choose:  5th saved " + result.get(4)
                + ", last saved " + result.get(result.size() - 1));

        result = new ArrayList<>();
        skipTooMuch(new int[] {2, 3, 3}, 0, new ArrayList<>(), result);
        System.out.println("i > 0:         " + result);

        result = new ArrayList<>();
        unsortedSkip(new int[] {3, 2, 3}, 0, new ArrayList<>(), result);
        System.out.println("not sorted:    " + result);
    }
}

Running it prints:

Output
no copy:       [[], [], [], [], [], [], [], []]
no un-choose:  5th saved [2, 3, 5, 5], last saved [2, 3, 5, 5, 3, 5, 5]
i > 0:         [[], [2], [2, 3], [3]]
not sorted:    [[], [3], [3, 2], [3, 2, 3], [3, 3], [2], [2, 3], [3]]

The no copy line holds eight empty lists. The result holds the same hand list eight times, and by the end the search has taken every coin back out of it.

In the no un-choose line, the fifth handful should be [2, 5], as in box 5 of the first picture. It comes out as [2, 3, 5, 5], because the 3 and the 5 from the branch before were never taken out. The last saved list, [2, 3, 5, 5, 3, 5, 5], holds seven coins from a set of three.

The i > 0 line has only four handfuls. Both [3, 3] and [2, 3, 3] are missing, because that check also blocks the two orange lines in the third picture. In the not sorted line, the coins [3, 2, 3] keep the two 3s apart, so the check never fires. The output repeats [3], and has both [3, 2] and [2, 3].

Spotting a backtracking problem

When is backtracking the right tool? Look for a problem that asks for every way, or for one way, to build something from a series of choices under rules. Typical wording is "list all subsets", "every arrangement", or "place the pieces so that no two clash". The inputs are usually small, because the number of answers grows very fast.

Adapting the template to such a problem means answering four questions. Here are the answers for the three searches on the coins:

QuestionEvery handfulPay exactly 5Every order
What has been built so far?the coins in the handthe coins in the hand and the amount leftthe coins in the row, and which are used
What can come next?any coin to the right of the last oneany coin to the right that is not over the amount leftany coin not used yet
When is a branch dropped?neverwhen the next coin is over the amount leftnever; used coins are skipped
When is an answer saved?at every boxwhen the amount left is 0when the row holds every coin

How much work it is

The cost of a backtracking search is the number of boxes it visits times the work done in each box. For n coins:

  • Every handful: O(n · 2n) time, because each coin doubles the number of boxes, which gives 2n of them, and saving a box copies up to n coins.
  • Every order: O(n · n!) time, because the bottom level holds n! rows and the levels above hold fewer than 2 · n! boxes together, each running a loop over n coins.
  • Pay exactly a target: O(n · 2n) time in the worst case, because pruning only removes boxes from the full tree. How many it removes depends on the coins and the target, as the drop from 1,048,576 calls to 43 shows.
  • Space: O(n) besides the answers, because the hand, the row and the chain of open calls never go deeper than n coins.

When a problem asks only how many handfuls pay an amount, not for the handfuls themselves, the same amount left comes up in many branches. Remembering the answer for each amount left, instead of searching it again, is the idea behind dynamic programming.

Where to go next

Picking a selection, where order does not matter:

  • Subsets lists every subset of distinct numbers, the same way collect lists every handful.
  • Subsets II adds equal values and the sibling check.
  • Combination Sum pays a target when each number may be used again and again.
  • Combination Sum II pays a target with each number used once, with pruning and equal values together.

Building an order:

Placing things under rules:

  • N-Queens places queens row by row and drops a square as soon as another queen attacks it.
  • Sudoku Solver fills one cell at a time and undoes digits that lead nowhere.
  • Word Search walks a path through a letter grid, marking cells and unmarking them on the way back.