O(n²) quadratic space
easy 14 minO(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
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.
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 . 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 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 to multiplies memory by 4, because .
Often shrinkable
Many 2D DP tables only read the previous row, so two rows are enough.
Counting the cells
The picture
Doubling n quadruples memory
| n | Grid | Cells | vs n = 3 |
|---|---|---|---|
| 3 | 9 | 1× | |
| 5 | 25 | about 2.8× | |
| 6 | 36 | 4×: n doubled | |
| 8 | 64 | about 7× | |
| 9 | 81 | 9×: n tripled |
Scaling rule
Scale
Practical memory limits
| n | cells | Memory at 8 bytes | Feasible? |
|---|---|---|---|
| 1,000 | 1,000,000 | 8 MB | Easy |
| 10,000 | 100,000,000 | 800 MB | Tight |
| 50,000 | 2,500,000,000 | 20 GB | Too much |
| 100,000 | 10,000,000,000 | 80 GB | Impossible on one machine |
From cells to bytes
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 letters of one string and the first of the other: cells.
The LCS recurrence
Filling one LCS cell
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)) # 25Example 2
Edit distance
The edit distance recurrence
CAT into CUT: the finished table
| ∅ | C | U | T | |
|---|---|---|---|---|
| ∅ | 0 | 1 | 2 | 3 |
| C | 1 | 0 | 1 | 2 |
| A | 2 | 1 | 1 | 2 |
| T | 3 | 2 | 2 | 1 |
Choosing the move for one cell
Example 3
Adjacency matrix
An adjacency matrix stores a graph with nodes as a grid: matrix[u][v] = 1 when and 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
| Operation | Adjacency matrix | Adjacency list |
|---|---|---|
| Space | ||
| Check edge (u, v) | ||
| Add edge | ||
| List neighbours of u | ||
| Best for | Dense graphs, all-pairs algorithms | Sparse graphs, BFS and DFS |
Matrix pays off
- Dense graphs where is close to .
- 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 cells, mostly zeros.
- Listing neighbours scans a whole row of cells.
More examples
Other quadratic structures
Distance matrices
Floyd-Warshall keeps
dist[i][j]for every pair of nodes: space, time.Images and grids
An image of pixels is an
image[h][w]array: for an 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 items, as in clustering and recommendations.
Optimisation
Rolling rows: from n² to n
Why two rows are enough
prev and curr, swap them after each row, and put the shorter string on the columns.What one row needs
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,001Limits
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 space by splitting the problem in half recursively, at roughly twice the time.
Can this table shrink?
Pattern spotting
Spotting O(n²) space in code
| Code shape | What it is | Space |
|---|---|---|
[[0] * (n + 1) for _ in range(m + 1)] | 2D DP table | |
matrix = [[0] * V for _ in range(V)] | Adjacency or distance matrix | |
grid[rows][cols] | Image or board | |
@lru_cache on f(i, j) | Memoised 2D recursion | cache plus stack |
prev, curr = [0] * (n + 1), ... | Rolling rows | |
for i ...: for j ...: count += 1 | Nested loop, nothing stored | space, time |
- 1Find the 2D structuretable, matrix, cache keyed by pairs
- 2Size each sidem + 1 rows, n + 1 columns
- 3MultiplyO(nm), or O(n²) if equal
- 4Check the readsonly the previous row?
- 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 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 .
- Doubling quadruples memory: . At that is about 800 MB.
- LCS and edit distance tables are ; the extra row and column are the empty prefix.
- Adjacency matrices cost regardless of edges; sparse graphs want an list.
- If row reads only row , two rows give space at the same time cost.
- Reconstructing the actual answer needs the full table, or Hirschberg's algorithm.