33. Dynamic Programming 2D (Longest Common Subsequence)
A 2D table where cell (i, j) answers the problem for the first i characters of one string and the first j of the other. LCS is the base of diff tools and edit-distance style problems.
How it works
Let dp[i][j] be the length of the longest common subsequence of x[:i] and y[:j]. Row 0 and column 0 are 0 (an empty string shares nothing).
- If
x[i-1] == y[j-1], that character extends the best answer without it:dp[i][j] = dp[i-1][j-1] + 1. - Otherwise drop one character from either string and keep the better result:
dp[i][j] = max(dp[i-1][j], dp[i][j-1]).
Fill row by row; the answer is in the bottom-right cell. Walking back from that cell along the choices recovers an actual subsequence.
Diagram
flowchart TD
S["Cell i, j"] --> Q{"x at i-1 equals y at j-1?"}
Q -->|yes| D["Diagonal cell plus 1"]
Q -->|no| M["Max of cell above and cell to the left"]
Step-by-step trace
Input: x = ABCBDAB (rows), y = BDCABA (columns). Full DP table.
| (empty) | B | D | C | A | B | A | |
|---|---|---|---|---|---|---|---|
| (empty) | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| A | 0 | 0 | 0 | 0 | 1 | 1 | 1 |
| B | 0 | 1 | 1 | 1 | 1 | 2 | 2 |
| C | 0 | 1 | 1 | 2 | 2 | 2 | 2 |
| B | 0 | 1 | 1 | 2 | 2 | 3 | 3 |
| D | 0 | 1 | 2 | 2 | 2 | 3 | 3 |
| A | 0 | 1 | 2 | 2 | 3 | 3 | 4 |
| B | 0 | 1 | 2 | 2 | 3 | 4 | 4 |
Result: LCS length is 4; walking back from the bottom-right cell gives BCBA.
Complexity
| Operation | Time | Space |
|---|---|---|
| LCS of lengths m and n | O(m * n) | O(m * n), or O(min(m, n)) for length only |
Python reference implementation
def lcs(x, y):
"""Length of the longest common subsequence of x and y."""
m, n = len(x), len(y)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if x[i - 1] == y[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]
Common mistakes and tips
- The
+1in table size is for the empty prefix; it removes all boundary checks. - Only the previous row is needed for the length, so two rows are enough.
- Edit distance uses the same grid with insert, delete and replace costs.
The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.