Edit Distance Levenshtein DP Typed
Compute the Levenshtein edit distance between two strings with typed insert, delete, and substitute operations.
Code
function editDistance(a: string, b: string): number {
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
Edit Distance Levenshtein DP Typed is built around the function editDistance.
Iteration is nested: for (let j = 0; j <= n; j++) prev[j] = j; frames the pass, for (let i = 1; i <= m; i++) does the per-item step.
Using it
The main signature reads function editDistance(a: string, b: string)
Key statements
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
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. The file defines `editDistance` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.