Skip to content

Lesson 20 of 40Trees and graphs

Backtracking

Generate every subset, permutation or combination with one choose, explore, un-choose template, and prune dead branches.

23 min read0/7 questions

Some problems have no clever shortcut: you must try the possibilities. Every way to seat four guests, every subset of features to test, every placement of queens on a board, every path through a letter grid. Backtracking is the disciplined way to try them all without missing any and without building the same thing twice.

It shows up in interviews constantly (subsets, permutations, combination sum, word search, N-queens) and in real tools like Sudoku solvers, regex engines and the dependency resolvers in package managers.

Build answers one choice at a time

Picture building a subset of [1, 2, 3]. You hold a partial answer, called the path. At each step you make a choice (add a number), explore everything that follows from it, then un-choose (remove the number) so the path is clean for the next option. Backing up to try another option is the "backtrack".

The choices form a decision tree. Here each node is the path at that moment, and every node is a valid subset. To avoid producing [2, 1] as well as [1, 2], each level only picks numbers after the last one chosen.

Decision tree for subsets of [1, 2, 3]
[][1,2,3][1,2][1,3][1][2,3][2][3]root

Start with an empty path. Record it: [] is a subset.

1/5
Quick check
Why does each level only choose numbers after the last one picked?
Need a nudge? A hint rules out a wrong answer.

The template

Every backtracking solution is a variation of this:

def backtrack(path, choices):
    if is_complete(path):
        record(path)
        return              # (subsets record at every node and do not return early)
    for choice in choices:
        if not valid(choice):
            continue        # pruning
        path.append(choice)             # choose
        backtrack(path, next_choices)   # explore
        path.pop()                      # un-choose

Here it is for subsets. Note path[:] (Python) and [...path] (TypeScript): the path keeps changing, so you must save a copy.

Python
def subsets(nums): result, path = [], [] def backtrack(start): result.append(path[:]) # every node is a subset for i in range(start, len(nums)): path.append(nums[i]) # choose backtrack(i + 1) # explore path.pop() # un-choose backtrack(0) return result print(subsets([1, 2, 3]))
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

The copy is removed: result.append(path) instead of result.append(path[:]). What does subsets([1, 2]) return now?

def subsets(nums):
  result, path = [], []
  def backtrack(start):
      result.append(path)
      for i in range(start, len(nums)):
          path.append(nums[i])
          backtrack(i + 1)
          path.pop()
  backtrack(0)
  return result

print(subsets([1, 2]))
Need a nudge? Hints walk you through it.

Permutations: order matters

A permutation uses every number once, in some order. Now [1, 2, 3] and [3, 2, 1] are different answers, so there is no start index. Instead, every level can pick any number not already used. Track that with a used array (or a set). You record only when the path is full.

Python
def permutations(nums): result, path = [], [] used = [False] * len(nums) def backtrack(): if len(path) == len(nums): result.append(path[:]) return for i, x in enumerate(nums): if used[i]: continue used[i] = True; path.append(x) # choose backtrack() # explore path.pop(); used[i] = False # un-choose backtrack() return result print(permutations([1, 2, 3]))
Output
Press Run (⌘ Enter) to see what happens.

Combinations sit in between: choose exactly k items, order ignored. That is the subsets code with one change: record only when len(path) == k.

Match the pairs0/4 matched

Match the problem to the backtracking variant.

Choose an item, then its match on the other side.

Pruning: skip branches that cannot work

Backtracking is exponential, so the biggest win is not exploring branches you already know are dead. That is pruning: a check before the "choose" step.

Example: combination sum. Find all combinations of candidates that add up to target. If you sort the candidates first, then the moment one candidate is too big, every candidate after it is too big as well, so you can break out of the loop instead of trying them.

def combination_sum(candidates, target):
    candidates.sort()
    result, path = [], []
 
    def backtrack(start, remaining):
        if remaining == 0:
            result.append(path[:])
            return
        for i in range(start, len(candidates)):
            if candidates[i] > remaining:
                break                   # prune: sorted, so the rest are too big
            path.append(candidates[i])
            backtrack(i, remaining - candidates[i])   # i, not i + 1: reuse allowed
            path.pop()
 
    backtrack(0, target)
    return result

