Recursion

Functions that call themselves — base cases, the call stack, recursion trees, memoization, and converting recursion to iteration.

Beginner 3 min readLesson 2 of 18 Interview Q&A

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:

  1. Base case — a small input answered directly, which stops the recursion.
  2. 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);
}

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.

factorial(1)← returns 1factorial(2)factorial(3)factorial(4)
Frames pile up until the base case, then unwind: 1 → 2 → 6 → 24.

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:

  1. Define precisely what the function returns for an input.
  2. Assume it works for smaller inputs.
  3. 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:

f(2)f(1)f(3)f(2)f(4)f(2)f(1)f(3)f(5)
f(3) and f(2) are computed repeatedly — the tree has O(2ⁿ) nodes.

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])

Types of recursion

TypeDescriptionExample
LinearOne recursive callfactorial, list traversal
Binary / treeTwo or more callsFibonacci, tree traversals, merge sort
TailThe recursive call is the very last actiongcd(a, b) = gcd(b, a % b)
Mutualf calls g, g calls fisEven/isOdd, recursive-descent parsers
BacktrackingRecurse, then undo a choicepermutations, 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;
}
Key takeaways
  • 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.
Interview questions
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.