Sub topic 8
Comparing Time and Space Costs
This chapter assumes you can read Big-O notation, write a recursive function with a base case, and describe how each call pushes a frame onto the call stack. The aim here is to count two costs for each approach: how much work it does (time) and how much memory it holds at once (space).
Same Work, Different Memory
A linear recursion and the equivalent loop usually do the same number of steps. The difference is memory. A loop keeps a fixed set of variables. A recursive function keeps one stack frame for every call that has started but not yet returned.
import timeit
def sum_rec(n):
if n == 0:
return 0
return n + sum_rec(n - 1)
def sum_iter(n):
total = 0
for i in range(1, n + 1):
total += i
return total
print(sum_rec(500), sum_iter(500)) # 125250 125250
print("recursive:", timeit.timeit(lambda: sum_rec(500), number=1000))
print("iterative:", timeit.timeit(lambda: sum_iter(500), number=1000))Both functions run in O(n) time. On CPython the recursive version is usually a few times slower, because each function call has to create a frame, bind arguments, and return. Big-O ignores that constant factor, but it shows up in real measurements. The larger difference is space. sum_rec(500) holds 500 frames at its deepest point, which is O(n) space. sum_iter uses O(1) extra space.
Multiple Recursion: Time Explodes, Space Does Not
A function that makes more than one recursive call can do far more work than its depth suggests. The version below counts the calls and tracks the deepest point reached.
calls = 0
max_depth = 0
def fib(n, depth=1):
global calls, max_depth
calls += 1
max_depth = max(max_depth, depth)
if n < 2:
return n
return fib(n - 1, depth + 1) + fib(n - 2, depth + 1)
print(fib(20)) # 6765
print(calls) # 21891
print(max_depth) # 20The function makes 21,891 calls, but the stack never gets deeper than 20 frames. Time grows exponentially, roughly O(φⁿ) with φ ≈ 1.618, and is often written loosely as O(2ⁿ). Space grows only linearly, O(n), because the left branch finishes and frees its frames before the right branch starts.
Summary of Costs
| Pattern | Time | Extra space | Main risk |
|---|---|---|---|
| Loop with fixed variables | O(n) | O(1) | None from the stack |
| Linear recursion (one call per level) | O(n) | O(n) stack | Depth limit for large n |
| Multiple recursion, no reuse | Exponential | O(depth) stack | Running time |
| Recursion over a balanced tree | O(nodes) | O(log nodes) stack | Usually safe |
Common Errors When Estimating Cost
- Counting total calls as space. Memory depends on depth. A function can make millions of calls and still use a shallow stack.
- Assuming recursion is always slower in Big-O. For linear recursion the time class is often the same. The cost is the per-call overhead and the stack space.
- Ignoring hidden copying. Slicing such as
lst[1:]in each call copies the list, so a "linear" recursion becomes O(n²) time and O(n²) total allocation. - Forgetting that unbalanced trees are deep. A tree that has degenerated into a chain has depth n, not log n.
Exercise
A recursive function processes a list by calling itself on lst[1:] until the list is empty, doing O(1) work per call otherwise. What are its time complexity and its peak stack depth for a list of length n?
Show answer
The stack depth is n frames, so stack space is O(n). Each slice copies the remaining elements, so the copies add up to n + (n-1) + ... + 1, which makes the time O(n²). Passing an index instead of slicing brings the time down to O(n).
Exercise
Naive recursive Fibonacci makes 21,891 calls for n = 20. Why does its maximum stack depth stay at 20?
Show answer
Only one chain of calls is active at a time. The fib(n-1) branch returns and frees its frames before fib(n-2) starts, so the deepest active chain is the path fib(20), fib(19), ..., fib(1). That path has 20 frames.