Edit distance
how it works
The idea on crate into cart, the example of the books this site follows (volume three, chapter 40). Then the whole method on the watch page's first example, seat into eats.
An edit changes a word by one letter: delete a letter, insert one, or replace one with another. How few edits turn crate into cart? Keep c, replace r with a, replace a with r, keep t and delete e: 3 edits. You might say swap r and a, then delete e. But a swap is not one of the edits, so it costs 2. To be sure nothing takes fewer, fill a table, as the books do. Each row stands for a start of crate, the empty start first, and each column for a start of cart. A cell holds the fewest edits that turn its row's start into its column's start. The first row and column take one edit a letter: nothing into car is 3 inserts, and cra into nothing is 3 deletes. Fill the other cells row by row. Compare the last letters of the cell's two starts. If they are the same, copy the cell up and to the left. If not, take 1 more than the cheapest of three cells. Above is for a delete, to the left for an insert, and up and to the left for a replace. For cr into ca: delete r, then c into ca, the cell above, holds 1, so 2. Or cr into c, to the left, holds 1, then insert a, so 2. Or c into c, up and to the left, holds 0, then replace r with a, so 1. The cell holds the cheapest, 1. The last cell is the answer. That fewest is the edit distance: 3 for crate into cart. To see which edits, read back: from the last cell, step to a cell it was built from. That is up and to the left when the letters match, or else one holding 1 fewer. Repeat up to the first cell. Written one above the other, the two words then make a line-up of the edits. This page counts cells, one for each cell the rule fills, not the first row and column: 20 for crate into cart, as the watch page counts. The code below, in the language Python, does the same.
| start | - | c | ca | car | cart |
|---|---|---|---|---|---|
| - | 0 | 1 | 2 | 3 | 4 |
| c | 1 | 0 | 1 | 2 | 3 |
| cr | 2 | 1 | 1 | 1 | 2 |
| cra | 3 | 2 | 1 | 2 | 2 |
| crat | 4 | 3 | 2 | 2 | 2 |
| crate | 5 | 4 | 3 | 3 | 3 |
| cell | holds | step to | edit |
|---|---|---|---|
| crate into cart | 3 | above | delete e |
| crat into cart | 2 | up-left | keep t |
| cra into car | 2 | up-left | replace a with r |
| cr into ca | 1 | up-left | replace r with a |
| c into c | 0 | up-left | keep c |
| crate | c | r | a | t | e |
|---|---|---|---|---|---|
| cart | c | a | r | t | - |
| edit | keep | replace | replace | keep | delete |
step 1 of 18
Turn seat into eats. An empty start takes one edit a letter, so the first row counts inserts and the first column counts deletes.
what it remembers to know where it is
- letters compared
- not yet
- edits in this cell
- not yet
Where it says not yet, nothing is held there at that moment.
step 2 of 18
s is not e, so take one edit more than the cheapest of above, 1, for a delete, to the left, 1, for an insert, and up and to the left, 0, for a replace: 1.
what it remembers to know where it is
- letters compared
- s e
- edits in this cell
- 1
step 6 of 18
Both letters are e, so this cell needs no edit of its own. Copy 1 from the cell up and to the left.
what it remembers to know where it is
- letters compared
- e e
- edits in this cell
- 1
step 9 of 18
e is not s, so take one edit more than the cheapest of above, 3, for a delete, to the left, 3, for an insert, and up and to the left, 3, for a replace: 4.
what it remembers to know where it is
- letters compared
- e s
- edits in this cell
- 4
step 11 of 18
Both letters are a, so this cell needs no edit of its own. Copy 1 from the cell up and to the left.
what it remembers to know where it is
- letters compared
- a a
- edits in this cell
- 1
step 16 of 18
Both letters are t, so this cell needs no edit of its own. Copy 1 from the cell up and to the left.
what it remembers to know where it is
- letters compared
- t t
- edits in this cell
- 1
step 17 of 18
t is not s, so take one edit more than the cheapest of above, 3, for a delete, to the left, 1, for an insert, and up and to the left, 2, for a replace: 2.
what it remembers to know where it is
- letters compared
- t s
- edits in this cell
- 2
step 18 of 18
Done: turning seat into eats takes 2 edits at the fewest.
what it remembers to know where it is
- letters compared
- not yet
- edits in this cell
- 2
Where it says not yet, nothing is held there at that moment.
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- the first row and column: an empty start takes one edit a letterPython lines 9, 10, 11, 12 and 13
- for each other cell, row by row, compare the two letters it stands forPython lines 14, 15 and 16
- the same letter, so no more edits than the cell up and to the leftPython line 17
- different: one more than the cheapest of above, to the left and up and to the leftPython lines 18 and 19
- the last cell is the fewest editsPython line 20
the same in Python
The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.
def edit_distance(a, b):
"""The fewest one-letter edits that turn word a into word b.
An edit deletes a letter, inserts a letter or replaces one with another.
a and b are words of any length. Returns the fewest edits.
"""
m, n = len(a), len(b)
# cell[i][j]: the fewest edits from a's first i letters to b's first j
cell = [[0] * (n + 1) for _ in range(m + 1)]
for j in range(n + 1):
cell[0][j] = j # nothing into j letters: j inserts
for i in range(m + 1):
cell[i][0] = i # i letters into nothing: i deletes
for i in range(1, m + 1): # each other cell, row by row
for j in range(1, n + 1):
if a[i - 1] == b[j - 1]: # the same last letter: no edit of its own
cell[i][j] = cell[i - 1][j - 1] # copy up and to the left
else: # one more than the cheapest of above, left and up-left
cell[i][j] = 1 + min(cell[i - 1][j], cell[i][j - 1], cell[i - 1][j - 1])
return cell[m][n] # the last cell
how it scales
The plot counts the cells the method fills on two words of letters each, measured from 10 to 100,000 letters.
Each mark across or up is ten times the one before. The line climbs two marks up for each mark across: 10,000 cells at 100 and 1,000,000 at 1,000: ten times the letters, 100 times the cells. Here the cost is the cells, and a slope of 2 means they grow as , as section 4's question 1 derives. Twice the letters make 4 times the cells.
cells filled, ten times more at each mark up
, how many letters the second word has, ten times more at each mark to the right
- two words of letters each, whatever their letterssolid where measured by running it; dashed where its formula carries it on to ten millionslope 2: ten times n, 100 times the work
| cells filled | time | |
|---|---|---|
| 1,000 | 1,000,000 | about 1 millisecond |
| 100,000 | 10,000,000,000 | about 10 seconds |
| 10,000,000 | 100,000,000,000,000 | about 1.2 days |
The cells filled are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.
make these counts yourself
Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.
"""Count edit distance's cells yourself, as the plot on this page does.
Run it with Python 3.12 or later. For each n from 10 to 100,000 it prints
the cells the method fills on two words of n letters each. The counts are
the same on any computer, whatever the letters; only the time differs.
"""
def edit_distance(a, b):
"""The fewest one-letter edits that turn word a into word b.
An edit deletes a letter, inserts a letter or replaces one with another.
a and b are words of any length. Returns the fewest edits.
"""
m, n = len(a), len(b)
# cell[i][j]: the fewest edits from a's first i letters to b's first j
cell = [[0] * (n + 1) for _ in range(m + 1)]
for j in range(n + 1):
cell[0][j] = j # nothing into j letters: j inserts
for i in range(m + 1):
cell[i][0] = i # i letters into nothing: i deletes
for i in range(1, m + 1): # each other cell, row by row
for j in range(1, n + 1):
if a[i - 1] == b[j - 1]: # the same last letter: no edit of its own
cell[i][j] = cell[i - 1][j - 1] # copy up and to the left
else: # one more than the cheapest of above, left and up-left
cell[i][j] = 1 + min(cell[i - 1][j], cell[i][j - 1], cell[i - 1][j - 1])
return cell[m][n] # the last cell
def count(a, b):
"""How many cells the method fills: each letter of a makes a row, with
one cell for each letter of b, whatever the letters."""
cells = 0
for _ in a: # a row for each letter of a
cells += len(b) # a cell in it for each letter of b
return cells
LETTERS = "abcdefghijklmnopqrstuvwxyz"
def plot_words(n):
"""The plot's two words of n letters: the first from a, the second
from n, round the alphabet."""
first = "".join(LETTERS[k % 26] for k in range(n))
second = "".join(LETTERS[(13 + k) % 26] for k in range(n))
return first, second
if __name__ == "__main__":
print(f"{'n':>7} {'cells':>12}")
for n in (10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10_000, 20_000, 50_000, 100_000):
print(f"{n:>7} {count(*plot_words(n)):>12}")
best, worst and average
Best, worst and average usually name different inputs of one size. Here the size is , the second word's length, and this page gives the first word letters too. Then every pair fills the same cells, whatever its letters. So the table has one column, under the name worst, and no average is worked out. In the grid below, from 1 up means for any of 1 or more.
A case is one kind of input: here, which letters. A bound says how fast its cost grows as the words grow.
The counts are in the grid below. A count is often made of pieces that grow at different speeds, and the fastest-growing piece swamps the rest. With its first row and column, the table holds numbers, as question 2 works out: at 1,000 letters each, 1,000,000 plus 2,001, and the 2,001 hardly matters. So how a cost grows is what tells one method from another, and the bounds keep just that.
| worsttwo words of letters each, whatever their letters | |
|---|---|
| cells filled | , from 1 up |
| how the cells filled grow in each case | |
| tight, | |
| ceiling, | |
| floor, | |
extra memory: A table of one number for each pair of starts, or two rows for the answer alone.
Extra memory is the room it needs on top of the input itself, while it runs.
| first word | second word | cells | edits |
|---|---|---|---|
| ape | ape | 9 | 0 |
| ape | pea | 9 | 2 |
| ape | dog | 9 | 3 |
| n | cells | numbers held |
|---|---|---|
| 1 | 1 | 4 |
| 2 | 4 | 9 |
| 3 | 9 | 16 |
| 7 | 49 | 64 |
| 100 | 10,000 | 10,201 |
| 1,000 | 1,000,000 | 1,002,001 |
where the formula comes from
Five questions, each worked line by line. Question 1 is the count the plot draws.
the move: a row for each letter
the line:order - p pe pea - given given given given a given 1 2 3 ap given 4 5 6 ape given 7 8 9 Ape into pea, each cell numbered in the order it is filled, row by row. Given cells are written first, not counted. 3 rows of 3, 9 cells. why it is allowed: Each letter of the first word has a row, and each row fills one cell for each letter of the second. Crate into cart fills 5 times 4, 20 cells.
the move: both of n letters
the line:why it is allowed: Here the first word has letters too, so is . For 3, 3 times 3, which is 9.
guess it, thenthe move: write it shorter
the line:why it is allowed: times is written , read squared. For 3, 9.
guess it, thenthe move: a ceiling
the line:why it is allowed: By line 3, as a number is at most itself.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 4, with the fixed multiple 1. reads is in, and means at most a fixed multiple of , from some on.
guess it, thenthe move: a floor
the line:why it is allowed: By line 3, as a number is at least itself.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 6, with the fixed multiple 1. means at least a fixed multiple of , above 0, from some on.
guess it, thenthe move: both together
the line:why it is allowed: Lines 5 and 7 bound by the same growth. means both.
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: count the rows and columns
the line:start - p pe pea - 0 1 2 3 a 1 1 2 2 ap 2 1 2 3 ape 3 2 1 2 Ape into pea, 4 rows of 4 numbers, 16 in all. The first row and column count, though no step fills them. why it is allowed: A row for the empty start, then one for each letter of the first word, so rows. The columns are the same for the second word. For 3, 4 times 4, which is 16.
the move: multiply out
the line:why it is allowed: times , then twice, then 1 times 1. For 3, 9 + 6 + 1, which is 16.
guess it, thenthe move: a ceiling
the line:why it is allowed: From 1 up, is at most , and so is 1, so is at most 3 lots of , and line 2's sum at most 4 lots. For 3, 16 is at most 36.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 3, with the fixed multiple 4.
guess it, thenthe move: a floor
the line:why it is allowed: By line 2: take away from , and is left, which is less. For 3, 16 is at least 9.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 5, with the fixed multiple 1.
guess it, thenthe move: both together
the line:why it is allowed: Lines 4 and 6 bound by the same growth.
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
the move: what a cell reads
the line:row - p pe pea a 1 1 2 2 ap 2 1 2 ? Ape into pea, filling the last cell of row ap. It reads 2 above, 2 to the left and 2 up and to the left, all in these two rows, and writes 3. why it is allowed: Above and up and to the left are in the row above, and to the left is in the cell's own row. So once a row is full, the rows above it are never read again.
the move: keep two rows
the line:why it is allowed: So keep two rows of numbers, the one above and the one being filled, and reuse them. For 3, 8 numbers, against the table's 16.
guess it, thenthe move: but not the edits
the line:why it is allowed: Each step back climbs at most one row, so the walk passes every row, and from 3 letters on, two rows have thrown away a row it needs. So two rows give how many edits, not which ones, as the books note (volume three, chapter 40).
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: the promise
the line:why it is allowed: This is what to prove. Lines 2 to 10 prove it, cell by cell, in the order the cells are filled.
the move: it starts right
the line:why it is allowed: Each edit adds or removes at most one letter. So nothing into a start takes at least one edit a letter, and one insert a letter does it: nothing into car, 3. A start into nothing is the same, with deletes.
guess it, thenthe move: suppose so far
the line:why it is allowed: Cells fill row by row, so the three a cell reads, above, to the left, and up and to the left, are written or filled before it. Suppose, for now, that each holds the fewest. This is fair, as cells are checked in the order they are filled, from line 2's first row and column, so the three it reads are checked already.
guess it, thenthe move: a list is a line-up
the line:sale seal edit s s keep - e insert a a keep l l keep e - delete Sale into seal as a line-up, read down, 2 edits. A dash is a gap. why it is allowed: Follow each letter of the first start through the list. It is deleted, or it ends as a letter of the second start, maybe changed. Edits never reorder letters, so these pairs stay in order, and the rest of the second start was inserted. Each delete, insert and changed pair took an edit of its own.
guess it, thenthe move: the line-up's last column
the line:why it is allowed: It holds the first start's last letter over a gap, a gap over the second's last letter, or the two last letters. Take it away, and the rest lines up the starts of the cell above, to the left, or up and to the left. Sale into seal ends e over a gap, a delete, and the rest lines up sal into seal, the cell above.
guess it, thenthe move: so at least
the line:why it is allowed: By line 4, any list costs at least its line-up, and by line 5 that is the line-up's last column plus a line-up of a smaller cell's starts. Done as edits one by one, that smaller line-up is a list for the smaller cell, so by line 3 it costs at least that cell. Up and to the left adds 0 when the last letters match, else 1.
guess it, thenthe move: each can be done
the line:why it is allowed: Take a fewest list for that smaller cell, by line 3. End it with the edit line 5 pairs with that cell: a delete for above, an insert for the left, a keep or replace for up-left. For cr into ca, up and to the left holds 0, c into c, and replacing r with a makes 1.
guess it, thenthe move: so the cell is right
the line:why it is allowed: By lines 6 and 7. When the last letters differ, that is what the method writes.
guess it, thenthe move: a match copies
the line:why it is allowed: From a fewest list for above, delete the second start's last letter at the end, and you reach up-left's starts. So up-left costs at most above + 1. From a fewest list for the left, first insert the first start's last letter, and the same holds. So by line 8, copying up-left is right. For crat into cart, t matches t: up-left holds 2, and above + 1 and left + 1 are both 3.
guess it, thenthe move: every cell
the line:why it is allowed: By line 2, the first row and column are. By lines 3 to 9, each later cell is right once those before it are. So, filled in order, every cell is, the last included.
guess it, thenthe move: count them
the line:why it is allowed: Every number the table holds, each right by line 10: the same count as question 2's . For 3, 16.
guess it, then
try it with a small : at , line 11 gives , which you can work out by hand
the move: count the calls
the line:call asks for a into b - into b, a into -, - into - - into b nothing a into - nothing - into - nothing Turning a into b takes 4 calls: the first asks for three cells, and each of those, with an empty word, asks for nothing. n calls 3 times the row above 0 1 - 1 4 3 2 19 12 3 94 57 4 481 282 5 2,524 1,443 Calls counted by running the plain method. Each row is more than 3 times the row above. why it is allowed: A call is one ask for a cell's answer. The first call counts 1. Its last letters differ, so it asks for above, to the left and up and to the left. Each makes all its own calls, as nothing is written down. A pair with an empty word asks for nothing.
the move: more letters, more calls
the line:why it is allowed: Above asks for up-left as its own left, and to the left asks for it as its own above. With an empty word, each makes 1 call, as up-left does.
guess it, thenthe move: each at least up-left
the line:why it is allowed: By line 2, each of line 1's three cells makes at least up-left's calls, and up-left has letters each. For 3, 94 is at least 1 + 3 times 19, which is 58.
guess it, thenthe move: leave out the 1
the line:why it is allowed: Line 3 without the first call's 1. For 3, 94 is more than 57.
guess it, thenthe move: repeat from 0
the line:why it is allowed: 0 letters make 1 call, and by line 4, each letter more at least triples the calls. So letters make at least 3s multiplied together. Name that : the calls are at least . For 10, at least 59,049, and counted, 12,146,179, against the table's 100 cells.
guess it, then
try it with a small : at , line 5 gives , which you can work out by hand
count it yourself
Ape into pea, step by step. Each cell filled adds 1 to the count on its own step.
| step | what happens | cells filled |
|---|---|---|
| 1 | Turn ape into pea. An empty start takes one edit a letter, so the first row counts inserts and the first column counts deletes. | 0 |
| 2 | a is not p, so take one edit more than the cheapest of above, 1, for a delete, to the left, 1, for an insert, and up and to the left, 0, for a replace: 1. | 1 |
| 3 | a is not e, so take one edit more than the cheapest of above, 2, for a delete, to the left, 1, for an insert, and up and to the left, 1, for a replace: 2. | 2 |
| 4 | Both letters are a, so this cell needs no edit of its own. Copy 2 from the cell up and to the left. | 3 |
| 5 | Both letters are p, so this cell needs no edit of its own. Copy 1 from the cell up and to the left. | 4 |
| 6 | p is not e, so take one edit more than the cheapest of above, 2, for a delete, to the left, 1, for an insert, and up and to the left, 1, for a replace: 2. | 5 |
| 7 | p is not a, so take one edit more than the cheapest of above, 2, for a delete, to the left, 2, for an insert, and up and to the left, 2, for a replace: 3. | 6 |
| 8 | e is not p, so take one edit more than the cheapest of above, 1, for a delete, to the left, 3, for an insert, and up and to the left, 2, for a replace: 2. | 7 |
| 9 | Both letters are e, so this cell needs no edit of its own. Copy 1 from the cell up and to the left. | 8 |
| 10 | e is not a, so take one edit more than the cheapest of above, 3, for a delete, to the left, 1, for an insert, and up and to the left, 2, for a replace: 2. | 9 |
| 11 | Done: turning ape into pea takes 2 edits at the fewest. | 9 |
In all, 9 cells filled. The formula from section 4, , gives at : the same.
where you meet it
Vladimir Levenshtein defined the distance in 1965, as the books note (volume three, chapter 40). Robert Wagner and Michael Fischer published this table for it in 1974, in the Journal of the ACM.
Near matches in a database
The database PostgreSQL has a levenshtein function in its fuzzystrmatch add-on. Given two words or names of up to 255 characters each, it returns the fewest edits between them, so a search can find names spelt almost right.
source: the PostgreSQL documentation, fuzzystrmatch (opens in a new tab)
Typing slips
Fred Damerau found in 1964 that over 80 per cent of the spelling errors he studied were a single slip: one letter deleted, inserted or replaced, or two neighbours swapped. So spelling checkers often count a swap as one edit, a variant named after him and Levenshtein.
source: F. J. Damerau, A technique for computer detection and correction of spelling errors (opens in a new tab), Communications of the ACM 7, 1964, and the books' volume three, chapter 40
Proteins
In 1970, Saul Needleman and Christian Wunsch published the same kind of table to compare proteins, letter by letter. Biologists still line sequences up this way, scoring how alike they are instead of counting edits.
source: S. B. Needleman and C. D. Wunsch, their paper (opens in a new tab), Journal of Molecular Biology 48, 1970, and the books' volume three, chapter 40
what is used instead
For whole genomes, the table's cells are far too many. Tools such as BLAST find good line-ups quickly instead, though they can miss the best, as the books note (volume three, chapter 40).
how it compares
The plain method asks for the same three cells as calls, with no table, so it works the same starts out again and again. A memo keeps each answer once worked out, as the page on solving each smaller problem once shows. The table fills every cell once, row by row, with no calls, and two rows are enough for the answer alone. Longest common subsequence is the most letters both words share in the same order: c, a and t in crate and cart. It fills the same kind of table, counting shared letters instead of edits, as the books note (volume three, chapter 40).
| way | work, 8 letters each | numbers kept |
|---|---|---|
| plain method | 398,593 calls | none |
| with a memo | 193 calls | 81 |
| the table | 64 cells | 81 |
| two rows | 64 cells | 18 |