Skip to the content.

30. Recursion and the Call Stack

Back to the index

A function that solves a problem by calling itself on a smaller input, plus a base case that stops it. Every call waits on the call stack until its sub-call returns.

How it works

Recursion has two parts: the base case (an input small enough to answer directly) and the recursive case (reduce the problem and combine the sub-answer). Each call gets its own frame on the call stack holding its local variables; frames pile up on the way down and are removed on the way back up.

The trace makes the stack visible for factorial(4): four calls go down, then four returns multiply the results on the way up.

Diagram

graph TD
    f4["factorial 4"] -->|calls| f3["factorial 3"]
    f3 -->|calls| f2["factorial 2"]
    f2 -->|calls| f1["factorial 1: base case"]
    f1 -.->|returns 1| f2
    f2 -.->|returns 2| f3
    f3 -.->|returns 6| f4

Step-by-step trace

Input: Evaluate factorial(4).

Step Event Call stack (top at right) Value
1 call factorial(4) f(4) -
2 call factorial(3) f(4) f(3) -
3 call factorial(2) f(4) f(3) f(2) -
4 call factorial(1) f(4) f(3) f(2) f(1) -
5 return from factorial(1) f(4) f(3) f(2) 1 (base case)
6 return from factorial(2) f(4) f(3) 2 * 1 = 2
7 return from factorial(3) f(4) 3 * 2 = 6
8 return from factorial(4) (empty) 4 * 6 = 24

Result: Result: 24.

Complexity

Operation Time Space
factorial(n) O(n) O(n) call stack
Naive Fibonacci (two calls each) O(2^n) O(n)
Memoized Fibonacci O(n) O(n)

Python reference implementation

def factorial(n):
    if n <= 1:           # base case stops the recursion
        return 1
    return n * factorial(n - 1)

Common mistakes and tips


The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.

Previous: KMP String Matching Next: Backtracking (Subsets)