Module 0 · Lesson 3 · ~25 min

Recursion, the call stack, and invariants

If recursion still feels like magic — like a function that somehow knows the answer to a problem one size smaller than itself — that's because nobody showed you the stack of paused function calls waiting on each other. Once you can picture that stack, recursion stops being magic and becomes mechanical.

The metaphor: nested envelopes

Recursion is the postal trick of putting a problem inside an envelope, sealing it, and handing it to a clerk who's allowed to open it, take out a smaller envelope, hand that to another clerk, and so on. Each clerk does a tiny piece of the work and waits for the inner clerk to finish before sealing their own envelope and handing it back up.

The pile of unfinished envelopes on each clerk's desk — that's the call stack. Every active recursive call is a paused envelope waiting on the answer from the one above it.

The metaphor

Recursion isn't magic — it's an explicit promise: "I'll solve a smaller version of this problem, then I'll combine its answer with mine." The base case is the smallest envelope, the one with the answer already inside.

Three things every recursive function needs

  1. A base case — when the problem is small enough that you can answer directly, no further envelopes needed.
  2. A recursive case — call yourself on a strictly smaller subproblem.
  3. A combiner — how you stitch the inner answer together with your own work.

Miss any of those and you get either an infinite stack or a wrong answer. Let's see all three on factorial:

def factorial(n):
    if n <= 1:                    # 1. base case
        return 1
    return n * factorial(n - 1)   # 2. recursive call    3. combiner: n *
function factorial(n) {
  if (n <= 1) return 1;            // 1. base case
  return n * factorial(n - 1);     // 2. recursive call    3. combiner: n *
}
function factorial(n: number): number {
  if (n <= 1) return 1;            // 1. base case
  return n * factorial(n - 1);     // 2. recursive call    3. combiner: n *
}

The call tree — the picture you have to be able to draw

Here's the actual sequence of frames when you call factorial(4). Hit play and watch the stack grow as each frame waits on the next, then unwind as answers come back up.

Four nested frames at peak for factorial. Each frame is a few words of state — the value of n, the return address, a register or two. That's the space cost of recursion: O(depth of recursion). Click "fib(4)" and watch how dramatically the same stack pattern compounds when each frame makes two calls instead of one — the same depth, but four calls happen sequentially in time.

Linear recursion vs. tree recursion

Two recursion shapes show up over and over.

Linear recursion — one self-call

Each frame makes one recursive call. Total frames = depth = O(n). Each does O(1) work. Total time = O(n). This is what factorial does.

Tree recursion — multiple self-calls

Each frame makes k recursive calls. Now the call tree branches. The Fibonacci textbook example branches by 2 at every level, so the tree has roughly 2ⁿ leaves and total work is O(2ⁿ). Death.

def fib(n):
    if n < 2: return n
    return fib(n-1) + fib(n-2)   # two calls per frame → exponential
function fib(n) {
  if (n < 2) return n;
  return fib(n - 1) + fib(n - 2);   // two calls per frame → exponential
}
function fib(n: number): number {
  if (n < 2) return n;
  return fib(n - 1) + fib(n - 2);   // two calls per frame → exponential
}

The fix is memoization: cache the answer to each subproblem the first time you compute it, and short-circuit on subsequent calls. Now the tree collapses to a chain of n unique subproblems, each O(1). O(n) total. We'll do this rigorously in Module 7 (DP).

The skill: invariants

The most useful mental tool for recursive code (and loops, by the way) is the loop invariant — a property that's true at the start of every recursive call.

For binary search:

Invariant — binary search

"At every step, if the target exists in the array, it lies somewhere in the range [lo, hi]." That's the contract. Each recursive call shrinks the range while preserving the contract. When lo > hi, the range is empty — meaning the target wasn't there. Done.

Once you can write down the invariant, the off-by-one bugs evaporate. You'll be able to defend your code aloud: "the invariant is X. Each recursive call preserves X while reducing the range by half. The base case is when the range is empty. So the total work is log₂ n." That's interview gold.

Recursion vs. iteration — what's the difference, really?

Anything you can do with recursion you can do with iteration plus an explicit stack. The choice is about readability, not capability.

Use recursion when…Use iteration when…
The data is naturally recursive (trees, JSON).The data is sequential (arrays, streams).
The "smaller subproblem" framing is obvious.You need a single, predictable, bounded loop.
The recursion depth is bounded (log n typically).You're worried about stack overflow on huge inputs.
Tail-call optimization or trampolines are available.Performance matters and call overhead would dominate.
Stack depth gotcha

Python has a default recursion limit of ~1000. JavaScript engines vary, but often around 10,000–30,000 frames. If you recurse over n = 100,000 elements linearly, you will overflow. For interview problems, this means: linear recursion on a long array is usually a code smell — convert it to a loop or rewrite with explicit stack.

Notebook prompt