Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the total trapped water to zero.
DSA Typescript
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, so totalWater should be initialized to 0.
2fill in blank
mediumComplete the code to create an array to store the maximum height to the left of each bar.
DSA Typescript
const leftMax: number[] = new Array(height.length).fill([1]);Attempts:
3 left
💡 Hint
Common Mistakes
Using null or undefined causes errors when comparing heights.
✗ Incorrect
We fill leftMax with zeros initially because no bars to the left means max height is zero.
3fill in blank
hardFix the error in the loop that calculates the leftMax array.
DSA Typescript
for (let i = 1; i < height.length; i++) { leftMax[i] = Math.max(leftMax[i - 1], [1]); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using i or height[i - 1] causes wrong max calculation.
✗ Incorrect
We compare the previous max with the current bar height to find the max height to the left.
4fill in blank
hardFill both blanks to calculate the trapped water at each bar using leftMax and rightMax arrays.
DSA Typescript
for (let i = 0; i < height.length; i++) { const waterAtI = Math.min([1], [2]) - height[i]; if (waterAtI > 0) totalWater += waterAtI; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using height[i] or totalWater inside Math.min causes wrong calculation.
✗ Incorrect
The trapped water depends on the smaller of the max heights on both sides minus the current height.
5fill in blank
hardFill all three blanks to create the rightMax array similar to leftMax but from the right side.
DSA Typescript
const rightMax: number[] = new Array(height.length).fill(0); rightMax[height.length - 1] = height[height.length - 1]; for (let i = height.length - 2; i >= 0; i--) { rightMax[i] = Math.[1](rightMax[i + 1], [2]); } // Then calculate total trapped water let totalWater = 0; for (let i = 0; i < height.length; i++) { const waterAtI = Math.min(leftMax[i], rightMax[i]) - height[i]; if (waterAtI > 0) totalWater += waterAtI; } return [3];
Attempts:
3 left
💡 Hint
Common Mistakes
Using Math.min instead of max, or returning wrong variable.
✗ Incorrect
We use Math.max to find the max height from the right side, compare with current height, and finally return totalWater.
