Sub topic 17
Recurrences, Time Complexity, and Stack Depth
Assume you know C functions, conditionals, loops, and basic recursion. You should also be comfortable with logarithms and Big-O notation. A recurrence describes the running time of a recursive function in terms of the running time for smaller inputs.
Writing a recurrence
For a recursive function, ask:
- How many recursive calls does one call make?
- How much work happens outside those calls?
- What is the smallest input, and how much time does it take?
For example, binary search makes one recursive call on half the input and does constant work to compare the middle element:
\[ T(n) = T(n/2) + c \]
Each call halves the input. After \(k\) calls, the remaining input is \(n/2^k\). The recursion stops when this is 1, so \(k = \log_2 n\). Therefore:
\[ T(n) = O(\log n) \]
The recursive stack also contains one frame for each call, so the stack depth is \(O(\log n)\).
Common recurrence patterns
| Pattern | Recurrence | Time complexity | Typical example |
|---|---|---|---|
| One smaller call | \(T(n)=T(n-1)+O(1)\) | \(O(n)\) | Countdown recursion |
| One halved call | \(T(n)=T(n/2)+O(1)\) | \(O(\log n)\) | Binary search |
| Two halved calls | \(T(n)=2T(n/2)+O(n)\) | \(O(n\log n)\) | Merge sort |
| Two calls of size \(n-1\) | \(T(n)=2T(n-1)+O(1)\) | \(O(2^n)\) | Naive Fibonacci |
Consider this Fibonacci function:
int fib(int n) {
if (n < 2) {
return n;
}
return fib(n - 1) + fib(n - 2);
}For each non-base call, there are two more calls:
\[ T(n) = T(n-1) + T(n-2) + O(1) \]
This grows exponentially, approximately \(O(2^n)\). The maximum stack depth follows only one branch at a time, so it is \(O(n)\), not \(O(2^n)\). Running time counts all calls. Stack depth counts the longest active chain.
Tail and tree recursion
A tail-recursive function performs its recursive call as its final operation:
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}Its stack depth depends on the number of remainder steps. For Euclid's algorithm, this is \(O(\log(\min(a,b)))\). C does not require compilers to eliminate tail calls, so do not automatically treat tail recursion as using constant stack space.
In tree recursion, calls branch before earlier calls return. The total number of calls can be exponential, while the stack depth can remain linear.
Exercise
What are the time complexity and stack depth of T(n) = T(n - 1) + O(1)?
Show answer
The time complexity is O(n), and the maximum stack depth is O(n).