AlgoViz

O(n²) quadratic space

easy 14 min

O(n²) space means memory grows with n × n: a 2D table or matrix with one cell for every pair.

Video lesson · Chapter 1 of 6

Remember the answer for every prefix pair

0:00 / 5:18

O(n²) quadratic space

1:27Reel

Read caption

A ferry dispatcher builds a directed adjacency matrix and counts its empty cells. Every ordered pair gets a place.

How it works

Step through the idea, or press Play.

Step 1 of 3

One cell per pair. A 2D table stores an answer for every pair (i, j): every prefix pair, every pair of nodes

Understand it

Start here

What O(n²) space means

An algorithm uses O(n²) space when the memory it holds at once grows with n×nn \times n. In practice that means a 2D array: a table with a cell for every pair of positions, or a matrix with a cell for every pair of nodes. A 1,000×1,0001{,}000 \times 1{,}000 table is already a million cells.

  • A cell for every pair

    Every pair of prefixes, of nodes or of points gets its own slot, filled or not.

  • Doubling quadruples

    Going from nn to 2n2n multiplies memory by 4, because (2n)2=4n2(2n)^2 = 4n^2.

  • Often shrinkable

    Many 2D DP tables only read the previous row, so two rows are enough.

Counting the cells

S(n)=n⋅n=O(n2)S(n,m)=(n+1)(m+1)=O(nm)S(n) = n \cdot n = O(n^2) \qquad S(n, m) = (n+1)(m+1) = O(nm)
A square n×nn \times n matrix is O(n2)O(n^2). A DP table over two inputs of lengths nn and mm is O(nm)O(nm), which we call quadratic when n≈mn \approx m. The +1+1 is the row and column for the empty prefix and does not change the class.

The picture

Doubling n quadruples memory

nGridCells n2n^2vs n = 3
33×33 \times 391×
55×55 \times 525about 2.8×
66×66 \times 6364×: n doubled
88×88 \times 864about 7×
99×99 \times 9819×: n tripled
Double the side and the area grows 4 times; triple it and it grows 9 times.

Scaling rule

S(kn)=(kn)2=k2⋅n2S(kn) = (kn)^2 = k^2 \cdot n^2
Multiply the input by kk and quadratic memory grows by k2k^2. Linear memory would only grow by kk.

Scale

Practical memory limits

nn2n^2 cellsMemory at 8 bytesFeasible?
1,0001,000,0008 MBEasy
10,000100,000,000800 MBTight
50,0002,500,000,00020 GBToo much
100,00010,000,000,00080 GBImpossible on one machine
Each 64-bit integer takes 8 bytes. Rule of thumb: an n×nn \times n table is fine up to about n=104n = 10^4.

From cells to bytes

bytes=8⋅n2n=104⇒8⋅108=800 MB\text{bytes} = 8 \cdot n^2 \qquad n = 10^4 \Rightarrow 8 \cdot 10^8 = 800\text{ MB}
Multiply the cell count by the size of one cell. Booleans or bytes shrink the constant, but not the n2n^2.

Example 1

Longest common subsequence

The LCS of two strings is the longest sequence of letters that appears in both, in order but not necessarily side by side. For ABCD and ACBF it has length 2 (AB or AC). The DP table gives cell dp[i][j] to the first ii letters of one string and the first jj of the other: (4+1)(4+1)=25(4+1)(4+1) = 25 cells.

The LCS recurrence

