Kolton Ndoj

Edit distance: how spell-check guesses what you meant

When you type 'recieve' and your device suggests 'receive', or search says 'Did you mean…?'

What problem does it solve?

How many single-letter changes does it take to turn one word into another?

The big idea

Count the fewest insertions, deletions and substitutions needed: 'kitten' becomes 'sitting' in exactly 3. Trying every possible edit sequence would explode, but there's a beautiful shortcut: the distance between two words depends only on the distances between their shorter beginnings. So you fill in a table, small problems first, and each cell needs only its three neighbours. This 'remember small answers to build big ones' trick is called dynamic programming.

How it works, step by step

  1. 1. Make a grid with one word along the top and the other down the side, each with an empty start.
  2. 2. Fill the first row and column with 0, 1, 2, 3… (building from nothing costs one per letter).
  3. 3. Each cell takes the smallest of: the cell above + 1 (delete), the cell left + 1 (insert), the cell diagonally up-left + 0 if the letters match or + 1 if not (substitute).
  4. 4. The bottom-right cell is the edit distance.
  5. 5. A spell-checker suggests dictionary words with small distance to what you typed.

The key formula

Di,j=min⁡{Di−1,j+1Di,j−1+1Di−1,j−1+[ai≠bj]D_{i,j}=\min\begin{cases} D_{i-1,j}+1\\ D_{i,j-1}+1\\ D_{i-1,j-1}+[a_i\ne b_j]\end{cases}
Di,jD_{i,j}
the distance between the first i letters of word a and the first j letters of word b
[ai≠bj][a_i\ne b_j]
1 if the two letters differ, 0 if they match

How fast is it?

A grid of m × n cells for words of lengths m and n, so it's fast for words. Real autocorrect is more than this: a classic approach also weighs keys that are close together on the keyboard and how common each word is, and modern phones use language models that look at the whole sentence.

Try it yourself

Fun fact

Vladimir Levenshtein defined it in 1965. Nearly the same table-filling trick is used to line up DNA sequences, so biologists can see how genes from humans and mice differ.

Related

Open it in the Math Lab →

Search · Intermediate