Backtracking
Reach for it when the problem says
- All subsets / permutations / combinations
- puzzles
- Solved
- 0/30Solved
- Problems
- 30Problems
- Variants
- 6Variants
Problems
6 variantsSubsets
0 of 5 solved- SubsetsDeep diveMediumDecode Subsets
- Subsets IIDeep diveMediumDecode Subsets II
- Letter Case PermutationDeep diveMediumDecode Letter Case Permutation
- Maximum Length of a Concatenated String with Unique CharactersDeep diveMediumDecode Maximum Length of a Concatenated String with Unique Characters
- Non-decreasing SubsequencesMediumDecode Non-decreasing Subsequences
Permutations
0 of 4 solved- PermutationsSprintDeep diveMediumDecode Permutations
- Permutations IIMediumDecode Permutations II
- Beautiful ArrangementMediumDecode Beautiful Arrangement
- Gray CodeMediumDecode Gray Code
Combinations
0 of 6 solved- Binary WatchUp nextDeep diveEasyDecode Binary Watch
- Combination SumSprintDeep diveMediumDecode Combination Sum
- Phone Keypad Letter CombinationsEssentialsSprintDeep diveMediumDecode Phone Keypad Letter Combinations
- Combination Sum IIDeep diveMediumDecode Combination Sum II
- Combination Sum IIIEssentialsDeep diveMediumDecode Combination Sum III
- CombinationsSprintDeep diveMediumDecode Combinations
Grid and graph paths
0 of 4 solvedConstraint placement
0 of 6 solved- Generate ParenthesesSprintDeep diveMediumDecode Generate Parentheses
- Matchsticks to SquareMediumDecode Matchsticks to Square
- Partition to K Equal Sum SubsetsMediumDecode Partition to K Equal Sum Subsets
- N-Queens CountSprintDeep diveHardDecode N-Queens Count
- Sudoku SolverDeep diveHardDecode Sudoku Solver
- N-Queens (return the boards)Deep diveHardDecode N-Queens (return the boards)
String partitioning
0 of 5 solved- Palindrome PartitioningDeep diveMediumDecode Palindrome Partitioning
- Restore IP AddressesMediumDecode Restore IP Addresses
- Splitting a String Into Descending Consecutive ValuesMediumDecode Splitting a String Into Descending Consecutive Values
- Word Break IIDeep diveHardDecode Word Break II
- Expression Add OperatorsDeep diveHardDecode Expression Add Operators
Pattern guide
Backtracking is how you solve problems that ask for every answer, or ask whether any arrangement works when no shortcut exists: all subsets, all orderings, every way to split a string, a Sudoku fill, a path that covers a grid. In interviews it is the pattern behind Subsets, Permutations, Combination Sum, Word Search and N-Queens, and it rewards the same three moves every time: choose, explore, un-choose.
What it is
You build a candidate answer step by step, keeping it in one shared list called the path. At each step you choose one option, explore everything that follows from it with a recursive call, then un-choose it so the path is clean for the next option. The recursive calls form a decision tree: the root is the empty path, each edge is a choice, and each leaf is either a complete answer or a dead end.
The power comes from pruning: as soon as a partial path breaks a rule, you stop and never build anything below it. Here is Combination Sum on [2, 3, 6, 7] with target 7. Each node shows the path and, as a subtitle, what is left to reach the target.
Start with an empty path and 7 to go. The loop will try each candidate in turn as the first pick.
The template is always the same shape. What changes from problem to problem is what a "choice" is, when the path is complete, and what rules prune a branch.
def backtrack(state):
if is_complete(state):
record(copy_of(state))
return
for choice in choices(state):
if breaks_a_rule(choice):
continue # prune
make(choice) # choose
backtrack(state) # explore
undo(choice) # un-choosepath[:] instead of path?How to recognise it
Wording clues
| Phrase in the prompt | What it suggests |
|---|---|
| "return all possible", "list every", "generate all" | Enumerate every answer: backtracking, since the output itself is exponential |
| "any order", "no duplicate combinations" | Fix a canonical build order (a start index) and skip equal values at the same level |
| "each number used once" / "may be reused" | Recurse with i + 1 / recurse with i |
| "split", "partition", "insert spaces or dots" | Choose where the next piece ends, check the piece, recurse on the rest |
| "cannot use a cell twice", "visit every square exactly once" | Grid DFS that marks cells on the path and unmarks them on return |
| "place so that no two attack / clash", "fill the board" | Constraint placement with sets that track what is taken |
Constraint clues
| Constraint | What it suggests |
|---|---|
n <= 10 to n <= 20 | 2^n or n! is acceptable. This is the strongest signal of all |
n <= 8 or n <= 9 with "orderings" | Factorial search is expected |
n <= 100 but target <= 30 | Exponential in theory, but a sorted break on the small target makes it fast |
Values up to 10^8 with n <= 16 | A table indexed by value is impossible; search over assignments instead |
Input and output shape
- The output is a list of lists or list of strings, and its size grows exponentially with the input.
- The output is a yes/no or a count, but deciding it needs trying arrangements (Matchsticks to Square, Beautiful Arrangement).
- The input is small: a short list, a short string, a tiny grid, a 9 by 9 board.
Looks like it but isn't
| Problem shape | Better pattern | Why |
|---|---|---|
"How many ways" with large n (like Climbing Stairs, Decode Ways) | Dynamic programming | Subproblems overlap and you only need a number, so cache instead of enumerating |
| "Can the string be split into words?" (yes/no) | Dynamic programming | Word Break I is O(n²) DP. Word Break II, which lists sentences, is backtracking |
| "Shortest path" in a grid | Graphs (BFS) | BFS finds the shortest path without exploring every path |
| "Count connected regions" | Graphs (DFS) | A visited cell stays visited forever. In backtracking you unmark it |
| "Best single choice at each step is provably safe" | Greedy | No undo is needed when a local choice is always right |
n stairs taking 1 or 2 steps, with n up to 45. Why is plain backtracking the wrong tool?The sub-patterns
Subsets
When: every element is independently in or out, and you want all the resulting collections. Variants add a rule (unique letters, non-decreasing order) or duplicates in the input.
Two equivalent shapes exist: the include-or-skip tree (two branches per element, record at the leaves) and the loop form (record at every node, loop over later elements). The loop form is the one that handles duplicates: sort, then skip nums[i] when i > start and it equals nums[i - 1].
At index 0, two choices: skip 1 or take it. We go down the skip branch first.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n · 2ⁿ) time, O(n) extra space. Classic problems: Subsets, Subsets II, Letter Case Permutation, Non-decreasing Subsequences.
Combinations
When: you choose a group where order does not matter, often with a size limit (k numbers) or a sum target. The start index is the whole trick: after choosing index i, the next choice starts at i + 1 (each used once) or at i (reuse allowed). That makes every group buildable in exactly one order.
Sort the input when there is a sum target, so you can break the loop the moment a candidate is too big: every later one is bigger too.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(k · C(n, k)) for fixed-size groups; exponential but heavily pruned for sum targets. Classic problems: Combinations, Combination Sum, Combination Sum II, Combination Sum III, Phone Keypad Letter Combinations, Binary Watch.
What does this print?
def count(nums, target, reuse):
found = 0
def build(start, remaining):
nonlocal found
if remaining == 0:
found += 1
return
for i in range(start, len(nums)):
if nums[i] > remaining:
break
build(i if reuse else i + 1, remaining - nums[i])
build(0, target)
return found
print(count([1, 2], 3, True), count([1, 2], 3, False))Permutations
When: order matters and every element must appear once. There is no start index; each level loops over all elements and skips the ones already in the path, tracked with a used array. With duplicates in the input, sort and skip nums[i] when it equals nums[i - 1] and the earlier copy is not used yet, which forces equal values to enter in left-to-right order.
Rules that apply per position (like Beautiful Arrangement's divisibility test) go straight into the loop as a filter.
Slot 1: pick 1. Mark it used.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n · n!) time, O(n) extra space. Classic problems: Permutations, Permutations II, Beautiful Arrangement, Gray Code.
String partitioning
When: you cut a string into consecutive pieces and each piece must pass a test (palindrome, dictionary word, IP octet, number one less than the last). The choice at each level is where the current piece ends. Check the piece the moment you choose it; a bad piece prunes everything after it.
From start = 0, the shortest piece is a, a palindrome. Take it and recurse from index 1.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n · 2ⁿ) in the worst case, since a string of length n has 2^(n-1) cut patterns. Classic problems: Palindrome Partitioning, Restore IP Addresses, Word Break II, Expression Add Operators.
Grid and graph paths
When: you walk a grid or graph and the path may not reuse a cell, or must cover every cell. This differs from ordinary graph DFS in one line: after exploring from a cell you unmark it, because a different path may need it. Marking in place (overwrite with # or 0, then restore) avoids a separate visited set.
Try every cell as a start. (1, 3) holds S, the first letter. Mark it as used.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: about O(cells · 3^L) for a path of length L, since each step after the first has at most three new directions. Classic problems: Word Search, Path with Maximum Gold, Unique Paths III, All Paths From Source to Target.
Constraint placement
When: you place items (queens, digits, sticks, brackets) into slots so that global rules hold. The trick is to keep the rules in O(1) lookup structures (sets of used columns and diagonals, per-row/column/box digit sets, bucket sums), and to place the most constrained item first so dead ends appear near the root. When you only need one solution, return True up the stack the moment you find it, or the un-choose steps will erase it.
Row 0: put a queen in column 0. Column 0, diagonal r - c = 0 and anti-diagonal r + c = 0 are now taken.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: exponential in the worst case (O(n!) for N-Queens, O(kⁿ) for bucket filling), but pruning keeps real inputs fast. Classic problems: N-Queens, Sudoku Solver, Generate Parentheses, Matchsticks to Square, Partition to K Equal Sum Subsets.
Decision checklist
Ask these in order. The first "yes" usually names the sub-pattern.
- Am I walking cells or nodes, and is reuse banned along a path? Grid and graph paths.
- Am I cutting a string into consecutive pieces? String partitioning.
- Does the order of chosen items matter, with each used once? Permutations.
- Am I choosing a group with a size or sum rule, order irrelevant? Combinations.
- Is each item simply in or out? Subsets.
- Am I filling slots under global rules (attacks, equal sums, balance)? Constraint placement.
Match each problem to its sub-pattern.
Traps
- Recording the live path.
result.append(path)stores a reference that later empties. Recordpath[:]or[...path]. - Forgetting to un-choose. Every
append,add, mark or+=before the recursive call needs its exact reverse after it. A missedused[i] = Falsesilently hides answers. - Wrong next index.
i + 1means each item once;imeans reuse;0(with ausedarray) means order matters. Mixing them up produces duplicates or misses answers. - Skipping duplicates at the wrong level. The rule is
i > start and nums[i] == nums[i - 1], after sorting. Writingi > 0skips legitimate picks deeper in the tree, so[2, 2]vanishes from Subsets II. - Undoing a finished solution. When one answer is enough (Sudoku, Matchsticks), return a boolean and stop on
True. Without it, the un-choose steps erase the board. - A visited set that never forgets. In grid paths, a cell marked visited on a failed path must be unmarked, unlike flood fill.
- Too-deep recursion. Python's default limit is about 1,000 frames. A path of length 2^n (Gray Code) needs a loop, not recursion.
Edge cases to always test: the empty input (Subsets of [] is [[]], but letter combinations of "" is []), a single element, all-equal values, no valid answer, and the largest allowed size to confirm the pruning works.
Put the body of a backtracking function in order.
- Tap the steps below in the right order.
[1, 2, 2], why is the skip condition i > start and not i > 0?How to talk it through
- Backtracking
- Building a solution one choice at a time, recursing to explore it, and undoing the choice to try the next one.
- Decision tree
- The tree of recursive calls: each edge is a choice, each node a partial path, each leaf a complete answer or a dead end.
- Pruning
- Stopping a branch as soon as the partial path breaks a rule, so nothing below it is built.
- Start index
- A parameter that limits choices to later elements, so each unordered group is built in exactly one order.
- Used array
- A boolean per element that marks what is already in the path. Used for permutations, where every level may pick from the whole input.
- Skip equal neighbours
- After sorting, skipping a value equal to the previous one at the same loop level, to avoid duplicate answers from duplicate inputs.