Sub topic 4
Building the Recurrence from Prefixes
This chapter assumes you know recursion, basic Python, and the definition of Levenshtein distance from the previous chapter. The goal here is a recurrence: a formula that computes the distance for two strings from the distances of smaller pieces of them.
Work with prefixes
Let a have length m and b have length n. Define D(i, j) as the edit distance between the first i characters of a and the first j characters of b. In Python those are a[:i] and b[:j]. The answer you want is D(m, n).
Prefixes are useful because each one is a smaller version of the same problem. If you can express D(i, j) using D values with smaller indices, recursion handles the rest.
Base cases
When one prefix is empty, there is only one way to finish the job:
- D(i, 0) = i, because you must delete all i characters of
a[:i]. - D(0, j) = j, because you must insert all j characters of
b[:j].
The recursive case
Look at an optimal edit sequence and ask what happens to the last characters, a[i-1] and b[j-1]. One of these three things must be true:
a[i-1]is deleted. Its cost is 1 plus the cost of turninga[:i-1]intob[:j]: D(i-1, j) + 1.b[j-1]is inserted. Its cost is 1 plus the cost of turninga[:i]intob[:j-1]: D(i, j-1) + 1.a[i-1]lines up withb[j-1]. If the two characters match, this costs nothing. If they differ, it is a substitution costing 1: D(i-1, j-1) + cost.
These three cases cover every possibility, so the true distance is the smallest of them:
D(i, j) = min( D(i-1, j) + 1, D(i, j-1) + 1, D(i-1, j-1) + [a[i-1] ≠ b[j-1]] )
The bracket evaluates to 1 when the characters differ and 0 when they match.
A direct implementation
The recurrence translates line for line into code. Memoization caches each (i, j) result so it is computed only once.
from functools import lru_cache
def edit_distance(a, b):
@lru_cache(maxsize=None)
def d(i, j):
if i == 0:
return j
if j == 0:
return i
cost = 0 if a[i - 1] == b[j - 1] else 1
return min(
d(i - 1, j) + 1, # delete a[i-1]
d(i, j - 1) + 1, # insert b[j-1]
d(i - 1, j - 1) + cost, # match or substitute
)
return d(len(a), len(b))
assert edit_distance("kitten", "sitting") == 3
assert edit_distance("", "abc") == 3
assert edit_distance("flaw", "lawn") == 2Common mistakes
- Off-by-one indexing. D(i, j) covers
a[:i], so its last character isa[i-1], nota[i]. - Forgetting the match case. Adding 1 to the diagonal every time gives a count of character positions, which is not the edit distance.
- Wrong base cases. D(i, 0) is i, not 0. An empty target still requires i deletions.
The next chapter turns this recurrence into a table that is filled bottom-up, with no recursion at all.
Exercise
Using the recurrence, compute D(2, 1) for a = "ab" and b = "b". Show which of the three cases gives the minimum.
Show answer
The base cases give D(1, 0) = 1, D(2, 0) = 2, D(0, 1) = 1. D(1, 1) compares "a" with "b": min(D(0,1)+1, D(1,0)+1, D(0,0)+1) = min(2, 2, 1) = 1. D(2, 1): the last characters 'b' and 'b' match, so the diagonal gives D(1, 0) + 0 = 1. Deletion gives D(1, 1) + 1 = 2, and insertion gives D(2, 0) + 1 = 3. The minimum is 1 (delete 'a').
Exercise
Why is it safe to look only at the last characters of the two prefixes instead of considering edits anywhere in the strings?
Show answer
Any optimal edit sequence can be written as an alignment, and the last column of that alignment is a deletion of a[i-1], an insertion of b[j-1], or a pairing of a[i-1] with b[j-1]. Everything before that column is an optimal solution for smaller prefixes. Taking the minimum over the three cases therefore covers every possible optimal solution.