Other common prunes: N-queens skips a square if its column or diagonal is already attacked; word search stops as soon as the next grid letter does not match the next letter of the word.

Put it in order4 steps

Order the body of the backtracking loop.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Cost

Backtracking costs roughly (number of nodes in the decision tree) × (work per node).

ProblemAnswersTime
Subsets of n2ⁿO(n · 2ⁿ) (copying each subset costs up to n)
Permutations of nn!O(n · n!)
Combinations, k of nC(n, k)O(k · C(n, k))

These numbers explode. 2²⁰ is about a million, fine. 2³⁰ is a billion, slow. 12! is 479 million. That is why these problems come with small inputs (n up to about 10 to 20), and that small limit is itself a hint that the expected solution is backtracking. Space is O(n) for the path and recursion stack, not counting the output.

Quick check
How many permutations does [1, 2, 3, 4, 5] have, and roughly how many does [1, ..., 10] have?
Need a nudge? A hint rules out a wrong answer.

Subsets two ways: loop or include/exclude

The subsets code above is the loop form: each call loops over the remaining items and every node of the tree is an answer. There is a second shape you should be able to write just as fast, the include/exclude form. At index i you make exactly one yes or no decision about nums[i], then move on to i + 1. Answers appear only at the leaves, once every item has been decided.

Python
def subsets_binary(nums): result, path = [], [] def decide(i): if i == len(nums): # every item has been decided result.append(path[:]) return path.append(nums[i]) # branch 1: include nums[i] decide(i + 1) path.pop() decide(i + 1) # branch 2: exclude nums[i] decide(0) return result assert len(subsets_binary([1, 2, 3, 4])) == 16print(subsets_binary([1, 2, 3]))
Output
Press Run (⌘ Enter) to see what happens.

Both produce the same 2ⁿ subsets in a different order. The include/exclude tree is a full binary tree of depth n, which makes its cost easy to state and makes it the natural shape for "pick or skip" problems with extra rules: partition into equal sums, target sum with plus and minus signs, or any problem where you later want to add memoisation. That last point matters. Include/exclude recursion has a small state (i plus whatever you carry), so it converts directly into dynamic programming, as Knapsack and Subset DP shows. The loop form is the better fit when there is a start index and an early break, as in combination sum.

Duplicates in the input: Combination Sum II

Now each candidate may be used once, and the input has repeats: [10, 1, 2, 7, 6, 1, 5], target 8. The two 1s are a trap. Using "the first 1 with 7" and "the second 1 with 7" gives [1, 7] twice.

The fix has two parts. Sort, so equal values sit next to each other. Then, inside the loop, skip a value that equals the previous one at the same level:

if i > start and candidates[i] == candidates[i - 1]: continue

Read it carefully, because the condition is i > start, not i > 0. At one level of the tree, the loop picks which value goes in the next position. Picking the first 1 or the second 1 for that position leads to identical subtrees, so you try only the first. But going deeper with a second 1 is fine: [1, 1, 6] is a real answer. When i == start, you are at the first option of a new level, and it must not be skipped even if it equals the item just before it.

Python
def combination_sum2(candidates, target): candidates = sorted(candidates) result, path = [], [] def backtrack(start, remaining): if remaining == 0: result.append(path[:]) return for i in range(start, len(candidates)): if i > start and candidates[i] == candidates[i - 1]: continue # same value already tried at this level if candidates[i] > remaining: break # sorted: the rest are too big path.append(candidates[i]) backtrack(i + 1, remaining - candidates[i]) # i + 1: each used once path.pop() backtrack(0, target) return result assert combination_sum2([2, 5, 2, 1, 2], 5) == [[1, 2, 2], [5]]print(combination_sum2([10, 1, 2, 7, 6, 1, 5], 8))
Output
Press Run (⌘ Enter) to see what happens.

The same one-line skip handles Subsets II (subsets of [1, 2, 2] without repeats) and, with a used array, Permutations II. For permutations the skip becomes if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]: continue, which means "only use the second copy after the first copy is already in the path". The alternative, building every answer and putting tuples in a set, works but does all the duplicate work first. Interviewers expect the skip.

