1. Running walls
Track the tallest wall seen from each side.
let leftMax = 0;
let rightMax = 0Typorithm · hard
Step 1 of 8 · intro card
Two Pointers
Two pointers move inward from the lower side; trapped water at each bar is its running max minus its height.
Water above a bar is bounded by the shorter of the tallest walls to its left and right.
Moving from whichever side is currently lower guarantees that side's running max is the true bound.
Each step adds the gap between the running max and the current bar's height.
Process the lower side each step.
Running max bounds the water.
Add runningMax minus height per bar.
function trap(height) {
let left = 0;
let right = height.length - 1;
let leftMax = 0;
let rightMax = 0;
let water = 0;
while (left < right) {
if (height[left] < height[right]) {
leftMax = Math.max(leftMax, height[left]);
water += leftMax - height[left];
left += 1;
} else {
rightMax = Math.max(rightMax, height[right]);
water += rightMax - height[right];
right -= 1;
}
}
return water;
}Connect each part of the code to the concept before you type.
Track the tallest wall seen from each side.
let leftMax = 0;
let rightMax = 0The lower wall bounds the water, so process that side.
if (height[left] < height[right]) {Water above a bar is its left max minus its own height.
water += leftMax - height[left]Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.