AlgoViz

Space complexity compared

easy 16 min

Space 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

0:00 / 4:59

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.

Step 1 of 3

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 O(n)O(n) space for O(1)O(1) 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

Stotal(n)=Sinput(n)⏟given to you+Saux(n)⏟what you allocateS_{\text{total}}(n) = \underbrace{S_{\text{input}}(n)}_{\text{given to you}} + \underbrace{S_{\text{aux}}(n)}_{\text{what you allocate}}
Reversing an array in place has total space O(n)O(n) (the array) but auxiliary space O(1)O(1) (two indices). Say which one you mean.

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 O(1)O(1).

The lineup

The five classes at a glance

ClassShapeTypical structuresEveryday pictureDeep dive
O(1)O(1) constantFlat lineA few variables, two pointers, in-place swapA calculator's single memory slotOpen
O(log⁡n)O(\log n) logarithmicGentle riseCall stack of recursive binary search or balanced BST walksRounds of a knockout tournamentOpen
O(n)O(n) linearDiagonalHash map or set, array copy, memo table, BFS queueA guest list, one line per guestOpen
O(n2)O(n^2) quadraticSteep climbn×nn \times n matrix, 2D DP table, adjacency matrixA chessboard or a pixel gridOpen
O(2n)O(2^n) exponentialExplosionEvery subset stored, bitmask DP memoEvery combination of items in a cartOpen
Each class has its own lesson; this page puts them side by side.

One line to remember each

  • O(1): one size forever

    However big nn gets, you keep the same handful of values.

  • O(log n): levels of recursion

    Each call halves the problem, so the stack is about log⁡2n\log_2 n 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

bytes=entries(n)×8entries∈{ 1,  log⁡2n,  n,  n2,  2n }\text{bytes} = \text{entries}(n) \times 8 \qquad \text{entries} \in \{\,1,\; \log_2 n,\; n,\; n^2,\; 2^n\,\}
We count one 64-bit number (8 bytes) per entry and use decimal units: 1 KB = 1,000 bytes, 1 MB = 10610^6, 1 GB = 10910^9, 1 TB = 101210^{12}.

Memory at small n (8 bytes per entry)

nO(1)O(1)O(log⁡n)O(\log n)O(n)O(n)O(n2)O(n^2)O(2n)O(2^n)
108 B27 B80 B800 B8.2 KB
208 B35 B160 B3.2 KB8.4 MB
508 B45 B400 B20 KB9 PB
1008 B53 B800 B80 KB103110^{31} B
1,0008 B80 B8 KB8 MB1030210^{302} B
At n=50n = 50, 250×8≈9×10152^{50} \times 8 \approx 9 \times 10^{15} bytes, about 9 petabytes. At 100 it is more storage than exists on Earth.

Ranking the classes from cheapest to most expensive

Every arrow is a jump that dwarfs the class before it once nn is large.

Scale

Memory at real input sizes

ClassEntries at n=103n = 10^3MemoryEntries at n=106n = 10^6Memory
O(1)O(1)18 B18 B
O(log⁡n)O(\log n)about 1080 Babout 20160 B
O(n)O(n)10310^38 KB10610^68 MB
O(n2)O(n^2)10610^68 MB101210^{12}8 TB
O(2n)O(2^n)21000≈103012^{1000} \approx 10^{301}impossible21062^{10^6}impossible
At a million items O(n)O(n) fits on a phone and O(n2)O(n^2) needs a warehouse of disks.

Doubling n

S(2n)≈{S(n)O(1)S(n)+1O(log⁡n)2 S(n)O(n)4 S(n)O(n2)S(n)2O(2n)S(2n) \approx \begin{cases} S(n) & O(1) \\ S(n) + 1 & O(\log n) \\ 2\,S(n) & O(n) \\ 4\,S(n) & O(n^2) \\ S(n)^2 & O(2^n) \end{cases}
The quickest test of a space class: what happens to memory when the input doubles. For 2n2^n, 22n=(2n)22^{2n} = (2^n)^2.

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

Sstack(n)=max depth(n)×frame sizee.g. 104 frames×100 B=1 MBS_{\text{stack}}(n) = \text{max depth}(n) \times \text{frame size} \qquad \text{e.g. } 10^4 \text{ frames} \times 100\,\text{B} = 1\,\text{MB}
Frame size is a constant (tens to hundreds of bytes), so only the depth matters in Big O. Recursive binary search is log⁡2n\log_2 n deep; a recursive sum over a list is nn deep.

Frames alive while fib(4) recurses

Naive Fibonacci makes O(2n)O(2^n) calls but never has more than nn frames alive at once, so its space is O(n)O(n).

Time vs space

One problem, four memory budgets

The nn-th Fibonacci number shows the whole spectrum. Each rewrite keeps the answer and changes what is kept alive.

ApproachTimeAuxiliary spaceWork at n=30n = 30Values alive at n=30n = 30
Naive recursionO(2n)O(2^n)O(n)O(n) stack2,692,537 calls30 frames
Memoised recursionO(n)O(n)O(n)O(n) memo + O(n)O(n) stack59 calls29 entries and 30 frames
Bottom-up tableO(n)O(n)O(n)O(n) array29 additions31 slots
Two variablesO(n)O(n)O(1)O(1)30 updates2 values
Memoisation spends O(n)O(n) memory to turn exponential time into linear time. Noticing that only the last two values matter then drops the memory to O(1)O(1).

The optimisation path

First buy time with memory, then win the memory back by keeping only what the next step reads.
Python
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]
All four agree on the answer; only the time and memory differ.
Edit and run it in your browser