Quick check
In Combination Sum II, what goes wrong if the skip is written if i > 0 and c[i] == c[i - 1]: continue instead of i > start?
Need a nudge? A hint rules out a wrong answer.

N-Queens: constant-time attack checks

Place n queens on an n × n board so that no two share a row, column or diagonal. Return every board. The structure gives the decision tree: there must be exactly one queen per row, so level r of the recursion chooses the column for row r. Rows can never clash, by construction.

The speed comes from how you check attacks. Scanning the board for every candidate square is O(n) per check. Instead keep three sets:

  • cols: columns already used.
  • diag: values of r - c already used. Every square on one top-left to bottom-right diagonal has the same r - c.
  • anti: values of r + c already used, for the other diagonal direction.

Matrix Traversal and In-Place Tricks shows why those two sums name the diagonals. With them, "is this square attacked?" is three set lookups, O(1).

Backtracking on 4-Queens
0123
Q

Row 0: try column 0. Now column 0, diagonal r - c = 0 and anti-diagonal r + c = 0 are taken.

1/5
Python
def solve_n_queens(n): cols, diag, anti = set(), set(), set() queens = [] # queens[r] = column of the queen in row r boards = [] def place(r): if r == n: boards.append(["." * c + "Q" + "." * (n - c - 1) for c in queens]) return for c in range(n): if c in cols or (r - c) in diag or (r + c) in anti: continue # attacked: prune cols.add(c); diag.add(r - c); anti.add(r + c); queens.append(c) place(r + 1) cols.remove(c); diag.remove(r - c); anti.remove(r + c); queens.pop() place(0) return boards for row in solve_n_queens(4)[0]: print(row)print([len(solve_n_queens(n)) for n in range(1, 9)])
Output
Press Run (⌘ Enter) to see what happens.

Without pruning the tree would have nⁿ leaves. One queen per row plus the column set cuts it to at most n!, and the diagonal sets cut far more, which is why n = 8 runs instantly. The counts 1, 0, 0, 2, 10, 4, 40, 92 are worth recognising: n = 2 and n = 3 have no solution, and 8-Queens has 92. If the problem only asks how many solutions, the same three sets can be stored as bitmasks for a faster count, a trick that starts from Bit Manipulation and that Bitmask DP and DP on Trees uses throughout.

Predict the outputPython

Using solve_n_queens above, what does this print?

print(len(solve_n_queens(4)), len(solve_n_queens(6)))
Need a nudge? Hints walk you through it.

Word Search: marking the grid in place

Does word appear in a letter grid as a path of adjacent cells, using each cell at most once? Start a DFS from every cell. At each step the cell must match the next letter, and it must not already be on the current path.

Tracking "on the path" with a visited set works, but the common trick is to overwrite the cell with a marker such as # before exploring and restore it afterwards. The mark is the choose step and the restore is the un-choose. It saves a set and its hashing, and the board[r][c] != word[i] check rejects marked cells for free, because # never matches a letter.

Python
def exist(board, word): rows, cols = len(board), len(board[0]) def dfs(r, c, i): if i == len(word): return True if not (0 <= r < rows and 0 <= c < cols) or board[r][c] != word[i]: return False board[r][c] = "#" # choose: mark used found = (dfs(r + 1, c, i + 1) or dfs(r - 1, c, i + 1) or dfs(r, c + 1, i + 1) or dfs(r, c - 1, i + 1)) board[r][c] = word[i] # un-choose: restore return found return any(dfs(r, c, 0) for r in range(rows) for c in range(cols)) B = [list("ABCE"), list("SFCS"), list("ADEE")]assert exist(B, "SEE") and not exist(B, "ABCB")assert B == [list("ABCE"), list("SFCS"), list("ADEE")] # restored after the searchprint(exist(B, "ABCCED"), exist(B, "SEE"), exist(B, "ABCB"))
Output
Press Run (⌘ Enter) to see what happens.

