Words wing · 1965

Levenshtein Distance

How different are two words? Count the smallest number of single-letter edits that turn one into the other. kitten becomes sitting in 3: change k to s, change e to i, add a g.

Words to know
The recipe: solve the small puzzles first

Trying every possible list of edits would take forever. Instead, build a table. The box in row r, column c answers a smaller puzzle: how many edits turn the first r letters of the top word into the first c letters of the bottom word? Each box only needs three boxes that are already filled in:

Write the smallest of the three. The bottom-right box is the answer for the whole words.

Detective questions
  1. Why is the top row 0, 1, 2, 3 …? What does the box in the top row, column 3 mean?
  2. The distance can never be more than the length of the longer word. Why not?
  3. Is the distance from A to B always the same as from B to A? Try swapping the words.
  4. Sometimes two different lists of edits are both shortest. Can you find a pair of words where that happens?
Curator's answers
  1. The top row starts from no letters at all. Turning nothing into the first 3 letters of a word takes 3 inserts.
  2. Substitute letters one by one until the shorter word runs out, then insert (or delete) the rest. That's at most the length of the longer word.
  3. Yes. Every edit can be undone by an opposite edit of the same cost: an insert by a delete, a substitution by substituting back. So any list of edits from A to B can be reversed into one from B to A.
  4. "ab" to "ba": substitute both letters (2 edits), or delete the a and insert it at the end (also 2). The table shows this when a box has more than one smallest neighbor.

Why it's clever

This trick, solving small versions of a problem first and saving the answers in a table, is called dynamic programming. It turns a search through billions of edit lists into filling in one box per pair of letters.

Spell checkers use it to suggest the word you meant. Biologists use close relatives of it to compare DNA, which is written with just four letters: A, C, G and T. It also helps match names in messy records, where "Jon Smyth" might be "John Smith".

From the archive

The Soviet mathematician Vladimir Levenshtein defined this distance in 1965, while studying codes that could fix errors in messages sent between computers. The table method was found by several people independently. A 1974 paper by Robert Wagner and Michael Fischer made it famous, and it is often named after them.