Trapping Rain Water II

Hard

Topics
ArrayBFSHeapMatrix

Given an m x n matrix of non-negative integers representing the height of each cell, return the volume of water that can be trapped after raining.

Example 1

0143132132+11+232+142233231012345
Numbers are wall heights; a shaded cell reads height+water. A cell’s water level is set by the lowest ridge it must cross to escape, so the border can never hold water and the interior is solved by growing inward from the lowest wall. Total trapped: 4.
2D grid — one row per line.
Input:  heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]
Output: 4

Example 2

033333132+12+12+13232+11+22+13332+12+12+1343333301234
Input:  heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]]
Output: 10

Constraints

  • m == heightMap.length
  • n == heightMap[i].length
  • 1 <= m, n <= 200
  • 0 <= heightMap[i][j] <= 2*10^4.
Editorial — intuition, approach, complexity and pitfalls

Intuition

The 1-D version of this problem has a clean answer: water over a bar is min(maxLeft, maxRight) - height, so two prefix scans settle it. The instinct is to carry that over by taking the min of the four directional maxima. It does not work. In two dimensions water does not escape along a row or a column, it escapes along any path to the border, including ones that wind diagonally around obstacles. A cell can be hemmed in along both axes and still drain through a gap that no row-or-column maximum knows about.

So ask the right question. The water level at a cell is decided by the lowest point on the best escape route — of every path from that cell to the border, take the one whose highest obstacle is smallest, and that obstacle's height is the level. That is a bottleneck-shortest-path problem, not a prefix-max problem.

Rather than solve it per cell, flood the whole grid inward from the rim at once. The border is where water spills out, so it holds none. Keep the current rim in a min-heap and always process its lowest cell, because the lowest point on the rim is where the basin spills first and therefore fixes the level for whatever sits behind it.

When the lowest rim cell at level L has an unvisited neighbour of terrain height h:

  • h < L — the neighbour is a dip behind a wall of height L, so it fills with L - h water, and its surface joins the rim at level L.
  • h >= L — the neighbour is higher than the spill point, so it stays dry and joins the rim at its own height h.

Both cases push max(L, h), which is why one line covers them. Processing in increasing order of level is what makes a visited cell final: nothing cheaper can arrive later to lower it.

💡 This is Dijkstra with max in place of + — the cost of a path is its highest barrier rather than its total, and the greedy pop is correct for the same reason it is in Dijkstra.

Approach

  1. If either dimension is under 3 there is no interior cell, so return 0.
  2. Push every border cell into a min-heap keyed on its own height and mark it visited. These are the initial rim.
  3. Pop the lowest cell, giving level L. For each unvisited orthogonal neighbour of height h: mark it visited, add max(0, L - h) to the total, and push it at level max(L, h).
  4. Stop when the heap drains. Every cell has then been assigned its final level exactly once.

Dry Run

heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]. It is 3x6, so the only interior cells are the four at row 1, columns 1..4, with heights 2, 1, 3, 2. Expected answer 4.

rim starts as all 14 border cells, keyed on their own heights

pop level=1 at (0,3)  -> neighbour (1,3) h=3   h >= L, stays dry
                                              water += 0     total 0
                                              pushed at max(1,3) = 3

pop level=3 at (0,2)  -> neighbour (1,2) h=1   dip behind a wall of 3
                                              water += 3-1 = 2   total 2
                                              pushed at 3

pop level=3 at (0,4)  -> neighbour (1,4) h=2   water += 3-2 = 1   total 3
                                              pushed at 3

pop level=3 at (1,0)  -> neighbour (1,1) h=2   water += 3-2 = 1   total 4
                                              pushed at 3

heap drains over the remaining border cells; no unvisited neighbours left

answer 4

The instructive pop is the first. Cell (0,3) has height 1 and is the lowest thing on the rim, but its inward neighbour (1,3) stands at 3 — taller than the spill point, so it takes no water and rejoins the rim at its own height. Had we processed a taller rim cell first we would have wrongly flooded it. That ordering is exactly what the heap enforces.

Complexity

  • Time — O(m*n log(m*n)): every cell is pushed and popped at most once, and each heap operation is logarithmic in the number of cells held. The border seeding is O(m*n) pushes. With m, n <= 200 that is 40,000 cells and roughly 40,000 * 16 heap steps.
  • Space — O(m*n): the visited grid, plus a heap that in the worst case holds most of the grid at once. There is no way around the visited grid here — unlike the 1-D problem, which is O(1) with two pointers.

Common Pitfalls

  • Porting the 1-D formula and taking min of the four directional maxima. It overestimates, because water can escape by a winding path those maxima cannot see. This is the mistake the problem is built to catch.
  • Pushing the neighbour at its own height instead of max(L, h). A filled dip's surface is at L, and forgetting that lets later cells drain through water that is already standing.
  • Marking visited at pop time rather than push time. The same cell then enters the heap from several neighbours and its water is counted more than once.
  • Keying the heap on terrain height rather than water level. They coincide only on the border; after the first fill the level is what orders correctly.
  • Including diagonals as neighbours. Water moves orthogonally between cells here, even though the escape path argument is what motivates the algorithm.
  • Skipping the rows < 3 || cols < 3 guard. It is not strictly needed for correctness — with no interior cell nothing is ever filled — but the constraints allow 1 x 1, and the early return makes that explicit.
  • Letting the running total overflow a 32-bit int on a large grid. 200 x 200 cells at up to 2*10^4 each is about 8*10^8, which fits, but it is close enough that accumulating in a 64-bit type is the safer habit.

Full Solution — all languages

import heapq

class Solution:
    def trapRainWater(self, heightMap):
        if not heightMap or not heightMap[0]:
            return 0
        rows, cols = len(heightMap), len(heightMap[0])
        if rows < 3 or cols < 3:
            return 0                      # no interior cell, so nothing can be enclosed

        visited = [[False] * cols for _ in range(rows)]
        wall = []                         # min-heap of (water level, row, col)

        # The border can never hold water: it is the rim the basin drains over.
        for r in range(rows):
            for c in range(cols):
                if r in (0, rows - 1) or c in (0, cols - 1):
                    heapq.heappush(wall, (heightMap[r][c], r, c))
                    visited[r][c] = True

        water = 0
        while wall:
            # The lowest unprocessed wall decides where the basin spills first.
            level, r, c = heapq.heappop(wall)
            for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                nr, nc = r + dr, c + dc
                if 0 <= nr < rows and 0 <= nc < cols and not visited[nr][nc]:
                    visited[nr][nc] = True
                    # Below the surrounding level, the gap fills; otherwise it is dry
                    # and becomes part of the rim at its own height.
                    water += max(0, level - heightMap[nr][nc])
                    heapq.heappush(wall, (max(level, heightMap[nr][nc]), nr, nc))
        return water
Asked at Walmart Labs
SensAI
Beta
Tap the mic to stop voice mode