Trade-offs

Spending and saving memory

Use more space to save time

  • Hash map: O(n)O(n) space for O(1)O(1) average lookup.
  • Memoisation: O(n)O(n) space so nothing is computed twice.
  • Prefix sums: O(n)O(n) space for O(1)O(1) range-sum queries.

Use less space, sometimes at a time cost

  • In-place sort: O(1)O(1) extra instead of an O(n)O(n) copy.
  • Two pointers on sorted data: O(1)O(1) instead of an O(n)O(n) hash set.
  • Space-optimised DP: O(n)O(n) instead of an O(n2)O(n^2) table.

Should I spend memory here?

Memory is a budget. Spend it where it removes repeated work, and check the limit before you do.

Constraints

Reading the limits from n

Largest n that fits

entries(n)×8 B≤M⇒M=1 GB:  n≤1.25×108  (O(n)),    n≤11,180  (O(n2)),    n≤26  (O(2n))\text{entries}(n) \times 8\,\text{B} \le M \quad\Rightarrow\quad M = 1\,\text{GB}: \; n \le 1.25 \times 10^8 \;(O(n)),\;\; n \le 11{,}180 \;(O(n^2)),\;\; n \le 26 \;(O(2^n))
1 GB holds 1.25×1081.25 \times 10^8 eight-byte entries. Take the square root for n2n^2 and log⁡2\log_2 for 2n2^n.

Practical limits with 1 GB of memory

ClassLargest nWhy
O(1)O(1)no limitMemory never grows
O(log⁡n)O(\log n)no practical limitEven n=1018n = 10^{18} needs only about 60 frames
O(n)O(n)about 125 million109/810^9 / 8 entries
O(n2)O(n^2)about 11,0001.25×108≈11,180\sqrt{1.25 \times 10^8} \approx 11{,}180
O(2n)O(2^n)about 26226≈6.7×1072^{26} \approx 6.7 \times 10^7 fits; 2272^{27} does not
Even 8 GB only moves the 2n2^n limit to 29, since every extra item doubles the memory.

What the constraint on n suggests

ConstraintSpace that is fineTypical problems
n≤10n \le 10O(2n)O(2^n) or morePermutations, N-Queens, Sudoku
n≤20n \le 20 to 2525O(2n)O(2^n), borderlineSubset DP, bitmask DP
n≤1,000n \le 1{,}000O(n2)O(n^2)2D DP, edit distance, LCS
n≤10,000n \le 10{,}000O(n2)O(n^2), borderlineAdjacency matrix, all-pairs tables
n≤105n \le 10^5 to 10610^6O(n)O(n)Hash map, one array, a queue
n≥108n \ge 10^8O(log⁡n)O(\log n) or O(1)O(1)In place, two pointers, streaming

Optimising

Moves that shrink memory

  • 2D DP to two rows

    If row ii only reads row i−1i-1, keep two rows: O(mn)→O(n)O(mn) \to O(n).

  • Matrix to adjacency list

    A sparse graph needs O(V+E)O(V + E) with lists instead of O(V2)O(V^2).

  • Recursion to a loop

    Removes the O(depth)O(\text{depth}) call stack and the recursion limit.

  • Copy to in place

    Swap inside the input with two pointers: O(n)→O(1)O(n) \to O(1) 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

dp[i][j]=f(dp[i−1][j−1],  dp[i−1][j],  dp[i][j−1])  ⇒  keep rows i−1 and i onlydp[i][j] = f\big(dp[i-1][j-1],\; dp[i-1][j],\; dp[i][j-1]\big) \;\Rightarrow\; \text{keep rows } i-1 \text{ and } i \text{ only}
For m=n=10,000m = n = 10{,}000 a full table is 10810^8 cells (800 MB); two rows are 2×10,0012 \times 10{,}001 cells (160 KB).

Method

Finding the space of any function

A checklist for auxiliary space

Take the largest of the data structures and the stack depth: that is the auxiliary space.
  1. 1

    List what is allocated

    Every list, dict, set, string and copy, with its size in terms of nn.

  2. 2

    Find the deepest recursion

    The longest chain of calls alive at once, not the total number of calls.

  3. 3

    Keep the biggest term

    O(n)+O(log⁡n)=O(n)O(n) + O(\log n) = O(n). Drop constants and smaller terms.

  4. 4

    State the convention

    Say whether the input and output are included.

Recap

Key takeaways

Key points

  • Space complexity counts extra memory as nn grows; running out crashes a program instead of slowing it.
  • Auxiliary space excludes the input; total space includes it. Interviews usually mean auxiliary.
  • At n=106n = 10^6: O(1)O(1) is 8 B, O(log⁡n)O(\log n) about 160 B, O(n)O(n) 8 MB, O(n2)O(n^2) 8 TB, O(2n)O(2^n) impossible.
  • Recursion costs max depth ×\times frame size, even with no arrays; Python stops near 1,000 frames.
  • Fibonacci: naive O(2n)O(2^n) time and O(n)O(n) stack, memo O(n)O(n) and O(n)O(n), two variables O(n)O(n) and O(1)O(1).
  • Shrink memory with rolling rows, adjacency lists, loops instead of recursion, in-place swaps and index arguments.

Sources