Recursion and Recurrences
Write recursive functions with clear base cases, trace them on the call stack, and estimate their running time with simple recurrence relations.
Welcome back!
Step 1 of 11Learn
Functions that call themselves
Some problems contain smaller copies of themselves. The factorial of 5, written 5!, is 5 × 4 × 3 × 2 × 1. But it's also just 5 × 4!. And 4! is 4 × 3!, and so on, until 1! = 1.
A recursive function solves a problem by calling itself on a smaller version:
function factorial(n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive case
}Every correct recursive function has two parts:
- A base case that returns an answer directly, without recursing. Without it, the function calls itself forever.
- A recursive case that reduces the problem and calls the function on the smaller input, making progress toward the base case.
When factorial(4) runs, it can't finish until factorial(3) returns, which waits for factorial(2), which waits for factorial(1). Each pending call is stored on the call stack, along with its local variables. When the base case returns 1, the calls finish in reverse order: 2 × 1 = 2, then 3 × 2 = 6, then 4 × 6 = 24.
The call stack has a limited size. Recursion that goes too deep, such as tens of thousands of levels in many JavaScript engines, or infinitely deep because of a missing base case, causes a stack overflow error. The memory used by recursion is part of its space complexity: factorial(n) uses O(n) stack space.
Step 2 of 11Practice · Code challenge
Write a recursive function sumDigits(n) that returns the sum of the decimal digits of a non-negative integer n. For example, sumDigits(472) is 4 + 7 + 2 = 13. Don't convert the number to a string.
sumDigits(472)sumDigits(0)sumDigits(9)sumDigits(1001)sumDigits(99999)
Step 3 of 11Learn
When recursion explodes
Recursion can be elegant and efficient, or catastrophically slow. The classic example is the Fibonacci sequence, where each number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13. A direct recursive translation:
function fib(n) {
if (n < 2) return n;
return fib(n - 1) + fib(n - 2);
}It's correct, but each call makes two more calls, and those make two more. The calls form a tree, and the same values are computed again and again: fib(5) computes fib(3) twice and fib(2) three times. The total number of calls grows roughly like 1.6ⁿ, which is exponential. fib(40) makes over 300 million calls; fib(80) would take longer than a human lifetime.
Compare that with factorial, which makes one call per level: n calls in total, O(n) time.
The lesson: count how many recursive calls each call makes and how much smaller the problem gets. One call on n − 1 gives linear growth. Two calls on n − 1 gives exponential growth. Two calls on n/2 gives something much better, as you'll see with merge sort.
The Fibonacci problem has an easy fix: remember results you've already computed, a technique called memoization, or build the answer from the bottom up in a loop. Both are O(n). You'll return to this idea in the dynamic programming lesson.
Step 4 of 11Practice · Put in order
When factorial(3) is called, in what order do these calls return their values?
Drag the items, or use the arrow buttons, to put them in order.
- factorial(3) returns 6
- factorial(2) returns 2
- factorial(1) returns 1
Step 5 of 11Learn
Recurrence relations
To analyze a recursive algorithm, write a recurrence relation: an equation that expresses the running time T(n) in terms of the running time on smaller inputs.
- Factorial: one recursive call on n − 1 plus constant work: T(n) = T(n − 1) + O(1). Unrolling gives n steps: O(n).
- Binary search, recursive version: one call on half the input plus constant work: T(n) = T(n/2) + O(1). The input halves log₂ n times: O(log n).
- Merge sort: two calls on halves plus linear work to merge: T(n) = 2T(n/2) + O(n). There are log₂ n levels of splitting, and each level does O(n) total work: O(n log n).
- Naive Fibonacci: two calls on slightly smaller inputs: T(n) = T(n − 1) + T(n − 2) + O(1), which grows exponentially, roughly O(2ⁿ) as an upper bound.
- Sum of an array by halves: T(n) = 2T(n/2) + O(1) gives O(n), because the tree has about 2n nodes, each doing constant work.
A helpful picture is the recursion tree: draw each call as a node with its children below. Add up the work at each level, then add up the levels. For merge sort, every level of the tree touches all n elements once, and there are about log₂ n levels, which is where n log n comes from.
More advanced courses use the Master Theorem to solve recurrences of the form T(n) = aT(n/b) + f(n) directly.
Step 6 of 11Practice · Match the pairs
Match each recurrence to its solution.
Tap an answer, then tap the place where it belongs (or drag it there).
- T(n) = T(n − 1) + O(1)
- T(n) = T(n/2) + O(1)
- T(n) = 2T(n/2) + O(n)
- T(n) = 2T(n − 1) + O(1)
Step 7 of 11Learn
Recursion or loops?
Anything you can write recursively, you can write with a loop, and vice versa. Which should you use?
Recursion shines when the problem or data is naturally recursive:
- Trees: a tree is a root plus smaller trees, so traversing it recursively is almost a one-line definition.
- Divide and conquer: merge sort and quicksort split a problem into halves and solve each half the same way.
- Backtracking: generating permutations, solving puzzles like Sudoku, or exploring paths, where you try a choice, recurse, and undo it.
Loops are usually better for simple linear repetition, such as summing an array or counting down. They avoid function-call overhead and can't overflow the call stack. Some languages optimize tail calls, where the recursive call is the very last action, so they use no extra stack space, but most JavaScript engines don't do this, so deep recursion in JavaScript can still overflow.
To write a recursive function confidently, use the recursive leap of faith: assume the function already works for smaller inputs, and ask only how to use that result to solve the current input. For the sum of an array: if I knew the sum of everything after the first element, I'd just add the first element. Then handle the base case, such as an empty array summing to 0, and check that every call moves closer to it.
Step 8 of 11Compare
Recursion or a loop?
| Aspect | Recursion | Loop |
|---|---|---|
| Natural fit | Trees, divide and conquer, backtracking | Walking a list or range step by step |
| Memory | One stack frame per pending call | Usually constant extra memory |
| Risk | Stack overflow on very deep inputs | Messier code for branching problems |
| Repeated subproblems | Can explode (naive fib) unless cached | Bottom-up tables avoid repeats |
Step 9 of 11Note
Step 10 of 11Practice · Work it out
Using the naive fib(n) above, where fib(0) and fib(1) return immediately, how many total calls to fib are made when computing fib(5), including the first call?
Step 11 of 11Practice · Choose one
A student's recursive function countDown(n) prints n and then calls countDown(n - 1), but it crashes with a stack overflow for every input. What is the most likely cause?
Lesson complete!