Sub topic 7
Bottom-Up Solution with a DP Table
The memoized solution from the previous chapter starts at the full problem and recurses down to the base cases. This chapter goes the other way. You start from the base cases and fill a table of answers to every subproblem until the full problem's answer appears in the last cell. This is called tabulation. It computes the same values as memoization, but it uses no recursion, so you control the evaluation order and never hit Python's recursion limit.
This chapter assumes you are comfortable with:
- the LCS recurrence from the optimal substructure chapter
- Python lists of lists and nested loops
- the idea of a subproblem defined by a pair of indices
Recovering the actual subsequence from the table comes in the next chapter. Here the goal is to build the table correctly and understand why each cell holds what it does.
Re-indexing the Recurrence for a Table
The memoized version used suffixes: solve(i, j) was the LCS length of a[i:] and b[j:]. Tables are usually easier to read with prefixes, so this chapter switches to that form.
Let dp[i][j] be the LCS length of the first i characters of a and the first j characters of b, that is, of a[:i] and b[:j]. With m = len(a) and n = len(b):
dp[0][j] = 0anddp[i][0] = 0, because an empty prefix shares nothing with anything.- 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 answer is
dp[m][n].
The table has m + 1 rows and n + 1 columns. The extra row and column hold the empty-prefix base cases. They make the recurrence apply uniformly to every interior cell, so you need no special-case code for i = 1 or j = 1.
Which Cells a Cell Depends On
Each interior cell reads at most three neighbors: the cell diagonally up-left, the cell directly above, and the cell directly to the left. Any fill order that computes those three before the current cell is valid.
Row-by-row, left-to-right order satisfies this. When you reach dp[i][j], the whole previous row is finished and the cells to the left in the current row are done.
The Implementation
The function below builds and returns the whole table. Returning the table instead of only the final number lets you inspect it here and reuse it for traceback in the next chapter.
def lcs_table(a, b):
m, n = len(a), len(b)
# One independent list per row; see the aliasing warning below.
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
def lcs_length(a, b):
return lcs_table(a, b)[len(a)][len(b)]
def print_table(a, b, dp):
header = " " + " ".join(" " + ch for ch in b)
print(header)
for i, row in enumerate(dp):
label = a[i - 1] if i > 0 else " "
print(label, " ".join(f"{v:2d}" for v in row))
a, b = "ABCBDAB", "BDCABA"
dp = lcs_table(a, b)
print_table(a, b, dp)
print("LCS length:", lcs_length(a, b)) # 4The loops never touch row 0 or column 0. Those cells stay at their initial value of zero, which is exactly the base case.
A Worked Table
Here is the table the code prints for a = "ABCBDAB" (rows) and b = "BDCABA" (columns). The first row and column are the empty-prefix base cases.
| Row | ε | B | D | C | A | B | A |
|---|---|---|---|---|---|---|---|
| ε | 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 |
A few cells, traced by hand:
dp[1][4](row A, column A) = 1. The characters match, so take the diagonaldp[0][3] = 0and add 1.dp[2][5](row B, second column B) = 2. They match again. The diagonaldp[1][4] = 1becomes 2, so"AB"is common to"AB"and"BDCAB".dp[5][3](row D, column C) = 2. No match. The cell above is 2 and the cell to the left is 2, so the value is 2.dp[7][6](bottom-right) = 4. No match (BvsA). The maximum of above (4) and left (4) is 4. This is the answer.
Two properties hold in every LCS table and make good sanity checks:
- Values never decrease moving right along a row or down a column. A longer prefix cannot have a shorter LCS.
- Adjacent cells differ by at most 1. Adding one character can extend the LCS by at most one.
If your table breaks either property, there is a bug.
Checking Against the Memoized Version
Tabulation and memoization evaluate the same recurrence, so they must agree on every input. A quick randomized comparison catches indexing mistakes early.
import random
from functools import lru_cache
def lcs_length_memo(a, b):
@lru_cache(maxsize=None)
def solve(i, j):
if i == len(a) or j == len(b):
return 0
if a[i] == b[j]:
return 1 + solve(i + 1, j + 1)
return max(solve(i + 1, j), solve(i, j + 1))
return solve(0, 0)
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]
random.seed(0)
for _ in range(2000):
a = "".join(random.choice("ACGT") for _ in range(random.randint(0, 12)))
b = "".join(random.choice("ACGT") for _ in range(random.randint(0, 12)))
assert lcs_length_table(a, b) == lcs_length_memo(a, b), (a, b)
print("all tests passed")The test includes empty strings, because randint(0, 12) can return 0. Empty inputs are a common edge case. The table version handles them without special code: the loops do not run, and dp[m][n] is a base-case zero.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| `dp = [[0] * (n + 1)] * (m + 1)` | Every row changes at once; answers are too large | Build each row separately with a list comprehension |
| Comparing `a[i]` with `b[j]` inside loops starting at 1 | `IndexError` at the last row or column, or a shifted answer | Compare `a[i - 1]` with `b[j - 1]` |
| Table sized `m × n` instead of `(m + 1) × (n + 1)` | No room for base cases; edge cells read garbage or wrap to index `-1` | Allocate one extra row and column |
| Adding 1 on a mismatch, or taking `max` on a match without the diagonal | Overcounts or undercounts | On a match, use only the diagonal plus 1 |
| Returning `dp[-1][-1]` from a table that was never filled | Returns 0 for every input | Make sure the loops cover `1..m` and `1..n` inclusive |
Fill Order Choices
Row-major order is conventional, but it is not the only correct order. Column-major order (outer loop over j, inner over i) also computes the up, left, and diagonal neighbors first. So does sweeping anti-diagonals, where i + j is constant. On a single diagonal no cell depends on another, so the cells can in principle be computed in parallel. What you cannot do is fill a row from right to left, because the left neighbor would not exist yet.
Row-major order has one more benefit. Each row reads only from itself and the row above it. A later chapter uses this to cut memory down to two rows.
Exercise
Using the worked table, what is dp[4][5] (row for the second "B" of a, column for the second "B" of b), and which neighbor or neighbors produce it?
Show answer
dp[4][5] = 3. The characters match (a[3] = "B", b[4] = "B"), so the value is the diagonal dp[3][4] = 2 plus 1. The cells above and to the left are not used on a match.
Exercise
A student initializes the table with dp = [[0] (n + 1)] (m + 1) and gets lcs_length("AB", "AB") == 3 or higher instead of 2. Explain the cause.
Show answer
All rows are the same list object. Writing dp[1][1] = 1 also sets dp[0][1] to 1, so the "row above" and the current row are the same storage. Base cases stop being zero, and later cells build on corrupted values, which inflates the result. Creating each row with a list comprehension fixes it.
Exercise
Would the algorithm still be correct if the outer loop ran over j and the inner loop over i? What about running the inner loop over j from n down to 1?
Show answer
Column-major order is correct, because the cells above, to the left, and up-left are all computed before dp[i][j]. Running j from n down to 1 is incorrect, because dp[i][j] needs dp[i][j-1] from the same row, and that cell has not been computed yet. It still holds its initial 0.
Exercise
Without running code, give lcslength("", "XYZ") and lcslength("ABC", "DEF"), and say which table cells hold the answers.
Show answer
Both are 0. For ("", "XYZ") the table is a single row, and dp[0][3] is a base case. For ("ABC", "DEF") no characters ever match, so every cell is the max of zero-valued neighbors, and dp[3][3] = 0.