Backtracking

How backtracking builds every subset, ordering or valid arrangement by choosing, exploring and undoing, and how interviewers test it.

17 minLesson 1 of 5
On this page
  1. How backtracking works
  2. Listing all subsets
  3. Time and space cost
  4. Variants of the template
  5. What interviewers ask about backtracking
  6. Related lessons

Backtracking is a way to generate every answer to a problem that is built from a series of choices, such as all subsets of a list, all orderings of a list, or all valid placements on a board. It uses one shared partial answer, extends it with a choice, recurses to make the remaining choices, and then removes the choice so the next option can be tried. You reach for it when a problem asks for all solutions, or for any solution that satisfies rules that can be checked while the answer is still being built.

The alternative is to build every complete candidate and check it afterwards. Backtracking tests each choice before making it, and drops a partial answer as soon as it breaks a rule, along with every answer that would have grown from it.

How backtracking works

The search keeps one list called path, which holds the choices made so far. At each decision point, a recursive function goes through the options that are still allowed and does three things for each one:

  1. Choose the option by adding it to the path.
  2. Explore by calling the function recursively to make the remaining decisions.
  3. Un-choose by removing the option from the path, which restores the path to what it was before step 1 so that the next option starts from the same state.

The call stack remembers where each decision point was, as in Recursion. Un-choosing is what lets all branches of the search share a single path instead of each branch copying it.

The simplest example is listing every sandwich you can make from three extras: cheese (C), egg (E) and tomato (T), including the plain sandwich with none. To avoid listing "egg then cheese" after "cheese then egg", each call only offers the extras that come after the last one chosen.

+C +E +T +E +T +T +T ∅ C E T CE CT ET CET a call only adds extras to the right of its last one
The call tree for three extras. Each node is one sandwich, and each sandwich appears exactly once.

Listing all subsets

The trace below follows the search from the first call. The path holds the sandwich being built, and the recorded list holds a copy of every sandwich found so far. Every call records the path as it stands, because every partial sandwich is itself a valid sandwich.

Listing every sandwich from three extrasUse the arrows or ← → keys
explore(start):  record a copy of path  for i from start to n - 1:    path.push(extras[i])    # choose    explore(i + 1)          # explore    path.pop()              # un-choose
  1. extras
    0C
    1E
    2T
    path
    recorded
    0∅
    start
    0

    1explore(0) starts with an empty path, which is a plain sandwich with no extras, so it records a copy of it.

  2. extras
    0Ci
    1E
    2T
    path
    0C
    recorded
    0∅
    start
    0

    2The loop chooses cheese by pushing C onto the path.

  3. extras
    0C
    1E
    2T
    path
    0C
    recorded
    0∅
    1C
    start
    1

    3explore(1) records the path C.

  4. extras
    0C
    1Ei
    2T
    path
    0C
    1E
    recorded
    0∅
    1C
    start
    1

    4explore(1) loops from index 1, so it pushes E.

  5. extras
    0C
    1E
    2T
    path
    0C
    1E
    recorded
    0∅
    1C
    2CE
    start
    2

    5explore(2) records CE.

  6. extras
    0C
    1E
    2Ti
    path
    0C
    1E
    2T
    recorded
    0∅
    1C
    2CE
    start
    2

    6The loop pushes T, the last extra.

  7. extras
    0C
    1E
    2T
    path
    0C
    1E
    2T
    recorded
    0∅
    1C
    2CE
    3CET
    start
    3

    7explore(3) records CET. Its loop has nothing left to try, so it returns.

  8. extras
    0C
    1E
    2Ti
    path
    0C
    1E
    recorded
    0∅
    1C
    2CE
    3CET
    start
    2

    8Back in explore(2), the loop un-chooses by popping T. The path is CE again, and explore(2) returns.

  9. extras
    0C
    1Ei
    2T
    path
    0C
    recorded
    0∅
    1C
    2CE
    3CET
    start
    1

    9explore(1) pops E, which leaves the path as C, and its loop then moves on to tomato.

  10. extras
    0C
    1E
    2Ti
    path
    0C
    1T
    recorded
    0∅
    1C
    2CE
    3CET
    start
    1

    10The loop pushes T, so the path is CT.

  11. extras
    0C
    1E
    2T
    path
    0C
    1T
    recorded
    0∅
    1C
    2CE
    3CET
    4CT
    start
    3

    11explore(3) records CT and returns immediately.

  12. extras
    0C
    1E
    2Ti
    path
    0C
    recorded
    0∅
    1C
    2CE
    3CET
    4CT
    start
    1

    12explore(1) pops T, and its loop is finished.

  13. extras
    0Ci
    1E
    2T
    path
    recorded
    0∅
    1C
    2CE
    3CET
    4CT
    start
    0

    13explore(0) pops C. Every sandwich that contains cheese has been recorded, so its loop moves on to egg.

  14. extras
    0C
    1Ei
    2T
    path
    0E
    recorded
    0∅
    1C
    2CE
    3CET
    4CT
    start
    0

    14The loop pushes E. The recursive call only offers extras after E, so cheese is never offered again and EC is never recorded.

  15. extras
    0C
    1E
    2T
    path
    0E
    recorded
    0∅
    1C
    2CE
    3CET
    4CT
    5E
    start
    2

    15explore(2) records E.

  16. extras
    0C
    1E
    2Ti
    path
    0E
    1T
    recorded
    0∅
    1C
    2CE
    3CET
    4CT
    5E
    start
    2

    16The loop pushes T, so the path is ET.

  17. extras
    0C
    1E
    2T
    path
    0E
    1T
    recorded
    0∅
    1C
    2CE
    3CET
    4CT
    5E
    6ET
    start
    3

    17explore(3) records ET.

  18. extras
    0C
    1E
    2Ti
    path
    0E
    recorded
    0∅
    1C
    2CE
    3CET
    4CT
    5E
    6ET
    start
    2

    18explore(2) pops T and is finished.

  19. extras
    0C
    1Ei
    2T
    path
    recorded
    0∅
    1C
    2CE
    3CET
    4CT
    5E
    6ET
    start
    0

    19explore(0) pops E and moves on to tomato.

  20. extras
    0C
    1E
    2Ti
    path
    0T
    recorded
    0∅
    1C
    2CE
    3CET
    4CT
    5E
    6ET
    start
    0

    20The loop pushes T, so the path is T.

  21. extras
    0C
    1E
    2T
    path
    0T
    recorded
    0∅
    1C
    2CE
    3CET
    4CT
    5E
    6ET
    7T
    start
    3

    21explore(3) records T.

  22. extras
    0C
    1E
    2Ti
    path
    recorded
    0∅
    1C
    2CE
    3CET
    4CT
    5E
    6ET
    7T
    start
    0

    22The last pop empties the path. The search has recorded 8 sandwiches, which is 2 × 2 × 2, because each extra is either in or out.

