DSA Visualizer · 25 visualizationsTrapping Rain Water
Trapping Rain Water
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Two pointers at the ends. Water above each bar is capped by the taller wall on whichever side is currently shorter.
Problem
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Examples
Constraints
- n == height.length
- 1 ≤ n ≤ 2 × 10⁴
- 0 ≤ height[i] ≤ 10⁵
Intuition
The water sitting above any bar is capped by the shorter of the tallest wall to its left and the tallest wall to its right. Rather than computing both walls for every index up front, walk two pointers inward: whichever side currently has the shorter bar is the one whose water level is already fully determined by its running max, so settle that side and advance it — the other side's true max can only help, never hurt, the bound already in hand.
Brute force → Optimal
For each index, scan left for the tallest bar and scan right for the tallest bar, then add min(leftMax, rightMax) − height[i].
Two pointers from both ends, each tracking its own running max. Always advance the side with the smaller current bar, since its water level is already decided.
Complexity
Edge cases
- Strictly increasing or strictly decreasing heights: no water is ever trapped, the answer is 0.
- A single bar or an empty map: there's nothing to trap between, the answer is 0.
Common mistakes
- Precomputing two full leftMax/rightMax arrays when the two-pointer version needs only O(1) extra space.
- Moving the pointer on the *taller* side instead of the shorter one, which breaks the guarantee that the moved side's water level is already final.