Recursion
Solve a problem by solving a smaller copy of it, until you hit a base case.
- current
- not reached yet
- result
- removed / popped
Call factorial(4)
4 isn’t a base case, so it needs factorial(3) first and waits.
VARIABLES
- n
- 4
- call stack
- factorial(4)
- returned
- -
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
A recursive function calls itself on a smaller input. Each call waits on the call stack until the smaller one returns.
Why it matters
Trees, nested structures and divide-and-conquer problems are naturally defined in terms of smaller versions of themselves.
Think of it like this
Russian nesting dolls: open each one to find a smaller one, until the last doll can’t be opened.
Use it when
- The structure is recursive - trees, nested lists, expressions
- Divide and conquer: split, solve the halves, combine
- Exploring choices, as in backtracking
Avoid it when
- Very deep inputs in Python - the default recursion limit is about 1000 frames
- Overlapping subproblems without memoization - the work can grow exponentially
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| Linear recursion, depth n | O(n) | O(n) stack |
| Naive binary recursion (fib) | O(2ⁿ) | O(n) stack |
| Divide and conquer (merge sort) | O(n log n) | O(n) |
Often confused with: iteration with an explicit stack - the same logic, without the recursion limit.
How to recognize it
Clues in interview prompts that point straight to this pattern.
- If the answer for n uses the answer for n − 1, recursion fits
- A linked list of 10⁵ nodes is too deep for plain recursion in Python
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- A missing or unreachable base case - infinite recursion
- Not shrinking the input on each call
- Recomputing the same subproblem many times instead of memoizing
Edge cases to test
- n = 0 or n = 1 - the base cases themselves
- Negative input - decide how to reject it
- Large n - hits the recursion limit
Knowledge check
Quick check to lock in the intuition.
Naive recursive fib(n) calls fib(n − 1) and fib(n − 2). Why is it slow?
Practice
Apply what you just watched on real interview problems.