Lesson 20 of 40Trees and graphs
Backtracking
Generate every subset, permutation or combination with one choose, explore, un-choose template, and prune dead branches.
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.
Start with an empty path. Record it: [] is a subset.
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-chooseHere it is for subsets. Note path[:] (Python) and [...path] (TypeScript): the path keeps changing, so you must save a copy.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.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]))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.
Press Run (⌘ Enter) to see what happens.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 problem to the backtracking variant.
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 resultOther 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.
Order the body of the backtracking loop.
- Tap the steps below in the right order.
Cost
Backtracking costs roughly (number of nodes in the decision tree) × (work per node).
| Problem | Answers | Time |
|---|---|---|
| Subsets of n | 2ⁿ | O(n · 2ⁿ) (copying each subset costs up to n) |
| Permutations of n | n! | O(n · n!) |
| Combinations, k of n | C(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.
[1, 2, 3, 4, 5] have, and roughly how many does [1, ..., 10] have?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.
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.
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.
if i > 0 and c[i] == c[i - 1]: continue instead of i > start?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 ofr - calready used. Every square on one top-left to bottom-right diagonal has the samer - c.anti: values ofr + calready 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).
Row 0: try column 0. Now column 0, diagonal r - c = 0 and anti-diagonal r + c = 0 are taken.
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.
Using solve_n_queens above, what does this print?
print(len(solve_n_queens(4)), len(solve_n_queens(6)))
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.
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
pathinstead 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
startindex 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 equalsnums[i - 1]at the same level.
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
numsare distinct.
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
numsare distinct.
- 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]: continueon sorted input, so equal values are tried once per position and duplicate answers never form.- diagonal keys
r - candr + cidentify the two diagonals through a square, so N-Queens checks attacks with set lookups.