Sub topic 10
Two-dimensional problems: longest common subsequence
This chapter assumes you have worked through tabulation and the one-dimensional coin change problem. It also assumes you are comfortable with nested lists in Python. Coin change needed one index, the amount. Some problems compare two sequences, and then the state needs two indices, so the table becomes a grid.
The problem
A subsequence is what remains after you delete zero or more characters from a string without reordering the rest. For example, "ACD" is a subsequence of "ABCD". The longest common subsequence (LCS) of two strings is the longest string that is a subsequence of both. For "ABCD" and "ACBD", the LCS has length 3. Both "ABD" and "ACD" work.
Brute force would list every subsequence of one string and check each against the other. A string of length m has 2^m subsequences, so this does not scale.
State, recurrence, and base cases
Define the state as:
dp[i][j]is the LCS length of the firsticharacters ofaand the firstjcharacters ofb.
Using prefix lengths instead of positions gives a clean base case. An empty prefix has nothing in common with anything, so dp[0][j] = 0 and dp[i][0] = 0.
For i, j >= 1, look at the last characters of the two prefixes, a[i-1] and b[j-1]:
- If they match, that character can end a common subsequence:
dp[i][j] = dp[i-1][j-1] + 1. - If they differ, at least one of them is not in the LCS. Drop one or the other and keep the better result:
dp[i][j] = max(dp[i-1][j], dp[i][j-1]).
This is optimal substructure: the best answer for the two prefixes comes from the best answers for slightly shorter prefixes.
Fill order
Each cell reads from three neighbours: the cell above, the cell to its left, and the cell diagonally above-left. If you fill row by row, left to right, all three are already computed when you reach a cell.
Worked example
Here is the filled table for a = "ABCD" (rows) and b = "ACBD" (columns). Row 0 and column 0 are the base cases.
| Row | "" | A | C | B | D |
|---|---|---|---|---|---|
| "" | 0 | 0 | 0 | 0 | 0 |
| A | 0 | 1 | 1 | 1 | 1 |
| B | 0 | 1 | 1 | 2 | 2 |
| C | 0 | 1 | 2 | 2 | 2 |
| D | 0 | 1 | 2 | 2 | 3 |
Take the cell at row B, column B. The characters match, so its value is the diagonal value 1 plus 1, which gives 2. The bottom-right cell, dp[4][4] = 3, is the answer.
Code
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("ABCD", "ACBD")) # 3
print(lcs_length("ABCBDAB", "BDCABA")) # 4The grid has (m + 1)(n + 1) states, and each one does constant work, so the function takes O(mn) time and O(mn) space. The memoized version uses the same recurrence, and recursion only visits the states it needs:
from functools import lru_cache
def lcs_length_memo(a, b):
@lru_cache(maxsize=None)
def go(i, j):
if i == 0 or j == 0:
return 0
if a[i - 1] == b[j - 1]:
return go(i - 1, j - 1) + 1
return max(go(i - 1, j), go(i, j - 1))
return go(len(a), len(b))
print(lcs_length_memo("ABCD", "ACBD")) # 3The memoized version can recurse up to about m + n calls deep. With long strings it will hit Python's default recursion limit of 1000, which is a good reason to prefer the table here.
Common errors
- Off-by-one indexing.
dp[i][j]describes prefixes of lengthiandj, so the characters to compare area[i - 1]andb[j - 1]. If you writea[i], you skip the first character and run past the end of the string. - Adding 1 on a mismatch. Only a match extends the subsequence. A mismatch copies the larger neighbour unchanged.
- Returning the wrong cell. The answer is in
dp[m][n], not indp[m-1][n-1].
The table holds more than the final length. The next chapter walks back from dp[m][n] to recover an actual subsequence.
Exercise
Fill the table by hand or run lcs_length to find the LCS length of "AGGTAB" and "GXTXAYB". Name one common subsequence of that length.
Show answer
The length is 4. "GTAB" is a common subsequence of that length: G, T, A, B appear in that order in both strings.
Exercise
A teammate changes the else branch to dp[i][j] = dp[i - 1][j]. Give two strings where this returns a wrong answer, and explain why.
Show answer
Try a = "A" and b = "AB". At i = 1, j = 2 the characters 'A' and 'B' differ, so the changed code reads dp[0][2] = 0 instead of dp[1][1] = 1 and returns 0. The correct answer is 1. Dropping the character from b, which is the left neighbour, can be the better choice, so the recurrence has to take the max of both options.