Sub topic 5
Filling the Dynamic Programming Table
This chapter assumes you can read Python, work with 2D lists, and follow the recurrence from the previous chapter. In that recurrence, dp[i][j] is the edit distance between the first i characters of a and the first j characters of b. Here you will turn that recurrence into a table, fill it in the right order, check it by hand, and avoid the mistakes that most often break implementations.
From recurrence to table
The recurrence defines each value in terms of three smaller subproblems:
dp[i-1][j] + 1: deletea[i-1]dp[i][j-1] + 1: insertb[j-1]dp[i-1][j-1] + cost: match (cost 0) or substitute (cost 1)
If you call the recurrence directly with plain recursion, it solves the same subproblems an exponential number of times. There are only (m+1) × (n+1) distinct pairs (i, j), though. A table with one cell per pair stores each answer once. Every cell is then computed in constant time from cells that are already filled.
The table has one more row and one more column than the string lengths. Row 0 and column 0 stand for the empty prefix. They hold the base cases: turning an empty string into j characters takes j insertions, and turning i characters into an empty string takes i deletions.
Which cells a cell depends on
Each cell reads from its neighbor above, its neighbor to the left, and its neighbor diagonally above-left. Any fill order that computes those three neighbors before the cell is correct.
These fill orders all work:
| Fill order | How it proceeds | Notes |
|---|---|---|
| Row-major | Row by row, left to right | The standard choice. Leads directly to the two-row optimization. |
| Column-major | Column by column, top to bottom | Equally correct. Useful when you want to keep the shorter string's columns. |
| Anti-diagonal | All cells with `i + j = k`, for increasing `k` | Cells on one anti-diagonal are independent of each other, so this order suits SIMD and GPU parallelism. |
An order that visits dp[i][j] before dp[i-1][j-1] fails without warning. It reads a zero placeholder and returns a distance that is too small.
A worked example by hand
Compute the distance from a = "flaw" (rows) to b = "lawn" (columns). Start with the base cases in row 0 and column 0, then fill row by row.
| Row | ε | l | a | w | n |
|---|---|---|---|---|---|
| ε | 0 | 1 | 2 | 3 | 4 |
| f | 1 | 1 | 2 | 3 | 4 |
| l | 2 | 1 | 2 | 3 | 4 |
| a | 3 | 2 | 1 | 2 | 3 |
| w | 4 | 3 | 2 | 1 | 2 |
Here are a few cells worked out in full:
- Row
f, columnl: the characters differ. The options are 1+1 (above), 1+1 (left), and 0+1 (diagonal). The minimum is 1. - Row
l, columnl: the characters match, so the diagonal givesdp[1][0] + 0 = 1. The other two options give 2 and 3. The result is 1. - Row
a, columna: the characters match. The diagonaldp[2][1] = 1plus 0 gives 1. - Row
w, columnn: the characters differ. The options are 3+1 (above), 1+1 (left), and 2+1 (diagonal). The minimum is 2.
The bottom-right cell gives the answer, 2: delete f, then insert n. The run of 1s along a shifted diagonal (l→l, a→a, w→w) shows the matched characters law. This pattern is the basis for traceback in a later chapter.
The implementation
This version fills the table in row-major order. It also returns the full table so you can inspect it.
def levenshtein_table(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, # delete a[i-1]
dp[i][j - 1] + 1, # insert b[j-1]
dp[i - 1][j - 1] + cost, # match or substitute
)
return dp
def print_table(a, b, dp):
header = ["", "ε"] + list(b)
print(" ".join(f"{h:>2}" for h in header))
labels = ["ε"] + list(a)
for label, row in zip(labels" ".join(f"{x:>2}" for x in [label] + row))
def levenshtein(a, b):
return levenshtein_table(a, b)[len(a
dp = levenshtein_table("flaw", "lawn")
print_table("flaw", "lawn", dp)
assert levenshtein("flaw", "lawnenshtein("kitten", "sitting") == 3
assert levenshtein("", "abc") == 3
assert levenshtein("abc", "") == 3
assert leven 0
assert levenshtein("same", "same") == 0Running it prints the same table you fil Common errors
Off-by-one on string indices
Table indices count prefix lengths. String indices count positions. Cell dp[i][j] compares a[i-1] with b[j-1]. If you write a[i] == b[j], the code compares the wrong characters, and in the last row and column it raises IndexError. Keep the two index systems separate in your head: the table is one larger in each dimension than the strings.
Aliased rows
The shortcut [[0] * (n + 1)] * (m + 1) builds a list of m + 1 references to the same row. Writing to one row writes to all of them.
m, n = 2, 2
bad = [[0] * (n + 1)] * (m + 1)
bad[1][0] = 99
print(bad) # [[99, 0, 0], [99, 0, 0], [99, 0, 0]]
good = [[0] * (n + 1) for _ in range(m + 1)]
good[1][0] = 99
print(good) # [[0, 0, 0], [99, 0, 0], [0, 0, 0]]With aliased rows, the base cases overwrite each other, and the result can still look plausible. Always build the rows with a comprehension.
Missing or wrong base cases
Starting every cell at 0 and skipping the initialization loops treats prefixes as free to delete or insert. The result then measures something closer to the best local alignment than to edit distance. A similar mistake fills only row 0 and forgets column 0. Test with one empty string. levenshtein("", "abc") must return 3, and levenshtein("abc", "") must also return 3.
Swapping the meaning of rows and columns
Levenshtein distance is symmetric, so swapping a and b does not change the final number. It does change the meaning of each step. A move down means "delete from a" only if rows index a. This matters for traceback and for weighted costs, where deletion and insertion can have different prices.
Edge cases
- Empty inputs. The loops over
range(1, m + 1)simply do not run, so the base case holds the answer. No special-case code is needed. - Identical strings. Every diagonal step costs 0, and the result is 0. A fast pre-check
if a == b: return 0saves the full fill. - Shared prefixes and suffixes. Stripping a common prefix and suffix before filling never changes the distance, and it often shrinks the table a lot. Many production libraries do this.
- Non-string sequences. The code only indexes and compares elements, so it works on lists of words, tokens, or DNA bases without any changes.
- Unicode. Python indexes strings by code point. A character such as "é" written as
eplus a combining accent counts as two elements. Normalize withunicodedata.normalize("NFC", s)first if that matters for your data.
Top-down versus bottom-up
You could instead memoize the recursive function with functools.lru_cache. It computes the same cells, but only the ones it reaches. In Python, recursion depth grows to about m + n, so long strings hit the default recursion limit of roughly 1000. The function-call overhead also makes it several times slower. The bottom-up table avoids both problems, and its fixed fill order is what makes the later memory and speed optimizations possible.
Exercise
Fill the full DP table for a = "ab" (rows) and b = "ba" (columns). What is the distance, and why doesn't it equal 1 even though the strings differ only by swapping two adjacent characters?
Show answer
Row ε is 0 1 2. Row a is 1 1 1. Row b is 2 1 2. The distance is 2. Levenshtein distance has only insert, delete, and substitute operations, so a swap costs two operations: either two substitutions, or one deletion plus one insertion. Counting a swap as one operation requires the transposition case covered in the chapter on OSA and Damerau-Levenshtein distance.
Exercise
A colleague's implementation creates the table with dp = [[0] (n + 1)] (m + 1) and returns wrong answers for some inputs but not others. Explain the bug and give one input pair that should expose it.
Show answer
The multiplication creates m + 1 references to one shared row list. Setting dp[i][0] = i in the base-case loop writes to all rows at once, so after the loop column 0 holds m in every row, and every row update overwrites the others. With a = "abc" and b = "" the result is still correct by accident, but levenshtein("a", "a") returns 1 instead of 0, because the shared row's dp[0][0] was overwritten to 1. The fix is [[0] * (n + 1) for _ in range(m + 1)].
Exercise
Which of these fill orders is valid: (1) row by row, right to left; (2) column by column, top to bottom; (3) by anti-diagonals i + j = k for increasing k?
Show answer
Orders 2 and 3 are valid. Order 1 fails because dp[i][j] needs its left neighbor dp[i][j-1], which a right-to-left sweep has not computed yet. Column-major order computes the above, left, and diagonal neighbors first. In anti-diagonal order, all three neighbors lie on diagonals k-1 or k-2, which are already finished.