Trapped Rainwater Volume on a 2D Elevation Grid
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
You are given a rectangular m x n grid height_map of non-negative integers, where height_map[r][c] denotes the ground elevation of unit square (r, c). After a heavy downpour saturates the entire grid, compute the total volume of standing water retained across all cells once runoff finishes draining.
def trap_rain_water(height_map: List[List[int]]) -> int:
pass
Water obeys two physical rules on the grid:
- Orthogonal movement only: Water flows between cells that share a side (north, south, east, or west), never across diagonal corners.
- Open perimeter: Any water reaching a cell on the outer edge of the grid (
r == 0,r == m - 1,c == 0, orc == n - 1) drains off the map immediately and cannot be held back.
Return a single integer equal to the sum of retained water depths over all m * n cells.
Examples
Example 1
Input:
height_map = [
[2, 5, 4, 5, 1],
[4, 1, 2, 1, 4],
[3, 4, 4, 3, 2]
]
Output:
5
Explanation: Only row 1, columns 1..3 ([1, 2, 1]) lie strictly inside the perimeter. Although corner (0, 4) has height 1, diagonal movement is not allowed, so the lowest orthogonal perimeter wall touching the interior trench is (2, 3) at elevation 3. All three interior squares fill to surface elevation 3, holding (3 - 1) + (3 - 2) + (3 - 1) = 2 + 1 + 2 = 5 units.
Example 2
Input:
height_map = [
[6, 6, 6, 6],
[6, 2, 3, 5],
[6, 1, 2, 4],
[6, 6, 6, 6]
]
Output:
8
Explanation: The 2 x 2 interior basin [[2, 3], [1, 2]] is surrounded by perimeter walls of heights 6, 5, and 4. Water spills out once it exceeds the 4-high notch at (2, 3), so every interior cell fills to level 4 and retains (4 - 2) + (4 - 3) + (4 - 1) + (4 - 2) = 8 units.
Constraints
m == len(height_map)n == len(height_map[r])for every0 <= r < m1 <= m, n <= 2000 <= height_map[r][c] <= 20000
Step-by-step walkthrough
Understand the terrain and why 2D differs from 1D
We are given an
m x ngridheight_mapwhereheight_map[r][c]is the ground elevation of square(r, c). Water moves between orthogonally adjacent cells (north, south, east, west), and any water reaching the outer perimeter drains off the map immediately. We want the total volume of standing water retained across all cells.If you have solved 1D Trapping Rain Water, it is tempting to scan straight left, right, up, and down from each cell and take the minimum of the four tallest walls. In 2D, that breaks because water can bend around corners! Look at cell
(1, 1)in this4 x 4grid:3 3 3 3 3 [1] 1 3 <-- Cell (1,1) sees height-3 walls straight up, down, left, and right, 3 1 1 0 yet its water flows right -> down -> right out the 0 gap! 3 3 3 3 Actual water retained = 0.Also note an immediate boundary fact: whenever
m < 3orn < 3, every cell sits on the outer perimeter, so0units can ever be retained.Brute-force mental model: water levels and iterative relaxation
For any cell
(r, c), think in terms of its final water surface level (ground elevation plus standing water depth). The water retained at(r, c)is simplywater_level - height_map[r][c].What determines an interior cell's
water_level? Water rises until it finds a path of 4-connected steps to the perimeter. Every escape path has some highest step (its bottleneck), and water escapes over the lowest bottleneck among all paths to the border:- On the perimeter,
water_level = height_map[r][c](drains immediately). - Inside the grid,
water_level = max(height_map[r][c], min(neighbor water_levels)).
A direct brute-force way to solve those equations is iterative relaxation: initialize every interior cell's level to the tallest height in the grid, then repeatedly sweep the grid and lower each cell's level to
max(height, lowest neighbor level)until a full sweep changes nothing. That works on tiny inputs, but along a winding snake-like channel of lengthm * n, a low perimeter level advances only one cell per sweep — costing up toO((m * n)^2)operations (~1.6 billion checks on a200 x 200grid).- On the perimeter,
Key insight: shrink the retaining wall from its lowest point
Instead of guessing high and relaxing repeatedly, we can lock in each cell's exact
water_levelonce, working inward from the perimeter.Picture the outer border of the grid as a closed retaining wall around the unknown interior. Where must interior water overflow first? Over the lowest cell anywhere on that retaining wall! Suppose the lowest wall cell has level
L, and it touches an unvisited interior neighbor(nr, nc)of ground heightH:- Water at
(nr, nc)cannot exceedmax(L, H), because any water aboveLspills directly onto this adjacent wall cell and off the map. - Water at
(nr, nc)cannot drop belowmax(L, H), because every path to the map edge must cross some cell of the current retaining wall, andLis the lowest wall cell anywhere!
Consequently,
(nr, nc)'s final water surface level is guaranteed to equalmax(L, H)right now. We addmax(L, H) - Hto our running total, mark(nr, nc)visited, and absorb(nr, nc)into the retaining wall with levelmax(L, H).To always pull the lowest cell on the active wall efficiently, we keep wall cells inside a min-heap (a binary-tree priority queue that pops its minimum element in
O(log N)time). In Python,heapqcompares tuples(water_level, r, c)lexicographically, soheappopalways yields the lowest active wall cell.- Water at
Seed the min-heap with the outer border
First, we push every perimeter cell (
r == 0,r == rows - 1,c == 0, orc == cols - 1) ontoboundary_heapat its ground height, markingvisited[r][c] = Trueas soon as it is pushed.Marking
visitedon push (rather than on pop) is vital: it ensures corner cells and interior cells are never pushed twice, preventing double-counting.from typing import List, Tuple import heapq def seed_outer_border( height_map: List[List[int]], ) -> Tuple[List[Tuple[int, int, int]], List[List[bool]]]: """Push every border cell onto a min-heap and mark it visited.""" rows = len(height_map) cols = len(height_map[0]) # visited[r][c] is True as soon as cell (r, c) is pushed onto the heap, # guaranteeing each cell is processed once and corners are never duplicated. visited = [[False] * cols for _ in range(rows)] # boundary_heap: min-heap of (water_level, row, col) tuples forming the active retaining wall boundary_heap: List[Tuple[int, int, int]] = [] for r in range(rows): for c in range(cols): if r == 0 or r == rows - 1 or c == 0 or c == cols - 1: heapq.heappush(boundary_heap, (height_map[r][c], r, c)) visited[r][c] = True return boundary_heap, visitedFlood inward and raise sunken neighbors to the wall level
Next, loop while
boundary_heapis non-empty: pop(boundary_level, r, c)and check each of its 4 orthogonal neighbors(nr, nc).Pay close attention to the elevation pushed onto
boundary_heapwheneverneighbor_height < boundary_level:Side-view cross section: wall=3 wall=3 water~~~3~~~ inner cell +----+ unvisited +----+~~~~~~~~~~~~+ sees a wall | 3 | height=1 --> | 3 | +2 water | ? of height 3, | | +----+ | | +----+ | NOT height 1! +----+---+ 1 + +----+------+-----+Once a sunken cell fills with water up to
boundary_level, that pooled water forms a flat surface at elevationboundary_level. So we pushwater_level = max(boundary_level, neighbor_height)onto the heap — notneighbor_height. Conversely, ifneighbor_height > boundary_level(for example, an inner ridge of height5inside a moat of level2),max(2, 5) = 5raises the wall height to5for any hollow tucked behind that ridge.from typing import List import heapq def trap_rain_water(height_map: List[List[int]]) -> int: if not height_map or not height_map[0]: return 0 rows = len(height_map) cols = len(height_map[0]) # Phase 1: Grids narrower than 3x3 have no interior cells — every cell touches the edge and spills. if rows < 3 or cols < 3: return 0 # Phase 2: Initialize the retaining wall with all outer boundary cells. boundary_heap, visited = seed_outer_border(height_map) # Phase 3: Repeatedly expand inward from the lowest point on the current retaining wall. trapped_water = 0 directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] while boundary_heap: boundary_level, r, c = heapq.heappop(boundary_heap) for dr, dc in directions: nr = r + dr nc = c + dc if nr < 0 or nr >= rows or nc < 0 or nc >= cols or visited[nr][nc]: continue visited[nr][nc] = True neighbor_height = height_map[nr][nc] # If neighbor_height < boundary_level, water fills the cell up to boundary_level. # Crucially, push max(boundary_level, neighbor_height) — NOT neighbor_height — because # the pooled water itself acts as a wall of height boundary_level for deeper cells behind it. water_level = max(boundary_level, neighbor_height) trapped_water += water_level - neighbor_height heapq.heappush(boundary_heap, (water_level, nr, nc)) return trapped_waterTrace Example 1 step by step
Let's trace Example 1 (
3 x 5grid, where row1, cols1..3are the 3 interior cells):c=0 c=1 c=2 c=3 c=4 r=0: 2 5 4 5 1 (all perimeter) r=1: 4 [1] [2] [1] 4 (3 interior cells in brackets) r=2: 3 4 4 3 2 (all perimeter)All 12 perimeter cells start inside
boundary_heap:1. Corner pops at levels 1 and 2 — (0,4)=1, (0,0)=2, (2,4)=2 — only touch already-visited perimeter cells. Notice (0,4)=1 cannot drain (1,3)=1 because diagonal flow is forbidden! 2. Pop (level=3, r=2, c=0): corner; orthogonal neighbors (1,0) and (2,1) are already visited. 3. Pop (level=3, r=2, c=3): -> discovers interior (1,3) of height 1: water_level = max(3, 1) = 3, adds 3 - 1 = 2 water, pushes (3, 1, 3). 4. Pop (level=3, r=1, c=3) <-- pooled water at (1,3) now acts as a height-3 wall! -> discovers interior (1,2) of height 2: water_level = max(3, 2) = 3, adds 3 - 2 = 1 water, pushes (3, 1, 2). 5. Pop (level=3, r=1, c=2): -> discovers interior (1,1) of height 1: water_level = max(3, 1) = 3, adds 3 - 1 = 2 water, pushes (3, 1, 1). 6. Remaining pops find all neighbors already visited. Total trapped water = 2 + 1 + 2 = 5.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple import heapq def seed_outer_border( height_map: List[List[int]], ) -> Tuple[List[Tuple[int, int, int]], List[List[bool]]]: """Push every border cell onto a min-heap and mark it visited.""" rows = len(height_map) cols = len(height_map[0]) # visited[r][c] is True as soon as cell (r, c) is pushed onto the heap, # guaranteeing each cell is processed once and corners are never duplicated. visited = [[False] * cols for _ in range(rows)] # boundary_heap: min-heap of (water_level, row, col) tuples forming the active retaining wall boundary_heap: List[Tuple[int, int, int]] = [] for r in range(rows): for c in range(cols): if r == 0 or r == rows - 1 or c == 0 or c == cols - 1: heapq.heappush(boundary_heap, (height_map[r][c], r, c)) visited[r][c] = True return boundary_heap, visited def trap_rain_water(height_map: List[List[int]]) -> int: if not height_map or not height_map[0]: return 0 rows = len(height_map) cols = len(height_map[0]) # Phase 1: Grids narrower than 3x3 have no interior cells — every cell touches the edge and spills. if rows < 3 or cols < 3: return 0 # Phase 2: Initialize the retaining wall with all outer boundary cells. boundary_heap, visited = seed_outer_border(height_map) # Phase 3: Repeatedly expand inward from the lowest point on the current retaining wall. trapped_water = 0 directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] while boundary_heap: boundary_level, r, c = heapq.heappop(boundary_heap) for dr, dc in directions: nr = r + dr nc = c + dc if nr < 0 or nr >= rows or nc < 0 or nc >= cols or visited[nr][nc]: continue visited[nr][nc] = True neighbor_height = height_map[nr][nc] # If neighbor_height < boundary_level, water fills the cell up to boundary_level. # Crucially, push max(boundary_level, neighbor_height) — NOT neighbor_height — because # the pooled water itself acts as a wall of height boundary_level for deeper cells behind it. water_level = max(boundary_level, neighbor_height) trapped_water += water_level - neighbor_height heapq.heappush(boundary_heap, (water_level, nr, nc)) return trapped_water✅ Submit now — all tests should pass.
Intuition & how it works
Imagine building a wooden retaining wall around the outer perimeter of an island: rainwater inside the island will always overflow across the lowest plank in that wall first. If the lowest plank has elevation L, any unvisited cell directly behind it cannot hold water above L (excess water spills right over that plank) and cannot drain lower than max(L, neighbor_height) (every other route to the sea must cross the retaining wall, where all planks are >= L). Once a sunken hollow fills up to L, its standing water forms a flat surface at elevation L that acts as the new retaining wall for cells further inland. Maintaining this shrinking wall with a min-heap (a binary-tree priority queue that pops its smallest element in O(log N) time) implements Priority-Flood — equivalent to Dijkstra's algorithm when path cost is the tallest step along a route rather than the sum of edge weights.
Why do simpler ideas fail? Extending 1D prefix/suffix maximums (taking the minimum of the tallest cells straight north, south, east, and west) overestimates water in 2D because water can snake around corners to escape through a distant low gap. Meanwhile, iteratively lowering each cell's water level toward its neighbors until convergence is accurate, but along a winding trench of length m * n a low border level propagates only one cell per pass, taking O((m * n)^2) time.
Let's trace Example 2 — a 4 x 4 basin [[2, 3], [1, 2]] ringed by 6s and 5, with one 4-high notch at (2, 3):
6 6 6 6 1. All 12 border cells enter the min-heap; lowest is (level=4, r=2, c=3).
6 [2][3] 5 2. Pop (4, 2, 3) -> visits (2,2)=2: retains 4-2=2, pushes (level=4, 2, 2).
6 [1][2] 4 --> 3. Pop (4, 2, 2) -> visits (1,2)=3 and (2,1)=1: retains 1+3=4, pushes both at level 4.
6 6 6 6 4. Pop (4, 1, 2) -> visits (1,1)=2: retains 4-2=2, pushes (level=4, 1, 1).
Total retained = 2 + 1 + 3 + 2 = 8 units (all four interior cells fill to level 4).
Complexity
Let N = m * n be the total number of cells in height_map.
- Time:
O(N log N). Each cell is markedvisitedthe moment it is pushed ontoboundary_heap, so the entire traversal performs at mostNheap pushes andNheap pops. Each heap operation on at mostNentries takesO(log N)time, and inspecting 4 neighbors per cell takesO(1)time. - Space:
O(N). Thevisitedmatrix storesNbooleans, andboundary_heapholds at mostN(water_level, row, col)tuples simultaneously.
Edge cases
- Thin grids (
m < 3orn < 3, including1 x 1): Every cell sits on the perimeter and drains immediately, returning0. - Flat, sloped, or pyramid terrains: Whenever every interior cell has a non-increasing orthogonal path to the perimeter,
water_level == neighbor_heighteverywhere and the total is0. - Single breach in a tall wall: One
0on the border connected to a low interior basin drains the entire basin to0. - Low diagonal corners (
[[2,5,4,5,1],[4,1,2,1,4],[3,4,4,3,2]]): Because movement is strictly 4-directional, the1at corner(0, 4)cannot drain adjacent interior cell(1, 3), which still fills to3. - Peaks or nested basins inside a pool: A tall pillar (
9) inside a level-4pool addsmax(4, 9) - 9 = 0without blocking flow around it, while a closed inner ring of5s inside a level-2moat raiseswater_levelto5for any deeper hollow inside that ring. - Maximum constraints (
200 x 200border of20000around0s): Retains198 * 198 * 20000 = 784,080,000units (fitting comfortably in 32-bit signed integers, and Pythonints have arbitrary precision).
Common mistakes
- Pushing
neighbor_heightinstead ofmax(boundary_level, neighbor_height): If cell(2, 2)of ground height2fills up to4and you push2onto the heap, neighbor(2, 1)sees a wall of height2instead of4and undercounts trapped water! - Using 1D row and column prefix maximums: Checking only straight sightlines misses bent escape routes that turn corners.
- Marking
visitedon pop rather than on push (or pushing corners twice): Lets the same cell enter the heap multiple times, double-counting its retained water. - Using a plain FIFO queue (BFS) instead of a min-heap: Flooding inward from a height-
6wall before the height-4notch is processed overfills the basin to6.
Alternative approaches
- Bucket queue (Dial's algorithm) in
O(N + H)time: Since0 <= height_map[r][c] <= 20000, you can replace the binary heap with an array ofH + 1 = 20001lists (bucket queue — an array indexed directly by integer priority so minimum extraction scans upward withoutlog Ncomparisons). Becausemax(boundary_level, neighbor_height) >= boundary_level, the active minimum bucket index never moves backward. - Iterative relaxation (
O(N^2)worst case): Repeatedly loweringlevel[r][c] = max(height[r][c], min_neighbor_level)until nothing changes is too slow on winding200 x 200grids, but serves as a compact brute-force oracle for randomized tests.
Follow-up questions
- What changes if water is also able to drain across diagonal neighbors (8-directional connectivity instead of 4)? Append the four diagonal offsets
(1, 1), (1, -1), (-1, 1), (-1, -1)todirectionsand keep the rest of the algorithm identical — the lowest-wall invariant holds on any undirected cell-adjacency graph! Adding diagonal edges only introduces extra escape paths, so water levels can only stay the same or drop (for instance, in Example 1, corner(0, 4) = 1would connect diagonally to(1, 3)and drain part of the trench). In an interview, clarify whether diagonal water is permitted to squeeze between two orthogonally touching wall cells. - How would you adapt the traversal to output an
m x nmatrix of final water-surface elevations rather than a single scalar volume? Initializesurface = [row[:] for row in height_map]so perimeter cells already hold their ground elevations. Wheneverheappopyields(boundary_level, r, c)and reaches an unvisited neighbor(nr, nc), assignsurface[nr][nc] = max(boundary_level, height_map[nr][nc])and push(surface[nr][nc], nr, nc)onto the heap; returnsurfaceonce the heap empties. - Suppose the elevation raster measures
100,000 x 100,000and exceeds available RAM — how could you compute the trapped volume out of core? A100,000 x 100,000grid contains10^10cells (~20 GB as 16-bit integers, plus tens of gigabytes forvisitedand heap nodes), and random heap accesses thrash disk I/O, so apply out-of-core tiled processing (partitioning a dataset larger than RAM into self-contained sub-grids processed sequentially or in parallel, as in Barnes's parallel Priority-Flood algorithm). Partition the raster into2,000 x 2,000tiles (2,500tiles of ~8 MB each, with ~20 million tile-border cells total):- Pass 1 (local tile summary, in parallel): Load one tile at a time, flood inward from its tile border, and record the minimum spill elevation between touching border segments to compress each tile into a small perimeter graph.
- Pass 2 (global border solve in RAM): Connect the ~20 million tile-border cells across adjacent tiles, seed the true outer perimeter of the
100,000 x 100,000raster into a min-heap, and solve every tile-border cell's global water elevation. - Pass 3 (final tile flood, in parallel): Reload each tile, seed its border cells with their solved global water elevations from Pass 2, run
trap_rain_waterinside the tile, and sum volumes in a 64-bit integer (10^10 * 20000 = 2 * 10^14exceeds 32-bit range).
Follow-up questions
- What changes if water is also able to drain across diagonal neighbors (8-directional connectivity instead of 4)?
- How would you adapt the traversal to output an `m x n` matrix of final water-surface elevations rather than a single scalar volume?
- Suppose the elevation raster measures `100,000 x 100,000` and exceeds available RAM — how could you compute the trapped volume out of core?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array