Sub topic 8
Using Two Rows Instead of a Full Table
This chapter assumes you have read the earlier chapters on the dynamic programming table and its complexity. It also assumes you are comfortable with Python lists and Big-O notation. The full table uses O(mn) memory. For two strings of 100,000 characters each, that is 10 billion cells, which is far more than most machines can hold. The fix is to notice how little of the table each step reads.
What Each Cell Depends On
Cell dp[i][j] reads three neighbors: dp[i-1][j] (above), dp[i][j-1] (left), and dp[i-1][j-1] (diagonal). All three are in row i-1 or in row i. Once row i is finished, the program never reads row i-1 again. So you only need to keep two rows: the previous one and the one being filled.
The Implementation
def levenshtein_two_rows(a, b):
if len(a) < len(b):
a, b = b, a # keep the shorter string in the row
prev = list(range(len(b) + 1))
for i, ca in enumerate(a, 1):
curr = [i]
for j, cb in enumerate(b, 1):
curr.append(min(
prev[j] + 1,
curr[j - 1] + 1,
prev[j - 1] + (ca != cb),
))
prev = curr
return prev[-1]
assert levenshtein_two_rows("flaw", "lawn") == 2
print(levenshtein_two_rows("kitten", "sitting")) # 3Here is how the code maps to the full-table version:
prevstarts as row 0, which holds0, 1, ..., n. This is the base case of turning the empty prefix into each prefix ofb.curr = [i]is the column-0 base case for rowi.(ca != cb)isTrueorFalse, and Python treats those as 1 and 0, so it works as the substitution cost.- After the outer loop finishes,
prevholds the last row, and its last entry is the answer.
Swapping the strings so that b is the shorter one keeps each row at length min(m, n) + 1. Levenshtein distance is symmetric, so the swap does not change the result. Time is still O(mn). Memory drops to O(min(m, n)).
Common Errors
| Mistake | Symptom |
|---|---|
| Writing `prev = curr` and then changing `curr` in place on the next row | Later rows silently read corrupted values |
| Forgetting `curr = [i]` | Column-0 base case is lost, and results come out too small |
| Using the longer string for the row | Correct answer but wasted memory |
Hirschberg's Idea: Linear Space with an Edit Script
Hirschberg's algorithm recovers an optimal alignment in linear space:
- Split
aat its midpoint intoa_leftanda_right. - Run the two-row algorithm forward on
a_leftagainstb. This gives the cost of aligninga_leftwith every prefix ofb. - Run it backward on the reversed
a_rightagainst the reversedb. This gives the cost of aligninga_rightwith every suffix ofb. - Choose the split column
kthat minimizes the forward cost plus the backward cost. An optimal alignment passes through that point. - Recurse on (
a_left,b[:k]) and (a_right,b[k:]).
Each level of recursion does about half the work of the level above it, so the total time stays O(mn), roughly twice the cost of filling the full table. Memory is O(m + n).
Exercise
You compare a 50-character query with a 2,000,000-character document using levenshteintworows. About how many integers does each row hold, and would the result change if the function did not swap the arguments?
Show answer
Each row holds 51 integers, because the shorter string sets the row length. Without the swap, each row would hold 2,000,001 integers. The distance would be the same, because Levenshtein distance is symmetric. Only the memory use changes.
Exercise
Why can't you recover the edit script from levenshteintworows, and what is the cheapest way to get one without O(mn) memory?
Show answer
Traceback needs the values in earlier rows, and this version overwrites them. Hirschberg's divide-and-conquer algorithm recovers an optimal script in O(m + n) memory and O(mn) time.