Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the first cell of the dp array with the grid's first cell value.
DSA Java
dp[0][0] = grid[1]0][0];
Attempts:
3 left
💡 Hint
Common Mistakes
Using dot notation instead of square brackets to access array elements.
Using multiplication or addition symbols instead of brackets.
✗ Incorrect
We use square brackets to access elements in a 2D array in Java, so dp[0][0] = grid[0][0]; is correct.
2fill in blank
mediumComplete the code to fill the first row of the dp array by accumulating sums from the left.
DSA Java
for (int j = 1; j < n; j++) { dp[0][j] = dp[0][j - 1] [1] grid[0][j]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication instead of addition.
Forgetting to accumulate sums and just assigning the current grid value.
✗ Incorrect
We add the current grid value to the sum from the left cell to accumulate the path sum.
3fill in blank
hardFix the error in the nested loop condition to correctly iterate over rows starting from 1.
DSA Java
for (int i = [1]; i < m; i++) { for (int j = 1; j < n; j++) { dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Starting the loop from 0 which overwrites the first row.
Using the wrong variable or limit in the loop.
✗ Incorrect
We start from 1 because the first row and first column are already initialized.
4fill in blank
hardFill both blanks to complete the code that initializes the first column of the dp array by accumulating sums from above.
DSA Java
for (int i = 1; i [1] m; i++) { dp[i][0] = dp[i - 1][0] [2] grid[i][0]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using <= instead of < in the loop condition causing index errors.
Using subtraction instead of addition when accumulating sums.
✗ Incorrect
The loop runs while i is less than m, and we add the current grid value to the sum from above.
5fill in blank
hardFill both blanks to complete the method that returns the minimum path sum from top-left to bottom-right in the grid.
DSA Java
public int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[][] dp = new int[m][n];
dp[0][0] = grid[0][0];
for (int i = 1; i < m; i++) {
dp[i][0] = dp[i - 1][0] [1] grid[i][0];
}
for (int j = 1; j < n; j++) {
dp[0][j] = dp[0][j - 1] [2] grid[0][j];
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
}
}
return dp[m - 1][n - 1];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using dot notation instead of brackets for array access.
Using subtraction instead of addition when accumulating sums.
✗ Incorrect
We use brackets to access grid elements and add values to accumulate sums in dp.
