Edit Distance program in Javascript
We have 2 strings and we can perform below operations on st1 to make it same as str2.
- Insert
- Remove
- Replace
Input: str1 = “cat”, str2 = “cut”
Output: 1
We can convert str1 into str2 by replacing ‘a’ with ‘u’.Input: str1 = “sunday”, str2 = “saturday”
Output: 3
Last three and first characters are same. We basically
need to convert “un” to “atur”. This can be done using
below three operations.
Replace ‘n’ with ‘r’, insert t, insert a
This program can be solved using dynamic programming. Please find the solution below
let str1 = "sunday"
let str2 = "saturday"
let m = str1.length-1;
let n = str2.length-1;
let dp = {}
for(let i = 0; i<=m; i++){
dp[i] = [];
}
for(let i = 0; i<=m; i++){
for(let j =0; j<=n; j++){
if(i == 0)
dp[i][j] = j;
else if(j == 0)
dp[i][j] = i;
else if(str1[i-1] == str2[j-1]){
dp[i][j] = dp[i - 1][j - 1]
}
else{
dp[i][j] = 1 + Math.min( dp[i][j-1], dp[i-1][j], dp[i-1][j-1]);
}
}
}
console.log(dp[m][n]);
Time Complexity: O(m x n)
One thought on “Edit Distance program in Javascript”
Thanks for your blog, nice to read. Do not stop.