Recursion solves a problem by expressing it in terms of smaller instances of the same problem. A recursive function needs a base case that answers the smallest inputs directly and a recursive case that shrinks the input and combines the results. It is the natural language of trees, divide and conquer, backtracking and dynamic programming, so learning to trust it pays off across the whole curriculum.
Think of it like
Which row am I in?
In a dark cinema you want to know your row number but cannot count the rows. So you ask the person in front of you, who asks the person in front of them, and so on. The person in the front row knows the answer immediately: row 1 (the base case). Each person then adds 1 to the answer they receive and passes it back (the recursive case). Nobody needs to see the whole cinema; everyone trusts the smaller answer.
How it works
A recursive definition has two parts. The base case stops the descent. The recursive case reduces the problem to one or more strictly smaller versions of itself and combines their answers. If every call makes progress toward a base case, the recursion terminates.
- 1
Define the contract
State in one sentence what the function returns for an input, for example "
factorial(n)returns n!". Everything else follows from this. - 2
Handle the base case
Answer the smallest inputs directly:
factorial(0) = factorial(1) = 1. - 3
Shrink the problem
Call the function on a smaller input:
factorial(n - 1). - 4
Combine
Use the smaller answer to build the full one:
n × factorial(n - 1). - 5
Check progress
Make sure every path reaches a base case.
n - 1from a positive integer always reaches 1.
def factorial(n: int) -> int:
if n <= 1: # base case: answer directly
return 1
return n * factorial(n - 1) # recursive case: shrink, then combineThe call stack
Each function call gets a stack frame holding its parameters, local variables and the return address (where to resume in the caller). Calling pushes a frame; returning pops it. Recursion simply pushes many frames of the same function, each with its own copy of the locals.
| Step | What happens | Stack (bottom to top) |
|---|---|---|
| 1 | Call factorial(4) | f(4) |
| 2 | f(4) calls factorial(3) and waits | f(4), f(3) |
| 3 | f(3) calls factorial(2) and waits | f(4), f(3), f(2) |
| 4 | f(2) calls factorial(1): base case returns 1 | f(4), f(3), f(2), f(1) |
| 5 | f(2) resumes and returns 2 × 1 = 2 | f(4), f(3), f(2) |
| 6 | f(3) resumes and returns 3 × 2 = 6 | f(4), f(3) |
| 7 | f(4) resumes and returns 4 × 6 = 24 | f(4) |
- Stack frame
- The memory for one active call: arguments, locals and the return address.
- Winding
- The descent phase, when calls are made and frames pile up.
- Unwinding
- The return phase, when each frame finishes its pending work and pops.
- Recursion depth
- The maximum number of frames alive at once. It determines the stack space used.
Recursion trees
When a function calls itself more than once, the calls form a tree. The naive Fibonacci definition fib(n) = fib(n - 1) + fib(n - 2) makes two calls per node, and the tree for fib(5) already has 15 nodes.
fib(5)
├── fib(4)
│ ├── fib(3)
│ │ ├── fib(2)
│ │ │ ├── fib(1)
│ │ │ └── fib(0)
│ │ └── fib(1)
│ └── fib(2)
│ ├── fib(1)
│ └── fib(0)
└── fib(3)
├── fib(2)
│ ├── fib(1)
│ └── fib(0)
└── fib(1)Time follows the number of nodes
- Each node does O(1) work outside its calls
- fib(n) makes 2·F(n+1) − 1 calls in total
- fib(30) makes about 2.7 million calls
- Growth is Θ(φⁿ) with φ ≈ 1.618
Space follows the height
- Only one root-to-leaf path is on the stack at a time
- The deepest path is fib(n), fib(n−1), …, fib(1)
- So the stack holds at most n frames
- Space is O(n), even though time is exponential
Memoization: a teaser
The fib(5) tree computes fib(3) twice and fib(2) three times. Caching each result the first time it is computed (memoization) collapses the tree into a chain: every value from 0 to n is computed once, so time drops from exponential to O(n). This is the core idea of DP Fundamentals.
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n: int) -> int:
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
fib(90) # instant; the naive version would need about 10^19 callsClassic examples
Fast power
Computing xⁿ by multiplying x n times takes O(n). Recursion does better by halving the exponent: compute x^(n/2) once and square it.
Tower of Hanoi
Move a stack of n disks from peg A to peg C using peg B, moving one disk at a time and never placing a larger disk on a smaller one. The recursive insight: to move the largest disk, everything above it must be out of the way on the spare peg.
- 1
Park the smaller disks
Recursively move the top
n - 1disks from A to B, using C as the spare. - 2
Move the largest disk
Move disk
nfrom A to C. It is now in its final position. - 3
Restack on top
Recursively move the
n - 1disks from B to C, using A as the spare.
hanoi(n, src, dst, via) running for real: watch each call park n - 1 disks on the spare peg, move disk n, then restack. The call stack never holds more than n + 1 frames.Permutations
To list every ordering of n items, choose each unused item for the first position, recursively arrange the rest, then undo the choice. This choose, explore, un-choose template is the heart of Backtracking. There are n! leaves and each takes O(n) to copy, so the total is O(n · n!).
| Function | Recurrence | Time | Stack depth |
|---|---|---|---|
| Factorial | T(n) = T(n − 1) + O(1) | O(n) | O(n) |
| Fast power | T(n) = T(n/2) + O(1) | O(log n) | O(log n) |
| Naive Fibonacci | T(n) = T(n − 1) + T(n − 2) + O(1) | O(φⁿ) | O(n) |
| Tower of Hanoi | T(n) = 2T(n − 1) + O(1) | O(2ⁿ) | O(n) |
| Permutations | T(n) = n · T(n − 1) + O(n) | O(n · n!) | O(n) |
| Merge Sort | T(n) = 2T(n/2) + O(n) | O(n log n) | O(log n) plus O(n) buffer |
Tail recursion
A call is a tail call when it is the very last thing the function does, so nothing is left to compute after it returns. A function whose recursive calls are all tail calls is tail-recursive. Because the current frame has no pending work, a compiler can reuse it instead of pushing a new one (tail-call optimization), turning the recursion into a loop with O(1) stack space.
Not tail-recursive
return n * fact(n - 1)- The multiplication happens after the call returns
- Each frame must stay alive: O(n) stack
Tail-recursive
return fact(n - 1, acc * n)- The pending work is carried in an accumulator
- Eligible for frame reuse: O(1) stack where supported
def fact_tail(n: int, acc: int = 1) -> int:
if n <= 1:
return acc
return fact_tail(n - 1, acc * n) # tail call: nothing left to do afterwardRecursion vs iteration
Recursion shines when
- The data is recursive: trees, nested structures, grammars
- The algorithm branches: divide and conquer, backtracking
- The code mirrors a mathematical definition
- Depth is small (for example log n for balanced splits)
Iteration shines when
- The process is a simple linear walk
- Depth could reach 10⁴ to 10⁶ (stack overflow risk)
- Every bit of speed matters (no call overhead)
- The language lacks tail-call optimization
The two are equally powerful: any recursive algorithm can be written iteratively with an explicit stack, and any loop can be written recursively. The choice is about clarity, depth limits and performance.
Converting recursion to an explicit stack
- 1
Identify the frame state
List what each call needs to remember: its arguments plus any partial results.
- 2
Seed the stack
Push the state for the initial call.
- 3
Loop until empty
Pop a state. If it is a base case, record its result. Otherwise push the states for its sub-calls.
- 4
Preserve order
A stack is last-in, first-out, so push sub-tasks in reverse of the order you want them processed.
- 5
Handle work after calls
If the original did work after its recursive calls (post-order), push a marker or a "phase" flag so you know when the children are done.
def fact_stack(n: int) -> int:
pending = []
while n > 1: # winding: remember the work left to do
pending.append(n)
n -= 1
result = 1 # base case
while pending: # unwinding: finish each pending multiplication
result *= pending.pop()
return resultThe Tower of Hanoi implementation below uses the same technique for a branching recursion: each stack entry is a pending "move k disks" task, and tasks are pushed in reverse so they execute in the original order. The explicit stack lives on the heap, which is typically far larger than the call stack.
Stack overflow
The call stack is a fixed-size region of memory. Recursion that goes too deep, or never stops because a base case is missing or unreachable, exhausts it. Python raises RecursionError, Java throws StackOverflowError, and C++ usually crashes with a segmentation fault.
Python
1,000
Default recursion limit (frames)
Linux main thread
8 MB
Typical default stack (ulimit -s)
Windows main thread
1 MB
Default reserved stack
JVM threads
~1 MB
Typical 64-bit default, set with -Xss
- Missing or unreachable base case.
fib(n)with onlyif n == 0recurses forever fromn = 1down through negative numbers. - No progress. Calling
f(n)fromf(n), or splitting[lo, hi]into[lo, hi]whenhi = lo + 1and the midpoint rounds the wrong way. - Legitimately deep input. A DFS on a path-shaped graph or a linked list with 10⁵ nodes needs 10⁵ frames.
Thinking recursively
- Trust the contract. Decide exactly what the function returns, then use that promise for the smaller input.
- Pick the right "smaller". For lists: drop the first element or split in half. For trees: the left and right subtrees. For numbers: n − 1 or n / 2.
- Keep base cases minimal but complete. Empty input, single element, zero, null node.
- Pass state down, return results up. Accumulators and paths go down as parameters; answers come back as return values.
- Look for repeated subproblems. If the recursion tree repeats the same arguments, memoize it.
Complexity
| Function | Recurrence | Time | Space (stack depth) |
|---|---|---|---|
| Factorial | T(n) = T(n − 1) + 1 | O(n) | O(n) |
| Fast power | T(n) = T(n/2) + 1 | O(log n) | O(log n) |
| Naive Fibonacci | T(n) = T(n − 1) + T(n − 2) + 1 | O(2ⁿ) | O(n) |
| Memoized Fibonacci | Each n computed once | O(n) | O(n) |
| Tower of Hanoi | T(n) = 2T(n − 1) + 1 | O(2ⁿ) | O(n) |
| Permutations | T(n) = n · T(n − 1) + O(n) | O(n · n!) | O(n) |
Naive Fibonacci is more precisely Θ(φⁿ), φ ≈ 1.618. Tail-recursive versions run in O(1) stack only where the language guarantees tail-call elimination.
Implementation
Three recursion shapes: a linear chain, a halving chain and a branching backtracking tree.
def factorial(n: int) -> int:
if n <= 1: # base case
return 1
return n * factorial(n - 1) # recursive case
def fast_pow(x: float, n: int) -> float:
"""x^n with O(log n) multiplications; supports negative n."""
if n < 0:
return 1 / fast_pow(x, -n)
if n == 0:
return 1.0
half = fast_pow(x, n // 2) # solve the half-size problem once
return half * half if n % 2 == 0 else half * half * x
def permutations(items: list[int]) -> list[list[int]]:
result: list[list[int]] = []
current: list[int] = []
used = [False] * len(items)
def build() -> None:
if len(current) == len(items): # base case: a full arrangement
result.append(current.copy())
return
for i, item in enumerate(items):
if used[i]:
continue
used[i] = True # choose
current.append(item)
build() # explore
current.pop() # un-choose
used[i] = False
build()
return result
print(factorial(10), fast_pow(2, 30), len(permutations([1, 2, 3, 4])))
# 3628800 1073741824.0 24Key takeaways
- Every recursive function needs a base case and a recursive case that makes progress toward it.
- Design with the leap of faith: assume the smaller call works and focus on combining its answer.
- Time is the size of the recursion tree times the work per node; space is the tree's height (stack depth).
- Repeated subproblems in the tree are a signal to memoize, which leads straight into dynamic programming.
- Tail recursion can run in O(1) stack only where the language guarantees it; Python and Java do not.
- Any recursion can be converted to iteration with an explicit stack, which avoids stack overflow on deep inputs.
Common pitfalls
- Missing or unreachable base cases (for example forgetting
n == 1in Fibonacci, or negative inputs) causing infinite recursion. - Making the same recursive call twice, as in
pow(x, n/2) * pow(x, n/2), which destroys the speedup. - Sharing a mutable list across calls without undoing changes in backtracking, or appending it without copying.
- Ignoring stack depth: recursing once per element on 10⁵ elements overflows Python's default limit of 1,000.
- Using a mutable default argument such as
moves=[]in Python, which is shared between calls of the function.
Interview tips
- Say the base case, the recursive case and the recurrence before writing code.
- Quote space as the recursion depth and mention the risk of stack overflow for large inputs.
- If the recursion tree has overlapping subproblems, mention memoization immediately; it often is the intended next step.
- Be ready to convert a recursive solution into an iterative one with an explicit stack.
Real-world applications
- Tree and graph algorithms: traversals, DFS, parsing nested JSON or HTML.
- Divide and conquer: merge sort, quick sort, binary search, FFT.
- Backtracking search: puzzles, constraint solvers, generating combinations.
- Compilers and interpreters: recursive-descent parsers and evaluators of expression trees.
Practice problems
Test yourself
What is the space complexity of the naive recursive fib(n)?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.