dp[i][j]={0i=0 or j=0dp[i−1][j−1]+1ai=bjmax⁡(dp[i−1][j],  dp[i][j−1])ai≠bjdp[i][j] = \begin{cases} 0 & i = 0 \text{ or } j = 0 \\ dp[i-1][j-1] + 1 & a_i = b_j \\ \max\big(dp[i-1][j],\; dp[i][j-1]\big) & a_i \ne b_j \end{cases}
A match extends the diagonal; a mismatch keeps the better of dropping one letter from either string. The answer is dp[m][n]dp[m][n].

Filling one LCS cell

Each cell is O(1)O(1) work, but all (m+1)(n+1)(m+1)(n+1) cells stay in memory until the end.
Python
def lcs_table(a, b):    m, n = len(a), len(b)    dp = [[0] * (n + 1) for _ in range(m + 1)]   # 25 cells for 4 x 4    for i in range(1, m + 1):        for j in range(1, n + 1):            if a[i - 1] == b[j - 1]:                dp[i][j] = dp[i - 1][j - 1] + 1            else:                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])    return dpdp = lcs_table("ABCD", "ACBF")for row in dp:    print(row)print("LCS length:", dp[-1][-1])                     # 2print("cells:", sum(len(r) for r in dp))             # 25
The full table for ABCD and ACBF, printed row by row.
Edit and run it in your browser

Example 2

Edit distance

The edit distance recurrence

dp[i][j]={max⁡(i,j)i=0 or j=0dp[i−1][j−1]ai=bj1+min⁡(dp[i−1][j−1]⏟replace,  dp[i−1][j]⏟delete,  dp[i][j−1]⏟insert)ai≠bjdp[i][j] = \begin{cases} \max(i, j) & i = 0 \text{ or } j = 0 \\ dp[i-1][j-1] & a_i = b_j \\ 1 + \min\big(\underbrace{dp[i-1][j-1]}_{\text{replace}},\; \underbrace{dp[i-1][j]}_{\text{delete}},\; \underbrace{dp[i][j-1]}_{\text{insert}}\big) & a_i \ne b_j \end{cases}
The borders count pure inserts or pure deletes. Inside, a match is free and a mismatch costs one edit plus the cheapest neighbour.

CAT into CUT: the finished table

∅CUT
∅0123
C1012
A2112
T3221
The bold diagonal is the cheapest path: match C, replace A with U, match T. One edit, using 4×4=164 \times 4 = 16 cells.

Choosing the move for one cell

Three neighbours, three operations. Walking back from the corner through the chosen moves lists the edits, which needs the whole table.

Example 3

Adjacency matrix

An adjacency matrix stores a graph with VV nodes as a V×VV \times V grid: matrix[u][v] = 1 when uu and vv are joined. Our 5-node graph with 6 edges uses all 25 cells, of which only 12 are ones (each undirected edge is written twice). The memory is fixed by the number of nodes, before a single edge is added.

Matrix against list

V2⏟matrixvsV+2E⏟list=O(V+E)V=5, E=6: 25 vs 17\underbrace{V^2}_{\text{matrix}} \quad\text{vs}\quad \underbrace{V + 2E}_{\text{list}} = O(V + E) \qquad V = 5,\ E = 6:\ 25 \text{ vs } 17
A graph has at most V(V−1)/2V(V-1)/2 undirected edges, so the list is never worse in Big O. It wins big whenever EE is far below V2V^2.
OperationAdjacency matrixAdjacency list
SpaceO(V2)O(V^2)O(V+E)O(V + E)
Check edge (u, v)O(1)O(1)O(deg⁡u)O(\deg u)
Add edgeO(1)O(1)O(1)O(1)
List neighbours of uO(V)O(V)O(deg⁡u)O(\deg u)
Best forDense graphs, all-pairs algorithmsSparse graphs, BFS and DFS

Matrix pays off

  • Dense graphs where EE is close to V2V^2.
  • Constant-time edge checks matter more than memory.
  • Floyd-Warshall and other all-pairs algorithms that fill every cell anyway.

Matrix wastes memory

  • Sparse graphs: road maps, social networks, the web.
  • A million nodes means 101210^{12} cells, mostly zeros.
  • Listing neighbours scans a whole row of VV cells.

More examples

Other quadratic structures

  • Distance matrices

    Floyd-Warshall keeps dist[i][j] for every pair of nodes: O(V2)O(V^2) space, O(V3)O(V^3) time.

  • Images and grids

    An image of h×wh \times w pixels is an image[h][w] array: O(n2)O(n^2) for an n×nn \times n picture.

  • Interval DP

    Matrix-chain order and palindrome tables store dp[i][j] for every substring range.

  • Pairwise scores

    Similarity or distance between every pair of nn items, as in clustering and recommendations.

Optimisation

Rolling rows: from n² to n

Why two rows are enough

dp[i][j] reads only dp[i−1][j−1], dp[i−1][j], dp[i][j−1]  ⇒  S=2(min⁡(n,m)+1)=O(min⁡(n,m))dp[i][j] \text{ reads only } dp[i-1][j-1],\ dp[i-1][j],\ dp[i][j-1] \;\Rightarrow\; S = 2\big(\min(n, m) + 1\big) = O(\min(n, m))
Row ii depends on row i−1i - 1 and nothing older. Keep prev and curr, swap them after each row, and put the shorter string on the columns.

What one row needs

Only the dashed part is wasted in the full table, and it is almost all of it.
Python
def lcs_two_rows(a, b):    if len(b) > len(a):        a, b = b, a                    # shorter string on the columns    n = len(b)    prev = [0] * (n + 1)    for i in range(1, len(a) + 1):        curr = [0] * (n + 1)        for j in range(1, n + 1):            if a[i - 1] == b[j - 1]:                curr[j] = prev[j - 1] + 1            else:                curr[j] = max(prev[j], curr[j - 1])        prev = curr    return prev[n]print(lcs_two_rows("ABCD", "ACBF"))            # 2print(lcs_two_rows("A" * 3000, "A" * 3000))    # 3000, with 2 rows of 3,001
Same answer as the full table with 10 cells instead of 25.
Edit and run it in your browser

Limits

When you cannot drop the table

Two rows give you the final number: the LCS length, the edit distance. They cannot tell you which letters or which edits, because finding those means walking back from the corner through the table, and the old rows are gone. Hirschberg's algorithm recovers the actual sequence in O(min⁡(n,m))O(\min(n, m)) space by splitting the problem in half recursively, at roughly twice the time.

Can this table shrink?

Also check the size first: beyond about n=104n = 10^4 a full n×nn \times n table is too big to keep.

Pattern spotting

Spotting O(n²) space in code

Code shapeWhat it isSpace
[[0] * (n + 1) for _ in range(m + 1)]2D DP tableO(nm)O(nm)
matrix = [[0] * V for _ in range(V)]Adjacency or distance matrixO(V2)O(V^2)
grid[rows][cols]Image or boardO(rows⋅cols)O(\text{rows} \cdot \text{cols})
@lru_cache on f(i, j)Memoised 2D recursionO(nm)O(nm) cache plus O(n+m)O(n + m) stack
prev, curr = [0] * (n + 1), ...Rolling rowsO(n)O(n)
for i ...: for j ...: count += 1Nested loop, nothing storedO(1)O(1) space, O(n2)O(n^2) time
Count what is alive at the peak, not how many times the loops run.
Working out the space of a 2D algorithm
  1. 1Find the 2D structuretable, matrix, cache keyed by pairs
  2. 2Size each sidem + 1 rows, n + 1 columns
  3. 3MultiplyO(nm), or O(n²) if equal
  4. 4Check the readsonly the previous row?
  5. 5Shrink if allowedtwo rows or a list

In the wild

Where O(n²) space shows up

  • DNA alignment

    Needleman-Wunsch scores every pair of positions in two sequences; long genomes need Hirschberg-style tricks.

  • Spell checkers

    Edit distance between a typo and candidate words picks the suggestions.

  • Routing tables

    All-pairs shortest paths in a small network store a V×VV \times V distance matrix.

  • Image processing

    Every filter, blur or convolution works on a 2D array of pixels.

Recap

Key takeaways

Key points

  • O(n²) space means a 2D structure with a cell for every pair; with two inputs it is O(nm)O(nm).
  • Doubling nn quadruples memory: (2n)2=4n2(2n)^2 = 4n^2. At n=104n = 10^4 that is about 800 MB.
  • LCS and edit distance tables are (m+1)×(n+1)(m+1) \times (n+1); the extra row and column are the empty prefix.
  • Adjacency matrices cost V2V^2 regardless of edges; sparse graphs want an O(V+E)O(V + E) list.
  • If row ii reads only row i−1i - 1, two rows give O(min⁡(n,m))O(\min(n, m)) space at the same time cost.
  • Reconstructing the actual answer needs the full table, or Hirschberg's algorithm.

Sources