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, or c == 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 every 0 <= r < m
  • 1 <= m, n <= 200
  • 0 <= height_map[r][c] <= 20000

Step-by-step walkthrough

  1. Understand the terrain and why 2D differs from 1D

    We are given an m x n grid height_map where height_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 this 4 x 4 grid:

    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 < 3 or n < 3, every cell sits on the outer perimeter, so 0 units can ever be retained.

  2. 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 simply water_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 length m * n, a low perimeter level advances only one cell per sweep — costing up to O((m * n)^2) operations (~1.6 billion checks on a 200 x 200 grid).

  3. 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_level once, 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 height H:

    1. Water at (nr, nc) cannot exceed max(L, H), because any water above L spills directly onto this adjacent wall cell and off the map.
    2. Water at (nr, nc) cannot drop below max(L, H), because every path to the map edge must cross some cell of the current retaining wall, and L is the lowest wall cell anywhere!

    Consequently, (nr, nc)'s final water surface level is guaranteed to equal max(L, H) right now. We add max(L, H) - H to our running total, mark (nr, nc) visited, and absorb (nr, nc) into the retaining wall with level max(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, heapq compares tuples (water_level, r, c) lexicographically, so heappop always yields the lowest active wall cell.

  4. Seed the min-heap with the outer border

    First, we push every perimeter cell (r == 0, r == rows - 1, c == 0, or c == cols - 1) onto boundary_heap at its ground height, marking visited[r][c] = True as soon as it is pushed.

    Marking visited on 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, visited
    
  5. Flood inward and raise sunken neighbors to the wall level

    Next, loop while boundary_heap is 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_heap whenever neighbor_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 elevation boundary_level. So we push water_level = max(boundary_level, neighbor_height) onto the heap — not neighbor_height. Conversely, if neighbor_height > boundary_level (for example, an inner ridge of height 5 inside a moat of level 2), max(2, 5) = 5 raises the wall height to 5 for 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_water
    
  6. Trace Example 1 step by step

    Let's trace Example 1 (3 x 5 grid, where row 1, cols 1..3 are 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.
    
  7. 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 marked visited the moment it is pushed onto boundary_heap, so the entire traversal performs at most N heap pushes and N heap pops. Each heap operation on at most N entries takes O(log N) time, and inspecting 4 neighbors per cell takes O(1) time.
  • Space: O(N). The visited matrix stores N booleans, and boundary_heap holds at most N (water_level, row, col) tuples simultaneously.

Edge cases

  • Thin grids (m < 3 or n < 3, including 1 x 1): Every cell sits on the perimeter and drains immediately, returning 0.
  • Flat, sloped, or pyramid terrains: Whenever every interior cell has a non-increasing orthogonal path to the perimeter, water_level == neighbor_height everywhere and the total is 0.
  • Single breach in a tall wall: One 0 on the border connected to a low interior basin drains the entire basin to 0.
  • Low diagonal corners ([[2,5,4,5,1],[4,1,2,1,4],[3,4,4,3,2]]): Because movement is strictly 4-directional, the 1 at corner (0, 4) cannot drain adjacent interior cell (1, 3), which still fills to 3.
  • Peaks or nested basins inside a pool: A tall pillar (9) inside a level-4 pool adds max(4, 9) - 9 = 0 without blocking flow around it, while a closed inner ring of 5s inside a level-2 moat raises water_level to 5 for any deeper hollow inside that ring.
  • Maximum constraints (200 x 200 border of 20000 around 0s): Retains 198 * 198 * 20000 = 784,080,000 units (fitting comfortably in 32-bit signed integers, and Python ints have arbitrary precision).

Common mistakes

  • Pushing neighbor_height instead of max(boundary_level, neighbor_height): If cell (2, 2) of ground height 2 fills up to 4 and you push 2 onto the heap, neighbor (2, 1) sees a wall of height 2 instead of 4 and undercounts trapped water!
  • Using 1D row and column prefix maximums: Checking only straight sightlines misses bent escape routes that turn corners.
  • Marking visited on 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-6 wall before the height-4 notch is processed overfills the basin to 6.

Alternative approaches

  • Bucket queue (Dial's algorithm) in O(N + H) time: Since 0 <= height_map[r][c] <= 20000, you can replace the binary heap with an array of H + 1 = 20001 lists (bucket queue — an array indexed directly by integer priority so minimum extraction scans upward without log N comparisons). Because max(boundary_level, neighbor_height) >= boundary_level, the active minimum bucket index never moves backward.
  • Iterative relaxation (O(N^2) worst case): Repeatedly lowering level[r][c] = max(height[r][c], min_neighbor_level) until nothing changes is too slow on winding 200 x 200 grids, 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) to directions and 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) = 1 would 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 n matrix of final water-surface elevations rather than a single scalar volume? Initialize surface = [row[:] for row in height_map] so perimeter cells already hold their ground elevations. Whenever heappop yields (boundary_level, r, c) and reaches an unvisited neighbor (nr, nc), assign surface[nr][nc] = max(boundary_level, height_map[nr][nc]) and push (surface[nr][nc], nr, nc) onto the heap; return surface once the heap empties.
  • Suppose the elevation raster measures 100,000 x 100,000 and exceeds available RAM — how could you compute the trapped volume out of core? A 100,000 x 100,000 grid contains 10^10 cells (~20 GB as 16-bit integers, plus tens of gigabytes for visited and 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 into 2,000 x 2,000 tiles (2,500 tiles of ~8 MB each, with ~20 million tile-border cells total):
    1. 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.
    2. 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,000 raster into a min-heap, and solve every tile-border cell's global water elevation.
    3. 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_water inside the tile, and sum volumes in a 64-bit integer (10^10 * 20000 = 2 * 10^14 exceeds 32-bit range).

Follow-up questions

Similar questions

More Chalk interview questions

All 1 Chalk questions →