Edit Distance program in Javascript

Edit Distance program in Javascript

Algorithm, Dynamic Programming, Javascript, Trending

We have 2 strings and we can perform below operations on st1 to make it same as str2.

  1. Insert
  2. Remove
  3. 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)

References:

https://www.geeksforgeeks.org/edit-distance-dp-5/

One thought on “Edit Distance program in Javascript

Leave a Reply