Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the total trapped water to zero.
DSA Javascript
let totalWater = [1];Attempts:
3 left
💡 Hint
Common Mistakes
Initializing totalWater to 1 or null causes wrong results.
✗ Incorrect
We start counting trapped water from zero because initially no water is trapped.
2fill in blank
mediumComplete the code to find the maximum height to the left of the current bar.
DSA Javascript
let leftMax = Math.max([1], height[i]);
Attempts:
3 left
💡 Hint
Common Mistakes
Using rightMax instead of leftMax causes incorrect calculation.
✗ Incorrect
leftMax keeps track of the highest bar seen so far from the left side.
3fill in blank
hardFix the error in the condition to move the left pointer when leftMax is less than rightMax.
DSA Javascript
if (leftMax [1] rightMax) { left++; } else { right--; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' instead of '<' reverses pointer movement logic.
✗ Incorrect
We move the left pointer when leftMax is less than rightMax to trap water correctly.
4fill in blank
hardFill both blanks to calculate trapped water at the left pointer correctly.
DSA Javascript
totalWater += (leftMax - height[[1]]) > 0 ? (leftMax - height[[2]]) : 0;
Attempts:
3 left
💡 Hint
Common Mistakes
Using right pointer index causes wrong trapped water calculation.
✗ Incorrect
We calculate trapped water at the left pointer using leftMax and height[left].
5fill in blank
hardFill all three blanks to complete the trapping rain water function.
DSA Javascript
function trap(height) {
let left = 0, right = height.length - 1;
let leftMax = 0, rightMax = 0;
let totalWater = 0;
while (left < right) {
if (height[left] < height[right]) {
leftMax = Math.max(leftMax, height[left]);
totalWater += (leftMax - height[left]) > 0 ? (leftMax - height[left]) : 0;
left[1];
} else {
rightMax = Math.max(rightMax, height[right]);
totalWater += (rightMax - height[right]) > 0 ? (rightMax - height[right]) : 0;
right[2];
}
}
return [3];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong pointer increments or returning wrong variable.
✗ Incorrect
We increment left pointer with ++, decrement right pointer with --, and return totalWater.
