Complete the code to initialize the 2D array for dynamic programming.
int[,] dp = new int[[1], [2]];
The DP table size must be (length + 1) to include empty prefixes.
Complete the code to fill the first row of the DP table.
for (int j = 0; j < dp.GetLength(1); j++) dp[0, j] = [1];
The first row represents converting empty string to prefixes of word2, so cost equals j.
Fix the error in the condition to check if characters are equal.
if (word1[i - 1] [1] word2[j - 1]) dp[i, j] = dp[i - 1, j - 1];
We check if characters are equal to avoid extra cost.
Fill both blanks to compute the minimum edit distance for dp[i, j].
dp[i, j] = 1 + Math.Min(dp[i - 1, j], dp[i, [1]]); dp[i, j] = Math.Min(dp[i, j], 1 + dp[[2], j - 1]);
We consider deletion (dp[i-1,j]), insertion (dp[i,j-1]), and substitution (dp[i-1,j-1]) costs.
Fill all three blanks to complete the Levenshtein distance function.
public int LevenshteinDistance(string word1, string word2) {
int m = word1.Length;
int n = word2.Length;
int[,] dp = new int[m + 1, n + 1];
for (int i = 0; i <= m; i++) dp[i, 0] = i;
for (int j = 0; j <= n; j++) dp[0, j] = j;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (word1[i - 1] [1] word2[j - 1]) {
dp[i, j] = dp[i - 1, j - 1];
} else {
dp[i, j] = 1 + Math.Min(dp[i - 1, j], Math.Min(dp[i, [2]], dp[[3], j - 1]));
}
}
}
return dp[m, n];
}The function compares characters, then calculates minimum edits considering insertion, deletion, and substitution.
