Sub topic 4
Building the Recurrence from Prefixes
This chapter assumes you can write recursive functions in Python, read Big-O notation, and know what memoization does. It also assumes the earlier definition: Levenshtein distance is the minimum number of single-character insertions, deletions, and substitutions that turn string a into string b.
The definition says what the distance is. It does not say how to compute it. There are infinitely many edit sequences, so trying them all is not an option. The way forward is to stop thinking about whole strings and think about prefixes.
The Subproblem: Distances Between Prefixes
Let a have length m and b have length n. Define:
D(i, j)= the edit distance betweena[:i](the firsticharacters ofa) andb[:j](the firstjcharacters ofb).
The answer we want is D(m, n). The plan is to express D(i, j) in terms of the same function on shorter prefixes. Once that works, the whole problem reduces to a finite set of (m + 1) × (n + 1) subproblems.
Two indexing conventions trip people up here:
| Symbol | Meaning |
|---|---|
| `i`, `j` | Prefix lengths, ranging from `0` to `m` and `0` to `n` |
| `a[i - 1]` | The last character of the prefix `a[:i]` |
| `b[j - 1]` | The last character of the prefix `b[:j]` |
| `D(0, 0)` | Distance between two empty strings, which is `0` |
Viewing an Edit Script as an Alignment
Any edit script can be drawn as an alignment, which means writing the two strings in columns. Each column contains one of the following:
- a character of
aabove a character ofb. If they are equal this is a match with cost 0, and otherwise it is a substitution with cost 1. - a character of
aabove a gap. This is a deletion with cost 1. - a gap above a character of
b. This is an insertion with cost 1.
Here is one alignment of kitten and sitting:
k i t t e n -
s i t t i n g
S . . . S . IThat alignment costs 3. Under this view the order in which the edits happen stops mattering. A script and an alignment describe the same set of choices, and the cost is the number of non-match columns.
The Last Column Decides Everything
Look at the last column of an optimal alignment of a[:i] and b[:j], where both prefixes are non-empty. Only three cases are possible:
a[i - 1]sits aboveb[j - 1]. The rest of the alignment alignsa[:i-1]withb[:j-1]. Cost:D(i - 1, j - 1)plus 0 if the characters are equal, 1 if not.a[i - 1]sits above a gap (a deletion). The rest alignsa[:i-1]with all ofb[:j]. Cost:D(i - 1, j) + 1.- A gap sits above
b[j - 1](an insertion). The rest aligns all ofa[:i]withb[:j-1]. Cost:D(i, j - 1) + 1.
No fourth case exists. A column with gaps in both rows contributes nothing, so we ignore it. Each case leaves a smaller subproblem, and the optimal alignment must use an optimal solution for that subproblem. If it used a worse one, you could swap in the better one and lower the total, which would contradict optimality. This cut-and-paste argument is the optimal substructure property that makes dynamic programming valid here.
Taking the best of the three cases gives the recurrence:
D(i, j) = min( D(i-1, j) + 1, # delete a[i-1]
D(i, j-1) + 1, # insert b[j-1]
D(i-1, j-1) + (0 if a[i-1] == b[j-1] else 1) ) # match / substituteBase Cases
The recurrence needs both prefixes to be non-empty. When one prefix is empty, the answer is forced:
D(i, 0) = i. The only way to turnicharacters into the empty string is to delete all of them.D(0, j) = j. The only way to buildjcharacters from nothing is to insert all of them.
Both formulas give D(0, 0) = 0, so the two rules agree at the corner.
Working the Recurrence by Hand
Compute D(2, 2) for a = "ab" and b = "ba".
D(1, 1):"a"vs"b". The characters differ, so the result ismin(D(0,1)+1, D(1,0)+1, D(0,0)+1) = min(2, 2, 1) = 1.D(1, 2):"a"vs"ba". Herea[0] = 'a'equalsb[1] = 'a', so the result ismin(D(0,2)+1, D(1,1)+1, D(0,1)+0) = min(3, 2, 1) = 1.D(2, 1):"ab"vs"b". Herea[1] = 'b'equalsb[0] = 'b', so the result ismin(D(1,1)+1, D(2,0)+1, D(1,0)+0) = min(2, 3, 1) = 1.D(2, 2):a[1] = 'b'differs fromb[1] = 'a', so the result ismin(D(1,2)+1, D(2,1)+1, D(1,1)+1) = min(2, 2, 2) = 2.
The distance is 2. Levenshtein distance has no swap operation, so the swap of two adjacent letters costs two edits. A later chapter on transpositions changes that.
A Useful Fact When Characters Match
When a[i - 1] == b[j - 1], you never need the other two branches. In that case D(i, j) = D(i - 1, j - 1).
The reason is that changing a prefix by one character changes the distance by at most 1. Take an optimal script from a[:i-1] to b[:j] and delete the final b[j-1] at the end. That gives a script to b[:j-1], so D(i-1, j-1) ≤ D(i-1, j) + 1. The same argument gives D(i-1, j-1) ≤ D(i, j-1) + 1. The diagonal branch is therefore never worse. This shortcut is safe, but it only works in the unit-cost case. With custom operation costs, the subject of a later chapter, you must keep the full min.
Translating the Recurrence to Code
A direct recursive translation is correct but very slow:
from functools import lru_cache
def lev_naive(a, b):
calls = 0
def d(i, j):
nonlocal calls
calls += 1
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, d(i, j - 1) + 1, d(i - 1, j - 1) + cost)
return d(len(a), len(b)), calls
def lev_memo(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, d(i, j - 1) + 1, d(i - 1, j - 1) + cost)
result = d(len(a), len(b))
return result, d.cache_info().currsize
print(lev_naive("kitten", "sitting")) # (3, <call count>)
print(lev_memo("kitten", "sitting")) # (3, number of distinct subproblems)
assert lev_naive("ab", "ba")[0] == 2
assert lev_memo("", "abc")[0] == 3The naive version makes three recursive calls per cell and recomputes the same (i, j) pairs over and over. Its call count follows a recurrence at least as large as the Delannoy numbers. For kitten and sitting that means well over 8,000 calls, and the count grows exponentially with string length. The memoized version solves each pair at most once. That is at most (m + 1)(n + 1) subproblems, which is 56 here.
Common Errors Checklist
| Error | Symptom |
|---|---|
| Comparing `a[i]` with `b[j]` instead of `a[i-1]` with `b[j-1]` | `IndexError`, or answers shifted by one character |
| Missing or zero base cases | Distances too small, `D("abc", "")` returns 0 |
| Dropping the insert or delete branch | Overestimates when lengths differ |
| Greedy "take substitution if characters differ" | Wrong answers like `D("a", "ba") = 2` instead of 1 |
| Unmemoized recursion on real inputs | Runtime blows up past about 12 characters |
Exercise
Use the recurrence and base cases to compute D(2, 3) for a = "at" and b = "cat". Show the values of D(1, 1), D(1, 2), D(2, 2), D(1, 3), and D(2, 3).
Show answer
D(1,1): "a" vs "c" differ, min(2, 2, 0+1) = 1. D(1,2): "a" vs "ca", a[0] = b[1], so D(0,1) + 0 = 1. D(2,2): "at" vs "ca", 't' differs from 'a', min(D(1,2)+1, D(2,1)+1, D(1,1)+1) = min(2, 3, 2) = 2, where D(2,1) = 2 ("at" vs "c"). D(1,3): "a" vs "cat", min(D(0,3)+1, D(1,2)+1, D(0,2)+1) = min(4, 2, 3) = 2. D(2,3): 't' equals 't', so D(1,2) + 0 = 1. The distance is 1: insert 'c' at the front.
Exercise
Explain why the alignment argument needs exactly three cases for the last column, and why a column with gaps in both rows can be ignored.
Show answer
The last column must contain the last character of a[:i], the last character of b[:j], or both. That gives deletion, insertion, or match/substitute. A column with gaps in both rows uses no characters and costs nothing, so removing it leaves an alignment with the same cost. Optimal alignments can therefore be assumed to have no such columns.
Exercise
The shortcut D(i, j) = D(i-1, j-1) when a[i-1] == b[j-1] relies on unit costs. Give a cost setting where it fails.
Show answer
Suppose an insertion or deletion can cost less than zero, or more generally the costs violate the "changing one character changes the distance by at most the cost of one indel" bound. For example, with deletion cost 0 and insertion cost 0, D(i-1, j) + 0 could be smaller than D(i-1, j-1). In that setting the diagonal is no longer guaranteed to be best, so you must evaluate all three branches.