CodingNodes / Two Pointers / Trapping Rain Water System design Space play · ←→ step · R restart

Problem

The array height describes a row of bars, each one unit wide. After it rains, water collects in the gaps between taller bars.

Return the total number of units of water the bars can hold. Water cannot sit above a bar that has no taller bar on at least one of its sides.

Constraints

  • 1 ≤ height.length ≤ 2 · 10⁴
  • 0 ≤ height[i] ≤ 10⁵

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(1)

Time: Each step moves left or right inward by one, so the pointers meet after n − 1 steps.

Space: Only four integers and a running total are kept.

Keep the tallest bar seen from each side. The side with the lower current bar is the limit: the opposite wall is at least as tall, so the water above that bar is its side max minus its own height. Handle that side and move its pointer inward.