Sub topic 10
Two-dimensional problems: longest common subsequence
Coin change needed only one number to describe a subproblem: the amount still left to make. Many problems need two. If a problem compares two sequences, or works on a range inside one sequence, a subproblem is a pair of positions, so the table becomes a grid. The longest common subsequence (LCS) problem is the standard example of a two-dimensional DP. This chapter covers how to define its state, why the recurrence is correct, which order fills the grid validly, and the mistakes people make most often with 2D tables.
This chapter assumes you can already write a 1D tabulation, that you know the difference between state, recurrence, and base case, and that you can read Python nested lists and functools.lru_cache.
The problem
A subsequence of a string is what remains after you delete zero or more characters without changing the order of the rest. "ACE" is a subsequence of "ABCDE". "AEC" is not. A substring is stricter: its characters must be next to each other. "ACE" is not a substring of "ABCDE".
Given strings a and b, the LCS is the longest string that is a subsequence of both. For a = "AGCAT" and b = "GAC", the LCS has length 2. "GA", "AC", and "GC" all qualify. An LCS is often not unique, but its length is. This chapter computes the length. The next chapter recovers an actual subsequence.
LCS is used in real tools. Line-based diff utilities and many version-control merge tools are built on it or on its close relatives.
Why one index is not enough
Consider the last character of each string. If both strings end with the same character, the LCS can use it as its final character, which leaves a smaller problem on both strings. If the last characters differ, at least one of them is not in the LCS, so you drop the last character of one string or the other. In both cases the smaller problem is "a prefix of a compared with a prefix of b". The two prefixes shrink independently, so one index cannot describe them. You need a pair.
The state
Define:
dp[i][j]is the length of an LCS ofa[:i]andb[:j], the firsticharacters ofaand the firstjcharacters ofb.
Here i ranges over 0..m and j over 0..n, where m = len(a) and n = len(b). Because the indices count characters rather than point at them, row 0 and column 0 stand for empty prefixes. That choice makes the base cases trivial, and it is why the code compares a[i - 1] with b[j - 1].
The final answer is dp[m][n].
Recurrence and base cases
Base cases: dp[0][j] = 0 and dp[i][0] = 0. An empty string has no common subsequence with anything except the empty one.
For i, j >= 1:
- If
a[i - 1] == b[j - 1]:dp[i][j] = dp[i - 1][j - 1] + 1 - Otherwise:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
Why matching is always safe
When the last characters are equal, it can look as though you should also check the "drop one" options. You don't have to. Take any common subsequence of a[:i] and b[:j]. If it doesn't end with the shared character x, you can append x, or swap its last character for x, without making it shorter. So some optimal answer always pairs the two final xs, and the rest of that answer is an LCS of a[:i-1] and b[:j-1]. This is optimal substructure: the optimal answer is built from an optimal answer to a smaller problem.
When the last characters differ, they can't both be the final character of a common subsequence. At least one of them is unused, so removing it loses nothing. You don't know which one is unused, so you try both and take the larger result.
Fill order
Every cell depends on the cell above it, the cell to its left, and the cell diagonally up and to the left.
Any order that computes those three cells before dp[i][j] is valid. The usual choice is row by row, left to right within each row. Column by column also works, and so does sweeping anti-diagonals. Right to left within a row does not work, because the left neighbour would not be filled yet.
Tabulated implementation
def lcs_length(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
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 dp[m][n]
print(lcs_length("AGCAT", "GAC")) # 2
print(lcs_length("ABCBDAB", "BDCABA")) # 4
print(lcs_length("", "ABC")) # 0Nothing in this function depends on the inputs being strings. It works on any two sequences whose items support ==, such as lists of lines, tokens, or tuples. A line-based diff passes in lists of lines.
A worked table
Here is the full table for a = "AGCAT" (rows) and b = "GAC" (columns). The - row and column are the empty-prefix base cases.
| Row | - | G | A | C |
|---|---|---|---|---|
| **-** | 0 | 0 | 0 | 0 |
| **A** | 0 | 0 | 1 | 1 |
| **G** | 0 | 1 | 1 | 1 |
| **C** | 0 | 1 | 1 | 2 |
| **A** | 0 | 1 | 2 | 2 |
| **T** | 0 | 1 | 2 | 2 |
Follow a few cells to see the recurrence at work:
- Row
A, columnA: the characters match, so take the diagonal (0) and add 1, giving 1. - Row
C, columnC: the characters match, and the diagonal isdp[2][2] = 1, so the cell is 2. This is the"GC"or"AC"subsequence. - Row
T, columnC:TandCdiffer, so take the max of above (2) and left (2).
The values never decrease as you move right or down. Adding a character can't make the LCS shorter. That property makes a quick sanity check when you print a table while debugging.
The same recurrence, top-down
The memoized version follows the recurrence almost word for word:
from functools import lru_cache
def lcs_length_memo(a, b):
@lru_cache(maxsize=None)
def solve(i, j):
if i == 0 or j == 0:
return 0
if a[i - 1] == b[j - 1]:
return solve(i - 1, j - 1) + 1
return max(solve(i - 1, j), solve(i, j - 1))
return solve(len(a), len(b))
print(lcs_length_memo("ABCBDAB", "BDCABA")) # 4Defining solve inside the outer function gives every call to lcs_length_memo its own cache, and lets solve read a and b without passing them as arguments. Two practical limits apply:
- Recursion depth. The deepest call chain can reach
m + nframes, because each step reducesi,j, or both by one. CPython's default recursion limit is 1000, so two 600-character strings can raiseRecursionError. The tabulated version has no such limit. - Coverage. When the strings share a lot, the matching branch skips many cells, and memoization can visit fewer than
m * nstates. When they share little, it visits nearly all of them, and the overhead of a function call and a cache lookup per state makes it several times slower than the loops.
Complexity
The table has (m + 1) * (n + 1) states, and each one takes O(1) work: one comparison plus either an addition or a max of two values. That gives O(mn) time and O(mn) space.
The space cost is the one that hurts first. Two 10,000-character inputs need about 10^8 cells. A Python list stores an 8-byte pointer per slot, so the pointers alone take around 800 MB, before counting the integer objects they point to. A later chapter shows how to keep only two rows, which cuts space to O(min(m, n)) if all you need is the length. Recovering the subsequence itself needs either the full table or a more advanced divide-and-conquer method (Hirschberg's algorithm).
Common errors
Aliased rows
bad = [[0] * 3] * 2
bad[0][0] = 1
print(bad) # [[1, 0, 0], [1, 0, 0]]
good = [[0] * 3 for _ in range(2)]
good[0][0] = 1
print(good) # [[1, 0, 0], [0, 0, 0]][row] * k repeats a reference to the same list k times, so writing to one row writes to all of them. In LCS this rarely crashes. It just returns wrong numbers, which makes it hard to find. Always build 2D tables with a comprehension.
Off-by-one between table and string
Table index i means "the first i characters", so the character it adds is a[i - 1]. Writing a[i] either skips the first character or raises IndexError on the last row.
Taking the diagonal when characters differ
Some people write max(dp[i-1][j-1] + 1, dp[i-1][j], dp[i][j-1]) without checking for a match. That counts characters that don't match, and the result can exceed the true LCS length.
Confusing subsequence with substring
The longest common substring problem uses a similar grid but a different recurrence. Mixing the two up is common enough that it helps to compare them directly:
| Row | LCS (subsequence) | Longest common substring |
|---|---|---|
| State meaning | best over prefixes `a[:i]`, `b[:j]` | longest match *ending exactly* at `a[i-1]`, `b[j-1]` |
| On match | `dp[i-1][j-1] + 1` | `dp[i-1][j-1] + 1` |
| On mismatch | `max(above, left)` | `0` |
| Answer | `dp[m][n]` | max over all cells |
The state definition decides the recurrence. If you change what a cell means, you have to rederive the rest of the recurrence too.
Edge cases
- Empty input: the loops don't run and
dp[0][0] = 0is returned. No special-case code is needed. - Identical strings: every diagonal cell matches, so the result is
len(a). - No shared characters: every cell stays 0.
- Case and Unicode: comparison uses
==, so"a"and"A"don't match. Normalize the inputs first, for example with.casefold(), if they should match. - Very unequal lengths: cost is still O(mn). A short pattern compared with a long text is cheap. Two long texts are expensive.
Exercises
Exercise
Fill in the last row of the LCS table for a = "ABCBDAB" and b = "BDCABA", or run lcs_length, and state the LCS length. Then name one LCS.
Show answer
The length is 4. "BCBA" is one LCS ("BDAB" and "BCAB" also work). The last row of the table, for columns -, B, D, C, A, B, A, is 0 1 2 2 3 4 4.
Exercise
Modify lcs_length to return the length of the longest common substring instead. What changes in the recurrence, and where is the answer found?
Show answer
On a mismatch, set dp[i][j] = 0 instead of taking the max of above and left. On a match, keep dp[i][j] = dp[i - 1][j - 1] + 1. Track a running best = max(best, dp[i][j]) inside the loop and return best, because the longest substring can end anywhere, not only at dp[m][n].
Exercise
A colleague fills the LCS table with the inner loop running j from n down to 1. Explain whether this gives correct results.
Show answer
It does not. When dp[i][j] is computed, its left neighbour dp[i][j - 1] in the same row has not been filled yet and still holds 0. Mismatch cells can therefore come out too small. The diagonal and above cells belong to the previous row and are correct, but the recurrence needs all three neighbours.
Exercise
lcslengthmemo raises RecursionError on two 800-character strings, while lcs_length succeeds. Why, and which version would you ship for inputs of unknown size?
Show answer
The recursive call chain can reach about m + n = 1600 frames, which is above CPython's default limit of 1000. The tabulated version uses loops, so stack depth isn't an issue. Ship the tabulated version. It has no depth limit, it avoids per-call overhead, and it is the version you need anyway to apply the two-row space optimization later.