Rainwater Collected Across Column Heights
Hard · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
You are given an integer list heights describing a row of adjacent vertical blocks, each spanning 1 unit horizontally and standing heights[i] units tall at position i.
During a downpour, water accumulates in valleys bounded by taller blocks on both sides, while any water reaching past index 0 or index len(heights) - 1 drains off the edges. Above position i, standing water reaches up to the smaller of the tallest block on its left (0..i) and the tallest block on its right (i..len(heights) - 1), contributing that surface elevation minus heights[i] units of volume.
Implement trap(heights: List[int]) -> int to return the total volume of standing water retained across the entire profile.
def trap(heights: List[int]) -> int:
Examples
Example 1
- Input:
heights = [3, 1, 0, 2, 1, 4, 1, 3] - Output:
10 - Explanation: Between index
0(height3) and index5(height4), the surface stabilizes at height3, holding2 + 3 + 1 + 2 = 8units over indices1..4. Between index5(height4) and index7(height3), the surface stabilizes at height3, holding2more units at index6, for8 + 2 = 10total.
Example 2
- Input:
heights = [3, 5, 1, 3, 0, 4] - Output:
8 - Explanation: Index
0sits outside peak5with nothing taller further left, so it retains0. Between index1(height5) and index5(height4), the surface sits at height4, retaining3 + 1 + 4 = 8units across indices2..4.
Constraints
n == len(heights)0 <= n <= 10^50 <= heights[i] <= 10^5- Profiles with fewer than
3blocks, or profiles that only ascend or only descend, retain0units.
Step-by-step walkthrough
Visualize how water sits above each column
Instead of trying to identify entire "ponds" from left to right, look at one single bar
iof width 1 and ask: how high does the water surface sit directly above bari?Water above column
iis held back on the left by the tallest bar inheights[0..i]and on the right by the tallest bar inheights[i..n-1]. Just like a wooden bucket with one tall slat and one short slat, water spills over whichever side is lower:Example 2: heights = [3, 5, 1, 3, 0, 4] ('#' = block, '~' = retained water) 5 | # 4 | # ~ ~ ~ # <-- water surface sits at min(5, 4) = 4 across columns 2..4 3 | # # ~ # ~ # 2 | # # ~ # ~ # 1 | # # # # ~ # +------------ 3 5 1 3 0 4 water: 0 + 0 + 3 + 1 + 4 + 0 = 8 Column-by-column formula: water_level[i] = min(max(heights[0..i]), max(heights[i..n-1])) water[i] = water_level[i] - heights[i]Notice a neat trick in that formula: because we include
heights[i]itself inside bothmax(heights[0..i])andmax(heights[i..n-1]),water_level[i]is always at leastheights[i], sowater[i]can never be negative!From O(n²) brute force to O(n) prefix and suffix maxima
Computing
max(heights[0..i])andmax(heights[i..n-1])from scratch for each columniscans up tonelementsntimes—roughly10¹⁰operations whenn = 10⁵, which will time out.We avoid repeated scanning by noticing that the tallest bar in
0..iis simplymax(left_best[i - 1], heights[i])(a prefix maximum, meaning a running maximum maintained from the start of the array), and similarly forright_bestfrom the right end:def trap_with_arrays(heights: List[int]) -> int: n = len(heights) if n == 0: return 0 left_best = [0] * n right_best = [0] * n left_best[0] = heights[0] for i in range(1, n): left_best[i] = max(left_best[i - 1], heights[i]) right_best[n - 1] = heights[n - 1] for i in range(n - 2, -1, -1): right_best[i] = max(right_best[i + 1], heights[i]) total_water = 0 for i in range(n): total_water += min(left_best[i], right_best[i]) - heights[i] return total_waterThis runs in
O(n)time, which easily passes time limits, but allocatesO(n)extra memory forleft_bestandright_best. Next, let's eliminate both arrays.Key idea: settle the shorter side with two pointers in O(1) space
Place one pointer
left = 0at the far left and one pointerright = n - 1at the far right, keeping two running integers: -left_max: tallest bar seen so far acrossheights[0..left]-right_max: tallest bar seen so far acrossheights[right..n-1]At index
left, we already know the exact tallest wall on its left (left_max), becauselefthas walked continuously from0. We do not yet know the exact tallest wall to its right, becauseheights[left+1 .. right-1]is still unexplored. Why don't we need to know it whenheights[left] <= heights[right]?Suppose heights[left] <= heights[right], and we update left_max = max(left_max, heights[left]): Case A: left_max came from heights[left] itself. Since heights[left] <= heights[right], bar `right` is already >= left_max! Case B: left_max came from an earlier bar `j < left` (so left_max == heights[j]). How did `left` step past `j` earlier? Only when heights[j] <= heights[r_then] for some pointer position `r_then >= right` still sitting to the right of `left`! [0 ... j ... left] (unexplored middle) [right ... r_then ... n-1] | | left_max <= heights[r_then] <= true_right_max_of(left)In both cases, there is definitely a bar to the right of
leftat least as tall asleft_max. Even if an unexplored bar in the middle is1000units tall,min(left_max, true_right_max)is stillleft_max!By exact symmetry, whenever
heights[left] > heights[right], there is a bar to the left ofrighttaller thanright_max, so the water level atrightisright_max. Thus at every step we settle the bar under the shorter pointer and step that pointer inward.Code the two-pointer loop
Let's translate that rule directly into
trap(heights). Notice three clean details: 1. Updatingleft_maxbefore subtractingheights[left]: ifheights[left]sets a newleft_max, thenleft_max - heights[left]is0, so a new peak adds0water without needingmax(0, ...). 2. Whenleft == right: the loop stops because the two pointers meet on the tallest bar of the entire array (or a tie for tallest), which can never trap water above itself. 3. Tiny inputs ([],[7],[3, 4]): for[],left = 0andright = -1, sowhile left < rightskips immediately and returns0without ever indexingheights.def trap(heights: List[int]) -> int: # left, right: inward-moving indices bounding the unsettled slice heights[left..right]. left = 0 right = len(heights) - 1 # left_max, right_max: tallest bar height seen so far from index 0..left and right..n-1. left_max = 0 right_max = 0 total_water = 0 # When heights has 0 or 1 bars, left >= right initially and the loop safely returns 0. while left < right: if heights[left] <= heights[right]: # Because heights[left] <= heights[right] (and any earlier taller left bar only # advanced past an even taller right bar), the true tallest bar to the right of # `left` is guaranteed >= left_max, so min(left_wall, right_wall) == left_max. if heights[left] > left_max: left_max = heights[left] water_at_left = left_max - heights[left] total_water += water_at_left left += 1 else: # Mirror case: heights[left] > heights[right] guarantees a left wall >= right_max. if heights[right] > right_max: right_max = heights[right] water_at_right = right_max - heights[right] total_water += water_at_right right -= 1 return total_waterTrace Example 1 and Example 2 step by step
First, let's trace Example 2 (
heights = [3, 5, 1, 3, 0, 4]), whereleftsteps from index0up to peak5at index1and thenrightwalks inward across the basin:left right heights[L] vs [R] pointer settled left_max right_max water added total ---- ----- ----------------- --------------- -------- --------- ----------- ----- 0 5 3 <= 4 left (idx 0) 3 0 3 - 3 = 0 0 1 5 5 > 4 right (idx 5) 3 4 4 - 4 = 0 0 1 4 5 > 0 right (idx 4) 3 4 4 - 0 = 4 4 1 3 5 > 3 right (idx 3) 3 4 4 - 3 = 1 5 1 2 5 > 1 right (idx 2) 3 4 4 - 1 = 3 8 1 1 loop ends (left == right at tallest bar 5) returns 8Now let's trace Example 1 (
heights = [3, 1, 0, 2, 1, 4, 1, 3]), where peak4sits at index5between two separate basins:left right heights[L] vs [R] pointer settled left_max right_max water added total ---- ----- ----------------- --------------- -------- --------- ----------- ----- 0 7 3 <= 3 left (idx 0) 3 0 3 - 3 = 0 0 1 7 1 <= 3 left (idx 1) 3 0 3 - 1 = 2 2 2 7 0 <= 3 left (idx 2) 3 0 3 - 0 = 3 5 3 7 2 <= 3 left (idx 3) 3 0 3 - 2 = 1 6 4 7 1 <= 3 left (idx 4) 3 0 3 - 1 = 2 8 5 7 4 > 3 right (idx 7) 3 3 3 - 3 = 0 8 5 6 4 > 1 right (idx 6) 3 3 3 - 1 = 2 10 5 5 loop ends (left == right at middle peak 4) returns 10Notice how indices
1..4filled to height3(left_max) while index6also filled to height3(right_max), accumulating10units in one linear sweep!Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def trap(heights: List[int]) -> int: # left, right: inward-moving indices bounding the unsettled slice heights[left..right]. left = 0 right = len(heights) - 1 # left_max, right_max: tallest bar height seen so far from index 0..left and right..n-1. left_max = 0 right_max = 0 total_water = 0 # When heights has 0 or 1 bars, left >= right initially and the loop safely returns 0. while left < right: if heights[left] <= heights[right]: # Because heights[left] <= heights[right] (and any earlier taller left bar only # advanced past an even taller right bar), the true tallest bar to the right of # `left` is guaranteed >= left_max, so min(left_wall, right_wall) == left_max. if heights[left] > left_max: left_max = heights[left] water_at_left = left_max - heights[left] total_water += water_at_left left += 1 else: # Mirror case: heights[left] > heights[right] guarantees a left wall >= right_max. if heights[right] > right_max: right_max = heights[right] water_at_right = right_max - heights[right] total_water += water_at_right right -= 1 return total_water✅ Submit now — all tests should pass.
Intuition & how it works
Picture each bar as a slice of canyon rock and focus on one vertical column at a time. Water above column i rises until it spills over whichever surrounding canyon wall is shorter: the tallest bar anywhere to its left, or the tallest bar anywhere to its right (min(tallest_left, tallest_right) - heights[i]).
Why do simpler approaches do extra work? Scanning outward from every single column to find its left and right walls repeats the same work n times, taking O(n²) time (10¹⁰ operations when n = 10⁵). Precomputing two prefix/suffix maximum arrays (running-maximum tables built in one left-to-right pass and one right-to-left pass) drops the runtime to O(n), but still allocates O(n) extra memory.
The two-pointer technique (placing left at index 0 and right at n - 1 and moving them toward each other) gets O(1) extra space because min(left_wall, right_wall) only depends on the smaller wall! Whenever heights[left] <= heights[right], we already know the true left wall left_max at left, and we know some bar on the right is at least as tall as left_max—so min(left_max, right_wall) is guaranteed to equal left_max right now. Let's trace heights = [3, 0, 1, 0, 2]:
heights = [3, 0, 1, 0, 2]
1. left=0 (3), right=4 (2): 3 > 2 -> settle right: right_max=2, water += 2-2 = 0, right=3
2. left=0 (3), right=3 (0): 3 > 0 -> settle right: right_max=2, water += 2-0 = 2, right=2
3. left=0 (3), right=2 (1): 3 > 1 -> settle right: right_max=2, water += 2-1 = 1, right=1
4. left=0 (3), right=1 (0): 3 > 0 -> settle right: right_max=2, water += 2-0 = 2, right=0
5. left == right == 0 (peak 3) -> stop! Total trapped water = 0 + 2 + 1 + 2 = 5.
Complexity
Let n = len(heights).
- Time:
O(n). Each iteration ofwhile left < rightperforms a constant number of comparisons and additions and either incrementsleftby1or decrementsrightby1, so the loop executes at mostmax(0, n - 1)times. - Space:
O(1)auxiliary space. Regardless of how largengrows, we store only five integer variables (left,right,left_max,right_max, andtotal_water).
Edge cases
- Empty or tiny inputs (
n < 3, e.g.[],[5],[3, 4]): Fewer than 3 bars cannot enclose a valley between two walls;[]and[5]skip the loop immediately (0), and 2-bar inputs update the outer maximum and add0. - Strictly increasing or decreasing ramps (
[1, 2, 3, 4]or[4, 3, 2, 1]): Every settled bar raisesleft_maxorright_maxto match its own height, contributing0water. - Asymmetric walls (
[5, 0, 0, 0, 1]): Water rises to height1(the shorter wall), trapping3units total rather than15. - Flat plateaus and ties (
[3, 3, 0, 0, 3, 3]): Using<=handles equal heights cleanly; either pointer can step inward on a tie without affectingleft_maxorright_max. - 64-bit overflow in fixed-width languages: With
n = 10⁵and outer walls of height10⁵around0s, trapped water reaches99,998 * 10⁵ ≈ 10¹⁰, which fits effortlessly in Pythonintbut requires a 64-bit integer (long/int64_t) in C++, Java, or Go.
Common mistakes
- Advancing the taller pointer instead of the shorter one: If
heights[left] > heights[right]and you advanceleft, no bar on the right is guaranteed to reachleft_max, so[2, 0, 1]falsely computes2 - 0 = 2instead of1(or0depending on setup). - Subtracting
heights[left]before updatingleft_max: Whenheights[left]is a brand-new peak (heights[left] > left_max), subtracting first produces a negative number unless wrapped inmax(0, ...). - Initializing
left_max = heights[0]before checkingif not heights:: Indexingheights[0]crashes withIndexErrorwhenheights == []. Starting both maxima at0avoids any special-case branch. - Taking
max(left_wall, right_wall)instead ofmin: Water spills over the lower wall, never the higher one.
Alternative approaches
- Prefix and suffix maximum arrays: Precompute
left_best[i] = max(heights[0..i])andright_best[i] = max(heights[i..n-1])in twoO(n)passes and summin(left_best[i], right_best[i]) - heights[i]. Runs inO(n)time andO(n)space, and is a great stepping-stone to explain first in an interview. - Monotonic stack (horizontal layers): Maintain a monotonic stack—a stack of bar indices kept in non-increasing height order. Whenever a new bar
heights[i]is taller than the bar at the top of the stack, pop that valley floorbottomand fill the horizontal rectangle bounded by the new top of the stackleft_wallandiwith(min(heights[left_wall], heights[i]) - heights[bottom]) * (i - left_wall - 1). Runs inO(n)time andO(n)space.
Follow-up questions
- Suppose each column i had a custom horizontal width widths[i] rather than unit width; how would you adjust the calculation? A column's horizontal span does not change how high water can rise—the surface above column
iis stillmin(tallest_left, tallest_right). The only change is that a water column of depthdover indexinow has cross-sectional aread * widths[i]instead ofd * 1. Multiplywater_at_leftbywidths[left]andwater_at_rightbywidths[right]inside the same two-pointer loop, keepingO(n)time andO(1)auxiliary space. - Why does the O(1)-space inward two-pointer scan still compute exact column depths without knowing the tallest unexplored bar in the middle? The formula
min(true_left_max, true_right_max)obeys a loop invariant (a condition guaranteed to hold on every iteration): wheneverheights[left] <= heights[right]and we updateleft_max = max(left_max, heights[left]),true_left_maxatleftequalsleft_max, whiletrue_right_maxatleftis at leastleft_max. Eitherleft_maxequalsheights[left](which is<= heights[right]), orleft_maxcame from an earlier indexj < leftthatleftonly stepped past when some right-side barheights[r_then]satisfiedheights[j] <= heights[r_then]. Becausetrue_right_max >= left_max, any even taller bar hidden in the unexplored interior can only increasetrue_right_maxfurther without changingmin(left_max, true_right_max) == left_max. - How would you generalize this problem to a 2D elevation matrix where water drains across any of the four cardinal neighbors? In 2D, water escapes along whichever 4-connected path to the outer border has the lowest maximum elevation, so independent row and column maxima fail whenever water snakes around corners. Instead, push all border cells into a min-heap (a priority queue that pops the lowest spill elevation in logarithmic time) and flood inward like Dijkstra's algorithm: repeatedly pop the lowest boundary
(level, r, c), and for each unvisited neighbor(nr, nc), accumulatemax(0, level - grid[nr][nc])water and push(max(level, grid[nr][nc]), nr, nc)into the heap. On anR × Cmatrix, every cell enters and leaves the heap once inO(R * C * log(R * C))time andO(R * C)space.
Follow-up questions
- Suppose each column i had a custom horizontal width widths[i] rather than unit width; how would you adjust the calculation?
- Why does the O(1)-space inward two-pointer scan still compute exact column depths without knowing the tallest unexplored bar in the middle?
- How would you generalize this problem to a 2D elevation matrix where water drains across any of the four cardinal neighbors?
Similar questions
- Reachable Negative-Weight Cycle Detection
- Streaming Integer Median Queries
- Cycle-Safe Edge Addition in a DAG
- Low-Latency Multi-Tenant Text Classification Service
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger