Skip to content
StackDecode
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

  1. Levenshtein distance counts the fewest single-character edits (insert, delete, substitute) between two strings.
  2. Fill a table where cell (i, j) is the distance between the first i letters of A and the first j letters of B.
  3. Matching letters copy the diagonal; otherwise add 1 to the cheapest of the three neighbours.
  4. The bottom-right cell is the answer. Spell checkers and fuzzy search use it.

Watch it run

Loading animation…