Skip to the workspace
Pebellslearn by building
Sequence DP: the Diff Engine  ›  Lesson

Edit Distance & Typo Tolerance

Edit Distance 30 minCount the fewest inserts, deletes and replacements between two strings, and what two rows can and can't tell you

dsa / Edit Distance & Typo Tolerance

Explore each scene at your own pace.

01 · Three ways to finish

Three ways to finish

Edit Distance & Typo Tolerance

Definition
Edit distance, also called Levenshtein distance, is the smallest number of single-character insertions, deletions and replacements needed to turn one string into another. A table of prefix answers computes it, taking the cheapest of three moves per cell.
In plain words
It counts how many small typing fixes separate two words. Turning shrad into shard takes two quick fixes, so the words are close, and a search box can suggest the nearer one with a did-you-mean.

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.

A cell with three arrows pointing into it, labelled insert, delete, replace, with the cheapest (replace, the diagonal) shown in bold and the formula 1 + min(delete=2, insert=1, replace=0) = 1

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 first i characters of a into the first j characters of b.

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] with b[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.

python

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:

watch it move · grid

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.

1 / 11
What does this print?
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"))
Scene 1 of 10
Project context and further resources
You're building a piece ofQuarry — version history
This piece — suggest(): Suggests the closest known term when a search is misspelt.
Scenario Someone searches Quarry for a field that doesn't exist. Typo tolerance finds the closest known name within a few edits and offers it as a suggestion.
suggest.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
suggest(term, vocabulary, limit) → str | NoneThe closest known word within limit edits, or None.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.