Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the first cell of the dp grid with the value from the input grid.
DSA C++
dp[0][0] = grid[1][0][0];
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses () instead of square brackets []
Using dot operator . which is invalid for vector element access
✗ Incorrect
The correct syntax to access an element in a 2D vector is with square brackets []. So dp[0][0] = grid[0][0];
2fill in blank
mediumComplete the code to fill the first row of the dp grid by accumulating sums from the left.
DSA C++
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
Using division which is not meaningful here
✗ 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 code to fill the first column of the dp grid by accumulating sums from above.
DSA C++
for (int i = 1; i < m; i++) dp[i][0] = dp[i-1][0] [1] grid[i][0];
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication instead of addition
Using division which is not meaningful here
✗ Incorrect
We add the current grid value to the sum from the above cell to accumulate the path sum.
4fill in blank
hardFill both blanks to compute the minimum path sum for each cell by choosing the smaller sum from top or left plus current grid value.
DSA C++
dp[i][j] = std::min(dp[i-[1]][j], dp[i][j-[2]]) + grid[i][j];
Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 or 2 instead of 1 for index subtraction
Using variable i instead of constant 1
✗ Incorrect
We subtract 1 from i or j to look at the top or left cell respectively.
5fill in blank
hardFill all three blanks to complete the function that returns the minimum path sum from top-left to bottom-right of the grid.
DSA C++
int minPathSum(std::vector<std::vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
std::vector<std::vector<int>> dp(m, std::vector<int>(n, 0));
dp[0][0] = grid[0][0];
for (int i = 1; i < m; i++) dp[i][0] = dp[i-[1]][0] + grid[i][0];
for (int j = 1; j < n; j++) dp[0][j] = dp[0][j-[2]] + grid[0][j];
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[i][j] = std::min(dp[i-[3]][j], dp[i][j-1]) + grid[i][j];
}
}
return dp[m-1][n-1];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 or 2 instead of 1 for index subtraction
Mixing up indices in nested loops
✗ Incorrect
We subtract 1 from indices to access previous row or column cells for accumulation and minimum calculation.
