Edit Distance & Typo Tolerance
In short: edit distance (Levenshtein distance) is the fewest single-character inserts, deletes and replacements that turn one string into another. It fills the same shape of table as LCS, but each cell now has three possible parents instead of two: delete (from above), insert (from the left), and keep-or-replace (the diagonal). On a match the diagonal is free; on a mismatch every option costs one more than its parent, and the cell takes the cheapest.

Someone types shrad into Quarry's search box. There is no field called
shrad, but there is one called shard, and a good engine says did you mean
shard? instead of returning nothing. To make that call, Quarry needs a number
for how far apart two strings are. The standard answer is the edit
distance (also called Levenshtein distance): the fewest single-character
inserts, deletes and replacements that turn one string into the
other.
It's the LCS table from the last lesson with one more choice per cell. That extra choice changes what the table can tell you, and what it costs to throw the table away.
Three ways to finish
Define one cell:
d[i][j]= the fewest edits that turn the firsticharacters ofainto the firstjcharacters ofb.
Think about the last step of the cheapest edit sequence:
- Keep. If
a[i-1] == b[j-1], the last characters already agree, and nothing needs to change:d[i-1][j-1]. - Replace
a[i-1]withb[j-1]:d[i-1][j-1] + 1. - Delete
a[i-1], then solve the rest:d[i-1][j] + 1. - Insert
b[j-1]at the end:d[i][j-1] + 1.
On a mismatch, take the smallest of the last three. The edges aren't zeros any
more. Turning i characters into nothing takes i deletes, so column 0 is
0, 1, 2, …, and building j characters from nothing takes j inserts, so
row 0 is too.
Filling (m + 1) × (n + 1) cells at constant work each is O(m · n) time, and
the full table costs O(m · n) space to store.
Here's the table for SORT into STORE. Each cell compares its three
neighbours, and the arrow shows which one it took:
Up is a delete, left is an insert and the diagonal is a keep or a replace. Every cell picks the cheapest of the three.
Row 0 builds STORE's prefixes from nothing, one insert per letter. Column 0 deletes SORT's prefixes, one delete per letter. 5 by 6 table. At row 0, column 5 — value 5. 10 of 30 cells filled.
def edit_distance(a, b):
d = [[max(i, j) if i * j == 0 else 0 for j in range(len(b) + 1)] for i in range(len(a) + 1)]
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
if a[i - 1] == b[j - 1]:
d[i][j] = d[i - 1][j - 1]
else:
d[i][j] = 1 + min(d[i - 1][j], d[i][j - 1], d[i - 1][j - 1])
return d[-1][-1]
print(edit_distance("index", "indent"))