Sub topic 8
Comparing Time and Space Costs
This chapter assumes you can read Big-O notation, write recursive and iterative functions in Python, and picture the call stack as one frame per active call, as earlier chapters described. Here you will learn to estimate what a recursive solution costs and compare it with a loop that does the same job. The estimate has two parts: how much work it does (time) and how much memory it holds while it runs (space).
Two Questions for Every Recursive Function
You can analyze any recursive function by answering two separate questions:
- How many calls happen in total, and how much work does each call do outside its recursive calls? Total calls multiplied by work per call gives the time cost.
- How deep does the chain of active calls get? Each active call holds a stack frame, so the maximum depth multiplied by the frame size gives the stack space cost.
These questions have different answers more often than people expect. Time depends on the total number of calls over the whole run. Stack space depends only on how many calls are alive at the same moment. A loop has no frames to stack up, so its extra space comes only from the variables it keeps.
Linear recursion
For a function that makes one recursive call per invocation, such as recursive factorial, both answers are easy. There are n + 1 calls, each doing constant work, so time is O(n). All of those calls are alive at the deepest point, so stack space is also O(n). The iterative version also runs in O(n) time, but it needs only O(1) extra space for result and i.
Tree Recursion: Time and Space Diverge
When a function makes two or more recursive calls, the number of calls can grow exponentially, while the depth grows only linearly. Naive Fibonacci shows this clearly. You can count the calls directly:
calls = 0
def fib(n):
global calls
calls += 1
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
for n in (10, 20, 25):
calls = 0
fib(n)
print(n, calls)
# 10 177
# 20 21891
# 25 242785The call count equals 2·F(n+1) − 1, where F is the Fibonacci sequence. It grows by a factor of about 1.618 for each step in n, so the time is O(φⁿ). The deepest chain is fib(n) → fib(n−1) → … → fib(1), which is only n frames deep. Python discards each branch's frames before it starts the next branch, so the stack never holds the whole tree.
The tree has 9 nodes, so the run makes 9 calls and the time cost tracks the node count. Its longest root-to-leaf path is 4 nodes, so the stack space tracks the height. The repeated fib(2) subtrees are the waste that the chapter on memoization removes.
Writing the Cost as a Recurrence
For less obvious functions, write the cost as a recurrence relation, an equation that defines the cost for input n in terms of the cost for smaller inputs. Then solve it or match it against a known pattern.
| Function shape | Time recurrence | Time | Max depth (stack space) |
|---|---|---|---|
| One call on n − 1, constant work (factorial, sum) | T(n) = T(n−1) + O(1) | O(n) | O(n) |
| One call on n / 2, constant work (binary search) | T(n) = T(n/2) + O(1) | O(log n) | O(log n) |
| Two calls on n − 1 and n − 2 (naive Fibonacci) | T(n) = T(n−1) + T(n−2) + O(1) | O(φⁿ) | O(n) |
| Two calls on n / 2, linear work (merge sort) | T(n) = 2T(n/2) + O(n) | O(n log n) | O(log n) stack, plus O(n) for merge buffers |
| One call per child node (tree traversal) | Each node visited once | O(n) | O(h), where h is tree height |
Here is how each iterative counterpart compares:
| Algorithm | Recursive space | Iterative space |
|---|---|---|
| Factorial, sum to n | O(n) | O(1) |
| Binary search | O(log n) | O(1) |
| Tree traversal | O(h) call stack | O(h) explicit stack |
| Fibonacci (bottom-up) | O(n) | O(1) |
The tree traversal row shows a pattern you will meet again. When the problem has a branching shape, an iterative version usually needs its own stack, and that stack has the same asymptotic size as the call stack it replaces. Converting to a loop doesn't make the memory cost go away. It moves the memory from the call stack, which is small and has a fixed limit, to the heap, which is large and grows as needed.
Hidden Costs Inside Each Call
The "work per call" term is where recursive code most often turns out more expensive than it looks. A common case in Python is slicing a list to make the recursive call:
def sum_slice(xs):
if not xs:
return 0
return xs[0] + sum_slice(xs[1:])
def sum_index(xs, i=0):
if i == len(xs):
return 0
return xs[i] + sum_index(xs, i + 1)
data = list(range(500))
print(sum_slice(data)) # 124750
print(sum_index(data)) # 124750Both functions return the same result and both recurse n times. However, xs[1:] copies the remaining list, which costs O(n) per call, so sum_slice takes O(n²) time. Its memory cost is also worse than it looks. Each pending frame keeps a reference to its own slice, so at the deepest point the slices of length n, n−1, …, 1 are all alive at once, for O(n²) peak memory. sum_index passes an integer index instead, which brings it back to O(n) time and O(n) stack space.
Constant Factors: Calls Are Not Free
Big-O hides constant factors, and in CPython a function call costs far more than a loop iteration. Every call allocates a frame, binds arguments, and later tears the frame down. You can measure the difference directly:
import timeit
def sum_rec(n):
if n == 0:
return 0
return n + sum_rec(n - 1)
def sum_loop(n):
total = 0
for i in range(1, n + 1):
total += i
return total
n = 900
t_rec = timeit.timeit(lambda: sum_rec(n), number=2000)
t_loop = timeit.timeit(lambda: sum_loop(n), number=2000)
print(f"recursive: {t_rec:.3f}s")
print(f"loop: {t_loop:.3f}s")
print(f"ratio: {t_rec / t_loop:.1f}x")Both functions are O(n), but on typical CPython builds the recursive version runs several times slower. The exact ratio depends on your Python version and machine. Recent CPython releases have made calls cheaper, but they still cost more than a loop iteration. In compiled languages such as C, Rust, or OCaml, the gap is usually much smaller, and a compiler may turn simple recursion into a loop on its own.
Common Mistakes in Cost Analysis
- Reporting O(1) space for a recursive function. If the function has no lists or dictionaries, it still uses stack frames. Linear recursion uses O(n) space.
- Equating total calls with stack depth. Naive Fibonacci makes exponentially many calls but is only O(n) deep. Depth is the height of the call tree, not its size.
- Assuming the iterative version always uses less memory. For trees and graphs, an explicit stack or queue grows like the recursion depth would.
- Forgetting that depth is capped. An O(n)-space recursive function in Python fails with
RecursionErroronce n passes roughly 1000. That limit comes from the runtime, not from Big-O. Treat depth as a correctness concern as well as a cost. - Ignoring per-call work. Copying, slicing, and concatenation inside a call can turn an O(n) algorithm into O(n²).
A Checklist for Comparing the Two Forms
When you weigh a recursive solution against an iterative one, work through these questions in order:
- Count total calls and per-call work to get time. Check for hidden copies.
- Find the maximum depth to get stack space. Compare it with your language's depth limit for the largest input you expect.
- Ask whether the iterative version needs its own stack. If it does, its space matches the recursive version's, but the memory lives on the heap.
- For hot code paths in Python, expect function-call overhead to make recursion slower by a constant factor even when the Big-O matches.
Exercise
A recursive binary search on a sorted list of 1,000,000 items calls itself on half the range each time and passes low and high indexes rather than slices. What are its time and stack space costs, and will it hit CPython's default recursion limit?
Show answer
Time is O(log n) and stack space is O(log n). The depth is about log2(1,000,000), roughly 20 frames, which is far below the default limit of 1000, so it will not raise RecursionError. An iterative version has the same O(log n) time and uses O(1) extra space.
Exercise
This function reverses a string: def rev(s): return s if len(s) <= 1 else rev(s[1:]) + s[0]. Give its time complexity and its stack depth for a string of length n.
Show answer
Time is O(n²). Each call slices s[1:], which copies O(n) characters, and the concatenation + s[0] builds a new string of length up to n. There are n calls, so the total work is quadratic. Stack depth is O(n), so in CPython it fails with RecursionError for strings longer than about 1000 characters.
Exercise
A recursive preorder traversal visits a binary tree with n nodes. What is the stack space if the tree is perfectly balanced, and what is it if every node has only a left child?
Show answer
Stack space is O(h), where h is the tree height. A balanced tree has h of about log2(n), so it needs O(log n) space. A tree where every node has only a left child is effectively a linked list with h = n, so it needs O(n) space and can overflow the recursion limit for large n. The time is O(n) in both cases.