Skip to content
TOPIC · 14 PROBLEMS · 5 PATTERNS

Backtracking

Try a choice, see where it leads, take it back, try the next. A careful way to walk through every option without losing your place.

How to spot a backtracking problem

“all possible”The answer is a list of every subset, ordering or combination, not a single number. You have to visit each one.
“generate”Build strings or arrangements piece by piece, as long as each piece follows the rules so far.
“n ≤ 10”Tiny limits on the input. The problem setter expects exponential work and is telling you so.
“place / fill”Queens on a board, digits in a grid. Put one down, check nothing clashes, and pull it back if you get stuck.

Five patterns cover almost everything

Subsets

O(n · 2ⁿ)

Walk the items once. For each, either add it to the path or skip it. Every node in the tree is an answer.

Reach for it when you need every selection of the items, in any size, with order not mattering.Go deeper: Backtracking: try, undo, try the next

Permutations

O(n · n!)

Fill the slots one at a time from the items not used yet. Mark an item used on the way down and free it on the way up.

Reach for it when order matters and every item appears exactly once.Go deeper: Backtracking: try, undo, try the next

Combinations

O(2ⁿ) or less

Loop from a start index so each set is built in one order only. Stop a branch as soon as it overshoots.

Reach for it when you pick items to meet a target or a size, and [1, 2] and [2, 1] count as the same.Go deeper: Backtracking: try, undo, try the next

Grid search

O(m · n · 4ᴸ)

Depth-first search from each cell. Mark the cell as used, try its four neighbours, then unmark it.

Reach for it when you trace a path through a grid that may not reuse a cell, such as spelling a word.Go deeper: BFS and DFS: same graph, different order

Constraint placement

O(n!)

Place one piece per row or cell, check it clashes with nothing so far, and back out the moment it does.

Reach for it when every placement must respect rules about rows, columns, diagonals or boxes.Go deeper: Backtracking: try, undo, try the next

The one template to memorise

Learn this one by heart: choose, go deeper, undo. Change what counts as an answer and where the loop starts, and it becomes nearly every problem below.

solution.py
def subsets(nums):
result, path = [], []
def explore(start):
result.append(path[:]) # every node is an answer
for i in range(start, len(nums)):
path.append(nums[i]) # choose
explore(i + 1) # go deeper
path.pop() # undo
explore(0)
return result

Problems, easy to hard

Do them in order the first time
#ProblemPatternDifficultySolution
1SubsetsSubsetsMediumRead
2CombinationsCombinationsMediumRead
3PermutationsPermutationsMediumRead
4Letter Combinations of a Phone NumberCombinationsMediumRead
5Subsets IISubsets + skip duplicatesMediumRead
6Combination SumCombinationsMediumRead
7Combination Sum IICombinationsMediumRead
8Permutations IIPermutationsMediumRead
9Generate ParenthesesConstraint placementMediumRead
10Palindrome PartitioningCombinationsMediumRead
11Word SearchGrid searchMediumRead
12N-QueensConstraint placementHardRead
13Sudoku SolverConstraint placementHardRead
14Word Search IIGrid search + trieHardRead
Next upDynamic programming