Edit Distance in TypeScript

function minDistance(word1: string, word2: string): number {
  const m = word1.length;
  const n = word2.length;
  
  // Create a 2D array to store the minimum number of operations
  const dp: number[][] = [];
  
  // Initialize the dp array with 0s
  for (let i = 0; i <= m; i++) {
    dp[i] = new Array(n + 1).fill(0);
  }
  
  // Fill the first row and column of the dp array
  for (let i = 1; i <= m; i++) {
    dp[i][0] = i;
  }
  for (let j = 1; j <= n; j++) {
    dp[0][j] = j;
  }
  
  // Fill the dp array
  for (let i = 1; i <= m; i++) {
    for (let j = 1; j <= n; j++) {
      if (word1[i - 1] === word2[j - 1]) {
        // If the characters are the same, no operation is needed
        dp[i][j] = dp[i - 1][j - 1];
      } else {
        // If the characters are different, choose the minimum of insert, delete, or replace
        dp[i][j] = 1 + Math.min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]);
      }
    }
  }
  
  // Return the minimum number of operations
  return dp[m][n];
}

PrevNext