The algorithm that measures how different two strings are
The Levenshtein distance is a string metric for measuring the difference between two sequences. Informally, it's the minimum number of single-character edits (insertions, deletions, or substitutions) required to change one word into another.
Example:
Distance between "kitten" and "sitting" is 3:
The Levenshtein distance is computed using dynamic programming. We build a matrix where each cell represents the distance between substrings.
Suggest corrections by finding dictionary words with smallest distance to misspelled words
Measure similarity between genetic sequences to study mutations and evolution
Find approximate matches in databases when exact matching isn't possible
function levenshteinDistance(a, b) {
const matrix = [];
// Initialize matrix
for (let i = 0; i <= b.length; i++) {
matrix[i] = [i];
}
for (let j = 0; j <= a.length; j++) {
matrix[0][j] = j;
}
// Fill the matrix
for (let i = 1; i <= b.length; i++) {
for (let j = 1; j <= a.length; j++) {
const cost = a[j-1] === b[i-1] ? 0 : 1;
matrix[i][j] = Math.min(
matrix[i-1][j] + 1, // deletion
matrix[i][j-1] + 1, // insertion
matrix[i-1][j-1] + cost // substitution
);
}
}
return matrix[b.length][a.length];
}