Skip to content

Edit distance explained: how Levenshtein counts the changes between two strings

Blog / Published 

The Levenshtein distance between two strings is the smallest number of single-character edits needed to turn one into the other. The allowed edits are inserting a character, deleting one, and substituting one character for another. It is also called edit distance, and it is the number behind many spelling suggestions and fuzzy searches.

A worked example

Turning kitten into sitting takes three edits: substitute k with s, substitute e with i, and insert g at the end. No sequence of fewer edits does it, so the distance is 3.

The distance between two identical strings is 0, and the distance from an empty string to a string of length n is n, because every character must be inserted.

How it is computed

The classic method fills a table with one row per character of the first string and one column per character of the second. Each cell holds the cheapest way to reach that prefix pair, and the answer is the bottom-right cell. The table needs time proportional to the product of the two lengths, which is fine for words and short lines but slow for long documents.

Damerau's variant

The plain version counts swapping two adjacent characters, such as teh to the, as two edits. Damerau's extension adds transposition as a single edit. Spell checkers often use it, because transposition is one of the most common typing mistakes.

Where it is used

Compare it yourself

The Levenshtein distance tool prints the number for two strings in your browser. To see the actual changes line by line rather than a single number, the text diff tool marks what was added and removed.

What the number does not tell you

A distance of 1 is not always a typo. cat and bat are one edit apart, and so are 1 and 7. Pick a threshold that fits the data, and check the matches you get back.

Written by Ján Turský

Creator of TextArray — building free, privacy-first tools that run entirely in your browser.