Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the left max array for trapping rain water.
DSA Java
int[] leftMax = new int[height.length]; leftMax[0] = height[0]; for (int i = 1; i < height.length; i++) { leftMax[i] = Math.[1](leftMax[i - 1], height[i]); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using Math.min instead of Math.max
Using addition instead of comparison
✗ Incorrect
We use Math.max to keep track of the highest bar from the left side at each position.
2fill in blank
mediumComplete the code to initialize the right max array for trapping rain water.
DSA Java
int[] rightMax = new int[height.length]; rightMax[height.length - 1] = height[height.length - 1]; for (int i = height.length - 2; i >= 0; i--) { rightMax[i] = Math.[1](rightMax[i + 1], height[i]); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using Math.min instead of Math.max
Using addition instead of comparison
✗ Incorrect
We use Math.max to keep track of the highest bar from the right side at each position.
3fill in blank
hardFix the error in calculating trapped water at each position.
DSA Java
int water = 0; for (int i = 0; i < height.length; i++) { water += Math.min(leftMax[i], rightMax[i]) - [1]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Subtracting leftMax or rightMax instead of height
Subtracting water variable itself
✗ Incorrect
We subtract the height of the current bar to find trapped water at that position.
4fill in blank
hardFill both blanks to complete the trapping rain water calculation loop.
DSA Java
int water = 0; for (int i = 0; i < height.length; i++) { int minHeight = Math.[1](leftMax[i], rightMax[i]); water += minHeight - [2]; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using Math.max instead of Math.min for minHeight
Subtracting wrong variable instead of height[i]
✗ Incorrect
We find the minimum of leftMax and rightMax, then subtract the current height to get trapped water.
5fill in blank
hardFill all three blanks to complete the trapping rain water function.
DSA Java
public int trap(int[] height) {
int n = height.length;
int[] leftMax = new int[n];
int[] rightMax = new int[n];
leftMax[0] = height[0];
for (int i = 1; i < n; i++) {
leftMax[i] = Math.[1](leftMax[i - 1], height[i]);
}
rightMax[n - 1] = height[n - 1];
for (int i = n - 2; i >= 0; i--) {
rightMax[i] = Math.[2](rightMax[i + 1], height[i]);
}
int water = 0;
for (int i = 0; i < n; i++) {
water += Math.min(leftMax[i], rightMax[i]) - [3];
}
return water;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using Math.min instead of Math.max for leftMax or rightMax
Subtracting wrong variable instead of height[i]
✗ Incorrect
We use Math.max to build leftMax and rightMax arrays, then subtract height[i] to calculate trapped water.