1 / 22
All subsets
function subsets(items) {
  const result = [];
  const path = [];
  function explore(start) {
    result.push([...path]); // record a copy, not path itself
    for (let i = start; i < items.length; i++) {
      path.push(items[i]);  // choose
      explore(i + 1);       // explore
      path.pop();           // un-choose
    }
  }
  explore(0);
  return result;
}
 
subsets(["C", "E", "T"]);
// [[], ["C"], ["C","E"], ["C","E","T"], ["C","T"], ["E"], ["E","T"], ["T"]]
def subsets(items):
    result = []
    path = []
 
    def explore(start):
        result.append(path[:])  # record a copy, not path itself
        for i in range(start, len(items)):
            path.append(items[i])  # choose
            explore(i + 1)         # explore
            path.pop()             # un-choose
 
    explore(0)
    return result
 
subsets(["C", "E", "T"])
# [[], ['C'], ['C', 'E'], ['C', 'E', 'T'], ['C', 'T'], ['E'], ['E', 'T'], ['T']]

Time and space cost

Backtracking visits every node of its call tree, and the number of nodes grows very fast: 2²⁰ is about a million, and 12! is about 479 million. It is practical for small inputs or when pruning removes most of the tree.

ApproachTimeSpaceWhy
All subsetsO(n · 2ⁿ)O(n)There are 2ⁿ subsets and each one is copied in O(n). The path and the call stack are at most n deep, not counting the output.
All orderingsO(n · n!)O(n)There are n! complete paths and each one is copied in O(n).
n queensO(n!) at mostO(n)Row 0 has at most n choices, row 1 at most n − 1 safe ones, and so on. Pruning cuts the real count far below this.

Variants of the template

Permutations

When the order of the choices matters, the same template applies with two changes. The options at each step are all items that are not yet in the path, which is tracked with a used array instead of a start index. The path is recorded only when it contains every item, instead of at every call.

