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.
- An edit is one of three moves: insert a letter, delete a letter, or substitute (swap one letter for a different one).
- The Levenshtein distance between two words is the fewest edits that turn the first into the second.
- A prefix is the start of a word: the prefixes of "cat" are "", "c", "ca" and "cat".
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:
- the box above it, plus 1: delete this row's letter;
- the box to the left, plus 1: insert this column's letter;
- the box up and to the left (diagonal): plus 0 if the two letters match, or plus 1 to substitute.
Write the smallest of the three. The bottom-right box is the answer for the whole words.
- Why is the top row 0, 1, 2, 3 …? What does the box in the top row, column 3 mean?
- The distance can never be more than the length of the longer word. Why not?
- Is the distance from A to B always the same as from B to A? Try swapping the words.
- Sometimes two different lists of edits are both shortest. Can you find a pair of words where that happens?
Curator's answers
- The top row starts from no letters at all. Turning nothing into the first 3 letters of a word takes 3 inserts.
- 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.
- 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.
- "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.