Edit Distance Levenshtein DP (JavaScript)

Compute the Levenshtein edit distance between two strings with insert, delete, and substitute operations each costing one.

JavascriptData Integrity

Code

javascriptsnippet
15 lines
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

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.