1. Home
  2. Design & Analysis of Algorithms
  3. Edit Distance (Levenshtein)

Edit Distance (Levenshtein)

How many inserts, deletes and replacements turn one word into another? Fill a dynamic-programming table to find the minimum.

Interactive 3DIntermediate13 min readDAAUpdated

Drag to rotate · Right-drag to pan · Click, then scroll to zoom · Space play · Left arrowRight arrow step

What's happening

The edit distance (Levenshtein distance) counts the fewest single-letter inserts, deletes and replacements that turn one word into another. It powers spell checkers and “did you mean…?”. Press Solve.

Pseudocode

  1. for i ← 0 to m: dp[i][0] ← i // delete i letters
  2. for j ← 0 to n: dp[0][j] ← j // insert j letters
  3. for i ← 1 to m:
  4. for j ← 1 to n:
  5. if A[i] == B[j]: dp[i][j] ← dp[i−1][j−1] // free: letters match
  6. else:
  7. dp[i][j] ← 1 + min( dp[i−1][j], // delete
  8. dp[i][j−1], // insert
  9. dp[i−1][j−1] ) // substitute
  10. trace back from dp[m][n] to read the edit script
Read this model as text · 45 steps

One run of the model above, written out step by step. Useful with a screen reader, on a slow connection, or for quick revision. The values may differ from the run on your screen.

  1. The edit distance (Levenshtein distance) counts the fewest single-letter inserts, deletes and replacements that turn one word into another. It powers spell checkers and “did you mean…?”. Press Solve.
  2. dp[i][j] = fewest edits (insert, delete, substitute) to turn the first i letters of KITTEN into the first j letters of SITTING. Turning i letters into nothing costs i deletions; building j letters from nothing costs j insertions.
  3. 'K' ≠ 'S'. Delete (above) = 1, insert (left) = 1, substitute (diagonal) = 0. Take the cheapest and add 1: 1.
  4. 'K' ≠ 'I'. Delete (above) = 2, insert (left) = 1, substitute (diagonal) = 1. Take the cheapest and add 1: 2.
  5. 'K' ≠ 'T'. Delete (above) = 3, insert (left) = 2, substitute (diagonal) = 2. Take the cheapest and add 1: 3.
  6. 'K' ≠ 'T'. Delete (above) = 4, insert (left) = 3, substitute (diagonal) = 3. Take the cheapest and add 1: 4.
  7. 'K' ≠ 'I'. Delete (above) = 5, insert (left) = 4, substitute (diagonal) = 4. Take the cheapest and add 1: 5.
  8. 'K' ≠ 'N'. Delete (above) = 6, insert (left) = 5, substitute (diagonal) = 5. Take the cheapest and add 1: 6.
  9. 'K' ≠ 'G'. Delete (above) = 7, insert (left) = 6, substitute (diagonal) = 6. Take the cheapest and add 1: 7.
  10. 'I' ≠ 'S'. Delete (above) = 1, insert (left) = 2, substitute (diagonal) = 1. Take the cheapest and add 1: 2.
  11. 'I' = 'I': the letters match, so no edit is needed. Copy the diagonal value 1.
  12. 'I' ≠ 'T'. Delete (above) = 3, insert (left) = 1, substitute (diagonal) = 2. Take the cheapest and add 1: 2.
  13. 'I' ≠ 'T'. Delete (above) = 4, insert (left) = 2, substitute (diagonal) = 3. Take the cheapest and add 1: 3.
  14. 'I' = 'I': the letters match, so no edit is needed. Copy the diagonal value 4.
  15. 'I' ≠ 'N'. Delete (above) = 6, insert (left) = 4, substitute (diagonal) = 5. Take the cheapest and add 1: 5.
  16. 'I' ≠ 'G'. Delete (above) = 7, insert (left) = 5, substitute (diagonal) = 6. Take the cheapest and add 1: 6.
  17. 'T' ≠ 'S'. Delete (above) = 2, insert (left) = 3, substitute (diagonal) = 2. Take the cheapest and add 1: 3.
  18. 'T' ≠ 'I'. Delete (above) = 1, insert (left) = 3, substitute (diagonal) = 2. Take the cheapest and add 1: 2.
  19. 'T' = 'T': the letters match, so no edit is needed. Copy the diagonal value 1.
  20. 'T' = 'T': the letters match, so no edit is needed. Copy the diagonal value 2.
  21. 'T' ≠ 'I'. Delete (above) = 4, insert (left) = 2, substitute (diagonal) = 3. Take the cheapest and add 1: 3.
  22. 'T' ≠ 'N'. Delete (above) = 5, insert (left) = 3, substitute (diagonal) = 4. Take the cheapest and add 1: 4.
  23. 'T' ≠ 'G'. Delete (above) = 6, insert (left) = 4, substitute (diagonal) = 5. Take the cheapest and add 1: 5.
  24. 'T' ≠ 'S'. Delete (above) = 3, insert (left) = 4, substitute (diagonal) = 3. Take the cheapest and add 1: 4.
  25. 'T' ≠ 'I'. Delete (above) = 2, insert (left) = 4, substitute (diagonal) = 3. Take the cheapest and add 1: 3.
  26. 'T' = 'T': the letters match, so no edit is needed. Copy the diagonal value 2.
  27. 'T' = 'T': the letters match, so no edit is needed. Copy the diagonal value 1.
  28. 'T' ≠ 'I'. Delete (above) = 3, insert (left) = 1, substitute (diagonal) = 2. Take the cheapest and add 1: 2.
  29. 'T' ≠ 'N'. Delete (above) = 4, insert (left) = 2, substitute (diagonal) = 3. Take the cheapest and add 1: 3.
  30. 'T' ≠ 'G'. Delete (above) = 5, insert (left) = 3, substitute (diagonal) = 4. Take the cheapest and add 1: 4.
  31. 'E' ≠ 'S'. Delete (above) = 4, insert (left) = 5, substitute (diagonal) = 4. Take the cheapest and add 1: 5.
  32. 'E' ≠ 'I'. Delete (above) = 3, insert (left) = 5, substitute (diagonal) = 4. Take the cheapest and add 1: 4.
  33. 'E' ≠ 'T'. Delete (above) = 2, insert (left) = 4, substitute (diagonal) = 3. Take the cheapest and add 1: 3.
  34. 'E' ≠ 'T'. Delete (above) = 1, insert (left) = 3, substitute (diagonal) = 2. Take the cheapest and add 1: 2.
  35. 'E' ≠ 'I'. Delete (above) = 2, insert (left) = 2, substitute (diagonal) = 1. Take the cheapest and add 1: 2.
  36. 'E' ≠ 'N'. Delete (above) = 3, insert (left) = 2, substitute (diagonal) = 2. Take the cheapest and add 1: 3.
  37. 'E' ≠ 'G'. Delete (above) = 4, insert (left) = 3, substitute (diagonal) = 3. Take the cheapest and add 1: 4.
  38. 'N' ≠ 'S'. Delete (above) = 5, insert (left) = 6, substitute (diagonal) = 5. Take the cheapest and add 1: 6.
  39. 'N' ≠ 'I'. Delete (above) = 4, insert (left) = 6, substitute (diagonal) = 5. Take the cheapest and add 1: 5.
  40. 'N' ≠ 'T'. Delete (above) = 3, insert (left) = 5, substitute (diagonal) = 4. Take the cheapest and add 1: 4.
  41. 'N' ≠ 'T'. Delete (above) = 2, insert (left) = 4, substitute (diagonal) = 3. Take the cheapest and add 1: 3.
  42. 'N' ≠ 'I'. Delete (above) = 2, insert (left) = 3, substitute (diagonal) = 2. Take the cheapest and add 1: 3.
  43. 'N' = 'N': the letters match, so no edit is needed. Copy the diagonal value 2.
  44. 'N' ≠ 'G'. Delete (above) = 4, insert (left) = 2, substitute (diagonal) = 3. Take the cheapest and add 1: 3.
  45. Edit distance = 3. Walking back from the corner reads one cheapest script: replace K with S, replace E with I, insert G. Time and space O(m × n) = 42 cells.

