Dynamic programmingAnimated
Levenshtein Distance
Edit distance with unit costs. Same algorithm as edit distance.
Time
O(n · m)
Extra space
O(min(n, m))
Use it for
Fuzzy search and autocorrect.
How it works
- Levenshtein distance counts the fewest single-character edits (insert, delete, substitute) between two strings.
- Fill a table where cell (i, j) is the distance between the first i letters of A and the first j letters of B.
- Matching letters copy the diagonal; otherwise add 1 to the cheapest of the three neighbours.
- The bottom-right cell is the answer. Spell checkers and fuzzy search use it.
Watch it run
Loading animation…