Three details to say out loud. The restore runs even when found is True, so the caller's board is left unchanged. or short-circuits, so the search stops at the first full match. And ABCB fails because reaching the second B would reuse the first one, which is marked. The cost is O(rows · cols · 3^L): every cell can start a path, and after the first step each cell has at most three unvisited neighbours. Two cheap prunes help on hard tests: return False at once if the board has fewer copies of some letter than the word needs, and if the last letter of the word is rarer on the board than the first, search for the reversed word. To find many words in one grid, use a trie, as Tries shows in Word Search II.

Where O(n · 2ⁿ) and O(n · n!) come from

The cost table above is worth being able to derive on a whiteboard, because interviewers ask "why?".

Subsets. The include/exclude tree is a full binary tree of depth n, so it has 2ⁿ leaves and about 2 · 2ⁿ nodes in total. Each leaf copies a path of up to n items. So O(n · 2ⁿ) time. The output itself holds 2ⁿ lists with an average length of n / 2, so no algorithm can do better, which is the lower-bound argument from the callout below.

Permutations. The root has n children, each of those has n − 1, and so on. Level k has n! / (n − k)! nodes. Summed over all levels, that is at most about e · n! nodes (roughly 2.72 · n!), because the sum 1 + 1/1! + 1/2! + ... converges to e. Each node does an O(n) loop over the used array, and each of the n! leaves copies n items, so O(n · n!).

Space. The recursion depth is n and the path holds at most n items, so O(n) extra space, not counting the output. Python's default recursion limit of 1000 is never the problem here, because inputs this size would take forever long before the stack fills. The time is the real limit.

When the question changes from "list them all" to "count them" or "find the best one", the exponential output is gone and so is the excuse. That is the signal to look for overlapping subproblems: Dynamic Programming for prefix-shaped choices, Bitmask DP and DP on Trees when the state is "which items have I used", as in the travelling salesman problem, where O(n² · 2ⁿ) replaces O(n!).

Common mistakes:

  • Appending path instead of a copy, so every result ends up as the same empty list.
  • Forgetting to un-choose (or un-marking used) on the way back.
  • Using a start index for permutations, which misses orders, or no start index for subsets, which produces duplicates.
  • Handling duplicates in the input: sort first, then skip nums[i] when it equals nums[i - 1] at the same level.
ChallengeMedium

Subsets

Given a list of distinct integers nums, return every possible subset (the power set). Include the empty subset and the full list. The subsets, and the numbers inside each one, can be in any order, but no subset may appear twice.

[1, 2, 3]  →  [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
[0]        →  [[], [0]]

Constraints

  • 0 <= nums.length <= 10
  • -10 <= nums[i] <= 10
  • All the numbers in nums are distinct.
def subsets(nums: list[int]) -> list[list[int]]: # For each number, branch twice: leave it out, or take it. pass
ChallengeMedium

Permutations

Given a list of distinct integers nums, return every possible ordering (permutation) of them. You can return the permutations in any order.

[1, 2, 3]  →  [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
[0, 1]     →  [[0, 1], [1, 0]]
[1]        →  [[1]]

Constraints

  • 1 <= nums.length <= 6
  • -10 <= nums[i] <= 10
  • All the numbers in nums are distinct.
def permute(nums: list[int]) -> list[list[int]]: # Fill positions one at a time with numbers you have not used yet. pass
Key terms
backtracking
Build answers one choice at a time, explore each choice fully, then undo it and try the next.
decision tree
The tree of all partial answers. Each level is one choice; backtracking walks it depth-first.
choose / explore / un-choose
The three steps in the loop: add to the path, recurse, remove from the path.
pruning
Skipping a branch as soon as you know it cannot lead to a valid answer.
start index
Only consider items after the last one chosen, so order-free answers (subsets, combinations) are not repeated.
include/exclude form
Recursion that makes one yes or no decision per item and records answers at the leaves. Converts easily into DP.
same-level skip
if i > start and a[i] == a[i - 1]: continue on sorted input, so equal values are tried once per position and duplicate answers never form.
diagonal keys
r - c and r + c identify the two diagonals through a square, so N-Queens checks attacks with set lookups.
Interview pattern: Backtracking30 problemsSpot it: All subsets / permutations / combinations · puzzles