Rainwater Held Between Terrain Columns
Arrays & HashingAuto-graded · 23 test casesLast updated
Compute total rainwater stored between unit-width columns of given heights, aiming for a single pass with constant extra memory using the two-pointer technique.
A strip of terrain is made of unit-width columns placed side by side. The list terrain gives the height of each column, from left to right. Every height is a non-negative integer.
After a heavy rain, water settles in the low areas between taller columns. Water cannot flow out past the ends of the strip, so it only stays above a column if there is a taller-or-equal column somewhere on both sides of it.
For a column at index i, the water sitting directly above it reaches the height of the lower of these two values:
- the tallest column at or to the left of
i, and - the tallest column at or to the right of
i.
The amount of water above column i is that level minus the height of column i. This is never negative.
Return the total amount of water (in unit squares) held above all columns.
A straightforward approach checks every column against both sides and takes quadratic time. Aim for a solution that runs in linear time and uses only constant extra space.
Constraints
0 <= len(terrain) <= 2 * 10^40 <= terrain[i] <= 10^5- The return value is a single non-negative integer.
- Strips with fewer than 3 columns hold no water, so the answer is
0.
Examples
Example 1
Input: stored_rainwater([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1])
Output: 6
Example 2
Input: stored_rainwater([4, 2, 0, 3, 2, 5])
Output: 9
Hints
Hint 1
For a single column, the water above it depends only on the smaller of two numbers: the tallest column to its left and the tallest column to its right (both including itself).
Hint 2
Precomputing prefix maxima and suffix maxima gives an O(n) time, O(n) space solution. To remove the arrays, notice you only need to know which side's maximum is smaller, not both exact values.
Hint 3
Use two pointers from the ends, with a running maximum for each side. Always advance the pointer whose current column is lower or equal; that side's running maximum is guaranteed to be the limiting level, so its water can be finalized immediately.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Idea
The water above column i is
min(max(terrain[0..i]), max(terrain[i..n-1])) - terrain[i]
and the answer is the sum of this over all columns. The approaches differ only in how they obtain the two maxima.
- Brute force: for every column, scan both directions. O(n^2) time, O(1) space.
- Prefix/suffix arrays: precompute the best-so-far from each side in two passes, then sum. O(n) time, O(n) space.
- Two pointers (final): O(n) time, O(1) space.
Two-pointer approach
Place one pointer at each end and keep left_max and right_max, the tallest columns seen so far from each side. At each step, handle the side with the lower-or-equal current column:
-
If
terrain[left] <= terrain[right], processleft:- if
terrain[left] >= left_max, it becomes the newleft_maxand holds no water; - otherwise it holds
left_max - terrain[left]units.
Then move
leftone step right. - if
-
Otherwise do the mirror image on the right side.
Why it is correct
If terrain[left] <= terrain[right], then some column on the right (at least terrain[right]) is as tall as the current left column. Because the tallest column seen so far always sits at one of the two pointers, and we only ever move the pointer at the lower column, the right side's true maximum is at least left_max. So the limiting level for the left column is exactly left_max, and its water is left_max - terrain[left] regardless of what lies between the pointers. The right side is symmetric. Each column is settled exactly once, and the final meeting column is the overall tallest, which holds no water.
Edge cases: an empty or tiny list never enters the loop and returns 0; monotonic or flat terrain keeps updating the running maximum and returns 0; [3,0,0,3] returns 6.
Complexity
- Time: O(n), since each iteration moves a pointer inward.
- Space: O(1), using only a few integer variables.
Reference solution
from typing import List
def stored_rainwater(terrain: List[int]) -> int:
left = 0
right = len(terrain) - 1
left_max = 0
right_max = 0
total = 0
while left < right:
if terrain[left] <= terrain[right]:
if terrain[left] >= left_max:
left_max = terrain[left]
else:
total += left_max - terrain[left]
left += 1
else:
if terrain[right] >= right_max:
right_max = terrain[right]
else:
total += right_max - terrain[right]
right -= 1
return total