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
- The edit distance is the fewest single-letter insertions, deletions and substitutions needed to turn one word into another.
- 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).
- If the letters match, copy the diagonal. Otherwise 1 + the smallest of: diagonal (substitute), above (delete), left (insert).
- The bottom-right cell is the answer. O(m × n). This is also called Levenshtein distance.
Watch it run
Loading animation…