Skip to problem
←

Trapping Rain Water

Hard 0 attempts

You're given n non-negative integers describing an elevation map, where each value is the height of a bar one unit wide. After rain falls, figure out how much water ends up trapped between the bars.

Water can escape beyond either end. A position holds water only up to the shorter of the tallest walls to its left and right. Return the total volume, not the largest single gap or a water-level array. Single bars, two bars, and monotonic profiles trap no water.

Function contract

Implement trap(height).

Output: Return the total number of unit squares of water trapped above the bars.

Example 1

Input
height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output
6

Example 2

Input
height = [4,2,0,3,2,5]
Output
9
Visual Aid
The lower wall limits the water
30211

For heights [3,0,2], the middle position holds 2 units of water. The left wall’s extra height cannot raise the water above the right wall.

Constraints
  • 1 <= height.length <= 20000
  • 0 <= height[i] <= 10^5

Two Pointers

At each position, water depth is min(left maximum, right maximum) minus the bar height. The two-pointer scan resolves the side with the lower current boundary: the opposite side already provides a sufficient wall, so the resolved side's running maximum determines its contribution. Move inward after accounting for that position.

Keep the running maximum before subtracting the current height, ensuring each contribution is nonnegative. Each pointer only moves inward, so every position is handled at most once.

javascript
function trap(height) {
  let left = 0, right = height.length - 1;
  let leftMax = 0, rightMax = 0, water = 0;
  while (left < right) {
    if (height[left] < height[right]) {
      leftMax = Math.max(leftMax, height[left]);
      water += leftMax - height[left];
      left++;
    } else {
      rightMax = Math.max(rightMax, height[right]);
      water += rightMax - height[right];
      right--;
    }
  }
  return water;
}

Time: O(n) | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript