Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the 2D array for dynamic programming.
DSA Javascript
const dp = Array(m + 1).fill().map(() => Array([1]).fill(0));
Attempts:
3 left
💡 Hint
Common Mistakes
Using m+1 for both dimensions, which causes incorrect table size.
Using n instead of n+1, missing the base case column.
✗ Incorrect
The dp array should have dimensions (m+1) x (n+1) to cover all prefixes of both strings.
2fill in blank
mediumComplete the code to fill the base case for the first column of the dp table.
DSA Javascript
for (let i = 0; i <= m; i++) { dp[i][0] = [1]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Setting dp[i][0] to 0, which ignores the cost of deletions.
Using n or m instead of i, which is incorrect indexing.
✗ Incorrect
The first column represents converting the first i characters of word1 to an empty string, so dp[i][0] = i.
3fill in blank
hardFix the error in the condition that checks if characters are equal.
DSA Javascript
if (word1[i - 1] [1] word2[j - 1]) { dp[i][j] = dp[i - 1][j - 1]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!=' which reverses the logic.
Using '>=' or '<=' which are not meaningful for character equality.
✗ Incorrect
We check if characters are equal using '=='. If equal, no operation is needed, so dp[i][j] = dp[i-1][j-1].
4fill in blank
hardFill both blanks to compute the minimum edit distance considering insert, delete, and replace operations.
DSA Javascript
dp[i][j] = 1 + Math.min(dp[i - 1][j], [1], [2]);
Attempts:
3 left
💡 Hint
Common Mistakes
Using invalid indices like dp[i][j+1] or dp[i+1][j] which are out of bounds.
Mixing up insert and delete indices.
✗ Incorrect
The three operations are delete (dp[i-1][j]), insert (dp[i][j-1]), and replace (dp[i-1][j-1]). We take the minimum plus one.
5fill in blank
hardFill all three blanks to complete the function that returns the edit distance between word1 and word2.
DSA Javascript
function editDistance(word1, word2) {
const m = word1.length;
const n = word2.length;
const dp = Array(m + 1).fill().map(() => Array([1]).fill(0));
for (let i = 0; i <= m; i++) dp[i][0] = i;
for (let j = 0; j <= n; j++) dp[0][j] = j;
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (word1[i - 1] [2] word2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
}
}
}
return dp[[3]][n];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using m+1 for columns instead of n+1.
Using '!=' instead of '==' for character comparison.
Returning dp[m+1][m+1] which is out of bounds.
✗ Incorrect
The dp array has n+1 columns, character equality uses '==', and the final answer is dp[m][n].
