Recursion & Recurrences
Functions that call themselves, and the equations that count their cost.
Naive recursive Fibonacci makes 331,160,281 calls to compute , while recursive merge sort sorts a million items with only 20 levels of calls. Both are recursion. The difference is in an equation that counts the calls, and this lesson teaches you to write that equation from code and to solve it.
What you’ll learn
- Write recursive functions with a base case, a recursive case and guaranteed progress, and prove them correct by induction.
- Predict the depth of the call stack, and turn recursion that is too deep into a loop with an explicit stack.
- Prove that the Tower of Hanoi needs exactly moves, and turn recursive code into a recurrence.
- Solve recurrences by unrolling, recursion trees and substitution, and apply the master theorem to .
- Recognize problems with self-similar structure, and the two traps: overlapping subproblems and deep stacks.
Anatomy of a recursive function
A recursive function solves a problem by solving smaller instances of the same problem. Every correct one has three parts:
- a base case, small enough to answer directly;
- a recursive case, which calls the function on smaller inputs and combines their answers;
- progress: every chain of calls reaches a base case after finitely many steps.
The correctness proof is induction on the input size. The base case is right by inspection, and if every call on a smaller input returns the right answer, the recursive case combines them into the right answer for .
def factorial(n): # n >= 0
if n == 0: # base case
return 1
return n * factorial(n - 1) # recursive case: n - 1 is closer to 0
def power(x, n): # x**n for an integer n >= 0
if n == 0:
return 1
half = power(x, n // 2) # ONE call on n // 2, used twice
return half * half if n % 2 == 0 else half * half * xFor , power makes calls instead of multiplications: halving the exponent is its progress. Writing power(x, n // 2) * power(x, n // 2) would still be correct, but the two calls per level would bring back calls in total.
Think first A function sums the even numbers up to as f(n) = n + f(n - 2), with the base case f(0) = 0. What happens when it is called with ?
The chain jumps over the base case and never reaches it, so the calls continue until the stack overflows. Progress means reaching a base case, not just getting smaller. A base case that every chain hits, such as if n <= 0: return 0, fixes it.
The call stack and its limits
Each call gets a stack frame on the call stack: its arguments, its local variables and the place to return to. The frame lives until the call returns. A recursive function's extra memory is therefore its maximum depth times the frame size, which is not its number of calls: factorial(n) is frames deep, power(x, n) about , and a function that makes a million calls can still be shallow.
The fix that always works is to keep the stack yourself. Flood fill, recoloring the region of equal cells around a starting cell, is the classic case: the recursive version is a few lines, but its depth can reach the number of cells, so a grid of one color already exceeds Python's default limit.
def fill_recursive(grid, r, c, old, new): # needs old != new, or it never stops
if not (0 <= r < len(grid) and 0 <= c < len(grid[0])) or grid[r][c] != old:
return
grid[r][c] = new
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
fill_recursive(grid, r + dr, c + dc, old, new)
def fill_iterative(grid, r, c, new):
old = grid[r][c]
if old == new:
return
stack = [(r, c)] # the explicit stack replaces the call stack
while stack:
r, c = stack.pop()
if 0 <= r < len(grid) and 0 <= c < len(grid[0]) and grid[r][c] == old:
grid[r][c] = new
stack.extend([(r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)])The explicit stack holds what the frames would have held: the cells still to visit. A Python list lives on the heap, which has room for millions of entries, so fill_iterative recolors a grid without trouble. Popping from the end visits cells depth-first; a queue would visit them breadth-first and recolor the same region.
Divide and conquer, and the Tower of Hanoi
Recursive algorithms split their input in a few typical shapes, and the shape decides the cost. power makes one call on half the input. Summing an array by halves makes two calls on halves, and so does merge sort, which then combines the sorted halves with a linear-time merge: this is divide and conquer. The Tower of Hanoi makes two calls on inputs only one smaller, and that turns out to be expensive.
The puzzle: disks of different sizes sit on peg A, the largest at the bottom. Move them all to peg C, one disk at a time, never putting a disk on a smaller one; peg B is a spare. The recursive solution is one sentence: move the top disks out of the way onto B, move the largest disk to C, then move the disks from B onto it.
def hanoi(n, src, dst, via, moves):
if n == 0:
return
hanoi(n - 1, src, via, dst, moves) # park n - 1 disks on the spare peg
moves.append((src, dst)) # move the largest disk
hanoi(n - 1, via, dst, src, moves) # bring the n - 1 disks on top of ithanoi(3, 'A', 'C', 'B', moves) produces A→C, A→B, C→B, A→C, B→A, B→C, A→C: seven moves.
The algorithm's count. Let be the number of moves
hanoimakes. Two recursive calls and one move of the largest disk give a recurrence, with :Solve it. Add 1 to both sides: . So doubles at every step, starting from :
No algorithm does better. Let be the true minimum. The largest disk moves at least once. Just before its first move, the other disks must all sit on the third peg, since they can be neither on top of it nor on its destination, and getting them there takes at least moves. After its last move, all disks must be brought onto it: at least more.
So the recursive algorithm is optimal. For the legendary 64 disks, at one move per second:
Think first How many moves does an optimal solution with 10 disks need, and with 11?
, and : each extra disk doubles the work and adds one move. Two calls on inputs only one smaller always cost exponential time, which is why the shape of a recursion matters more than the length of its code.
From code to recurrence, and solving it
To analyze recursive code, charge each call only for its own work and write the cost of the recursive calls as the unknown function itself. The result is a recurrence:
| Code | Recurrence | Solution |
|---|---|---|
power(x, n) | ||
| sum of an array by halves | ||
| merge sort | ||
| find the maximum, recurse on the rest | ||
hanoi(n) | ||
naive fib(n) |
Three methods solve almost every recurrence you will meet.
Unrolling: expand until a pattern appears. , so .
Recursion trees: draw the calls as a tree, write each node's own work, and sum level by level. For , level holds calls on inputs of size , which costs in total, and there are levels. With and a power of two, exactly.
Substitution: guess the answer, then prove it by induction. The substitution method is the only one of the three that is a proof by itself, and it has one classic trap.
Guess for all powers of two . Inductive step, for : assume the bound for and substitute it.
Base case: , and holds for . So works for every power of two :
The classic mistake is to "prove" by assuming and concluding . The induction must return the bound with the same constant, , and that fails:
Naive Fibonacci is the warning example. It computes inside the call for and then again directly: the subproblems overlap. With base cases and , its number of calls satisfies and .
Using and , how many calls does the naive recursion make to compute ?
Show the answer
177
runs . Adding 1 to both sides shows that obeys the Fibonacci recurrence, so : here . The calls grow like , where is the golden ratio: .
Think first Summing an array by halves, , has only about levels of calls. Why does it still take time?
Time is the number of calls times the work per call, not the depth. The tree has leaves and internal calls, in all, each doing constant work. The depth, , bounds the memory on the stack, not the time.
The master theorem
Divide-and-conquer recurrences have the form : subproblems of size , plus work to split and combine. When , the recursion tree settles everything. Level has calls of size , so it costs
a geometric series with ratio over about levels. The bottom level has leaves. The ratio is below 1, equal to 1 or above 1 exactly when is above, equal to or below .
| Recurrence | Where it comes from | and | Solution |
|---|---|---|---|
| binary search | ; | case 2: | |
| sum by halves, tree traversal | ; | case 1: | |
| merge sort | ; | case 2: | |
| Karatsuba multiplication | ; | case 1: | |
| Strassen matrix multiplication | ; | case 1: | |
| quadratic combine step | ; | case 3: |
The theorem does not cover these, and each has its own tool:
- shrinks by subtraction, not division. Unroll it: .
- falls in a gap: is below , but not by a polynomial factor. The recursion tree's level costs are , a harmonic sum, giving .
- splits unequally. Every full level costs , and there are between and levels: .
- shrinks by a square root. Set and : then , so .
What is the solution of ?
Show the answer
B.
: case 2. Every level costs , and there are about levels, so .
Recognizing it
Reach for recursion when the problem is self-similar: the answer for the whole is built from answers for parts of the same kind. The signals in a statement:
- the input is recursive by nature: a tree, a nested list, an expression with brackets, a directory hierarchy;
- a big instance splits into halves that are solved the same way (sorting, counting pairs across two halves, closest points);
- "list or count all subsets, permutations or arrangements" with or so: recursion that makes one choice per level, which is backtracking;
- a quantity can be halved: an exponent, a search range.
| Problem (in brief) | Recursive idea | Cost |
|---|---|---|
| Height of a binary tree | , empty tree | time; depth = height, up to |
| with up to | square the result for ; multiply by if is odd | multiplications |
| Count the inversions of an array | merge sort that also counts the pairs that cross the two halves | |
| All subsets of items with a property | include or exclude item , then recurse on | leaves |
Evaluate a nested expression like (2+(3*4)) | an expression is a number or a bracketed pair of expressions |
Common bugs
- A base case that some inputs skip, like
n - 2jumping over 0 for odd , or a missing case for the empty input. - No progress: a range that does not shrink. With
mid = (lo + hi) // 2on the inclusive range with , recursing on calls itself on the same range forever. - Forgetting to
returnthe recursive result: in Python the function then returnsNone. - Backtracking that changes shared state (a list, a "used" array) and does not undo the change after the call.
- A memo dictionary declared as a default argument,
def f(n, memo={}), which survives between test cases. - Exponential blowup from overlapping subproblems, and stack overflow from linear depth.
You must list every subset of items whose weights sum exactly to a target. Which approach fits?
- A recursion that includes or excludes each item in turn, one item per level
- The master theorem with ,
- Binary search on the target
- A single loop that adds the items in sorted order
Show the answer
A. A recursion that includes or excludes each item in turn, one item per level
The answer may be any of the subsets, and a recursion that branches on "take item or not" visits each exactly once, at depth at most 15. This is backtracking, and it can also prune a branch as soon as its sum exceeds the target (with positive weights).
Key takeaways
- A recursive function needs a base case, a recursive case on smaller inputs, and progress toward the base case; its correctness proof is induction on the input size.
- Memory is the maximum depth of the call stack, not the number of calls. Python stops at 1000 frames by default, and an explicit stack turns any recursion into a loop.
- The Tower of Hanoi needs exactly moves: the recurrence counts the algorithm, and an argument about the largest disk shows nothing does better.
- Solve recurrences by unrolling, recursion trees, or substitution, where the induction must return the same constant. Overlapping subproblems make naive recursion exponential: Fibonacci makes calls.
- Master theorem: is , or as is below, equal to or above . It does not cover subtraction, unequal splits or the gaps between cases.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
What does the master theorem give for ?
Show the answer
B.
Here , , , and . Level of the recursion tree costs , a geometric series that grows toward the leaves, so the leaves dominate: .
Why can no strategy solve the Tower of Hanoi with fewer than moves?
- Because the recursive algorithm makes moves, and recursive algorithms are optimal
- Because there are ways to arrange the disks
- Because before the largest disk's first move, and after its last, all other disks must be moved as a whole tower
- Because the master theorem gives
Show the answer
C. Because before the largest disk's first move, and after its last, all other disks must be moved as a whole tower
Before its first move, the largest disk's source and destination must be free of smaller disks, so the other disks all sit on the third peg; after its last move they must all come onto it. That gives , hence , which the recursive algorithm achieves.
A recursive depth-first search over a tree with nodes crashes in Python with RecursionError when the tree is a long path. What is the most robust fix?
- Rewrite the search with an explicit stack in a loop
- Add memoization to the recursive function
- Call
sys.setrecursionlimit(10**9)and keep the recursion - Recurse on the children in the opposite order
Show the answer
A. Rewrite the search with an explicit stack in a loop
The depth of the recursion equals the depth of the tree, on a path. An explicit stack keeps the same information on the heap, with no depth limit and no risk of overflowing the call stack.
Which recurrence can the master theorem, in the form , solve directly?
Show the answer
D.
, , and : case 1 gives . The others fall outside the theorem: subtraction instead of division ( by unrolling), a non-polynomial gap (), and unequal parts ().
A student "proves" is : assume ; then . What is wrong?
- Nothing: the bound is correct
- The induction must prove with the same constant, but it only gives
- The base case was not checked
- Substitution only works for recurrences with one recursive call
Show the answer
B. The induction must prove with the same constant, but it only gives
Each level of the induction would raise the constant by 1, and over levels that is the hidden factor. The true solution is , and substitution proves correctly.
Go deeper
- The Master Theorem & Akra–Bazzi · Solving divide-and-conquer recurrences, with proofs.
- Linear Recurrences & Matrix Powers · Characteristic roots, Fibonacci in closed form, and the n-th term in O(log n) steps.
- Fast Exponentiation & Modular Arithmetic · Repeated squaring, modular inverses, Fermat’s little theorem and the Chinese remainder theorem.
Further reading
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapters 2 and 4.
- J. Erickson, Algorithms (2019), chapter 1, "Recursion", free online at jeffe.cs.illinois.edu.
- R. L. Graham, D. E. Knuth & O. Patashnik, Concrete Mathematics, 2nd ed. (Addison-Wesley, 1994), chapter 1, "Recurrent Problems".