Example 1
- Input
- height = [0,1,0,2,1,0,1,3,2,1,2,1]
- Output
- 6
The valleys hold 1 + 1 + 2 + 1 + 1 = 6 units: one above index 2, one above index 4, two above index 5, one above index 6 and one above index 9.
Given an array height describing an elevation map where each bar has width 1, compute how many units of rain water are trapped after raining. Water sits above a bar up to the lower of the tallest bars on its left and right.
Given a non-empty array height of non-negative integers, imagine a row of vertical bars with width 1 and the listed heights. Return the total units of water held between those bars after rain. Water spills past an exposed edge; the bars themselves occupy space and do not count as water.
For each position, the water level is limited by the lower of the tallest bars on its left and right, including the current bar. Subtract the current height from that level and sum the resulting amounts.
n == height.length1 <= n <= 2 * 10^40 <= height[i] <= 10^5The valleys hold 1 + 1 + 2 + 1 + 1 = 6 units: one above index 2, one above index 4, two above index 5, one above index 6 and one above index 9.
The trapped amounts per index are 0, 2, 4, 1, 2, 0, which total 9 units of water.
The two equal walls bound one zero-height position, which holds 2 units. Equal boundary heights are valid.
Every position has no taller wall to its left than its own height, so water drains away.
One bar has no interior valley; no water is trapped.
A valley holds water only if a wall blocks escape on both sides. The lower wall sets the spill level. In Example 1 at index 5, the tallest wall on the left is 2 and on the right is 3, so height 0 holds min(2, 3) - 0 = 2 units. At a tall peak the bar reaches the water level and holds nothing. Width is 1, so these per-position depths also give volumes.
Reveal Brute Force Scans: intuition, complexity, and code
[2, 0, 2] hold 2 units; ties in running maxima must still move one pointer.[4, 2, 0, 3, 2, 5] hold 9 units, including water above the internal bar of height 3.When each position is bounded by the best values from both sides, converging pointers that track the smaller bound settle every position in one pass.