Sub topic 11
Space complexity and the call stack
This chapter assumes you can read Big O expressions, simplify them, and analyze loops and simple recursion. It applies the same tools to memory instead of time.
What space complexity measures
Space complexity describes how the memory an algorithm needs grows with input size n. It is written in Big O notation, like time complexity.
Usually you count auxiliary space: the extra memory beyond the input itself. An algorithm that reverses a list in place uses O(1) auxiliary space. One that builds a reversed copy uses O(n).
Memory comes from two places:
- Data structures you create, such as lists, dictionaries, and copies of slices.
- The call stack, which holds one frame (local variables plus a return address) for every function call that has started but not yet returned.
Loops usually cost O(1) space
A loop reuses the same variables on each pass. The total function from the earlier chapter keeps only s and x, so its auxiliary space is O(1) even though its time is O(n).
Recursion costs stack space
Each recursive call adds a frame. The space used by the stack is the maximum depth of recursion times the size of one frame. It is not the total number of calls.
def sum_recursive(items, i=0):
if i == len(items):
return 0
return items[i] + sum_recursive(items, i + 1)
def sum_iterative(items):
s = 0
for x in items:
s += x
return s
print(sum_recursive([1, 2, 3, 4])) # 10
print(sum_iterative([1, 2, 3, 4])) # 10Both versions take O(n) time. sum_recursive reaches depth n + 1 before any call returns, so it uses O(n) stack space. sum_iterative uses O(1).
Time and space can differ sharply
The naive Fibonacci function from the spine makes O(2^n) calls. Its depth, though, is only n, because the first recursive call finishes before the second starts. At any moment the stack holds one path from the root to a leaf. So fib_naive uses O(n) space with exponential time.
fib_memo stores one result per value from 2 to n, which is O(n) for the dictionary. The recursion also reaches depth n, so the stack adds another O(n). Added together, space is still O(n), but time drops to O(n).
Space in divide and conquer
For merge_sort, the recursion halves the list each time, so the depth is O(log n). Each call also builds slices and a merged list. The calls that are active at once hold lists whose sizes sum to about n + n/2 + n/4 + ..., which is O(n). Total auxiliary space is O(n).
Binary search in its loop form uses O(1) space. A recursive version that passes lo and hi indexes instead of slicing uses O(log n) stack space. A version that slices the list would add O(n) for copying.
| Algorithm | Time | Auxiliary space |
|---|---|---|
| `sum_iterative` | O(n) | O(1) |
| `sum_recursive` | O(n) | O(n) |
| `fib_naive` | O(2^n) | O(n) |
| `fib_memo` | O(n) | O(n) |
| `merge_sort` | O(n log n) | O(n) |
| `binary_search` (loop) | O(log n) | O(1) |
Common mistakes
- Counting total calls as stack size. Only the deepest chain of active calls counts.
- Ignoring hidden copies. Slicing,
list(...), and string concatenation in a loop allocate new memory. - Forgetting that the stack counts. A recursive algorithm with no data structures can still use O(n) space.
Exercise
A recursive binary search takes the sorted list, lo, and hi as arguments and calls itself on one half by changing lo or hi. It does not slice the list. What are its time complexity and auxiliary space complexity?
Show answer
Time is O(log n), because each call halves the range. Auxiliary space is O(log n), because the recursion reaches depth about log2(n) and each frame has constant size. The loop version of binary search does the same work in O(1) space.