Sub topic 7
Bottom-Up Solution with a DP Table
This chapter assumes you know the LCS recurrence from the optimal substructure chapter and can read nested Python loops over a list of lists. The memoized version from the previous chapter starts at the full problem and recurses down to smaller ones. The bottom-up version works the other way. It solves the smallest subproblems first and stores every answer in a table, so it needs no recursion at all.
The Table and What a Cell Means
For sequences a of length m and b of length n, build a table dp with m + 1 rows and n + 1 columns. Cell dp[i][j] holds the LCS length of the prefixes a[:i] and b[:j].
The extra row and column stand for empty prefixes. An empty sequence shares nothing with any other sequence, so row 0 and column 0 are all zeros. These zeros are the base case of the recurrence, stored as data.
Every other cell follows the recurrence, using prefix indices:
- If
a[i-1] == b[j-1], thendp[i][j] = dp[i-1][j-1] + 1. - Otherwise,
dp[i][j] = max(dp[i-1][j], dp[i][j-1]).
The - 1 offsets are there because cell i refers to a prefix of length i, and the last character of that prefix is at index i - 1.
Fill Order
A cell reads from three neighbors: above, left, and diagonally above-left. Filling the table row by row, left to right, guarantees that all three are ready before you need them.
A Worked Table
Here is the filled table for a = "ABCB" (rows) and b = "BCB" (columns):
| Row | ε | B | C | B |
|---|---|---|---|---|
| ε | 0 | 0 | 0 | 0 |
| A | 0 | 0 | 0 | 0 |
| B | 0 | 1 | 1 | 1 |
| C | 0 | 1 | 2 | 2 |
| B | 0 | 1 | 2 | 3 |
At row C, column C the characters match, so the cell is the diagonal value 1 plus 1, which gives 2. At row C, last column B they differ, so the cell takes max(1, 2) = 2. The bottom-right cell, 3, is the answer for the full strings. The LCS here is "BCB".
The Code
def lcs_length_table(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_table("ABCB", "BCB")) # 3
print(lcs_length_table("ABCBDAB", "BDCABA")) # 4
print(lcs_length_table("", "ABC")) # 0Common Errors
- Off-by-one indexing. Comparing
a[i]withb[j]instead ofa[i-1]withb[j-1]skips the first characters and raises anIndexErroron the last row. - Adding 1 on a mismatch. A mismatch never grows the LCS. It only takes the better of the two neighbors.
- Using
dp[i-1][j-1]on a mismatch. That value can be smaller than both neighbors, so the result undercounts.
Compared with memoization, the table version has no recursion limit and no function-call overhead. It does compute every cell, even ones the top-down version would never visit. The next chapter uses the full table to recover the subsequence itself.
Exercise
Using the worked table for "ABCB" and "BCB", what would row A look like if a were "BBCB" instead, and does the final answer change?
Show answer
Row 1 becomes 0, 1, 1, 1, because the first B matches column B (diagonal 0 + 1 = 1) and the later cells carry that 1 forward. The final answer is still 3, since "BCB" remains the longest common subsequence.
Exercise
Why is filling the table column by column, top to bottom, also correct?
Show answer
Each cell needs only the cells above, to the left, and diagonally above-left. Column-major order also fills all three before the current cell, so every dependency is ready when it is read.