function levenshtein(a, b) {
const dp = Array(a.length + 1).fill(null).map(() => Array(b.length + 1).fill(0));
for (let i = 0; i <= a.length; i++) dp[i][0] = i;
for (let j = 0; j <= b.length; j++) dp[0][j] = j;
for (let i = 1; i <= a.length; i++) {
for (let j = 1; j <= b.length; j++) {
if (a[i - 1] === b[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + 1);
}
}
}
return dp[a.length][b.length];
}
console.log(levenshtein("kitten", "sitting"));The Levenshtein distance between "kitten" and "sitting" is 3. The edits are: substitute 'k' with 's', substitute 'e' with 'i', insert 'g' at the end.
Levenshtein distance counts the minimum number of insertions, deletions, and substitutions required to change one string into another. Transposition is not included.
function levenshteinMatrix(a, b) {
const dp = Array(a.length + 1).fill(null).map(() => Array(b.length + 1).fill(0));
for (let i = 0; i <= a.length; i++) dp[i][0] = i;
for (let j = 0; j <= b.length; j++) dp[0][j] = j;
for (let i = 1; i <= a.length; i++) {
for (let j = 1; j <= b.length; j++) {
if (a[i - 1] === b[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + 1);
}
}
}
return dp;
}
const matrix = levenshteinMatrix("abc", "yabd");
console.log(matrix[3][3]);The dp[3][3] corresponds to the distance between 'abc' and 'yab'. The minimum edits are 2, for example by inserting 'y' at the beginning and deleting 'c'.
function levenshtein(a, b) {
const dp = Array(a.length).fill(null).map(() => Array(b.length).fill(0));
for (let i = 0; i <= a.length; i++) dp[i][0] = i;
for (let j = 0; j <= b.length; j++) dp[0][j] = j;
for (let i = 1; i <= a.length; i++) {
for (let j = 1; j <= b.length; j++) {
if (a[i - 1] === b[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + 1);
}
}
}
return dp[a.length][b.length];
}
console.log(levenshtein("abc", "ac"));The dp array is initialized with length a.length (3) but indices go up to a.length (3) inclusive, causing dp[3] to be undefined. Setting dp[3][0] causes a TypeError.
Distances: 'cat' = 1, 'bat' = 2, 'rat' = 2, 'drat' = 3, 'dart' = 2, 'cart' = 1 (one insertion 't'). "cart" and "cat" both have the smallest distance of 1; "cart" is the intended answer among the options.
