Rainwater Trapped Across Unit-Width Elevation Columns
Medium · Coding & Algorithms · Quantitative Researcher · Technical Screen
Problem Statement
You are given a sequence of contiguous vertical columns, each of horizontal width 1, resting side by side on level ground without gaps. Column i rises to integer height heights[i] (0 indicates ground level). Neither the left edge before index 0 nor the right edge after index len(heights) - 1 has a retaining wall, so water that is not enclosed on both sides drains off the ends.
Implement the function:
def trapped_water(heights: list[int]) -> int:
Compute and return the total volume of rainwater retained across the profile, counted in 1 x 1 unit cells:
- Consider the
1 x 1cell above columnispanning vertical elevationytoy + 1(for integery >= 0). - That cell retains water if and only if
heights[i] <= y, at least one columnL < isatisfiesheights[L] > y, and at least one columnR > isatisfiesheights[R] > y. - Every other cell above
heights[i]spills away.
Examples
Example 1
Input: heights = [4, 1, 2, 0, 5]
Output: 9
Walk-through: Between the column of height 4 at index 0 and the column of height 5 at index 4, water settles at elevation 4. Columns 1, 2, and 3 retain 4 - 1 = 3, 4 - 2 = 2, and 4 - 0 = 4 unit cells (3 + 2 + 4 = 9).
Example 2
Input: heights = [0, 2, 4, 3, 1]
Output: 0
Walk-through: Heights climb to a single central peak at index 2 and descend afterward, so no column has a strictly taller boundary on both left and right.
Example 3
Input: heights = [2, 0, 3, 1, 0, 2, 4]
Output: 8
Walk-through: Column 1 sits between height 2 (index 0) and height 3 (index 2), trapping 2 cells up to elevation 2. Columns 3, 4, and 5 sit between height 3 (index 2) and height 4 (index 6), filling to elevation 3 and trapping 2, 3, and 1 cells (2 + 2 + 3 + 1 = 8).
Constraints
1 <= len(heights) <= 10^50 <= heights[i] <= 10^5- The total retained cell count can exceed
2^31 - 1(up to roughly10^10); Python's arbitrary-precisioninthandles this without overflow.
Step-by-step walkthrough
Visualize the profile and find the water at one bar
Let's draw Example 1 (
heights = [4, 1, 2, 0, 5]), using#for solid column blocks and~for retained unit cells of water:level 5 | # 4 | # ~ ~ ~ # 3 | # ~ ~ ~ # 2 | # ~ # ~ # 1 | # # # ~ # +--------------- i = 0 1 2 3 4 h = 4 1 2 0 5 water 0 3 2 4 0 -> total = 9Look at any single column
i. Water rises aboveheights[i]until it spills over whichever side has the lower tallest wall:- Let
Lbe the tallest bar inheights[0 .. i](from the left edge throughiitself). - Let
Rbe the tallest bar inheights[i .. n - 1](fromiitself through the right edge).
Water at column
isettles at levelmin(L, R). Since the bar itself takes up the bottomheights[i]squares, the number of water squares above columniis:water[i] = min(L, R) - heights[i]Including bar
iitself insideLandRis a handy trick: bothLandRare automatically at leastheights[i], somin(L, R) - heights[i]is0when bariis a peak and never turns negative.- Let
Start from brute force and precomputed arrays
If we apply
min(L, R) - heights[i]directly by scanning left forLand scanning right forRat every columni, each of thencolumns scansO(n)bars. That takesO(n^2)time — roughly10^10steps whenn = 100,000, which is far too slow.Why is the brute-force scan wasteful? Adjacent columns compute almost the exact same left maximum! You could fix the speed by precomputing two arrays in
O(n)time: one pass left-to-right forleft_max[i]and one pass right-to-left forright_max[i].Can we keep that
O(n)single-pass speed without allocating twoO(n)arrays? Yes — notice thatmin(L, R)only cares about the smaller of the two walls, not the exact height of the taller one.Key insight: two pointers and the taller anchor wall
Place one pointer
leftat index0and another pointerrightat indexn - 1. Maintain two running numbers as the pointers walk inward:left_max: the tallest bar seen so far inheights[0 .. left]right_max: the tallest bar seen so far inheights[right .. n - 1]
At column
left, we already know its full left wallL = left_max. We haven't scanned the middle bars yet, so we don't know the exact tallest barRto its right — but we don't needR's exact value if we already knowR >= left_max! WheneverR >= left_max,min(L, R)simplifies straight toleft_max.Here is the invariant that gives us that guarantee: at every step, compare
heights[left]andheights[right], and only move the shorter pointer inward.heights[0 .. left] unseen middle heights[right .. n - 1] tallest = left_max tallest = right_max | | v v heights[left] <= heights[right] (taller anchor stays put!)Why does
heights[left] <= heights[right]guaranteeheights[right] >= left_max? Because we never step past the taller of the two current bars! Every bar we stepped past earlier on the left was shorter than (or equal to) whichever right-side bar was standing there at the time, and the currentheights[right]is at least as tall as all of them. Soheights[right]acts as an unmoved anchor wall that is at leastleft_max, locking inwater[left] = left_max - heights[left].By symmetry, when
heights[left] > heights[right],heights[left]is an anchor wall at least as tall asright_max, locking inwater[right] = right_max - heights[right].Write the two-pointer loop
In each iteration of
while left < right, check which pointer stands at the shorter (or tied) bar, update that side's running maximum before subtracting the bar's height, add the trapped water, and advance that pointer one step inward.def trapped_water(heights: list[int]) -> int: # Two pointers starting at the extreme left and right bars of the profile. left = 0 right = len(heights) - 1 # Running maximum bar heights seen so far: # - left_max: max height in heights[0 .. left] # - right_max: max height in heights[right .. len(heights) - 1] left_max = 0 right_max = 0 total_water = 0 # Walk the shorter pointer inward until both pointers meet at a tallest bar. while left < right: if heights[left] <= heights[right]: # Because we never move the taller pointer, heights[right] is at least # as tall as every bar we already passed on the left (heights[right] >= left_max). # That guarantees the right side has a wall >= left_max, so left_max # is the exact water level at `left`. if heights[left] > left_max: # Update left_max first so a new tallest bar adds 0, never negative water. left_max = heights[left] total_water += left_max - heights[left] left += 1 else: # Mirror case: heights[left] > heights[right], and heights[left] >= right_max, # so right_max is the exact water level at `right`. if heights[right] > right_max: right_max = heights[right] total_water += right_max - heights[right] right -= 1 return total_waterWhy stop at
left < rightwithout processing the meeting bar? Because we never move away from a tallest bar, the two pointers always meet at a global maximum bar of the entire array — and a tallest bar never holds water above itself.Trace the pointers on two examples
First, trace Example 1 (
heights = [4, 1, 2, 0, 5]), where the right wall (5) is tallest:left right compare update & water added left_max right_max total_water 0 4 4 <= 5 left_max = 4; add 4 - 4 = 0; l=1 4 0 0 1 4 1 <= 5 add 4 - 1 = 3; l=2 4 0 3 2 4 2 <= 5 add 4 - 2 = 2; l=3 4 0 5 3 4 0 <= 5 add 4 - 0 = 4; l=4 4 0 9 4 4 stop (pointers meet at height 5) -> return 9Now trace
[5, 1, 0, 2], where the left wall (5) is taller sorightmoves instead:left right compare update & water added left_max right_max total_water 0 3 5 > 2 right_max = 2; add 2 - 2 = 0; r=2 0 2 0 0 2 5 > 0 add 2 - 0 = 2; r=1 0 2 2 0 1 5 > 1 add 2 - 1 = 1; r=0 0 2 3 0 0 stop (pointers meet at height 5) -> return 3Both traces match the physical water level without ever needing extra arrays.
Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def trapped_water(heights: list[int]) -> int: # Two pointers starting at the extreme left and right bars of the profile. left = 0 right = len(heights) - 1 # Running maximum bar heights seen so far: # - left_max: max height in heights[0 .. left] # - right_max: max height in heights[right .. len(heights) - 1] left_max = 0 right_max = 0 total_water = 0 # Walk the shorter pointer inward until both pointers meet at a tallest bar. while left < right: if heights[left] <= heights[right]: # Because we never move the taller pointer, heights[right] is at least # as tall as every bar we already passed on the left (heights[right] >= left_max). # That guarantees the right side has a wall >= left_max, so left_max # is the exact water level at `left`. if heights[left] > left_max: # Update left_max first so a new tallest bar adds 0, never negative water. left_max = heights[left] total_water += left_max - heights[left] left += 1 else: # Mirror case: heights[left] > heights[right], and heights[left] >= right_max, # so right_max is the exact water level at `right`. if heights[right] > right_max: right_max = heights[right] total_water += right_max - heights[right] right -= 1 return total_water✅ Submit now — all tests should pass.
Intuition & how it works
Imagine pouring rain onto a row of stone pillars standing side by side: above any single pillar, water can only rise as high as the shorter of two walls — the tallest pillar anywhere to its left and the tallest pillar anywhere to its right — because any higher water simply spills over the lower side. Using two pointers (a technique where two indices start at opposite ends of an array and walk toward each other), we stand at both outer edges and always step inward from whichever edge currently has the shorter pillar. Because we never move away from the taller pillar, it stays put as an "anchor wall" that is guaranteed to be at least as tall as every pillar we have already walked past on the opposite side, letting us lock in that side's water column immediately.
Why not just scan left and scan right from every single pillar to find its two bounding walls? Doing a full left-and-right scan for each of the n pillars repeats almost identical work n times, costing O(n^2) time — around 10 billion operations when n = 100,000. Precomputing two helper arrays of running maxima from the left and from the right brings the time down to O(n), and the two-pointer trick achieves the exact same O(n) single pass while using O(1) extra memory instead of two n-element arrays.
Let's watch the pointers walk inward on heights = [4, 1, 3, 0, 2]:
Start: left=0 (h=4), right=4 (h=2), left_max=0, right_max=0, total_water=0
1. h[left]=4 > h[right]=2 -> anchor at left (4); right_max=2; add 2-2=0; right -> 3
2. h[left]=4 > h[right]=0 -> anchor at left (4 >= right_max 2); add 2-0=2; right -> 2
3. h[left]=4 > h[right]=3 -> anchor at left (4); right_max=3; add 3-3=0; right -> 1
4. h[left]=4 > h[right]=1 -> anchor at left (4 >= right_max 3); add 3-1=2; right -> 0
5. left == right == 0 -> pointers meet at tallest bar (4); stop with total_water = 4
Column 3 (between height 3 and height 2) trapped 2 units up to level 2, and column 1 (between height 4 and height 3) trapped 2 units up to level 3, totaling 4.
Complexity
Let n be len(heights).
- Time:
O(n). Forn >= 1, each iteration ofwhile left < righteither incrementsleftby1or decrementsrightby1, so the loop runsn - 1times and performsO(1)comparisons and arithmetic per step. - Space:
O(1). We only store five integer variables (left,right,left_max,right_max, andtotal_water), regardless of how largeheightsgrows.
Edge cases
- One or two bars (
[5]or[3, 0]): With one bar,left == right == 0immediately so the loop never runs and returns0. With two bars, one iteration updates a running maximum and addsmax - max = 0. - Flat bare ground (
[0, 0, 0, 0]) or single-peak ridge ([0, 2, 4, 3, 1]): Every bar we step past equals the running maximum on its side, so every subtraction adds0. - Unequal outer walls (
[5, 0, 0, 2]): Water settles at the lower wall (2), adding2 + 2 = 4asrightwalks left toward the anchor bar of height5. - Equal heights and plateaus (
[2, 2, 0, 2, 2]): Using<=inheights[left] <= heights[right]breaks ties cleanly on the left; both2s setleft_max = 2and only the middle0adds2. - Descending runoff tail (
[4, 1, 0, 1, 4, 3, 2, 1]): Asrightwalks inward up the1, 2, 3, 4slope,right_maxrises at every step soright_max - heights[right] == 0— none of the outer slope traps water. - 32-bit integer overflow (
[10^5, 0, ..., 0, 10^5]): Two walls of height100,000surrounding99,998zeros hold9,999,800,000units, exceeding2^31 - 1. Pythonintgrows automatically, whereas C++ or Java requires a 64-bitlong long/long.
Common mistakes
- Using
max(L, R)instead ofmin(L, R): Water spills over whichever bounding wall is shorter, never the taller one. - Subtracting
heights[left]before updatingleft_max: Wheneverheights[left] > left_max, computingleft_max - heights[left]first produces a negative number and shrinks the total. Updateleft_maxfirst (or wrap the difference inmax(0, ...)). - Advancing the pointer on the taller side: If you move the taller side on
[3, 0, 1],leftsteps past3assuming the right side can hold level3, overcounting water that actually spills over1. - Treating the whole array as one big basin between
heights[0]andheights[-1]: Taller interior bars split the profile into independent pools at higher water levels (as in Example 3).
Alternative approaches
- Prefix and suffix maximum arrays: Build
left_max[i]in one left-to-right pass (left_max[i] = max(left_max[i - 1], heights[i]), meaning each entry stores the maximum of the prefix up toi) andright_max[i]in one right-to-left pass, then summin(left_max[i], right_max[i]) - heights[i]. This takesO(n)time andO(n)space, and is the easiest version to write under time pressure if you forget the two-pointer invariant. - Monotonic stack (layer-by-layer): Maintain a monotonic stack (a stack of indices whose bar heights stay non-increasing from bottom to top). Whenever a new bar is taller than the index on top of the stack, pop that valley floor; if the stack still has a left wall beneath it, add the horizontal strip
(min(new_height, left_wall_height) - floor_height) * horizontal_width. This also runs inO(n)time andO(n)space and processes bars strictly left-to-right.
Follow-up questions
- How would you generalize this problem to a 2D R x C elevation grid? In 2D, water can leak out along crooked winding paths in any of four directions, so two pointers are not enough. Instead, push all border cells into a min-heap (a priority queue that always pops the smallest boundary height in
O(log(R * C))time) to represent the outer "sea wall", then repeatedly pop the lowest boundary cellh, flood any unvisited neighbornbwithmax(0, h - height[nb])water, and pushnbinto the heap with effective wall heightmax(h, height[nb])inO(R * C * log(R * C))total time. - How could you report the trapped water per column or identify each distinct pool? Create an array
water = [0] * nand assignwater[left] = left_max - heights[left](orwater[right] = right_max - heights[right]) inside the two-pointer loop. To list separate pools, scanwaterfrom left to right and group maximal contiguous runs of indices wherewater[i] > 0. - What approach works if column heights arrive one by one in a left-to-right stream and you must update the total after each arrival? Two pointers cannot start before seeing the right end of the stream, so use a monotonic non-increasing stack instead: each newly arrived bar pops any shorter bars to its left and immediately adds the horizontal water strips bounded between the new bar and the next taller bar still on the stack. Every bar is pushed once and popped at most once, giving amortized
O(1)time per arrival (meaning even though a tall bar may pop many bars at once, the average work per bar acrossnarrivals is constant).
Follow-up questions
- How would you generalize this problem to a 2D R x C elevation grid?
- How could you report the trapped water per column or identify each distinct pool?
- What approach works if column heights arrive one by one in a left-to-right stream and you must update the total after each arrival?
Similar questions
- Maximum Rocks Along an Up-Right Grid Path
- Decision Tree Split Selection and MSE Gradient Update
- Palindromic Substring Count
- Strictly Rising Subarrays and Three-Group Partition Score
- Hierarchical Resource Tree Manager
- Largest Component Root in Parent-Link Forest
More Goldman Sachs interview questions
- Constant-Time LRU Cache with Fixed Capacity Easy
- Highest Frequency Within Increment Budget Medium
- Strictly Rising Subarrays and Three-Group Partition Score Medium Pro
- Real-Time Telemetry Dashboard: Range Rollups and Watermarking Medium Pro
- Monte Carlo Estimation of Pi Using Cardboard and a Six-Sided Die Medium Pro
- Largest Component Root in Parent-Link Forest Medium Pro
- Translating Equity Signals into Portfolios: Validation, Regimes, and Information Theory Medium Pro
- Maximum Floored Student Average Across Streaming, Disk, and Parallel Execution Medium Pro
- Cheapest Directed Tour Across All Locations Medium Pro
- Room Allocation with Custom Sorting, Streams, and Append-Only Logs Medium Pro