Skip to content
StackDecode
Dynamic programmingAnimated

Edit Distance

Fewest insertions, deletions and substitutions to turn one string into another.

Time

O(n · m)

Extra space

O(n · m)

Use it for

Spell checking, fuzzy matching.

How it works

  1. The edit distance is the fewest single-letter insertions, deletions and substitutions needed to turn one word into another.
  2. Cell (i, j) = distance between the first i letters of A and the first j letters of B. The first row and column are just i and j (all insertions or deletions).
  3. If the letters match, copy the diagonal. Otherwise 1 + the smallest of: diagonal (substitute), above (delete), left (insert).
  4. The bottom-right cell is the answer. O(m × n). This is also called Levenshtein distance.

Watch it run

Loading animation…