Space complexity compared
easy 16 minSpace complexity measures how much extra memory an algorithm needs as the input grows.
See it run
Step through the five space curves, then watch the same problems solved with less and less memory: Fibonacci four ways, a copy against an in-place swap, and a DP table rolled down to two rows.
Operations
The five space curves
Add the five classes to the chart one at a time, from the flat O(1) line to the O(2ⁿ) explosion, and read off the memory each needs at n = 10 and n = 20.
Step 1 of 8
Five ways memory can grow
- O(1)1
- O(\log n)3.3
- O(n)10
- O(n^2)100
- O(2^n)1024off the chart
entries kept in memory, 8 bytes each
Each curve is the number of 8-byte entries an algorithm keeps alive at input size n. Unlike a slow program, one that runs out of memory crashes at once, so these curves decide whether your code runs at all.
Step 1: Five ways memory can grow
import mathBYTES = 8 # one 64-bit number per entrydef entries(n): return { "O(1)": 1, "O(log n)": math.log2(n), "O(n)": n, "O(n^2)": n * n, "O(2^n)": 2 ** n, }for n in (10, 20, 1000): sizes = {k: round(v * BYTES) for k, v in entries(n).items() if v < 10**15} print(n, sizes)- Time
- memory only
- Space
- O(1) to O(2ⁿ)
- n = 20, O(n)
- 160 B
- n = 20, O(2ⁿ)
- about 8.4 MB
Test a space class by doubling n: the memory stays the same, grows by one entry, doubles, quadruples or squares.
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Calling a recursive function O(1) space
criticalEvery unfinished call keeps a stack frame. A recursion that is n deep uses O(n) memory even with no arrays, and in Python it fails with RecursionError near 1,000 frames.
Wrongdef total(arr, k=0): # "O(1) space"? if k == len(arr): return 0 return arr[k] + total(arr, k + 1) # n frames deepRightdef total(arr): # truly O(1) extra s = 0 for x in arr: s += x return sCounting calls instead of depth
majorNaive Fibonacci makes O(2ⁿ) calls, but its space is O(n): only one root-to-leaf chain is alive at a time. Space follows the deepest chain, not the size of the call tree.
Wrong# fib_naive makes ~2^n calls# so its space must be O(2^n) <- wrongRight# at most n frames are alive at once# time O(2^n), space O(n)Slicing inside recursion
majorarr[1:]copies n - 1 items. Doing it at every level allocates O(n²) memory over the run, with all slices alive along the chain. Pass indices instead.Wrongdef total(arr): if not arr: return 0 return arr[0] + total(arr[1:]) # a new copy per levelRightdef total(arr, k=0): if k == len(arr): return 0 return arr[k] + total(arr, k + 1) # no copiesKeeping a full DP table you never read
majorIf row i only reads row i - 1, the rest of the table is dead memory. For two 10,000-character strings the full table is 800 MB; two rows are 160 KB.
Wrongdp = [[0] * (n + 1) for _ in range(m + 1)] # O(m * n)Rightprev = [0] * (n + 1) # O(n)for i in range(1, m + 1): curr = [0] * (n + 1) ... # fill from prev prev = currAn adjacency matrix for a sparse graph
majorA matrix is O(V²) however few edges exist. A million nodes is 10^12 cells. An adjacency list is O(V + E).
Wrongadj = [[0] * n for _ in range(n)] # O(V^2)for u, v in edges: adj[u][v] = adj[v][u] = 1Rightadj = [[] for _ in range(n)] # O(V + E)for u, v in edges: adj[u].append(v) adj[v].append(u)Memoising deep recursion in Python
minorlru_cache fixes the time but not the depth: fib_memo(5000) still recurses 5,000 frames and raises RecursionError. Fill the table bottom-up, then roll it.
Wrong@lru_cache(maxsize=None)def fib(n): return n if n < 2 else fib(n - 1) + fib(n - 2)fib(5000) # RecursionErrorRightdef fib(n): prev, curr = 0, 1 for _ in range(n): prev, curr = curr, prev + curr return prev # O(1) space, no recursion
Interview tips
How to explain it
- Space complexity is how the extra memory grows with n; running out crashes a program instead of slowing it.
- Auxiliary space excludes the input; say whether you count the output too.
- At n = 10⁶: O(1) 8 B, O(log n) about 160 B, O(n) 8 MB, O(n²) 8 TB, O(2ⁿ) impossible.
- Always give time and space together, and mention the trade-off you chose.
Spot it in code
- A few scalars or two pointers: O(1).
- Recursion that halves the input: O(log n) stack. Recursion that shrinks by one: O(n) stack.
- A set, dict, copy or memo keyed by item: O(n). A grid indexed by two items: O(n²).
- A memo keyed by a bitmask or a list of all subsets: O(2ⁿ).
Memory tricks
- ONE variable, ONE size forever. LOG = Levels Of recursive Going.
- N = Need memory for N items. N squared = Need an N by N grid.
- 2 to the N = TWO choices per item stored.
- Double n: same, plus one, double, four times, squared.
Watch out
- The call stack counts, and Python stops near 1,000 frames.
- Slices like arr[1:] are copies.
- Roll DP rows and prefer adjacency lists before you hit Memory Limit Exceeded.