Levenshtein distance in JavaScript
Advanced · 4 min read
Type recieve and a spell checker suggests receive. Search for lagso and a good search box still finds lagos. Behind both is a way of measuring how different two words are. The best known is the Levenshtein distance: the smallest number of single-character edits that turn one string into the other.
In this tutorial you will learn the three kinds of edit, see how a table of small answers builds up to the big one, and write levenshtein(a, b) keeping only two rows of that table. You should know for loops, arrays and Math.min. The table idea, called dynamic programming, is explained from zero.
The three edits
Each edit changes one character and costs 1:
- Insert a character:
cattocart. - Delete a character:
carttocat. - Substitute one character for another:
cattocut.
kitten to sitting takes 3: substitute k for s, substitute e for i, and insert g at the end. There is no way to do it in 2, so the distance is 3.
Small answers build big ones
Trying every possible sequence of edits would take forever. Instead, we solve small versions of the problem first and reuse them. Make a table where the cell in row i and column j holds the distance between the first i characters of a and the first j characters of b.
Each cell is the cheapest of three moves:
- the cell above plus 1 (delete a character from
a), - the cell to the left plus 1 (insert a character into
a), - the cell diagonally above-left plus 0 if the two characters match, or 1 if they don't (substitute).
Solving a problem by filling in a table of smaller answers is called dynamic programming.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
61 Levenshtein distance
hardCount the single-character insertions, deletions and substitutions needed to turn one string into another. 'kitten' to 'sitting' is 3.
Stuck? Three hints, smallest first
- 1. Fill a table where cell (i, j) is the distance between the first i and first j characters.
- 2. Each cell is the cheapest of: delete, insert, or substitute.
- 3. Only the previous row is ever needed, so two arrays are enough.
Step 1: the easy cases
console.log('lagos' === 'lagos'); // true, so the distance is 0
console.log(''.length, 'abc'.length); // 0 3
If the strings are equal, the distance is 0. If one is empty, you need one insertion (or deletion) for every character of the other, so the distance is the other string's length. The function checks these first.
Step 2: the first row
Turning an empty string into the first j characters of b takes j insertions. So the top row of the table is just 0, 1, 2, and so on:
const b = 'sitting';
const previous = [...Array(b.length + 1).keys()];
console.log(previous); // [ 0, 1, 2, 3, 4, 5, 6, 7 ]
Array(8) makes an empty array of length 8, keys() gives its indexes 0 to 7, and [...] collects them into an array.
Step 3: fill one row from the row above
const a = 'k';
const b = 'sitting';
const previous = [0, 1, 2, 3, 4, 5, 6, 7];
const i = 1;
const current = [i];
for (let j = 1; j <= b.length; j++) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + cost);
}
console.log(current); // [ 1, 1, 2, 3, 4, 5, 6, 7 ]
The new row starts with i, since turning i characters into nothing takes i deletions. Then each cell takes the cheapest of the three moves. k against s is a substitution, so current[1] is 1. The strings are counted from 1 in the table but from 0 in JavaScript, which is why we compare a[i - 1] with b[j - 1].
Step 4: only two rows at a time
Each row only ever looks at the row above it. So we don't need the whole table, just the previous row and the current one. When a row is done, it becomes the previous row for the next:
function levenshtein(a, b) {
if (a === b) return 0;
if (a === '') return b.length;
if (b === '') return a.length;
let previous = [...Array(b.length + 1).keys()];
for (let i = 1; i <= a.length; i++) {
const current = [i];
for (let j = 1; j <= b.length; j++) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
current[j] = Math.min(
previous[j] + 1,
current[j - 1] + 1,
previous[j - 1] + cost
);
}
previous = current;
}
return previous[b.length];
}
console.log(levenshtein('kitten', 'sitting')); // 3
console.log(levenshtein('flaw', 'lawn')); // 2
console.log(levenshtein('saturday', 'sunday')); // 3
console.log(levenshtein('', 'abc')); // 3
console.log(levenshtein('sitting', 'kitten')); // 3
The answer is the last cell of the last row. The order of the arguments doesn't matter: sitting to kitten is also 3, because every insert one way is a delete the other way.
Step 5: swaps cost two
function levenshtein(a, b) {
if (a === b) return 0;
if (a === '') return b.length;
if (b === '') return a.length;
let previous = [...Array(b.length + 1).keys()];
for (let i = 1; i <= a.length; i++) {
const current = [i];
for (let j = 1; j <= b.length; j++) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + cost);
}
previous = current;
}
return previous[b.length];
}
console.log(levenshtein('teh', 'the')); // 2
console.log(levenshtein('abc', 'cba')); // 2
console.log(levenshtein('👍', '')); // 2
There is no "swap two letters" edit, so the common typo teh costs 2, the same as two unrelated substitutions. A variant called Damerau-Levenshtein adds a swap at cost 1, which suits typo checking better.
The last line shows another limit: the loop walks code units, the small pieces JavaScript stores strings in, and most emoji take two. So one emoji counts as two edits.
The full solution
The panel has levenshtein and prints the distance for four pairs of words. Press Run, then read the checks underneath, including the one about swaps.
function levenshtein(a, b) {
if (a === b) return 0;
if (a === '') return b.length;
if (b === '') return a.length;
// Row 0: turning '' into the first j characters of b costs j insertions.
let previous = [...Array(b.length + 1).keys()];
for (let i = 1; i <= a.length; i++) {
const current = [i];
for (let j = 1; j <= b.length; j++) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
current[j] = Math.min(
previous[j] + 1, // delete from a
current[j - 1] + 1, // insert into a
previous[j - 1] + cost // substitute
);
}
previous = current; // only the last row matters
}
return previous[b.length];
}
for (const [a, b] of [['kitten', 'sitting'], ['flaw', 'lawn'], ['saturday', 'sunday'], ['abc', 'cba']]) {
console.log((a + ' -> ' + b).padEnd(24), levenshtein(a, b));
}
Output
11 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 11 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('kitten to sitting', levenshtein('kitten', 'sitting'), 3);
test('flaw to lawn', levenshtein('flaw', 'lawn'), 2);
test('identical strings are zero apart', levenshtein('lagos', 'lagos'), 0);
test('an empty string costs one edit per character', levenshtein('', 'abc'), 3);
test('and the same the other way round', levenshtein('abc', ''), 3);
test('saturday to sunday', levenshtein('saturday', 'sunday'), 3);
test('the distance is symmetric', levenshtein('sitting', 'kitten'), levenshtein('kitten', 'sitting'));
test('a reversal costs two substitutions: there is no transpose operation', levenshtein('abc', 'cba'), 2);
test('the distance never exceeds the longer string', levenshtein('abc', 'wxyz') <= 4, true);
test('and the triangle inequality holds', levenshtein('kitten', 'sunday') <= levenshtein('kitten', 'sitting') + levenshtein('sitting', 'sunday'), true);
test('an emoji costs TWO edits, because the walk is over code units', levenshtein('👍', ''), 2);
Keeping only the previous row drops the memory from O(n × m) to O(m) and costs nothing except the ability to reconstruct which edits were needed. If you want the edit script rather than the count, keep the whole table and walk back through it.
No transposition is the property to remember: swapping two adjacent characters costs 2 here, so 'teh' and 'the' are as far apart as 'teh' and 'toa'. For typo correction that is usually wrong, and Damerau-Levenshtein — which adds a swap operation at cost 1 — is the variant you want.
Because it walks code units, an emoji counts as two edits. For user-facing fuzzy matching, run it over grapheme clusters instead, or a one-character difference in an emoji will outrank a real one in a word.
Common mistakes
- Comparing
a[i]withb[j]. The table is offset by one. Comparea[i - 1]withb[j - 1]. - Forgetting to start each row with
i. Withoutcurrent = [i], the left edge of the table is wrong and every answer is off. - Keeping the whole table when you only need the count. Two rows are enough, unless you want to list which edits were made.
Try it yourself
- Write
closest(word, list)that returns the word inlistwith the smallest distance toword. - Make the comparison ignore case, so
'Lagos'and'lagos'are 0 apart. - Run the function over
[...a]and[...b]so an emoji counts as one edit.