Sub topic 19
Recurrences, time complexity, and stack depth
This chapter assumes you can trace a recursive function (base case, recursive case, return order) and that you know what a stack frame is. You should also know big-O notation. Here we turn a recursive function into a recurrence relation, solve it for running time, and separately work out how deep the call stack grows.
From code to recurrence
A recurrence relation is an equation that gives the cost T(n) of an input of size n in terms of the cost on smaller inputs. To write one, read the function in three steps:
- Choose the size measure n (a number's value, an array length, a list length).
- Count the recursive calls and the size of each argument.
- Add the non-recursive work done in one call, such as a loop or a comparison.
The base case gives the starting value, usually T(1) = c or T(0) = c.
| Function | Recurrence | Solution |
|---|---|---|
| factorial(n) | T(n) = T(n-1) + 1 | Θ(n) |
| binary search | T(n) = T(n/2) + 1 | Θ(log n) |
| fib(n) | T(n) = T(n-1) + T(n-2) + 1 | Θ(φⁿ), at most O(2ⁿ) |
| Tower of Hanoi | T(n) = 2T(n-1) + 1 | Θ(2ⁿ) |
| merge sort | T(n) = 2T(n/2) + n | Θ(n log n) |
| gcd(a, b) | T drops quickly: b becomes a mod b | O(log min(a, b)) |
Counting calls and depth in C
The program below counts the total number of calls and the largest number of active frames. Each function increments depth on entry and decrements it before returning. It reads the result into a variable first so the print order is well defined.
#include <stdio.h>
int calls = 0, depth = 0, max_depth = 0;
void enter(void) {
calls++;
depth++;
if (depth > max_depth) {
max_depth = depth;
}
}
long fact(int n) {
enter();
long r = (n <= 1) ? 1 : n * fact(n - 1);
depth--;
return r;
}
int fib(int n) {
enter();
int r = (n < 2) ? n : fib(n - 1) + fib(n - 2);
depth--;
return r;
}
int main(void) {
long f = fact(5);
printf("fact(5)=%ld calls=%d depth=%d\n", f, calls, max_depth);
calls = 0; depth = 0; max_depth = 0;
int g = fib(5);
printf("fib(5)=%d calls=%d depth=%d\n", g, calls, max_depth);
return 0;
}The output is:
fact(5)=120 calls=5 depth=5
fib(5)=5 calls=15 depth=5Both functions reach depth 5, but fib makes three times as many calls. Running time follows the number of calls. Stack space follows only the longest chain of active calls.
Solving recurrences
Unrolling (substitution)
Expand the recurrence until a pattern appears. For T(n) = T(n-1) + n:
T(n) = n + (n-1) + (n-2) + … + 1 = n(n+1)/2, so T(n) = Θ(n²).
For T(n) = 2T(n-1) + 1, unrolling gives 1 + 2 + 4 + … + 2ⁿ⁻¹ = 2ⁿ - 1. This matches the Hanoi move count.
Recursion tree
Draw one node per call and label each node with its own non-recursive work. Then sum the work level by level. The tree for fib(4) shows why the cost explodes: the same subproblem appears many times.
For merge sort, each level does about n work in total and there are log n levels, which gives n log n.
Master theorem
This applies to T(n) = aT(n/b) + Θ(nᵏ), where a ≥ 1, b > 1, and k ≥ 0.
| Condition | Result |
|---|---|
| a > bᵏ | Θ(n^(log_b a)) |
| a = bᵏ | Θ(nᵏ log n) |
| a < bᵏ | Θ(nᵏ) |
Examples:
- T(n) = 2T(n/2) + 1 has a = 2 and bᵏ = 1, so a > bᵏ and T(n) = Θ(n).
- T(n) = T(n/2) + 1 has a = 1 and bᵏ = 1, so they are equal and T(n) = Θ(log n).
- T(n) = 3T(n/2) + n has a = 3 and bᵏ = 2, so T(n) = Θ(n^(log₂3)), about n¹·⁵⁸.
- T(n) = 2T(n/2) + n² has a = 2 and bᵏ = 4, so T(n) = Θ(n²).
Stack depth and space
Depth is the length of the longest chain of calls that are active at the same time. It is the height of the recursion tree, not the number of nodes. Each active call holds one stack frame with its parameters, locals, and return address. So the extra space is roughly depth × frame size.
| Function | Time | Max depth | Stack space |
|---|---|---|---|
| fact(n) | Θ(n) | n | Θ(n) |
| binary search (recursive) | Θ(log n) | log n | Θ(log n) |
| fib(n) | Θ(φⁿ) | n | Θ(n) |
| hanoi(n) | Θ(2ⁿ) | n | Θ(n) |
| merge sort | Θ(n log n) | log n | Θ(log n) for the stack, plus Θ(n) for the merge buffer |
Exponential time does not mean exponential stack. fib and hanoi visit exponentially many nodes, but only one root-to-leaf path is on the stack at any moment.
Tail recursion
A call is a tail call when nothing remains to do after it returns. gcd(b, a % b) is one. An optimizing compiler may reuse the current frame, which reduces the stack to O(1). The C standard does not guarantee this. fact as written is not a tail call, because the multiplication happens after the call returns. For GATE, state the space as O(depth) unless the question says the compiler optimizes tail calls.
Very deep recursion, such as depth 10⁶, can overflow the stack on a typical system with an 8 MB default limit. The result is a crash, which is undefined behavior from the C point of view.
Common errors
- Counting nodes when the question asks for depth, or the reverse.
- Forgetting the non-recursive work. A function with a loop of length n inside each call has a different recurrence from one with constant work.
- Using the Master theorem on subtraction recurrences such as T(n-1).
- Writing the recurrence for n/2 when the code is
n/2on an int. This is still fine asymptotically, but check that the argument really shrinks. - Treating
fibas O(n) because the depth is n. The time is exponential.
Exercise
A function g(n) returns 1 when n <= 1. Otherwise it runs a loop of n iterations (constant work each), then calls g(n/2) twice. Write the recurrence, solve it, and give the maximum stack depth.
Show answer
T(n) = 2T(n/2) + n, with T(1) = c. Here a = 2, b = 2, k = 1, so a = bᵏ and T(n) = Θ(n log n). Each call halves n, so the depth is Θ(log n). Only one of the two calls is active at a time, so the stack uses Θ(log n) space.
Exercise
For f(n) = f(n-1) + f(n-1) + 1 with f(0) = 1 calls counted by T(n), what is T(n) and what is the maximum depth? Why is the depth not as large as T(n)?
Show answer
T(n) = 2T(n-1) + 1 with T(0) = 1 gives T(n) = 2ⁿ⁺¹ - 1 = Θ(2ⁿ). The maximum depth is n + 1 frames, which is Θ(n). The second call starts only after the first returns, so at any moment the stack holds one root-to-leaf path, not the whole tree.