All orderings
function permutations(items) {
  const result = [];
  const path = [];
  const used = new Array(items.length).fill(false);
  function explore() {
    if (path.length === items.length) {
      result.push([...path]);
      return;
    }
    for (let i = 0; i < items.length; i++) {
      if (used[i]) continue;
      used[i] = true;     // choose
      path.push(items[i]);
      explore();          // explore
      path.pop();         // un-choose
      used[i] = false;
    }
  }
  explore();
  return result;
}
 
permutations(["Ana", "Ben", "Cy"]).length; // 6
def permutations(items):
    result = []
    path = []
    used = [False] * len(items)
 
    def explore():
        if len(path) == len(items):
            result.append(path[:])
            return
        for i in range(len(items)):
            if used[i]:
                continue
            used[i] = True          # choose
            path.append(items[i])
            explore()               # explore
            path.pop()              # un-choose
            used[i] = False
 
    explore()
    return result
 
len(permutations(["Ana", "Ben", "Cy"]))  # 6

Choosing updates both used and path, so un-choosing has to undo both. There are 3 × 2 × 1 = 6 results, because each position has one fewer item left.

Constraint problems with pruning

In the n queens problem, you place n queens on an n × n board so that no two share a row, column or diagonal. Each call places the queen for one row and tries each column in turn.

The new ingredient is pruning: before choosing a column, the code checks whether the square is attacked and skips it if so. A partial board that has gone wrong is abandoned immediately, and so is every board that would have been built from it.

Placing four queens, one row at a timeUse the arrows or ← → keys
explore(row):  if row == n: record placed; return  for col from 0 to n - 1:    if col or a diagonal is taken: skip   # prune    place queen at (row, col)             # choose    explore(row + 1)                      # explore    remove queen from (row, col)          # un-choose
  1. 0123
    row 0Q
    row 1
    row 2
    row 3
    row
    0
    placed
    [0]

    1Row 0 places its first queen in column 0.

  2. 0123
    row 0Q
    row 1
    row 2
    row 3
    row
    1
    placed
    [0]

    2In row 1, column 0 shares a column with the first queen and column 1 shares a diagonal with it, so both are skipped.

  3. 0123
    row 0Q
    row 1Q
    row 2
    row 3
    row
    1
    placed
    [0, 2]

    3Column 2 is safe, so the second queen goes there.

  4. 0123
    row 0Q
    row 1Q
    row 2
    row 3
    row
    2
    placed
    [0, 2]

    4Every square in row 2 is attacked by an existing queen, so this branch is a dead end.

  5. 0123
    row 0Q
    row 1
    row 2
    row 3
    row
    1
    placed
    [0]

    5The search un-chooses by removing the queen at (1, 2).

  6. 0123
    row 0Q
    row 1Q
    row 2
    row 3
    row
    1
    placed
    [0, 3]

    6Row 1 tries column 3, which is safe, so the queen goes there.

  7. 0123
    row 0Q
    row 1Q
    row 2
    row 3
    row
    2
    placed
    [0, 3]

    7In row 2, column 0 is taken, so it is skipped.

  8. 0123
    row 0Q
    row 1Q
    row 2Q
    row 3
    row
    2
    placed
    [0, 3, 1]

    8Column 1 is safe, so the third queen goes there.

  9. 0123
    row 0Q
    row 1Q
    row 2Q
    row 3
    row
    3
    placed
    [0, 3, 1]

    9Every square in row 3 is attacked, so this is another dead end.

  10. 0123
    row 0Q
    row 1Q
    row 2
    row 3
    row
    2
    placed
    [0, 3]

    10The search removes the queen from row 2. Columns 2 and 3 of that row are attacked as well, so row 2 has no other option.

  11. 0123
    row 0Q
    row 1
    row 2
    row 3
    row
    1
    placed
    [0]

    11The search removes the queen at (1, 3). Row 1 has no columns left.

  12. 0123
    row 0
    row 1
    row 2
    row 3
    row
    0
    placed
    []

    12The search removes the queen in the corner. No solution has a queen in the corner, and the search never filled a complete board to find that out.

  13. 0123
    row 0Q
    row 1
    row 2
    row 3
    row
    0
    placed
    [1]

    13Row 0 tries column 1.

  14. 0123
    row 0Q
    row 1
    row 2
    row 3
    row
    1
    placed
    [1]

    14In row 1, columns 0 to 2 are attacked.

  15. 0123
    row 0Q
    row 1Q
    row 2
    row 3
    row
    1
    placed
    [1, 3]

    15Column 3 is safe, so the queen goes there.

  16. 0123
    row 0Q
    row 1Q
    row 2Q
    row 3
    row
    2
    placed
    [1, 3, 0]

    16In row 2, column 0 is safe, so the queen goes there.

  17. 0123
    row 0Q
    row 1Q
    row 2Q
    row 3
    row
    3
    placed
    [1, 3, 0]

    17In row 3, columns 0 and 1 are taken.

  18. 0123
    row 0Q
    row 1Q
    row 2Q
    row 3Q
    row
    3
    placed
    [1, 3, 0, 2]

    18Column 2 is safe, so the fourth queen goes there.

  19. 0123
    row 0Q
    row 1Q
    row 2Q
    row 3Q
    row
    4
    placed
    [1, 3, 0, 2]

    19explore(4) sees that every row has a queen and records the solution. The search placed only 8 queens along the way, instead of checking all 256 boards that have one queen per row.

