Recursion
Functions that call themselves — base cases, the call stack, recursion trees, memoization, and converting recursion to iteration.
A recursive function solves a problem by calling itself on smaller instances of the same problem. It's the natural way to express anything self-similar: trees, nested structures, divide-and-conquer, and backtracking.
Every correct recursive function has two parts:
- Base case — a small input answered directly, which stops the recursion.
- Recursive case — reduce the problem, call yourself, and combine the result.
int factorial(int n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive case: smaller problem
}
int sumDigits(int n) {
if (n < 10) return n;
return n % 10 + sumDigits(n / 10);
}
void reverse(char[] s, int l, int r) {
if (l >= r) return;
char t = s[l]; s[l] = s[r]; s[r] = t;
reverse(s, l + 1, r - 1);
}def factorial(n: int) -> int:
if n <= 1: # base case
return 1
return n * factorial(n - 1)
def sum_digits(n: int) -> int:
return n if n < 10 else n % 10 + sum_digits(n // 10)
def flatten(x):
"""Recursion is natural for nested data."""
if not isinstance(x, list):
return [x]
return [y for item in x for y in flatten(item)]function factorial(n: number): number {
if (n <= 1) return 1; // base case
return n * factorial(n - 1);
}
const sumDigits = (n: number): number => (n < 10 ? n : (n % 10) + sumDigits(Math.floor(n / 10)));
function flatten(x: unknown): unknown[] {
return Array.isArray(x) ? x.flatMap(flatten) : [x];
}What happens on the call stack
Each call pushes a stack frame holding its arguments, locals and return address. Calls wait for the deeper call to return, then the frames unwind.
Too deep a recursion exhausts the stack: StackOverflowError (Java), RecursionError (Python's default limit is 1000), RangeError: Maximum call stack size exceeded (JS).
The leap of faith
Don't trace every call in your head. Instead:
- Define precisely what the function returns for an input.
- Assume it works for smaller inputs.
- Use that to solve the current input, and make sure the base case is right.
That's mathematical induction — and it's how you write tree algorithms in three lines.
Recursion trees and overlapping subproblems
Naive Fibonacci branches twice per call:
Caching results — memoization — collapses the tree to n distinct calls: O(2ⁿ) → O(n). This is the gateway to dynamic programming.
long fib(int n, long[] memo) {
if (n <= 1) return n;
if (memo[n] != 0) return memo[n];
return memo[n] = fib(n - 1, memo) + fib(n - 2, memo);
}
// call: fib(50, new long[51])from functools import cache
@cache
def fib(n: int) -> int:
return n if n <= 1 else fib(n - 1) + fib(n - 2)const memo = new Map<number, number>();
function fib(n: number): number {
if (n <= 1) return n;
if (memo.has(n)) return memo.get(n)!;
const v = fib(n - 1) + fib(n - 2);
memo.set(n, v);
return v;
}Types of recursion
| Type | Description | Example |
|---|---|---|
| Linear | One recursive call | factorial, list traversal |
| Binary / tree | Two or more calls | Fibonacci, tree traversals, merge sort |
| Tail | The recursive call is the very last action | gcd(a, b) = gcd(b, a % b) |
| Mutual | f calls g, g calls f | isEven/isOdd, recursive-descent parsers |
| Backtracking | Recurse, then undo a choice | permutations, N-Queens |
Converting recursion to iteration
Any recursion can be rewritten with an explicit stack (that's what the CPU does anyway). Do it when depth could reach tens of thousands — e.g. DFS on a long path graph.
// Recursive pre-order → iterative with an explicit stack
List<Integer> preorder(TreeNode root) {
List<Integer> out = new ArrayList<>();
Deque<TreeNode> st = new ArrayDeque<>();
if (root != null) st.push(root);
while (!st.isEmpty()) {
TreeNode n = st.pop();
out.add(n.val);
if (n.right != null) st.push(n.right); // right first so left is processed first
if (n.left != null) st.push(n.left);
}
return out;
}def preorder(root):
out, st = [], [root] if root else []
while st:
n = st.pop()
out.append(n.val)
if n.right: st.append(n.right) # right first so left pops first
if n.left: st.append(n.left)
return outfunction preorder(root: TreeNode | null): number[] {
const out: number[] = [];
const st = root ? [root] : [];
while (st.length) {
const n = st.pop()!;
out.push(n.val);
if (n.right) st.push(n.right);
if (n.left) st.push(n.left);
}
return out;
}- Recursion = base case + smaller recursive case + combine.
- Trust the function's contract for smaller inputs (induction) instead of tracing every call.
- Each call costs a stack frame: space is O(depth).
- Overlapping subproblems ⇒ memoize ⇒ dynamic programming.
- Java/Python/JS lack tail-call optimisation; use explicit stacks for very deep recursion.
QCompute xⁿ efficiently.medium
Fast exponentiation: pow(x, n) = pow(x*x, n/2) for even n, x * pow(x, n-1) for odd n. O(log n) multiplications. Handle negative n as 1 / pow(x, -n) and watch overflow on Integer.MIN_VALUE.
QSolve the Tower of Hanoi for n disks. How many moves?easy
Move n−1 disks to the spare peg, move the largest to the target, then move the n−1 disks onto it. T(n) = 2T(n−1) + 1 = 2ⁿ − 1 moves — provably optimal.
QWhen is recursion a bad idea?easy
When depth can be huge (stack overflow), when subproblems overlap and aren't memoized (exponential blow-up), or in hot loops where call overhead matters. Iteration or bottom-up DP is often better there.