Sub topic 8
Using Two Rows Instead of a Full Table
This chapter assumes you have already built the full (m+1) by (n+1) Levenshtein table from earlier chapters. You should be comfortable with the recurrence, with Python lists, and with Big-O notation. Here we keep the same recurrence and change only how much of the table stays in memory.
Why the Full Table Is Wasteful
The full table costs O(mn) memory. Comparing two 10,000-character strings means 100 million cells. As Python integers in nested lists, that takes gigabytes. Most of those cells are never read again after they are written.
Each cell dp[i][j] reads exactly three neighbors:
- dp[i-1][j], the cell directly above (a deletion)
- dp[i][j-1], the cell to the left (an insertion)
- dp[i-1][j-1], the cell diagonally up-left (a match or substitution)
All three are in row i or row i-1. Once row i is finished, rows 0 through i-1 are never touched again. If you only need the distance, and not the edit script, you can keep just two rows.
The Two-Row Implementation
Call the previous row prev and the row being filled curr. Row 0 of the full table is [0, 1, ..., n], which is the distance from the empty prefix of a to each prefix of b. Every new row starts with i, the cost of deleting the first i characters of a.
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
assert levenshtein_two_rows("kitten", "sitting") == 3
assert levenshtein_two_rows("", "abc") == 3
assert levenshtein_two_rows("abc", "") == 3The expression (ca != cb) is a boolean. Python treats it as 1 or 0 in arithmetic, so it gives the substitution cost directly.
Why the swap gives O(min(m, n))
Each row has one cell per character of the string that runs along the columns, plus one. Swapping so that b is the shorter string makes the row length min(m, n) + 1. Plain Levenshtein distance is symmetric, meaning d(a, b) = d(b, a), so the swap does not change the answer. Time stays O(mn), since every cell is still computed once.
Going Down to One Row
You can shrink memory further to a single list plus one saved integer. The trick is that overwriting row[j] destroys dp[i-1][j], which the next cell needs as its diagonal. So you save it in a variable before you overwrite it.
def levenshtein_one_row(a, b):
if len(a) < len(b):
a, b = b, a
row = list(range(len(b) + 1))
for i, ca in enumerate(a, 1):
diag = row[0] # dp[i-1][0]
row[0] = i # dp[i][0]
for j, cb in enumerate(b, 1):
up = row[j] # dp[i-1][j], about to be overwritten
row[j] = min(up + 1, row[j - 1] + 1, diag + (ca != cb))
diag = up # becomes the diagonal for column j+1
return row[-1]
for x, y in [("kitten", "sitting"), ("flaw", "lawn"), ("", "ab"), ("abc", "abc")]:
assert levenshtein_one_row(x, y) == levenshtein_two_rows(x, y)Asymptotically, this saves nothing over two rows. In practice it halves allocation and avoids building a new list for every row. That matters in C or Rust inner loops, and somewhat in Python too.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Forgetting `curr = [i]` and starting with `[0]` | Distances come out too small whenever `a` has leading characters to delete | Seed each row with `i` |
| Reusing one list as both rows: `prev = curr` and then mutating `curr` in place | `prev` and `curr` refer to the same object, so diagonal reads return new values | Build a fresh `curr` each row, or use the one-row version with a saved `diag` |
| In the one-row version, updating `diag` before computing `row[j]` | Off-by-one diagonal values and wrong distances | Read `up`, compute, then set `diag = up` |
| Swapping strings under asymmetric costs | Wrong weighted distance | Swap costs too, or don't swap |
| Expecting traceback afterwards | The edit script can't be reconstructed | Keep the full table, or use Hirschberg's method |
What You Lose: Traceback
Traceback walks from dp[m][n] back to dp[0][0] and reads values from every row along the path. The two-row version has already thrown those rows away. You get the distance and nothing about which edits produced it.
Recomputing rows during traceback is possible, but done naively it costs O(m²n) time. Hirschberg's algorithm, published in 1975, recovers a full optimal alignment in O(mn) time and O(min(m, n)) space. It does this by dividing the problem in half.
Hirschberg's Idea
Any optimal alignment of a with b must cross the middle row of a at some column j. If you split a into a[:mid] and a[mid:], there is a column j such that:
d(a, b) = d(a[:mid], b[:j]) + d(a[mid:], b[j:])
You can find that j with two linear-space passes:
- Run the two-row algorithm forward on
a[:mid]againstb. Its final row gives d(a[:mid], b[:j]) for everyj. - Run it on the reversed strings
a[mid:]andb. Its final row gives d(a[mid:], b[j:]) for everyj, indexed from the end. - Pick the
jthat minimizes the sum.
def last_row(a, b):
"""Return the final DP row: distances from a to every prefix of b."""
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
def split_point(a, b):
mid = len(a) // 2
left = last_row(a[:mid], b) # left[j] = d(a[:mid], b[:j])
right = last_row(a[mid:][::-1], b[::-1]) # right[k] = d(a[mid:], last k chars of b)
n = len(b)
best_j = min(range(n + 1), key=lambda j: left[j] + right[n - j])
return mid, best_j, left[best_j] + right[n - best_j]
mid, j, total = split_point("kitten", "sitting")
assert total == levenshtein_two_rows("kitten", "sitting") == 3
print(mid, j, total) # 3 3 3: "kit"->"sit" and "ten"->"ting"Hirschberg's algorithm then recurses on the two halves, (a[:mid], b[:j]) and (a[mid:], b[j:]). It stops at base cases where one string is empty or a has a single character, and there the edits can be written down directly. Joining the pieces gives the full edit script.
Cost of the divide step
The top level touches about mn cells. The two subproblems together cover about mn/2 cells, because their b pieces add up to n and each uses half of a. The next level covers mn/4, and so on. The total is about 2mn, still O(mn), at roughly twice the constant factor of one table fill. Memory is O(n) for the rows plus O(log m) recursion depth.
| Approach | Time | Extra memory | Edit script? |
|---|---|---|---|
| Full table | O(mn) | O(mn) | Yes, by direct traceback |
| Two rows | O(mn) | O(min(m, n)) | No |
| One row plus `diag` | O(mn) | O(min(m, n)) | No |
| Hirschberg | O(mn), about 2x the work | O(min(m, n)) | Yes |
Choosing Between Them
- Use two rows, or one row, when you only need a number. Typical cases are ranking spelling suggestions, deduplicating records, and checking whether two strings fall under a threshold.
- Keep the full table when the strings are short, say a few thousand characters, and you need the edit script. It is simpler and faster than Hirschberg.
- Use Hirschberg when you need an alignment of long sequences, such as genomic reads or large text files, and the full table won't fit in memory.
Exercise
Run levenshteintworows("ab", "b") by hand. Write prev after each outer iteration, and give the final answer. Remember that the function first checks whether a should be swapped.
Show answer
len("ab") = 2 is not less than len("b") = 1, so there is no swap. The initial prev is [0, 1]. For i=1, ca='a': curr = [1], then j=1, cb='b' gives min(1+1, 1+1, 0+1) = 1, so prev = [1, 1]. For i=2, ca='b': curr = [2], then j=1 gives min(1+1, 2+1, 1+0) = 1, so prev = [2, 1]. The result is prev[-1] = 1, which is one deletion of 'a'.
Exercise
A colleague writes a two-row version but puts curr = prev at the start of each row and then assigns curr[j] = ... in place. Explain why this gives wrong answers, and give the smallest change that fixes it.
Show answer
curr = prev makes both names point to the same list. Once curr[j-1] has been written, prev[j-1] returns that new row-i value instead of the old row-i-1 value, so the diagonal term is wrong. Also, curr[0] is never reset to i. The fix is to create a new list each row, for example curr = [i] followed by appends, or curr = prev[:] with curr[0] = i. Another option is the one-row version, which saves the old value in diag before overwriting it.
Exercise
Why does Hirschberg's algorithm need the second pass to run on reversed strings instead of running forward on a[mid:] against b?
Show answer
A forward pass on a[mid:] against b gives the distances from a[mid:] to prefixes b[:j]. The split condition needs distances to suffixes b[j:]. Reversing both strings turns suffixes into prefixes, so the final row of the reversed pass gives d(a[mid:], b[j:]) for every j in a single linear-space run.