Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Recursion

    Backtracking: Exploring Every Choice

    Walking through a maze with a piece of chalk. At each fork, choose a path and mark it. Walk until you reach the end or a dead end. At a dead end, walk back

    Chapter 6 of 95 min readOften asked in interviews

    The Plain Picture#

    Walking through a maze with a piece of chalk. At each fork, choose a path and mark it. Walk until you reach the end or a dead end. At a dead end, walk back to the last fork, rub out your mark, and try the next path. Eventually you've tried every path — without ever getting lost.

    The Real Names#

    Backtracking is recursion that builds a solution one choice at a time, explores each choice fully, then undoes it to try the next. Its shape is always:

    Output
      explore(state):
          if state is a complete solution: record it; return
          for each choice available now:
              CHOOSE    (apply the choice to the state)
              EXPLORE   explore(state)          ← recursion
              UNCHOOSE  (undo the choice)       ← the "back" in backtracking

    The choices form a decision tree; backtracking is a depth-first walk over it. The whole topic — pruning, N-Queens, Sudoku, combination sum — is in Backtracking (coming soon). Here are the two patterns every other problem builds on.

    Under the Hood#

    All subsets — "include it or not?"#

    For each item, there are exactly two choices: leave it out, or put it in.

    Java
    static void subsets(char[] items, int i, StringBuilder chosen, List<String> out) {
        if (i == items.length) {
            out.add("{" + chosen + "}");
            return;
        } // decided every item → a complete subset
    
        subsets(items, i + 1, chosen, out); // choice 1: EXCLUDE items[i]
    
        chosen.append(items[i]); // CHOOSE:   include items[i]
        subsets(items, i + 1, chosen, out); // EXPLORE
        chosen.deleteCharAt(chosen.length() - 1); // UNCHOOSE: undo, so the caller's state is unchanged
    }
    Output
    8 subsets: [{}, {c}, {b}, {bc}, {a}, {ac}, {ab}, {abc}]

    The decision tree (left = exclude, right = include):

                                   { }
                     a? ┌───────────┴───────────┐
                       { }                     {a}
             b? ┌───────┴──────┐        ┌──────┴───────┐
               { }            {b}      {a}           {ab}
          c? ┌──┴──┐       ┌──┴──┐   ┌──┴──┐       ┌──┴──┐
            {}   {c}     {b}  {bc} {a}  {ac}    {ab}  {abc}        ← 2³ = 8 leaves = 8 subsets

    n items → 2ⁿ subsets → O(2ⁿ · n) time (each subset takes O(n) to build and copy). That's why subset problems have n ≤ ~20 (Big-O and Complexity Ch 10).

    All permutations — "which item goes next?"#

    Java
    static void permutations(
        List<Character> remaining,
        StringBuilder built,
        List<String> out
    ) {
        if (remaining.isEmpty()) {
            out.add(built.toString());
            return;
        }
        for (int i = 0; i < remaining.size(); i++) {
            char c = remaining.remove(i);
            built.append(c); // CHOOSE c to go next
            permutations(remaining, built, out); // EXPLORE
            built.deleteCharAt(built.length() - 1);
            remaining.add(i, c); // UNCHOOSE: put everything back exactly
        }
    }
    Output
    6 permutations: [abc, acb, bac, bca, cab, cba]

    n choices, then n−1, then n−2… → n! orderings → O(n! · n). Permutation problems have n ≤ ~10.

    Why "unchoose" matters: there's one shared StringBuilder and one list for the whole search. If a call doesn't undo its change before returning, the caller continues with corrupted state and every later result is wrong. This is the #1 backtracking bug (Ch 9). (The alternative — passing a fresh copy down each branch — is simpler to reason about but costs O(n) per call.)

    Check yourself

    4 questions
    1

    What are the three steps inside a backtracking loop?

    Show answer

    Choose, explore (recurse), unchoose (undo).

    2

    How many subsets does a set of 4 items have? How many permutations?

    Show answer

    2⁴ = 16 subsets; 4! = 24 permutations.

    3

    What goes wrong if you forget to deleteCharAt after the "include" branch in subsets?

    Show answer

    The included character stays in chosen, so the caller's later branches start from the wrong state and produce wrong subsets.

    4

    Why do subset problems usually limit n to about 20?

    Show answer

    There are 2ⁿ subsets; 2²⁰ ≈ 1 million is fine, 2³⁰ ≈ 1 billion isn't.