Recursion: a function that calls itself, and the stack that keeps track
How recursion really runs, what the call stack does, why every recursive function needs a base case, and how to estimate its time and space.
In short
A recursive function solves a problem by calling itself on a smaller version of it, until it reaches a base case it can answer directly. Each pending call waits on the call stack, so recursion costs memory too.
The idea: trust the smaller problem
5! = 5 × 4!. And 4! = 4 × 3!. If you trust that factorial(4) returns the right answer, factorial(5) is one multiplication. That trust, plus a case that stops the chain, is all recursion is.
- Base case: the smallest input, answered directly (
n ≤ 1 → 1). - Recursive case: shrink the problem and combine the result (
n × factorial(n − 1)). - Progress: every call must move towards the base case, or it never ends.
Watch the call stack
Each call adds a frame with its own n. The frames pile up until the base case returns, then they resolve one by one from the top. Step through it and watch the values come back down.
call stack
1def factorial(n):2 if n <= 1:3 return 14 rest = factorial(n - 1)5 return n * rest
Variables
Time and space of recursion
- Time = number of calls × work per call. Factorial makes n calls with O(1) work each: O(n).
- Space = the deepest the stack gets. Factorial goes n frames deep: O(n), even though it looks like no memory is used.
- Two recursive calls per step (like naive Fibonacci) can mean O(2ⁿ) calls: the same subproblems get solved again and again. That's where memoization and dynamic programming come in.
Where recursion shines
Recursion is natural when the data is recursive itself: trees (a tree is a node plus smaller trees), graphs (DFS), divide and conquer (merge sort, quicksort) and backtracking (try a choice, recurse, undo). You'll use it constantly in later units.
Key takeaways
- 01Recursion = base case + a smaller recursive case that makes progress.
- 02Every pending call waits on the call stack: depth is space.
- 03Time = number of calls × work per call; watch out for repeated subproblems.
- 04Trees, DFS, divide and conquer and backtracking are recursive by nature.
Check your understanding
1 of 3
What stops a recursive function from calling itself forever?
Related topics