Space complexity: counting memory, not just time
Two functions can give the same answer in the same O(n) time while one needs 40 MB and the other a few hundred bytes. Space complexity is how you see that difference before you run anything: count the extra arrays, maps and call frames that grow with the input.
01 Same answer, same time, different memory
Both functions below add up the squares of 0 to n − 1, and both loop n times. The only difference is a pair of square brackets.
That is a real run on CPython 3.14, 64-bit; other versions print slightly different numbers. The brackets make a list of a million squares, about 8 MB of pointers plus about 32 MB for the integer objects, and only then does sum start. Without them, sum pulls one square at a time from a generator, so only one is alive at once.
The list version builds all n squares before sum reads the first one. The generator makes one square, adds it, and drops it. Shown at the moment the last square is made.
02 Count what grows with the input
Space complexity counts the memory a function needs on top of its input, as n grows. You count it like time: find what is created, ask how big it gets in terms of n, and keep the biggest term.
| What the code makes | Example | Extra space |
|---|---|---|
| A few variables | total = 0; i = 0 | O(1) |
| A list, set or dict of up to n items | seen = set() | O(n) |
| A copy of the input | xs[1:], sorted(xs), list(xs) | O(n) |
| A grid of n by n | [[0] * n for _ in range(n)] | O(n²) |
| Recursion n calls deep | f(n) calls f(n - 1) | O(n), in stack frames |
Most people do not count the input, and say whether they count the output. A function that must return a list of n items needs that list whatever you do, so "O(1) extra space" usually means: besides the input and the answer.
03 The call stack counts too
This recursive sum creates no list and no dictionary. It looks like O(1) space. It is not: every call that is still waiting for an answer keeps a frame on the call stack, with its own i and its place in the addition.
- running
- waiting for an answer
- read by the top frame
Nothing has run. The list xs holds 3 numbers, and the stack is empty.
For a list of n items the stack reaches n + 1 frames, so this is O(n) space. A loop with one running total does the same job in O(1), and it has no depth limit: in CPython, total on a list of 5,000 items raises RecursionError under the default limit of 1000.
def total(xs, i=0):if i == len(xs):return 0return xs[i] + total(xs, i + 1)
def total(xs):s = 0for x in xs:s += xreturn s
04 Space is the peak, not the total
Memory that is freed can be used again. So space complexity is about the most memory alive at any one moment, not the sum of everything ever allocated. That is why time and space can be very different for the same code.
O(n): the stack only ever holds one path from fib(20) down to a base case.A finished branch pops its frames before the next branch pushes any, so the same stack memory is reused thousands of times. Count the deepest path, not the number of calls.
05 Same answer, less memory
The usual way to save space is to notice what the code never reads again. Counting the ways to climb n stairs, one or two at a time, only ever looks at the last two answers. The rest of the table can go.
def ways(n): # n >= 1dp = [0] * (n + 1)dp[0] = dp[1] = 1for i in range(2, n + 1):dp[i] = dp[i - 1] + dp[i - 2]return dp[n]
def ways(n):prev, cur = 1, 1for _ in range(2, n + 1):prev, cur = cur, prev + curreturn cur
The second way is to swap recursion for a loop when the recursion goes n deep. Reversing a linked list recursively keeps one frame per node; the loop keeps three pointers.
def reverse(head):if head is None or head.next is None:return headnew_head = reverse(head.next)head.next.next = headhead.next = Nonereturn new_head
def reverse(head):prev = Nonewhile head:nxt = head.nexthead.next = prevprev, head = head, nxtreturn prev
06 Memory you did not see
def total(xs):
if not xs:
return 0
return xs[0] + total(xs[1:])A slice in every callEach call copies the rest of the list, and every waiting frame keeps its copy alive. That is n + (n − 1) + … + 1 items at the deepest point: O(n²) space, on top of the n frames.sum([x * x for x in xs])A list made only to be read onceThe brackets build all n values first. Drop them and the generator gives O(1) extra space for the same result.ys = sorted(xs)Copies with friendly namessorted, list(xs), xs[:] and xs + ys all make a new list of O(n). xs.sort() sorts in place, although CPython’s sort still uses temporary space of up to about half the list while merging.@cache
def f(n): ...A cache that keeps everythingA memo stores one entry per distinct argument for as long as the program runs. That is often the right trade, but it is O(n) space or more, and it never shrinks by itself.Recursion depth is space you can run out of long before memory is full. CPython stops at a recursion limit, 1000 by default, and other languages overflow a fixed-size thread stack. If your recursion goes n deep and n can be large, write the loop.