Skip to content

Space complexity: counting memory, not just time

BasicsConcept

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.

peak.py
import tracemalloc
def total_list(n):
return sum([i * i for i in range(n)])
def total_gen(n):
return sum(i * i for i in range(n))
for f in (total_list, total_gen):
tracemalloc.start()
f(1_000_000)
_, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
print(f"{f.__name__}: peak {peak:,} bytes")
Shell
$ python3 peak.py
total_list: peak 40,447,584 bytes
total_gen: peak 408 bytes

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.

What each version holds in memory at its busiest moment, for 8 numbers
total_list · a list of all 8 squares
00
11
42
93
164
255
366
497
total_gen · the running sum and one square
sum = 91next = 49

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.

Common things that take memory, and how they grow
What the code makesExampleExtra space
A few variablestotal = 0; i = 0O(1)
A list, set or dict of up to n itemsseen = set()O(n)
A copy of the inputxs[1:], sorted(xs), list(xs)O(n)
A grid of n by n[[0] * n for _ in range(n)]O(n²)
Recursion n calls deepf(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.

total.py
def total(xs, i=0):
if i == len(xs):
return 0
return xs[i] + total(xs, i + 1)
print(total([4, 7, 1])) # 12
total([4, 7, 1]): one push or pop per step
Step 1 of 9
Most at once 0
Call stack · top is running
Empty
xs · the input list
40
71
12
  • running
  • waiting for an answer
  • read by the top frame

Nothing has run. The list xs holds 3 numbers, and the stack is empty.

0 frames now

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.

Recursion · O(n) space
def total(xs, i=0):
if i == len(xs):
return 0
return xs[i] + total(xs, i + 1)
Loop · O(1) space
def total(xs):
s = 0
for x in xs:
s += x
return 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.

fib.py
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
Calls made by fib(20)21,891Time grows exponentially: every call in the whole call tree runs once.
Frames alive at once20 at mostSpace is 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.

Whole table · O(n)
def ways(n): # n >= 1
dp = [0] * (n + 1)
dp[0] = dp[1] = 1
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
Last two only · O(1)
def ways(n):
prev, cur = 1, 1
for _ in range(2, n + 1):
prev, cur = cur, prev + cur
return 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.

Recursive · O(n) stack
def reverse(head):
if head is None or head.next is None:
return head
new_head = reverse(head.next)
head.next.next = head
head.next = None
return new_head
Loop · O(1) extra
def reverse(head):
prev = None
while head:
nxt = head.next
head.next = prev
prev, head = head, nxt
return 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.

07 Check yourself

Question

A function loops over xs with two variables, best and i, and creates nothing else. What is its extra space?

Question

fib(30) makes about 2.7 million calls. What is the largest number of its frames on the stack at once?

Question

Which version of "reverse a linked list" uses O(1) extra space?

08 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?