DSA/Lesson 10 of 11/6 min read
Recursion and Backtracking
How recursion works, base cases, the call stack, tail recursion, divide and conquer, and backtracking for subsets, permutations and constraint problems.
On this page
Recursion
A function that solves a problem by calling itself on a smaller instance. Every recursive solution needs:
- a base case that stops the recursion;
- a recursive case that moves toward the base case;
- trust that the smaller call returns the right answer (the leap of faith).
def factorial(n):
if n <= 1: # base case
return 1
return n * factorial(n - 1)How the call stack works
Each call pushes a stack frame holding its parameters, local variables and return address. Frames pop as calls return. Deep recursion can cause a stack overflow (Python default limit is about 1000 frames).
factorial(3)
factorial(2)
factorial(1) -> 1
-> 2 * 1 = 2
-> 3 * 2 = 6Space complexity of recursion is at least O(max depth).
Base Case
Missing or wrong base cases are the top recursion bug.
- Handle the smallest valid inputs: empty array,
n == 0, null node. - Make sure every recursive call shrinks the problem, otherwise it loops forever.
- For trees, the base case is usually
if not node: return ....
Recursion patterns
| Pattern | Example |
|---|---|
| Linear | Sum of list, factorial |
| Binary (two calls) | Fibonacci, tree height |
| Multiple branches | Permutations, combination sum |
| Mutual recursion | is_even calls is_odd |
| Accumulator | Pass partial result down as a parameter |
Overlapping subproblems
Naive Fibonacci recomputes the same values exponentially: fib(5) calls fib(3) twice and fib(2) three times, O(2^n) time. Caching results (memoization) brings it down to O(n). This is the bridge to dynamic programming.
Tail Recursion
A call is tail recursive when the recursive call is the very last action, with nothing left to do after it.
def fact_tail(n, acc=1):
if n <= 1:
return acc
return fact_tail(n - 1, acc * n)Languages with tail call optimization (Scheme, Scala with @tailrec, many functional languages) reuse the frame, making it O(1) space. Python, Java and JavaScript engines in practice do not optimize tail calls, so convert deep recursion to a loop.
Divide and Conquer
Split into independent subproblems, solve them recursively, combine the results.
| Algorithm | Split | Combine | Time |
|---|---|---|---|
| Merge sort | Halves | Merge O(n) | O(n log n) |
| Quick sort | Partition O(n) | Nothing | O(n log n) avg |
| Binary search | Half | Nothing | O(log n) |
| Fast power | Half the exponent | Square | O(log n) |
| Closest pair of points | Halves | Strip check | O(n log n) |
def power(x, n):
if n == 0:
return 1
half = power(x, n // 2)
return half * half if n % 2 == 0 else half * half * xDivide and conquer has independent subproblems; dynamic programming has overlapping ones.
Backtracking
Build a solution incrementally and abandon (backtrack) a partial solution as soon as it cannot lead to a valid answer. It is DFS over a tree of choices.
Template:
def backtrack(path, choices):
if is_solution(path):
result.append(path[:]) # copy!
return
for choice in choices:
if not valid(choice, path):
continue
path.append(choice) # choose
backtrack(path, next_choices)
path.pop() # un-chooseChoose, explore, un-choose. Forgetting to undo the choice, or appending path without copying, are the classic bugs.
Subsets
Each element is either in or out: 2^n subsets, O(n * 2^n) total.
def subsets(nums):
res = []
def go(i, path):
if i == len(nums):
res.append(path[:])
return
go(i + 1, path) # skip
path.append(nums[i])
go(i + 1, path) # take
path.pop()
go(0, [])
return resWith duplicates, sort first and skip nums[i] == nums[i - 1] at the same recursion level.
Bitmask alternative: every integer from 0 to 2^n - 1 encodes a subset.
Permutations
n! orderings, O(n * n!) total. Track used elements with a boolean array or swap in place.
def permute(nums):
res = []
def go(path, used):
if len(path) == len(nums):
res.append(path[:])
return
for i, x in enumerate(nums):
if used[i]:
continue
used[i] = True
path.append(x)
go(path, used)
path.pop()
used[i] = False
go([], [False] * len(nums))
return resCombinations (choose k of n) are subsets limited to size k; pass a start index to avoid reordering.
N-Queens
Place n queens on an n x n board so none attack each other. Place one queen per row; track used columns and both diagonals in sets.
def solve_n_queens(n):
cols, d1, d2, count = set(), set(), set(), 0
def go(r):
nonlocal count
if r == n:
count += 1
return
for c in range(n):
if c in cols or (r - c) in d1 or (r + c) in d2:
continue
cols.add(c); d1.add(r - c); d2.add(r + c)
go(r + 1)
cols.remove(c); d1.remove(r - c); d2.remove(r + c)
go(0)
return countDiagonal trick: cells on the same main diagonal share r - c; on the anti-diagonal they share r + c.
Pruning
Cutting branches early is what makes backtracking practical.
- Feasibility pruning: stop when the partial sum already exceeds the target (combination sum on sorted input).
- Bounding: in optimization, stop when the best possible completion cannot beat the current best (branch and bound).
- Ordering: try the most constrained choice first (Sudoku: the cell with fewest candidates).
- Symmetry: skip duplicate states, for example the duplicate-skip rule in subsets II.
Other classic backtracking problems: Sudoku solver, word search in a grid, palindrome partitioning, generate parentheses, letter combinations of a phone number, rat in a maze.
Quick revision
- Recursion = base case + smaller recursive case; space is at least the max depth.
- Python, Java and JS do not optimize tail calls; convert deep recursion to loops.
- Divide and conquer: independent subproblems; DP: overlapping subproblems.
- Backtracking template: choose, explore, un-choose; copy the path when saving it.
- Subsets
O(n * 2^n), permutationsO(n * n!). - N-Queens: sets for columns,
r - candr + cdiagonals. - Pruning (feasibility, bounds, ordering) is what makes backtracking fast enough.