Sub topic 11
Space Complexity and the Call Stack
Time is not the only resource an algorithm uses. It also needs memory. This chapter shows how to measure memory with the same Big O tools you already use for time, and how recursion adds a hidden memory cost through the call stack.
It assumes you can read Big O expressions, analyze simple loops, and write a recursive function. You should also know the recurrence idea from the previous chapters.
What space complexity measures
Space complexity describes how the memory an algorithm uses grows with input size n. It uses the same notation as time complexity. O(1) means memory does not grow with n. O(n) means memory grows in proportion to n.
You will usually count auxiliary space. This is the extra memory the algorithm allocates beyond the input itself. Some sources count the input too, which they call total space. When you read a claim like "O(1) space", check which one it means. This chapter uses auxiliary space unless it says otherwise.
What counts as memory:
- Variables, lists, dictionaries, and sets that the algorithm creates.
- Copies of the input, including slices.
- Stack frames from function calls, which are easy to forget.
Counting memory in iterative code
For loops, look at what the code creates, not how many times it runs.
def total(items):
s = 0
for x in items:
s += x
return s # O(1) auxiliary space: one integer, however long items is
def doubled(items):
result = []
for x in items:
result.append(2 * x)
return result # O(n) auxiliary space: result grows with itemsBoth functions take O(n) time. The first uses O(1) space and the second uses O(n). Time and space are separate measurements, and one algorithm can be cheap in one and expensive in the other.
The call stack
Each time a function is called, the runtime pushes a stack frame onto the call stack. A frame holds the function's parameters, its local variables, and the place to resume when the call returns. When the call returns, its frame is popped and the memory is released.
A recursive function makes a new call before the previous one has finished. Frames pile up until a base case is reached, and then they unwind.
def total_rec(items, i=0):
if i == len(items):
return 0
return items[i] + total_rec(items, i + 1)For total_rec([1, 2, 3]), the calls nest like this:
At the deepest point, four frames exist at once. For a list of n items there are n + 1 frames. Each frame has constant size, so the auxiliary space is O(n). The time is also O(n), but the iterative total does the same job in O(1) space.
The rule for recursion
The space used by the call stack is the maximum depth of the recursion, multiplied by the space per frame. Two points matter here:
- Depth is not the total number of calls. Only the calls currently active, on one path from the root call to the current call, are on the stack.
- If each frame uses O(1) space, the stack space is O(depth).
This rule explains a result that surprises many learners. Take fib_naive from the topic's earlier examples. It makes O(2^n) calls, but its stack depth is only n. The call fib_naive(n - 1) finishes completely before fib_naive(n - 2) starts, so only one chain of calls is alive at a time. Its auxiliary space is O(n), not O(2^n).
fib_memo also uses O(n) space. It has a stack depth of n and a dictionary with about n entries, which is O(n) + O(n) = O(n).
Hidden copies: slicing in recursion
Frame size is only constant if the arguments are not copied. In Python, a slice creates a new list. A recursive function that slices its input holds many copies at once.
def total_slice(items):
if not items:
return 0
return items[0] + total_slice(items[1:])Each call receives a list one item shorter than the previous one, and every earlier list stays alive until the recursion unwinds. The memory held at the deepest point is about n + (n - 1) + ... + 1, which is n(n + 1)/2. That is O(n^2) space. Slicing also copies elements, so the time is O(n^2) as well. Passing an index, as total_rec does, avoids the copies.
Comparing recursion and iteration
Binary search can be written either way, and the two versions differ in space.
def binary_search_iter(sorted_items, target):
lo, hi = 0, len(sorted_items) - 1
while lo <= hi:
mid = (lo + hi) // 2
if sorted_items[mid] == target:
return mid
if sorted_items[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1 # O(log n) time, O(1) space
def binary_search_rec(sorted_items, target, lo=0, hi=None):
if hi is None:
hi = len(sorted_items) - 1
if lo > hi:
return -1
mid = (lo + hi) // 2
if sorted_items[mid] == target:
return mid
if sorted_items[mid] < target:
return binary_search_rec(sorted_items, target, mid + 1, hi)
return binary_search_rec(sorted_items, target, lo, mid - 1)
# O(log n) time, O(log n) space: depth is about log2(n) + 1The time is the same. The recursive version needs one frame per halving, so about log2(n) + 1 frames. For a million items that is roughly 21 frames, which is small. The cost matters far more when the depth is linear, as in total_rec.
Recursion limits in practice
Real runtimes cap the stack. Python raises RecursionError when the depth passes a limit, which is 1000 by default. Languages such as Java and C throw a stack overflow error or crash when the thread's stack memory runs out.
import sys
def total_rec(items, i=0):
if i == len(items):
return 0
return items[i] + total_rec(items, i + 1)
print(sys.getrecursionlimit()) # commonly 1000
try:
print(total_rec(list(range(5000))))
except RecursionError:
print("RecursionError: depth O(n) exceeded the limit")
print(sum(range(5000))) # 12497500, with O(1) auxiliary spaceThe recursive function works for a list of 100 items and fails for 5000. The algorithm is correct. Its O(n) stack space is what breaks it.
Some languages perform tail-call optimization, which reuses one frame when the recursive call is the last action. Python and Java do not, so a tail-recursive function still uses O(n) stack there. Do not count on this optimization unless you know the language guarantees it.
You have two ways to avoid deep stacks. You can rewrite the recursion as a loop, using your own list as an explicit stack if needed. Or you can change the algorithm so its depth is logarithmic, as divide-and-conquer methods often do.
Space in divide and conquer
For merge sort, the topic's merge_sort function has two kinds of space cost:
- Stack depth: each call halves the list, so the depth is about log2(n) and the stack uses O(log n).
- Data: each call builds
left,right, andmergedlists. Along one path, the sizes are about n, n/2, n/4, and so on. That sum is less than 2n, so the data uses O(n).
The total auxiliary space is O(n) + O(log n), which simplifies to O(n). Using the simplification rules from earlier, the larger term wins. Array-based merge sort with a single reusable buffer also has O(n) auxiliary space. Quicksort, done in place, needs only O(log n) stack when the smaller side is processed first.
Summary of costs
| Algorithm | Time | Auxiliary space | Where the space goes |
|---|---|---|---|
| Iterative `total` | O(n) | O(1) | One accumulator |
| `doubled` | O(n) | O(n) | Result list |
| `total_rec` (index) | O(n) | O(n) | n + 1 stack frames |
| `total_slice` | O(n^2) | O(n^2) | Slices alive on the stack |
| Iterative binary search | O(log n) | O(1) | Three integers |
| Recursive binary search | O(log n) | O(log n) | log n frames |
| `fib_naive` | O(2^n) | O(n) | Depth of one call chain |
| `fib_memo` | O(n) | O(n) | Depth n plus memo dictionary |
| `merge_sort` (list version) | O(n log n) | O(n) | Copies and merged lists |
Time and space trade-offs
Many algorithms trade one resource for the other. fib_memo spends O(n) memory to turn an exponential running time into a linear one. Lookup tables, caches, and hash sets follow the same pattern. Using less memory can mean redoing work, and using more memory can save work.
When you choose between them, ask which resource is scarcer. A server with plenty of RAM may favor speed. An embedded device or a very large dataset may favor low memory.
Common errors
- Counting the input as auxiliary space. Reading a list of n items does not make an O(1)-space algorithm into an O(n)-space one.
- Equating space with the number of calls. A recursion with 2^n calls can still have O(n) depth.
- Forgetting the stack. A function with no lists or dictionaries can still use O(n) space through recursion.
- Overlooking hidden copies from slicing,
list(...), string concatenation in loops, orsorted(...). - Assuming the language removes tail calls.
Exercise
A recursive function count_down(n) calls count_down(n - 1) until n is 0. It does O(1) work per call and creates no lists. What are its time and auxiliary space complexities, and what would you change to make the space O(1)?
Show answer
Time is O(n) because there are n + 1 calls with constant work each. Auxiliary space is O(n) because all n + 1 frames are on the stack at the deepest point. To get O(1) space, replace the recursion with a loop, such as while n > 0: n -= 1, so no frames accumulate.
Exercise
fib_naive(30) makes over a million calls. Why does it not need over a million stack frames at once, and what is its auxiliary space?
Show answer
Only the calls on the current path from the root to the active call are on the stack. Each call finishes before its sibling starts, so the maximum number of frames alive at once is the depth, which is about 30, or n in general. The auxiliary space is O(n).
Exercise
A recursive merge sort sorts each half by passing slices items[:mid] and items[mid:]. Name two kinds of space it uses and give the total auxiliary space.
Show answer
It uses stack space of O(log n) for the recursion depth, and O(n) for the slices and merged lists alive along a path of calls. The total is O(n) + O(log n) = O(n).