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.

See it run

Fill an LCS table and an edit-distance table cell by cell, build an adjacency matrix edge by edge, then squeeze a whole DP table into two rows.

Operations

LCS table

Longest common subsequence of "ABCD" and "ACBF". Every pair of prefixes gets one cell, so the table has (4 + 1) × (4 + 1) = 25 cells.

Step 1 of 19

Two strings, one cell per prefix pair

∅ACBF
∅00000
A0????
B0????
C0????
D0????

allocated 25 cells before doing any work

We want the LCS of "ABCD" and "ACBF". Cell dp[i][j] holds the LCS length of the first i letters of one string and the first j of the other. With m = n = 4 that is (m+1)(n+1) = 25 cells: S(m, n) = O(mn), which is O(n^2) when the strings are about the same length.

Step 1: Two strings, one cell per prefix pair

def lcs_length(a, b):    m, n = len(a), len(b)    dp = [[0] * (n + 1) for _ in range(m + 1)]   # (m+1) x (n+1) cells    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           # match: diagonal + 1            else:                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])  # best of up and left    return dp[m][n]print(lcs_length("ABCD", "ACBF"))   # 2
Time
O(m·n)
Space
O(m·n)
two strings of 1,000
1,002,001 cells
length only, two rows
O(min(m, n))

Every cell reads only its up, left and up-left neighbours. That locality is what later lets you drop all but two rows when you only need the length.

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Building a 2D list with [[0] * n] * n

    critical

    Multiplying the outer list copies the reference, not the row. Every row is the same list object, so writing one cell writes the whole column. Build each row separately.

    Wrong
    n = 3grid = [[0] * n] * ngrid[0][1] = 1print(grid)   # [[0, 1, 0], [0, 1, 0], [0, 1, 0]]
    Right
    n = 3grid = [[0] * n for _ in range(n)]grid[0][1] = 1print(grid)   # [[0, 1, 0], [0, 0, 0], [0, 0, 0]]
  • Adjacency matrix for a huge sparse graph

    critical

    A matrix costs V² cells no matter how few edges exist. A million-node road map would need about 10^12 cells. Use an adjacency list, which costs O(V + E).

    Wrong
    V = 1_000_000matrix = [[0] * V for _ in range(V)]   # about 8 TB: MemoryError
    Right
    from collections import defaultdictadj = defaultdict(list)for u, v in roads:    adj[u].append(v)    adj[v].append(u)                    # O(V + E)
  • Rolling rows when you need the reconstruction

    major

    Two rows give you the final number, but backtracking to recover the actual subsequence or list of edits needs the whole table. Decide what the problem asks for before optimising.

    Wrong
    length = lcs_two_rows(a, b)# "now walk back to print the LCS" - the rows are gone
    Right
    dp = full_lcs_table(a, b)          # keep O(m*n) to backtrackseq = backtrack(dp, a, b)# or Hirschberg: O(min(m, n)) space, about 2x the time
  • One row updated in place without saving the diagonal

    major

    With a single 1D row, dp[j - 1] has already been overwritten with the current row's value by the time you need the old diagonal. Keep the old value in a variable before you overwrite it.

    Wrong
    for j in range(1, n + 1):    if a[i - 1] == b[j - 1]:        dp[j] = dp[j - 1] + 1       # dp[j-1] is already the new row    else:        dp[j] = max(dp[j], dp[j - 1])
    Right
    diag = 0                        # old dp[j-1], before overwritefor j in range(1, n + 1):    old = dp[j]    if a[i - 1] == b[j - 1]:        dp[j] = diag + 1    else:        dp[j] = max(dp[j], dp[j - 1])    diag = old
  • Forgetting the extra row and column

    major

    Prefix DP needs a slot for the empty prefix. Sizing the table m × n forces awkward special cases and usually an index error on dp[i - 1] when i = 0.

    Wrong
    dp = [[0] * n for _ in range(m)]dp[i][j] = dp[i - 1][j - 1] + 1   # i = 0 reads dp[-1]: the last row
    Right
    dp = [[0] * (n + 1) for _ in range(m + 1)]# row 0 and column 0 stand for the empty prefix
  • Thinking memoised recursion saves the table

    minor

    Caching f(i, j) for every pair still stores up to m·n results, and the recursion adds O(m + n) stack frames on top. It is the same O(m·n) space, just hidden in a dictionary.

    Wrong
    @lru_cache(None)def f(i, j): ...     # "no table, so O(1) space"
    Right
    @lru_cache(None)def f(i, j): ...     # O(m*n) cache + O(m + n) stack

Interview tips

  • How to explain it

    • O(n²) space means memory grows with n × n: a 2D table or matrix with a cell for every pair.
    • With two inputs of sizes m and n it is O(m·n); it becomes O(n²) when m ≈ n.
    • Doubling n quadruples the memory, because (2n)² = 4n².
    • Time and space are separate: Floyd-Warshall is O(n³) time but O(n²) space.
  • Spot it in code

    • `[[0] * (n + 1) for _ in range(m + 1)]`: a 2D DP table, O(m·n).
    • `matrix = [[0] * V for _ in range(V)]`: adjacency or distance matrix, O(V²).
    • `@lru_cache` on a function of (i, j): the cache can grow to O(m·n).
    • A set or dict keyed by pairs (i, j) can hold up to n² entries.
  • Shrink it

    • If row i reads only row i - 1, keep two rows: O(min(m, n)).
    • Put the shorter string on the columns so each row is shorter.
    • Sparse graph? Use an adjacency list, O(V + E).
    • Need the actual path or sequence in small memory? Hirschberg's algorithm.
  • Watch out

    • `[[0] * n] * n` aliases every row to the same list.
    • n = 10,000 already means 10^8 cells, about 800 MB at 8 bytes each.
    • Python lists of ints cost at least 8 bytes per slot; arrays or NumPy are tighter.