Sub topic 2
How Much Time and Memory It Costs
This chapter assumes you can read the Levenshtein recurrence and the full-table levenshtein(a, b) function, and that you know Big-O notation.
Time and Space
For strings of length m and n, the table has (m+1)(n+1) cells. Each cell takes constant work: three lookups and a minimum. That gives O(mn) time and O(mn) space. Two 10,000-character strings need about 100 million cells. In Python lists, that table takes gigabytes of memory, so space usually runs out before time does.
Recovering the Edit Script with Traceback
The bottom-right cell holds the distance but not the edits themselves. To recover them, start at dp[m][n] and step back to any neighbor that could have produced the current value. A diagonal step is a keep or a substitution, an upward step is a deletion, and a leftward step is an insertion.
def edit_script(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
cost = 0 if a[i - 1] == b[j - 1] else 1
dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost)
ops, i, j = [], m, n
while i > 0 or j > 0:
if i > 0 and j > 0 and dp[i][j] == dp[i - 1][j - 1] + (a[i - 1] != b[j - 1]):
ops.append(("keep" if a[i - 1] == b[j - 1] else "sub", a[i - 1], b[j - 1]))
i, j = i - 1, j - 1
elif i > 0 and dp[i][j] == dp[i - 1][j] + 1:
ops.append(("del", a[i - 1], ""))
i -= 1
else:
ops.append(("ins", "", b[j - 1]))
j -= 1
return dp[m][n], ops[::-1]
print(edit_script("kitten", "sitting"))Traceback adds O(m + n) steps, but it needs the whole table.
Using Two Rows Instead of a Full Table
Row i depends only on row i−1. If you keep just those two rows, memory drops to O(min(m, n)) when the shorter string goes along the row. The catch is that you lose the table that traceback needs. Hirschberg's algorithm gets the script back in linear space by splitting the problem at a middle row and recursing on each half.
def levenshtein_two_rows(a, b):
if len(a) < len(b):
a, b = b, a
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") == 2Custom Costs for Each Operation
You can weight each operation by replacing each +1 with its own cost. The base cases have to change too:
| Item | Unit cost | Weighted |
|---|---|---|
| `dp[i][0]` | `i` | `i * del_cost` |
| `dp[0][j]` | `j` | `j * ins_cost` |
| Mismatch | `1` | `sub_cost` |
A common mistake is to weight the inner loop but leave the base cases as i and j.
Exercise
Two strings have lengths 20,000 and 500. How many cells does the full table hold, and roughly how many values does the two-row version store?
Show answer
The full table holds 20,001 × 501 ≈ 10 million cells. The two-row version keeps two rows of 501 values each, about 1,002 values in total.
Exercise
If subcost is 2 or more and inscost = del_cost = 1, does the algorithm ever pick a substitution?
Show answer
Not when sub_cost is above 2, because a delete plus an insert costs 2 and is always cheaper. At exactly 2 the two options tie.