1 / 19

To check a square in O(1) time, the code keeps three sets: the columns in use, the values of row - col in use, and the values of row + col in use. All squares on one down-right diagonal share the same row - col, and all squares on one down-left diagonal share the same row + col.

Place n queens
function solveQueens(n) {
  const cols = new Set(), down = new Set(), up = new Set();
  const placed = []; // placed[row] = column of that row's queen
  const solutions = [];
  function explore(row) {
    if (row === n) { solutions.push([...placed]); return; }
    for (let col = 0; col < n; col++) {
      // prune: column or diagonal already taken
      if (cols.has(col) || down.has(row - col) || up.has(row + col)) continue;
      // choose
      cols.add(col); down.add(row - col); up.add(row + col);
      placed.push(col);
      explore(row + 1); // explore
      // un-choose
      cols.delete(col); down.delete(row - col); up.delete(row + col);
      placed.pop();
    }
  }
  explore(0);
  return solutions;
}
 
solveQueens(4); // [[1, 3, 0, 2], [2, 0, 3, 1]]
def solve_queens(n):
    cols, down, up = set(), set(), set()
    placed = []  # placed[row] = column of that row's queen
    solutions = []
 
    def explore(row):
        if row == n:
            solutions.append(placed[:])
            return
        for col in range(n):
            if col in cols or row - col in down or row + col in up:
                continue  # prune
            cols.add(col)  # choose
            down.add(row - col)
            up.add(row + col)
            placed.append(col)
            explore(row + 1)  # explore
            cols.remove(col)  # un-choose
            down.remove(row - col)
            up.remove(row + col)
            placed.pop()
 
    explore(0)
    return solutions
 
solve_queens(4)  # [[1, 3, 0, 2], [2, 0, 3, 1]]

Combinations that add up to a target

A common interview version is: given positive numbers, find every combination that adds up to a target, where each number may be used any number of times. The path holds the numbers chosen so far, and the function also carries the amount still needed. When that amount is 0, the path is a solution. A number larger than the remaining amount is pruned, because every number is positive and adding it can only overshoot.

The only change from the subsets template is that the recursive call passes i instead of i + 1, which allows the same number to be chosen again. Passing i + 1 would be the version where each number can be used once.

Combinations that reach a target
function combinationSum(numbers, target) {
  const result = [];
  const path = [];
  function explore(start, remaining) {
    if (remaining === 0) {
      result.push([...path]);
      return;
    }
    for (let i = start; i < numbers.length; i++) {
      if (numbers[i] > remaining) continue; // prune
      path.push(numbers[i]);                // choose
      explore(i, remaining - numbers[i]);   // explore; i allows reuse
      path.pop();                           // un-choose
    }
  }
  explore(0, target);
  return result;
}
 
combinationSum([2, 3, 6, 7], 7); // [[2, 2, 3], [7]]
def combination_sum(numbers, target):
    result = []
    path = []
 
    def explore(start, remaining):
        if remaining == 0:
            result.append(path[:])
            return
        for i in range(start, len(numbers)):
            if numbers[i] > remaining:
                continue  # prune
            path.append(numbers[i])                  # choose
            explore(i, remaining - numbers[i])       # explore; i allows reuse
            path.pop()                               # un-choose
 
    explore(0, target)
    return result
 
combination_sum([2, 3, 6, 7], 7)  # [[2, 2, 3], [7]]

Input with duplicate values

If the input contains repeated values, such as [1, 2, 2], the subsets template records the subset [1, 2] twice, once for each 2. The fix has two parts. First sort the input, so equal values are next to each other. Then, inside the loop, skip a value that equals the one before it unless it is the first option at this decision point: if i > start and items[i] == items[i - 1]: continue. The i > start condition keeps [2, 2] valid, because a repeat is only skipped when an identical value was just tried at the same position. Permutations with repeated values use the same idea: sort the input, and skip items[i] when it equals items[i - 1] and used[i - 1] is false.