Try this in the 3D model

  • Solve KITTEN → SITTING. Why is the answer 3, and which cells lie on the path?
  • Press Example: SUNDAY → SATURDAY. Find a cell where the letters match and the value is copied free from the diagonal.
  • Try two identical words. What does the path look like and what is the distance?
  • Try CAT → DOG. Do you need insertions or deletions, or only replacements?

Measuring how different two words are

When you type “recieve” a spell checker suggests “receive”. It finds the closest word by counting the fewest single-letter edits:

  • insert a letter,
  • delete a letter,
  • replace one letter by another.

The minimum number is the edit distance (or Levenshtein distance). KITTEN → SITTING needs 3: replace K with S, replace E with I, insert G.

The dynamic-programming idea

Let dp[i][j] be the edit distance between the first i letters of A and the first j letters of B.

  • dp[i][0] = i (delete everything) and dp[0][j] = j (insert everything).
  • If the last letters match: dp[i][j] = dp[i−1][j−1] (no cost).
  • Otherwise: dp[i][j] = 1 + min(dp[i−1][j], dp[i][j−1], dp[i−1][j−1]), corresponding to delete, insert and replace.
for i in 1..m:
    for j in 1..n:
        if A[i] == B[j]:  dp[i][j] = dp[i−1][j−1]
        else:             dp[i][j] = 1 + min(delete, insert, replace)
