Edit Distance Levenshtein DP (JavaScript)
Compute the Levenshtein edit distance between two strings with insert, delete, and substitute operations each costing one.
Code
function editDistance(a, b) {
const m = a.length, n = b.length;
let prev = new Array(n + 1);
for (let j = 0; j <= n; j++) prev[j] = j;
for (let i = 1; i <= m; i++) {
const curr = new Array(n + 1);
curr[0] = i;
for (let j = 1; j <= n; j++) {
if (a[i - 1] === b[j - 1]) curr[j] = prev[j - 1];
else curr[j] = 1 + Math.min(prev[j], curr[j - 1], prev[j - 1]);
}
prev = curr;
}
return prev[n];
}How the snippet works
Count the function editDistance as the entire surface area of Edit Distance Levenshtein DP (JavaScript).
The structure is a loop within a loop: for (let j = 0; j <= n; j++) prev[j] = j; outside, for (let i = 1; i <= m; i++) inside.
Applying it
The primary signature is function editDistance(a, b)
Statements that matter
return prev[n];
Interactive Tools for This Topic
Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does this require external packages?
- No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `editDistance` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.