Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a stack for storing indices.
DSA Java
Stack<Integer> stack = new Stack<>(); int i = 0; while (i < height.length) { if (stack.isEmpty() || height[i] [1] height[stack.peek()]) { stack.push(i++); } else { int top = stack.pop(); // Calculate trapped water here } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' instead of '<' causes incorrect stack behavior.
Using '==' does not handle all cases properly.
✗ Incorrect
We push the current index if the current height is less than the height at the top index of the stack.
2fill in blank
mediumComplete the code to calculate the distance between current index and stack top after popping.
DSA Java
int distance = i - stack.peek() - [1];Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 or 2 causes wrong distance calculation.
Using -1 leads to negative distance.
✗ Incorrect
Distance is the difference between current index and stack top minus 1.
3fill in blank
hardFix the error in calculating bounded height for trapped water.
DSA Java
int bounded_height = Math.min(height[i], height[stack.peek()]) - height[[1]];
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'i' or 'stack.peek()' instead of 'top' causes wrong height calculation.
Using 'height[i]' is incorrect as it is a value, not an index.
✗ Incorrect
We subtract the height of the popped top bar to get the bounded height.
4fill in blank
hardFill both blanks to update total trapped water correctly.
DSA Java
water += distance * [1];
i++;Attempts:
3 left
💡 Hint
Common Mistakes
Using height[top] or height[i] directly causes wrong water calculation.
Using stack.peek() is incorrect as it is an index, not height.
✗ Incorrect
Total trapped water increases by distance times bounded height.
5fill in blank
hardFill all three blanks to complete the trapping rain water function using stack.
DSA Java
public int trap(int[] height) {
int water = 0;
Stack<Integer> stack = new Stack<>();
int i = 0;
while (i < height.length) {
if (stack.isEmpty() || height[i] [1] height[stack.peek()]) {
stack.push(i++);
} else {
int top = stack.pop();
if (stack.isEmpty()) continue;
int distance = i - stack.peek() - [2];
int bounded_height = Math.min(height[i], height[stack.peek()]) - height[[3]];
water += distance * bounded_height;
}
}
return water;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' instead of '<' in comparison.
Incorrect distance calculation by subtracting wrong value.
Using wrong variable for height subtraction.
✗ Incorrect
The function uses a stack to find trapped water by comparing heights and calculating bounded areas.
