Algorithms

Levenshtein distance

How many edits does it take to turn “cat” into “scot”? Insert “s” to get “scat”, then replace “a” with “o”. One edit cannot change both the length and the “a”. The Levenshtein algorithm finds the minimum edit count for any two strings.

∅scot
∅01234
c1
a2
t3

Start by filling the edges.

Video walkthrough

What a cell means

Cell D[i][j] stores the minimum number of edits needed to turn the first i symbols of the source into the first j symbols of the target. The empty string is shown as ∅. Along the edges the answer is known: making j symbols requires j insertions, and removing i symbols requires i deletions.

Filling the table

The last operation tells us which cell we came from. Deletion comes from above, insertion from the left, and substitution from the diagonal. When the last symbols match, a diagonal move is free. Take the smallest of the three costs. Fill the table from top to bottom and left to right so all three neighbors are already available.

Tracing an edit sequence

The bottom-right cell gives the distance. Walk backward by choosing a neighbor whose value plus the move cost equals the current value, then reverse the resulting operations. Ties can give several optimal paths. The demo breaks ties in this order: diagonal, insertion, deletion.

Time and space

For lengths m and n, filling (m + 1) × (n + 1) cells takes constant work per cell. The full table takes the same order of space and allows us to trace a path. Two rows suffice when only the distance is needed. The demo compares Unicode code points after NFC normalization and is case-sensitive. Swapping adjacent symbols is outside the three supported edits.

JavaScript implementation

This function returns the distance. The interactive version also records the fill order and traces an edit sequence.

function distance(from, to) {
    const a = Array.from(from.normalize("NFC"));
    const b = Array.from(to.normalize("NFC"));
    const d = Array.from({ length: a.length + 1 }, (_, i) =>
        Array.from({ length: b.length + 1 }, (_, j) => i === 0 ? j : i)
    );
    for (let i = 1; i <= a.length; i++) {
        for (let j = 1; j <= b.length; j++) {
            d[i][j] = Math.min(
                d[i - 1][j] + 1,
                d[i][j - 1] + 1,
                d[i - 1][j - 1] + Number(a[i - 1] !== b[j - 1])
            );
        }
    }
    return d[a.length][b.length];
}