Edit Distance
Type "recieve" and a spell-checker suggests "receive". It needs a way to say which dictionary words are close to what you typed. The standard measure is the edit distance (Levenshtein distance): the fewest single-character insertions, deletions and substitutions that turn one string into the other. It is the LCS table's sibling, a DP over pairs of prefixes, with a minimum instead of a maximum and a richer set of moves. This lesson builds the table, recovers the actual edits, relates the distance to the LCS, and shows how to compute it in linear space.
The problem
Given and , transform into with these operations, each costing 1:
- insert a character,
- delete a character,
- substitute one character by another (a "match", keeping a character unchanged, costs 0).
The edit distance is the minimum total cost. For example, TRACE becomes CRATER with 3 operations: substitute the first T by C, substitute the C by T, and insert R at the end.
The recurrence
Let be the edit distance between the prefixes and . Turning a prefix into the empty string takes deletions, and building from nothing takes insertions, so and .
For , think of an optimal edit sequence written as an alignment: the two strings placed in two rows, with gaps, so that every column is a match, a substitution, a deletion (a character of over a gap) or an insertion (a gap over a character of ). Look at the last column. It is one of three kinds:
- above : a match if (cost 0) or a substitution (cost 1), and the rest of the alignment aligns with ;
- above a gap: is deleted, and the rest aligns with ;
- a gap above : is inserted, and the rest aligns with .
In each case the rest must be an optimal alignment of the shorter prefixes (cut and paste), so
where is 1 if the characters differ and 0 if they are equal.
The table
The animation fills the table for TRACE (rows) and CRATER (columns). Row 0 and column 0 hold the base cases; every other cell looks at its three neighbours up-left, up and left, and the last frame walks back from the corner to read off the edits.
The Python version fills the same table and walks back with the same preferences as the animation: a diagonal step (match or substitution) if it explains the cell's value, otherwise a deletion, otherwise an insertion.
def edit_table(x, y):
m, n = len(x), len(y)
D = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
D[i][0] = i
for j in range(n + 1):
D[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
D[i][j] = min(D[i - 1][j - 1] + (x[i - 1] != y[j - 1]),
D[i - 1][j] + 1,
D[i][j - 1] + 1)
return D
def edits(D, x, y):
i, j, ops = len(x), len(y), []
while i > 0 or j > 0:
if i > 0 and j > 0 and D[i][j] == D[i - 1][j - 1] + (x[i - 1] != y[j - 1]):
ops.append(f"keep {x[i - 1]}" if x[i - 1] == y[j - 1] else f"sub {x[i - 1]}->{y[j - 1]}")
i, j = i - 1, j - 1
elif i > 0 and D[i][j] == D[i - 1][j] + 1:
ops.append(f"del {x[i - 1]}"); i -= 1
else:
ops.append(f"ins {y[j - 1]}"); j -= 1
return ops[::-1]
x, y = "TRACE", "CRATER"
D = edit_table(x, y)
print(" " + " ".join(y))
for i in range(len(x) + 1):
print((" " if i == 0 else x[i - 1]) + " " + " ".join(str(v) for v in D[i]))
print("distance:", D[-1][-1])
print("edits:", ", ".join(edits(D, x, y))) C R A T E R
0 1 2 3 4 5 6
T 1 1 2 3 3 4 5
R 2 2 1 2 3 4 4
A 3 3 2 1 2 3 4
C 4 3 3 2 2 3 4
E 5 4 4 3 3 2 3
distance: 3
edits: sub T->C, keep R, keep A, sub C->T, keep E, ins R
The edits match the animation's last frame: two substitutions and one insertion, with R, A and E kept. Reading the operations in order and applying them to TRACE gives CRACE, CRATE, CRATER.
Each cell costs , so the algorithm runs in time and space, and the walk back takes steps.
Edit distance and LCS
If substitutions are forbidden (only insertions and deletions, each costing 1), the characters that are kept form a common subsequence, and every other character is deleted from or inserted from . So the cheapest way keeps an LCS:
With substitutions allowed, a substitution replaces a deletion plus an insertion, so , and also , since each operation changes the length by at most one. The program checks the identity and both bounds on many random pairs.
import random
def lcs(x, y):
prev = [0] * (len(y) + 1)
for ch in x:
cur = [0]
for j, d in enumerate(y, 1):
cur.append(prev[j - 1] + 1 if ch == d else max(prev[j], cur[-1]))
prev = cur
return prev[-1]
def distance(x, y, sub_cost=1):
prev = list(range(len(y) + 1))
for i, ch in enumerate(x, 1):
cur = [i]
for j, d in enumerate(y, 1):
cur.append(min(prev[j - 1] + (0 if ch == d else sub_cost), prev[j] + 1, cur[-1] + 1))
prev = cur
return prev[-1]
rng = random.Random(3)
ok = True
for _ in range(500):
x = "".join(rng.choice("abc") for _ in range(rng.randint(0, 8)))
y = "".join(rng.choice("abc") for _ in range(rng.randint(0, 8)))
indel = distance(x, y, sub_cost=2) # a substitution never beats delete + insert
ok &= indel == len(x) + len(y) - 2 * lcs(x, y)
ok &= abs(len(x) - len(y)) <= distance(x, y) <= indel
print("identity and bounds hold on 500 random pairs:", ok)
for a, b in [("recieve", "receive"), ("recieve", "relieve"), ("kitchen", "sitting")]:
print(f"{a} -> {b}: distance {distance(a, b)}, insert/delete only {distance(a, b, 2)}, LCS {lcs(a, b)}")identity and bounds hold on 500 random pairs: True
recieve -> receive: distance 2, insert/delete only 2, LCS 6
recieve -> relieve: distance 1, insert/delete only 2, LCS 6
kitchen -> sitting: distance 5, insert/delete only 8, LCS 3
Setting the substitution cost to 2 is the same as forbidding substitutions, since a delete plus an insert also costs 2. The output holds a surprise for the spell-checker of the introduction: "recieve" is at distance 2 from "receive" (two substitutions) but only 1 from "relieve" (one substitution), so plain edit distance prefers the wrong word. Real spell-checkers add word frequencies and a cheap operation for the most common typing error, swapping two adjacent letters. That extension, the Damerau-Levenshtein distance (in its simplest "optimal string alignment" form), adds a fourth case when , and with it "recieve" is at distance 1 from "receive" too.
Linear space
Row of the table depends only on row , so the distance itself needs only two rows, space, as the distance function above does. Recovering the edits in linear space is also possible, with Hirschberg's method: compute the middle row's values from both ends, find where an optimal path crosses the middle, and recurse on the two halves.
Note: No algorithm is known that computes the edit distance in time for any , and Backurs and Indyk showed in 2015 that one would refute the Strong Exponential Time Hypothesis. The quadratic DP is essentially optimal, a result of fine-grained complexity, treated in Parameterized & Fine-Grained Complexity.
In C++
The two-row version in C++, with std::vector<int> rows that swap after each character of .
#include <algorithm>
#include <cstdio>
#include <string>
#include <vector>
int edit_distance(const std::string& x, const std::string& y) {
std::vector<int> prev(y.size() + 1), cur(y.size() + 1);
for (size_t j = 0; j <= y.size(); ++j) prev[j] = static_cast<int>(j);
for (size_t i = 1; i <= x.size(); ++i) {
cur[0] = static_cast<int>(i);
for (size_t j = 1; j <= y.size(); ++j)
cur[j] = std::min({prev[j - 1] + (x[i - 1] != y[j - 1]), prev[j] + 1, cur[j - 1] + 1});
std::swap(prev, cur);
}
return prev[y.size()];
}
int main() {
const char* pairs[][2] = {{"TRACE", "CRATER"}, {"recieve", "receive"}, {"kitchen", "sitting"},
{"", "abc"}, {"dynamic", "programming"}};
for (auto& p : pairs)
std::printf("d(\"%s\", \"%s\") = %d\n", p[0], p[1], edit_distance(p[0], p[1]));
}d("TRACE", "CRATER") = 3
d("recieve", "receive") = 2
d("kitchen", "sitting") = 5
d("", "abc") = 3
d("dynamic", "programming") = 8
The practice problem Edit Distance asks for exactly this number.
Test yourself
What is the edit distance between CAT and CUT?
- 0
- 1
- 2
- 3
What are the values in row 0 of the edit-distance table for of length 4?
With only insertions and deletions allowed, strings of lengths 7 and 5 with an LCS of length 4 are at distance...
- 2
- 3
- 4
- 8