Backtracking (LeetCode #9)
Backtracking is recursion over a space of choices: build a solution one decision at a time, recurse, then undo the decision so the next branch starts clean. The template never changes; the work is choosing the state, the choices, and the pruning. This post covers the nine NeetCode Backtracking problems.
The technique
backtrack(state):
if state is complete:
record it; return
for each choice:
if choice is allowed:
apply(choice)
backtrack(state)
undo(choice)
The undo is what makes it backtracking rather than plain recursion. Pruning — skipping a choice that cannot lead to a solution — is the difference between fast and time-out.
Subsets
The question. Return all subsets of distinct integers.
Input: [1,2] -> [[], [1], [2], [1,2]]
The idea. Each element is an include/exclude decision → a binary tree with \(2^n\) leaves.
Walk it through. Exclude 1, exclude 2 → []; exclude 1, include 2 → [2]; include 1, exclude 2 → [1]; include 1, include 2 → [1,2].
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, rounded corners=2pt, minimum width=0.7cm, font=\scriptsize\ttfamily, inner sep=2pt}]
\node[n, fill=blue!8] (r) at (0,0) {[]};
\node[n, fill=blue!8] (l) at (-1.3,-0.9) {[]}; \node[n, fill=blue!8] (rr) at (1.3,-0.9) {[1]};
\node[n, fill=green!12] (a) at (-2.0,-1.8) {[]}; \node[n, fill=green!12] (b) at (-0.6,-1.8) {[2]};
\node[n, fill=green!12] (c) at (0.6,-1.8) {[1]}; \node[n, fill=green!12] (d) at (2.0,-1.8) {[1,2]};
\draw[->, thick] (r) -- (l) node[font=\tiny\ttfamily, midway, left] {skip 1};
\draw[->, thick] (r) -- (rr) node[font=\tiny\ttfamily, midway, right] {take 1};
\draw[->, thick] (l) -- (a); \draw[->, thick] (l) -- (b);
\draw[->, thick] (rr) -- (c); \draw[->, thick] (rr) -- (d);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-2.3) {one binary choice per element};
\end{tikzpicture}
def subsets(nums):
out, path = [], []
def backtrack(i):
if i == len(nums):
out.append(path[:]); return # snapshot
backtrack(i + 1) # exclude
path.append(nums[i]); backtrack(i + 1); path.pop() # include
backtrack(0)
return out
\(O(n \cdot 2^n)\) time.
Combination Sum
The question. Return unique combinations summing to target; each candidate may be reused.
Input: [2,3,6,7], target = 7 -> [[2,2,3], [7]]
The idea. Choose numbers in non-decreasing order; recurse with the same index i to allow reuse; prune when a candidate exceeds the remainder.
Walk it through on [2, 3, 6, 7], target = 7. Sorting lets us stop a loop as soon as a candidate is too big, and passing i (not i+1) lets a number repeat:
backtrack(0, remaining=7)
├─ take 2 → backtrack(0, rem=5)
│ ├─ take 2 → backtrack(0, rem=3)
│ │ ├─ take 2 → rem=1, next candidate 2 > 1 → stop
│ │ └─ take 3 → rem=0 → [2,2,3] ✓
│ └─ take 3 → rem=2, next candidate 3 > 2 → stop
├─ take 3 → backtrack(1, rem=4)
│ └─ take 3 → rem=1, next 6 > 1 → stop
├─ take 6 → backtrack(2, rem=1), every candidate > 1 → stop
└─ take 7 → rem=0 → [7] ✓
Result [[2,2,3], [7]].
def combination_sum(candidates, target):
out, path = [], []
candidates.sort()
def backtrack(start, remaining):
if remaining == 0:
out.append(path[:]); return
for i in range(start, len(candidates)):
if candidates[i] > remaining:
break # prune (sorted)
path.append(candidates[i])
backtrack(i, remaining - candidates[i]) # i: reuse allowed
path.pop()
backtrack(0, target)
return out
Why i and not i+1. Passing the same i lets the current candidate be chosen again. Requiring the next pick to come from index ≥ i keeps each combination in non-decreasing order, which is why [2,3,2] and [3,2,2] never appear alongside [2,2,3].
Why the break works. After sorting, once candidates[i] > remaining, every later candidate is at least as large, so the whole rest of the loop is hopeless.
Complexity. Exponential in the depth (bounded by target / min(candidates)); the sort is \(O(n \log n)\).
Edge cases. target = 0 → [[]]. A candidate larger than target is skipped by the break immediately. All candidates positive is assumed.
Permutations
The question. Return all orderings of distinct integers.
The idea. Fix positions left to right. At position start, try every remaining element by swapping it into that slot, recurse on start + 1, then swap back. After the swap, positions 0..start-1 are already fixed, so each leaf is one full permutation.
Walk it through on [1, 2, 3]. Each node shows the array after its swap:
[1,2,3]
├─ swap(0,0) [1,2,3]
│ ├─ swap(1,1) [1,2,3] → 123 ✓
│ └─ swap(1,2) [1,3,2] → 132 ✓
├─ swap(0,1) [2,1,3]
│ ├─ swap(1,1) [2,1,3] → 213 ✓
│ └─ swap(1,2) [2,3,1] → 231 ✓
└─ swap(0,2) [3,2,1]
├─ swap(1,1) [3,2,1] → 321 ✓
└─ swap(1,2) [3,1,2] → 312 ✓
Six leaves, matching \(3!\).
def permutations(nums):
out = []
def backtrack(start):
if start == len(nums):
out.append(nums[:]); return
for i in range(start, len(nums)):
nums[start], nums[i] = nums[i], nums[start]
backtrack(start + 1)
nums[start], nums[i] = nums[i], nums[start] # undo
backtrack(0)
return out
Why each permutation appears exactly once. At depth start, every unused element is placed at index start; the recursion then permutes all (n − start − 1)! orderings of the rest. No element can be placed twice at the same index because the swap exchanges distinct positions, and the undo restores the array for the next choice.
Why swap instead of a used array. Swapping needs no extra set — the front of the array is the used set. The only cost is that the original array is mutated (restored by the undo).
Complexity. \(O(n \cdot n!)\) time (there are \(n!\) leaves, each requiring an \(O(n)\) copy at the leaf) and \(O(n)\) recursion space.
Edge cases. Empty input → [[]] (one empty permutation). Duplicate values would produce duplicate permutations; use a used set or sort-and-skip if the input may repeat.
Subsets II
The question. Like Subsets, but the input may contain duplicates, and the result must not contain duplicate subsets.
Input: [1,2,2]
Output: [[], [1], [2], [1,2], [2,2], [1,2,2]]
The idea. Sort so duplicates are adjacent. At each level, if the current element equals the previous within the same loop, skip it — that path would reproduce subsets already generated.
Walk it through. Sorted [1,2,2]. Choose the first 2, then the second 2 → [2,2]. When the loop reaches the second 2 as a level’s first pick, skip it (same as the previous pick at this level).
def subsets_with_dup(nums):
out, path = [], []
nums.sort()
def backtrack(start):
out.append(path[:])
for i in range(start, len(nums)):
if i > start and nums[i] == nums[i-1]:
continue # skip duplicate at this level
path.append(nums[i])
backtrack(i + 1)
path.pop()
backtrack(0)
return out
Combination Sum II
The question. Like Combination Sum, but each candidate may be used once and the input may contain duplicates.
Input: candidates = [10,1,2,7,6,1,5], target = 8
Output: [[1,1,6], [1,2,5], [1,7], [2,6]]
The idea. Combine the two fixes: sort, recurse with i + 1 (no reuse), and skip duplicates within a level.
Walk it through on [10, 1, 2, 7, 6, 1, 5], target = 8. Sorted: [1, 1, 2, 5, 6, 7, 10].
| start | path | remaining | step |
|---|---|---|---|
| 0 | [1] |
7 | first 1; then at the next level try 1 again |
| 1 | [1,1] |
6 | second 1 → then 6 |
| 2 | [1,1,6] |
0 | ✓ [1,1,6] |
| 0 | [1] |
7 | 2, 5 |
[1,2] |
5 | then 5 → ✓ [1,2,5] |
|
[1,5] |
2 | next candidate 6 > 2 → stop |
|
| 0 | [1] |
7 | 7 → ✓ [1,7] |
| 2 | [2] |
6 | 6 → ✓ [2,6] |
| — | [2,2]... |
2+2=4, then 5>4 stop; no match |
|
| — | [2,5]... |
2+5=7, then 6>1 stop |
When the loop reaches the second 1 at start = 0 (i.e. i = 1, which equals candidates[i-1]), it is skipped: the first 1 at this level already explored every subset that begins with a 1, so repeating it would duplicate results.
def combination_sum2(candidates, target):
out, path = [], []
candidates.sort()
def backtrack(start, remaining):
if remaining == 0:
out.append(path[:]); return
for i in range(start, len(candidates)):
if i > start and candidates[i] == candidates[i-1]:
continue # skip duplicate at this level
if candidates[i] > remaining:
break # prune
path.append(candidates[i])
backtrack(i + 1, remaining - candidates[i]) # i+1: use once
path.pop()
backtrack(0, target)
return out
Why i > start in the skip. Only duplicates within the current level are skipped. The same value appearing deeper (as in [1,1,6]) is a different element and must remain allowed. The condition compares only choices at the same recursion depth.
Why i + 1. Unlike Combination Sum, each candidate is a single physical item, so after taking it the search must move past it.
Complexity. Exponential; the sort is \(O(n \log n)\).
Edge cases. target = 0 → [[]]. Duplicate candidates are handled by the level skip. A candidate bigger than remaining cuts the loop early.
Word Search
The question. Return True if a word can be built from adjacent grid cells, each used once.
The idea. DFS from every cell, marking visited by overwriting the cell and restoring it on the way out (the backtracking undo on a grid).
Walk it through on
A B C E
S F C S
A D E E
with word = "ABCCED". Starting at (0,0), the path is:
A(0,0) → B(0,1) → C(0,2) → C(1,2) → E(2,2) → D(2,1)
Each cell is set to "#" when entered so it cannot be reused, and restored to its letter when the DFS unwinds. From C(0,2) there is only one adjacent C, at (1,2); the other neighbours can’t continue the word. The word "ABCB" fails because it would need to revisit B(0,1).
def word_search(board, word):
rows, cols = len(board), len(board[0])
def dfs(r, c, i):
if i == len(word):
return True
if r < 0 or r >= rows or c < 0 or c >= cols or board[r][c] != word[i]:
return False
board[r][c] = "#" # mark
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] # restore
return found
return any(dfs(r, c, 0) for r in range(rows) for c in range(cols))
Why the mark/restore pair. The "#" prevents the current path from stepping back onto itself; restoring the original letter is the undo that lets a different starting path use the same cell. Without the restore, later searches would see a grid full of "#" and fail.
Why four calls. The four recursive calls are the four grid moves; the or short-circuits as soon as one direction completes the word.
Pruning. The bounds and the character check happen before marking, so dead directions return immediately rather than recursing deeper.
Complexity. \(O(R \cdot C \cdot 4^L)\) worst case for a word of length \(L\) (each step has up to four neighbours); \(O(L)\) stack space.
Edge cases. A word longer than the number of cells → False. Single-cell word → matches if the cell equals it. Empty word → True (the i == len(word) check fires at once).
Palindrome Partitioning
The question. Partition a string so every piece is a palindrome; return all such partitions.
Input: "aab"
Output: [["a","a","b"], ["aa","b"]]
The idea. At each step, choose a prefix s[start:i] that is a palindrome, recurse on the rest, and undo. The pruning is “only recurse on palindromic prefixes”.
Walk it through on "aab": choose "a" (palindrome), recurse "ab" → "a" then "b" → ["a","a","b"]; also choose "aa" then "b" → ["aa","b"].
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, rounded corners=2pt, minimum width=0.9cm, font=\scriptsize\ttfamily, inner sep=2pt}]
\node[n, fill=blue!8] (r) at (0,0) {aab};
\node[n, fill=blue!8] (l) at (-1.4,-0.9) {a|ab}; \node[n, fill=blue!8] (rr) at (1.4,-0.9) {aa|b};
\node[n, fill=green!12] (a) at (-2.2,-1.8) {a|a|b}; \node[n, fill=green!12] (b) at (-0.6,-1.8) {a|ab(dead)};
\node[n, fill=green!12] (c) at (1.4,-1.8) {aa|b (ok)};
\draw[->, thick] (r) -- (l); \draw[->, thick] (r) -- (rr);
\draw[->, thick] (l) -- (a); \draw[->, thick] (l) -- (b);
\draw[->, thick] (rr) -- (c);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-2.3) {only palindromic prefixes branch};
\end{tikzpicture}
def partition(s):
out, path = [], []
def is_pal(t):
return t == t[::-1]
def backtrack(start):
if start == len(s):
out.append(path[:]); return
for end in range(start + 1, len(s) + 1):
piece = s[start:end]
if is_pal(piece): # prune: only palindromes
path.append(piece)
backtrack(end)
path.pop()
backtrack(0)
return out
\(O(n \cdot 2^n)\) in the worst case.
Letter Combinations of a Phone Number
The question. Given digits 2-9, return all letter combinations the number could spell (standard phone keypad).
Input: "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
The idea. For each digit, choose one of its letters and recurse to the next digit.
Walk it through on "23": 2 → abc, 3 → def. Choose a, then d/e/f → ad, ae, af; then b, etc.
def letter_combinations(digits):
if not digits:
return []
mapping = {"2":"abc","3":"def","4":"ghi","5":"jkl",
"6":"mno","7":"pqrs","8":"tuv","9":"wxyz"}
out, path = [], []
def backtrack(i):
if i == len(digits):
out.append("".join(path)); return
for ch in mapping[digits[i]]:
path.append(ch)
backtrack(i + 1)
path.pop()
backtrack(0)
return out
\(O(4^n \cdot n)\).
N-Queens
The question. Place n queens so none attack; return all boards.
The idea. One queen per row, tracking occupied columns and both diagonals in sets. Cells on a \ diagonal share row - col; on a / diagonal share row + col.
Walk it through for n = 4. Rows are placed top to bottom; board stores the column chosen for each row. One valid partial path:
| row | try columns | blocked by | place | cols |
r−c |
r+c |
|---|---|---|---|---|---|---|
| 0 | 0,1,2,3 | none | 1 | {1} | {−1} | {1} |
| 1 | 0,1,2,3 | col 1, diag r−c=0(↔ r0c1) |
3 | {1,3} | {−1,−2} | {1,4} |
| 2 | 0 blocked by diag r=c; 1 blocked by col; 2 blocked by diag; 3 blocked by diag r+c=5? no: 2+2 |
|||||
| 2 | 0 | diag2 2+0=2? not in {1,4}; diag1 2−0=2? no; col 0 free |
0 | {0,1,3} | {2,−1,−2} | {2,1,4} |
| 3 | 0 col taken; 1 diag1 2; 2 free |
2 | {0,1,2,3} | {2,−1,−2,1} | {2,1,4,5} |
That places queens at (0,1), (1,3), (2,0), (3,2):
.Q..
...Q
Q...
..Q.
def solve_n_queens(n):
out, board = [], []
cols, diag1, diag2 = set(), set(), set()
def backtrack(r):
if r == n:
out.append(["." * c + "Q" + "." * (n - c - 1) for c in board]); return
for c in range(n):
if c in cols or r - c in diag1 or r + c in diag2:
continue # attacked -> prune
cols.add(c); diag1.add(r - c); diag2.add(r + c)
board.append(c)
backtrack(r + 1)
board.pop()
cols.remove(c); diag1.remove(r - c); diag2.remove(r + c)
backtrack(0)
return out
Why r − c and r + c. On a \ diagonal, row and column increase together, so r − c is constant. On a / diagonal, row increases while column decreases, so r + c is constant. Two sets therefore detect both diagonal attacks in \(O(1)\), and the column set handles vertical attacks. Placing one queen per row removes horizontal attacks by construction.
Why the undo removes exactly the three set entries. Each level adds one column and two diagonals; popping the board and discarding those same keys restores the state for the sibling branches.
Complexity. \(O(n!)\) candidates, heavily pruned (at most one queen per row/column/diagonal); \(O(n)\) space for the board and sets.
Edge cases. n = 1 → one board. n = 2 and n = 3 → no solutions. n = 4 → two solutions (the board above and its mirror [2,0,3,1]).
Pitfalls
- Appending the live list. Use
path[:]. - Forgetting to undo. The next branch inherits dirty state.
- Not skipping duplicates in Subsets II / Combination Sum II. Sort, then skip equal values at the same level.
- Wrong reuse index.
iallows reuse,i+1forbids it. - Not restoring the grid. Word Search must reset the cell on the way out.
How do Subsets II and Combination Sum II avoid duplicate results? Why does N-Queens use r - c and r + c?
ASolution
Both sort first and, within a recursion level, skip a value equal to the previous one — that branch would reproduce an identical result. On a board, cells on the same \ diagonal share r - c and on the same / diagonal share r + c, so two sets test diagonal attacks in \(O(1)\).
Next: Tries (LeetCode #10) — a tree keyed by characters (complete; see the existing post).