Searching for one answer in a grid

Some problems ask whether one valid arrangement exists, not for all of them. The classic case is word search: given a grid of letters, decide whether a word can be spelled by moving between adjacent cells without using a cell twice. The recursive function returns true as soon as one branch succeeds, and each caller passes that result straight up so the rest of the search is skipped. The choice here is to mark the current cell as visited, and un-choosing restores the letter.

Word search in a grid
function exists(board, word) {
  const rows = board.length, cols = board[0].length;
  function explore(r, c, k) {
    if (k === word.length) return true;
    if (r < 0 || c < 0 || r >= rows || c >= cols || board[r][c] !== word[k]) return false;
    const letter = board[r][c];
    board[r][c] = "#";                         // choose: mark the cell as used
    const found = explore(r + 1, c, k + 1) || explore(r - 1, c, k + 1) ||
                  explore(r, c + 1, k + 1) || explore(r, c - 1, k + 1);
    board[r][c] = letter;                      // un-choose
    return found;
  }
  for (let r = 0; r < rows; r++)
    for (let c = 0; c < cols; c++)
      if (explore(r, c, 0)) return true;
  return false;
}
 
exists([["A", "B"], ["C", "D"]], "ABDC"); // true
exists([["A", "B"], ["C", "D"]], "ABCD"); // false
def exists(board, word):
    rows, cols = len(board), len(board[0])
 
    def explore(r, c, k):
        if k == len(word):
            return True
        if r < 0 or c < 0 or r >= rows or c >= cols or board[r][c] != word[k]:
            return False
        letter = board[r][c]
        board[r][c] = "#"                      # choose: mark the cell as used
        found = (explore(r + 1, c, k + 1) or explore(r - 1, c, k + 1) or
                 explore(r, c + 1, k + 1) or explore(r, c - 1, k + 1))
        board[r][c] = letter                   # un-choose
        return found
 
    return any(explore(r, c, 0) for r in range(rows) for c in range(cols))
 
exists([["A", "B"], ["C", "D"]], "ABDC")  # True
exists([["A", "B"], ["C", "D"]], "ABCD")  # False

When backtracking does not apply

Backtracking enumerates answers, so it is the wrong tool when the question asks only for a count or an optimum and the same smaller problem appears again and again. Counting the ways to make change for an amount, or finding the longest increasing subsequence, would take exponential time with backtracking and polynomial time with dynamic programming. If a simple rule shows that a locally best choice is always safe, a greedy algorithm avoids the search entirely.

What interviewers ask about backtracking

The signals are in the wording of the problem. Phrases such as "return all", "list every", "generate all", or "find all combinations" point to backtracking, because the output itself is exponentially large and there is nothing faster than producing it. Problems that ask whether a valid arrangement exists, such as solving a Sudoku, placing queens, or finding a word in a grid of letters, also fit, because you build the arrangement step by step and abandon it as soon as it breaks a rule. If the problem asks only for the number of ways or the best value, check whether dynamic programming fits first.

When you start, say out loud what the path holds, what the options are at each step, when a path is complete, and what lets you prune. Interviewers usually follow with these questions:

  • "What is the time complexity?" It is the number of nodes in the call tree times the work per node. For subsets it is O(n · 2ⁿ), because there are 2ⁿ results and each takes O(n) to copy. For permutations it is O(n · n!).
  • "Why do you copy the path when you record it?" The path is one list that is changed for the rest of the search. A stored reference would show whatever the path contains at the end, which is empty. A copy keeps the contents at the moment of recording.
  • "How do you avoid duplicate results?" For subsets and combinations, pass a start index so each call only looks at later items, which stops the same set appearing in a different order. If the input has repeated values, sort it and skip a value equal to the previous one at the same position.
  • "How do you stop at the first solution?" Make the recursive function return a boolean, return true when a complete answer is found, and return true from every caller as soon as a recursive call returns true.
Quick check

In the subsets code, what happens if the loop starts at 0 instead of start?

How many orderings does a permutation search on 5 items record?

Why does backtracking un-choose after the recursive call returns?

You are asked how many ways there are to climb 40 stairs taking 1 or 2 steps at a time. Is backtracking the right tool?

Introduction to Dynamic Programming covers storing answers when the search keeps asking the same smaller question. Greedy Algorithms covers problems where one choice can be proven best.