Space complexity compared
easy 16 minSpace complexity measures how much extra memory an algorithm needs as the input grows.
Video lesson · Chapter 1 of 5
Find the peak on the workbench
Space complexity compared
1:25Reel
Read caption
Rue compares five concrete storage models at eight and sixteen inputs. Freeze memory at its busiest moment.
How it works
Step through the idea, or press Play.
Count what you store. Variables, arrays, hash maps, memo tables and every stack frame a recursive call keeps alive
Understand it
Start here
Why compare space complexities
Time complexity tells you how long code runs. Space complexity tells you how much memory it needs while it runs. A slow program still finishes; a program that runs out of memory crashes with "Memory Limit Exceeded" or an out-of-memory error. Knowing which space class you are in tells you, before you run anything, whether the input will fit.
Judge limits
Online judges usually allow 256 MB to 512 MB per program.
Real machines
A phone app may get a few hundred MB of 1 to 4 GB; a server has 8 to 64 GB or more.
Trade-offs
Extra memory often buys speed: a hash map spends space for lookups.
Definitions
Auxiliary space and total space
There are two ways to count. Total space includes the input itself. Auxiliary space is only the extra memory the algorithm allocates on top of the input: new arrays, hash maps, memo tables and the call stack. When an interviewer asks for the space complexity, they almost always mean auxiliary space.
Total = input + auxiliary
Counts as auxiliary space
- New lists, sets, dicts and strings you build.
- Memo tables and DP tables.
- Every stack frame alive during recursion.
- Slices and copies such as
arr[1:].
Usually not counted
- The input you were given.
- The output you must return, by most conventions (say so if you exclude it).
- A fixed number of scalar variables: that is .
The lineup
The five classes at a glance
| Class | Shape | Typical structures | Everyday picture | Deep dive |
|---|---|---|---|---|
| constant | Flat line | A few variables, two pointers, in-place swap | A calculator's single memory slot | Open |
| logarithmic | Gentle rise | Call stack of recursive binary search or balanced BST walks | Rounds of a knockout tournament | Open |
| linear | Diagonal | Hash map or set, array copy, memo table, BFS queue | A guest list, one line per guest | Open |
| quadratic | Steep climb | matrix, 2D DP table, adjacency matrix | A chessboard or a pixel grid | Open |
| exponential | Explosion | Every subset stored, bitmask DP memo | Every combination of items in a cart | Open |
One line to remember each
O(1): one size forever
However big gets, you keep the same handful of values.
O(log n): levels of recursion
Each call halves the problem, so the stack is about frames deep.
O(n): one slot per item
Double the input, double the memory.
O(n²): an n by n grid
Double the input, four times the memory.
O(2ⁿ): two choices per item
One more item doubles the memory.
The picture
How the five curves grow
Memory from entries
Memory at small n (8 bytes per entry)
| n | |||||
|---|---|---|---|---|---|
| 10 | 8 B | 27 B | 80 B | 800 B | 8.2 KB |
| 20 | 8 B | 35 B | 160 B | 3.2 KB | 8.4 MB |
| 50 | 8 B | 45 B | 400 B | 20 KB | 9 PB |
| 100 | 8 B | 53 B | 800 B | 80 KB | B |
| 1,000 | 8 B | 80 B | 8 KB | 8 MB | B |
Ranking the classes from cheapest to most expensive
Scale
Memory at real input sizes
| Class | Entries at | Memory | Entries at | Memory |
|---|---|---|---|---|
| 1 | 8 B | 1 | 8 B | |
| about 10 | 80 B | about 20 | 160 B | |
| 8 KB | 8 MB | |||
| 8 MB | 8 TB | |||
| impossible | impossible |
Doubling n
Hidden cost
The call stack counts
Every call that has not returned yet keeps a stack frame: its parameters, local variables and return address. A recursive function with no arrays at all still uses memory proportional to its maximum recursion depth, not the total number of calls.
Stack space of recursion
Frames alive while fib(4) recurses
Time vs space
One problem, four memory budgets
The -th Fibonacci number shows the whole spectrum. Each rewrite keeps the answer and changes what is kept alive.
| Approach | Time | Auxiliary space | Work at | Values alive at |
|---|---|---|---|---|
| Naive recursion | stack | 2,692,537 calls | 30 frames | |
| Memoised recursion | memo + stack | 59 calls | 29 entries and 30 frames | |
| Bottom-up table | array | 29 additions | 31 slots | |
| Two variables | 30 updates | 2 values |
The optimisation path
from functools import lru_cachedef fib_naive(n): # O(2^n) time, O(n) stack return n if n < 2 else fib_naive(n - 1) + fib_naive(n - 2)@lru_cache(maxsize=None)def fib_memo(n): # O(n) time, O(n) memo + stack return n if n < 2 else fib_memo(n - 1) + fib_memo(n - 2)def fib_table(n): # O(n) time, O(n) array if n < 2: return n dp = [0] * (n + 1) dp[1] = 1 for i in range(2, n + 1): dp[i] = dp[i - 1] + dp[i - 2] return dp[n]def fib_two_vars(n): # O(n) time, O(1) space prev, curr = 0, 1 for _ in range(n): prev, curr = curr, prev + curr return prevprint([f(25) for f in (fib_naive, fib_memo, fib_table, fib_two_vars)])# [75025, 75025, 75025, 75025]Trade-offs
Spending and saving memory
Use more space to save time
- Hash map: space for average lookup.
- Memoisation: space so nothing is computed twice.
- Prefix sums: space for range-sum queries.
Use less space, sometimes at a time cost
- In-place sort: extra instead of an copy.
- Two pointers on sorted data: instead of an hash set.
- Space-optimised DP: instead of an table.
Should I spend memory here?
Constraints
Reading the limits from n
Largest n that fits
Practical limits with 1 GB of memory
| Class | Largest n | Why |
|---|---|---|
| no limit | Memory never grows | |
| no practical limit | Even needs only about 60 frames | |
| about 125 million | entries | |
| about 11,000 | ||
| about 26 | fits; does not |
What the constraint on n suggests
| Constraint | Space that is fine | Typical problems |
|---|---|---|
| or more | Permutations, N-Queens, Sudoku | |
| to | , borderline | Subset DP, bitmask DP |
| 2D DP, edit distance, LCS | ||
| , borderline | Adjacency matrix, all-pairs tables | |
| to | Hash map, one array, a queue | |
| or | In place, two pointers, streaming |
Optimising
Moves that shrink memory
2D DP to two rows
If row only reads row , keep two rows: .
Matrix to adjacency list
A sparse graph needs with lists instead of .
Recursion to a loop
Removes the call stack and the recursion limit.
Copy to in place
Swap inside the input with two pointers: extra.
Pass indices, not slices
arr[1:]copies; recursing on(arr, lo, hi)does not.Generators
Yield one item at a time instead of building a full list.
Why two rows are enough
Method
Finding the space of any function
A checklist for auxiliary space
- 1
List what is allocated
Every list, dict, set, string and copy, with its size in terms of .
- 2
Find the deepest recursion
The longest chain of calls alive at once, not the total number of calls.
- 3
Keep the biggest term
. Drop constants and smaller terms.
- 4
State the convention
Say whether the input and output are included.
Recap
Key takeaways
Key points
- Space complexity counts extra memory as grows; running out crashes a program instead of slowing it.
- Auxiliary space excludes the input; total space includes it. Interviews usually mean auxiliary.
- At : is 8 B, about 160 B, 8 MB, 8 TB, impossible.
- Recursion costs max depth frame size, even with no arrays; Python stops near 1,000 frames.
- Fibonacci: naive time and stack, memo and , two variables and .
- Shrink memory with rolling rows, adjacency lists, loops instead of recursion, in-place swaps and index arguments.