Skip to content
Chethan Yadav_
Data Structures & Algorithms

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:

  1. a base case that stops the recursion;
  2. a recursive case that moves toward the base case;
  3. 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 = 6

Space 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

PatternExample
LinearSum of list, factorial
Binary (two calls)Fibonacci, tree height
Multiple branchesPermutations, combination sum
Mutual recursionis_even calls is_odd
AccumulatorPass 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.

AlgorithmSplitCombineTime
Merge sortHalvesMerge O(n)O(n log n)
Quick sortPartition O(n)NothingO(n log n) avg
Binary searchHalfNothingO(log n)
Fast powerHalf the exponentSquareO(log n)
Closest pair of pointsHalvesStrip checkO(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 * x

Divide 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-choose

Choose, 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 res

With 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 res

Combinations (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 count

Diagonal 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), permutations O(n * n!).
  • N-Queens: sets for columns, r - c and r + c diagonals.
  • Pruning (feasibility, bounds, ordering) is what makes backtracking fast enough.