Skip to content

Backtracking

Reach for it when the problem says

  • All subsets / permutations / combinations
  • puzzles
Solved
0/30Solved
Problems
30Problems
Variants
6Variants

Problems

6 variants

Subsets

0 of 5 solved

Permutations

0 of 4 solved

Combinations

0 of 6 solved

Grid and graph paths

0 of 4 solved

Constraint placement

0 of 6 solved

String partitioning

0 of 5 solved

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.

Combination Sum: candidates [2, 3, 6, 7], target 7
[]need 7[2,2,2]need 1, dead end[2,2,3]need 0, answer[2,2]need 3[2,3]need 2, 3 > 2 so stop[2]need 5[3,3]need 1, dead end[3]need 4[6]need 1, dead end[7]need 0, answerroot

Start with an empty path and 7 to go. The loop will try each candidate in turn as the first pick.

1/6

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-choose
Quick check
In Python, why do backtracking solutions record path[:] instead of path?
Need a nudge? A hint rules out a wrong answer.

How to recognise it

Wording clues

Phrase in the promptWhat 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

ConstraintWhat it suggests
n <= 10 to n <= 202^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 <= 30Exponential in theory, but a sorted break on the small target makes it fast
Values up to 10^8 with n <= 16A 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 shapeBetter patternWhy
"How many ways" with large n (like Climbing Stairs, Decode Ways)Dynamic programmingSubproblems overlap and you only need a number, so cache instead of enumerating
"Can the string be split into words?" (yes/no)Dynamic programmingWord Break I is O(n²) DP. Word Break II, which lists sentences, is backtracking
"Shortest path" in a gridGraphs (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"GreedyNo undo is needed when a local choice is always right
Quick check
A problem asks for the number of ways to climb n stairs taking 1 or 2 steps, with n up to 45. Why is plain backtracking the wrong tool?
Need a nudge? A hint rules out a wrong answer.

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].

Include or skip on [1, 2, 3]
1
0
↑i
2
1
3
2
path = []

At index 0, two choices: skip 1 or take it. We go down the skip branch first.

1/5
Python
def subsets_with_dup(nums): nums = sorted(nums) result, path = [], [] def build(start): result.append(path[:]) for i in range(start, len(nums)): if i > start and nums[i] == nums[i - 1]: continue # same value already tried at this level path.append(nums[i]) build(i + 1) path.pop() build(0) return result print(subsets_with_dup([1, 2, 2]))
Output
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.

Python
def combination_sum(candidates, target): nums = sorted(candidates) result, path = [], [] def build(start, remaining): if remaining == 0: result.append(path[:]) return for i in range(start, len(nums)): if nums[i] > remaining: break # sorted, so nothing later fits either path.append(nums[i]) build(i, remaining - nums[i]) # i, not i + 1: reuse allowed path.pop() build(0, target) return result print(combination_sum([2, 3, 6, 7], 7))
Output
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.

Predict the outputPython

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))
Need a nudge? Hints walk you through it.

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.

Filling slots for permutations of [1, 2, 3]
1
0
2
1
3
2
path = [1]used = 1

Slot 1: pick 1. Mark it used.

1/5
Python
def permute_unique(nums): nums = sorted(nums) result, path = [], [] used = [False] * len(nums) def build(): if len(path) == len(nums): result.append(path[:]) return for i in range(len(nums)): if used[i]: continue if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]: continue # equal copies must be used left to right used[i] = True path.append(nums[i]) build() path.pop() used[i] = False build() return result print(permute_unique([1, 1, 2]))
Output
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.

Palindrome partitions of aab
a
0
↑start↑end
a
1
b
2
pieces = [a]

From start = 0, the shortest piece is a, a palindrome. Take it and recurse from index 1.

1/5
Python
def partition(s): result, pieces = [], [] def build(start): if start == len(s): result.append(pieces[:]) return for end in range(start + 1, len(s) + 1): piece = s[start:end] if piece != piece[::-1]: continue # prune: this piece is not allowed pieces.append(piece) build(end) pieces.pop() build(0) return result print(partition("aab"))
Output
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.

Word Search: tracing SEE
ABCE
SFCS
ADEE

Try every cell as a start. (1, 3) holds S, the first letter. Mark it as used.

1/5
Python
def exist(board, word): rows, cols = len(board), len(board[0]) def search(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 on the path found = any(search(r + dr, c + dc, i + 1) for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1))) board[r][c] = word[i] # un-choose: restore return found return any(search(r, c, 0) for r in range(rows) for c in range(cols)) grid = [list("ABCE"), list("SFCS"), list("ADEE")]print(exist(grid, "SEE"), exist(grid, "ABCB"))
Output
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.

4-queens, one queen per row
Q...
....
....
....

Row 0: put a queen in column 0. Column 0, diagonal r - c = 0 and anti-diagonal r + c = 0 are now taken.

1/4
Python
def can_partition_k_subsets(nums, k): total = sum(nums) if total % k: return False target = total // k values = sorted(nums, reverse=True) # most constrained first if values[0] > target: return False buckets = [0] * k def place(i): if i == len(values): return True tried = set() for b in range(k): if buckets[b] + values[i] > target or buckets[b] in tried: continue # overfull, or same as a bucket we tried tried.add(buckets[b]) buckets[b] += values[i] if place(i + 1): return True # stop: keep the solution buckets[b] -= values[i] return False return place(0) print(can_partition_k_subsets([4, 3, 2, 3, 5, 2, 1], 4))print(can_partition_k_subsets([1, 2, 3, 4], 3))
Output
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.

  1. Am I walking cells or nodes, and is reuse banned along a path? Grid and graph paths.
  2. Am I cutting a string into consecutive pieces? String partitioning.
  3. Does the order of chosen items matter, with each used once? Permutations.
  4. Am I choosing a group with a size or sum rule, order irrelevant? Combinations.
  5. Is each item simply in or out? Subsets.
  6. Am I filling slots under global rules (attacks, equal sums, balance)? Constraint placement.
Match the pairs0/6 matched

Match each problem to its sub-pattern.

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

Traps

  • Recording the live path. result.append(path) stores a reference that later empties. Record path[:] or [...path].
  • Forgetting to un-choose. Every append, add, mark or += before the recursive call needs its exact reverse after it. A missed used[i] = False silently hides answers.
  • Wrong next index. i + 1 means each item once; i means reuse; 0 (with a used array) 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. Writing i > 0 skips 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 it in order5 steps

Put the body of a backtracking function in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Quick check
In Subsets II, after sorting [1, 2, 2], why is the skip condition i > start and not i > 0?
Need a nudge? A hint rules out a wrong answer.

How to talk it through

Key terms
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.