Trapping Rain Water
Problem
An elevation map is given as an array height of non-negative integers, where each value is the height of a bar of width 1. After heavy rain, water settles in the dips between taller bars. Compute the total number of unit cells of water that remain trapped.
heighthas at most 20,000 bars; an empty map is allowed and traps nothing.- Each bar height is an integer from 0 to 30,000.
Examples
height = [2, 0, 1, 3, 0, 1, 2]→6. Between the bars of height 2 and 3, indices 1 and 2 hold2 + 1; between the 3 and the final 2, indices 4 and 5 hold2 + 1.height = [5, 1, 3, 0, 4, 2, 6]→15. The left wall of 5 and right wall of 6 cap the level at 5 everywhere, so the columns hold4 + 2 + 5 + 1 + 3 = 15.height = [1, 2, 3, 4]→0. Strictly rising terrain has no dip to fill.
Hints
- Look at a single column. How high can the water sit there, and what two quantities decide that?
- The water level above column
iismin(tallest bar to its left, tallest bar to its right); precomputing those two arrays gives an O(n) answer. - To drop the extra arrays, walk two pointers inward and notice that the side with the smaller running maximum is the one whose water level is already known for certain.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.