answer = dp[m][n]

Reading the table

Each cell depends on its left, upper and upper-left neighbours, so you can fill it row by row. Starting at the bottom-right corner and always stepping to the neighbour that explains the value gives the edit script. A diagonal step with the same value is a match, a diagonal step with +1 is a replacement, a step up is a deletion and a step left is an insertion.

It is the same table-filling pattern as the longest common subsequence; LCS only allows inserts and deletes.

Code

def edit_distance(a, b):
    m, n = len(a), len(b)
    dp = [[0] * (n + 1) for _ in range(m + 1)]
    for i in range(m + 1):
        dp[i][0] = i
    for j in range(n + 1):
        dp[0][j] = j
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if a[i - 1] == b[j - 1]:
                dp[i][j] = dp[i - 1][j - 1]
            else:
                dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1])
    return dp[m][n]

print(edit_distance("kitten", "sitting"))   # 3

Where is it used?

Spell checkers and autocorrect, DNA sequence alignment, plagiarism detection, diff tools, search with typos, and speech or OCR error measurement.

Common mistakes

  • Forgetting the base row and column, which must count 0, 1, 2, …
  • Adding 1 even when the letters match.
  • Using min(left, up) only and forgetting the diagonal (replace).
  • Confusing the table index (1-based, with an extra row and column) with string index (0-based).

Complexity at a glance

Case / operationTimeWhy
Fill the tableO(m × n)Each of the (m+1)(n+1) cells looks at three neighbours.
MemoryO(m × n)Can be reduced to O(min(m, n)) if only the distance is needed.
Extra spaceO(m × n) table

Quick check

Test yourself — pick an answer to see if you got it.

1. Which three operations does Levenshtein distance allow?

2. What is the edit distance between "CAT" and "CUT"?

3. When A[i] = B[j], what is dp[i][j]?

4. What do the first row and column of the table contain?

Saved in this browser.
Spotted a mistake or a bug in the 3D model?

Report a mistake

in Edit Distance (Levenshtein). Thank you — every report makes the lesson better for the next reader.

We'll also include a link to the step of the 3D model you're on and your browser type, so we can reproduce it.