Puddles in a Valley: Water Volume Between Terrain Columns
Arrays & HashingAuto-graded · 25 test casesLast updated
Tests whether a candidate can compute trapped water volume across a height profile using the two-pointer O(1)-space technique.
Puddles in a Valley: Water Volume Between Terrain Columns
Imagine a cross-section of uneven terrain represented as a row of vertical columns, each exactly one unit wide, standing flush against one another on level ground. After a rainstorm, water fills the low-lying gaps between taller columns. Any water that has no taller column blocking it on one side simply drains away off the edge of the terrain.
Given the column heights from left to right, return the total volume of water that remains pooled in the terrain, counted in unit squares.
Rules
- Each column at index
ihas width 1 and heightterrain[i]. A height of0means the ground is bare at that position. - A unit square of water sitting at position
iat vertical levely(occupying the band fromytoy + 1) is retained if and only if:terrain[i] <= y, there exists at least one column strictly taller thanysomewhere to the left ofi, and there exists at least one column strictly taller thanysomewhere to the right ofi. - Water that does not satisfy both conditions drains off. There are no walls or barriers beyond the leftmost and rightmost columns.
- Return the total count of retained unit squares across all positions and all levels.
Constraints
1 <= len(terrain) <= 10^50 <= terrain[i] <= 10^5- The answer fits in a Python integer (it stays below
10^10, but may exceed2^31 − 1).
Examples
Example 1
Input: trapped_water([3, 0, 2, 0, 4])
Output: 7
Example 2
Input: trapped_water([1, 2, 3, 2, 1])
Output: 0
Example 3
Input: trapped_water([2, 0, 2, 1, 0, 1, 3])
Output: 6
Hints
Hint 1
For any single column, the water it can hold is determined by the tallest column to its left and the tallest column to its right. What formula relates those two values to the water at that column?
Hint 2
A straightforward approach precomputes a left-max array and a right-max array in O(n) time and O(n) space. Can you derive the two-pointer technique from that?
Hint 3
With two pointers starting at opposite ends, you only need to process the side whose current bar is shorter. Ask yourself: if the left bar is shorter than the right bar, what does that tell you about the binding constraint on the left column?
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Per-column water formula
Consider any column at index i. A unit square of water at level y is retained only when a taller column exists on both sides. For a fixed i, the retained levels form a contiguous range from terrain[i] up to (but not including) the smaller of the two surrounding peaks. So the water held at column i is:
water[i] = max(0, min(left_peak, right_peak) - terrain[i])
where left_peak = max(terrain[0..i]) and right_peak = max(terrain[i..n-1]). Including terrain[i] in both maxima guarantees the term is never negative, so the max(0, ...) wrapper is redundant.
Precomputing prefix and suffix max arrays gives a clean O(n) time, O(n) space solution. The two-pointer approach below reduces space to O(1).
Two-pointer method
Place one pointer l at the left end and r at the right end. Track running maxima lmax and rmax for each side (each includes the bar at the current pointer).
At every step, compare terrain[l] and terrain[r] and move whichever pointer sits on the shorter bar:
- If
terrain[l] < terrain[r]: the right side is guaranteed to have at least one bar as tall asterrain[r], which is already taller thanterrain[l]. That makeslmaxthe binding constraint for columnl. Addlmax - terrain[l]to the total and advancel. - Otherwise (
terrain[l] >= terrain[r]): by the mirror argument,rmaxis the binding constraint for columnr. Addrmax - terrain[r]and moverleft.
The loop stops when the pointers meet. The column they land on is always a peak (a tallest bar), which holds zero water, so skipping it is correct.
Why it is correct
When the left branch fires, every previous right-side move occurred at a bar no taller than the current terrain[r]. Therefore rmax <= terrain[r], which means the right side certainly has a bar at least as tall as lmax (because terrain[l] < terrain[r] and lmax >= terrain[l]). So min(left_peak, right_peak) = lmax for that column, and the contribution is exact.
The right branch is symmetric. Each pointer moves inward exactly once per iteration, so every column except the final meeting point is settled with its correct water value.
Complexity
- Time: O(n) — each of the
n − 1iterations does O(1) work. - Space: O(1) extra — two pointers, two running maxima, and the running total.
Note: the answer can reach around 10^10, which overflows 32-bit integers in C++ or Java. Use long in those languages; Python handles it automatically.
Trace on example 3
terrain = [2, 0, 2, 1, 0, 1, 3]
| l | r | branch | lmax | rmax | added | total |
|---|---|---|---|---|---|---|
| 0 | 6 | left (2 < 3) | 2 | 0 | 0 | 0 |
| 1 | 6 | left (0 < 3) | 2 | 0 | 2 | 2 |
| 2 | 6 | left (2 < 3) | 2 | 0 | 0 | 2 |
| 3 | 6 | left (1 < 3) | 2 | 0 | 1 | 3 |
| 4 | 6 | left (0 < 3) | 2 | 0 | 2 | 5 |
| 5 | 6 | left (1 < 3) | 2 | 0 | 1 | 6 |
Pointers meet at index 6; result is 6.
Edge cases
- Single column: the loop never runs, returning 0.
- Two columns: one step adds
max − h = 0, returning 0. - Strictly increasing or single-peak profile (e.g.,
[1,2,3,2,1]): every column is its own running max, so each contribution is 0. - All zeros or a flat plateau: all contributions are 0.
- Tie at the boundary (e.g.,
[3, 0, 3]): theelsebranch handles the tie and correctly settles the right pointer first; the middle column then contributesmin(3, 3) − 0 = 3.
Reference solution
from typing import List
def trapped_water(terrain: List[int]) -> int:
l, r = 0, len(terrain) - 1
lmax = rmax = 0
total = 0
while l < r:
if terrain[l] < terrain[r]:
# Right side is taller, so lmax is the binding limit for column l.
lmax = max(lmax, terrain[l])
total += lmax - terrain[l]
l += 1
else:
# Left side is taller or equal, so rmax is the binding limit for column r.
rmax = max(rmax, terrain[r])
total += rmax - terrain[r]
r -= 1
return total