Trapping Rain Water II (LeetCode 407): Solution and Explanation

Hard
Array
Breadth First Search
Heap Priority Queue
Matrix

Given a 2D height map, compute how much rain water stays trapped. Water on each cell rises to the lowest wall that separates it from the edge of the map.

Intuition

In the 1D version, water at a position is limited by the shorter of the two tallest walls on either side. In 2D, water can escape in any direction, so a cell is limited by the lowest point of the tallest ring that encloses it.

The border cells can never hold water: anything poured on them runs off. They form the first ring of walls.

Water leaks out of a ring at its lowest point. So take the lowest wall on the ring: any unvisited neighbor behind it is enclosed by walls at least that high, and it fills exactly up to that level if it is lower.

After visiting a neighbor, it joins the ring with height max(level, its own height), since a filled cell acts as a wall at the water surface. A min-heap always hands you the current lowest wall.

Approach: Min-heap flood from the border

  1. Push every border cell into a min-heap as (height, r, c) and mark it visited.
  2. Pop the lowest entry (level, r, c).
  3. For each of the four neighbors that is in bounds and not visited, mark it visited and add max(0, level - height) to the answer.
  4. Push that neighbor with key max(level, height): either the water surface or its own top is the new wall.
  5. When the heap is empty, every cell has been reached from its lowest enclosing wall. Return the total.

Step-by-step example

heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]
  1. All 14 border cells go into the heap. The inner cells are (1,1)=2, (1,2)=1, (1,3)=3 and (1,4)=2.
  2. Pop a level-1 wall at (0,3): it reaches (1,3) of height 3, which holds no water and joins the heap as a wall of 3.
  3. The level-2 walls reach no new inner cells.
  4. Pop (0,2) at level 3: it reaches (1,2) of height 1, which fills 3 - 1 = 2 units.
  5. Pop (0,4) at level 3: it reaches (1,4) of height 2, which fills 1 unit.
  6. Pop (1,0) at level 3: it reaches (1,1) of height 2, which fills 1 unit.
  7. The heap drains with no more water. Total = 2 + 1 + 1 = 4.

Code: Python, Java, C++

1class Solution:
2    def trapRainWater(self, heightMap: List[List[int]]) -> int:
3        m, n = len(heightMap), len(heightMap[0])
4        seen = [[False] * n for _ in range(m)]
5        heap = []
6        for r in range(m):
7            for c in range(n):
8                if r == 0 or r == m - 1 or c == 0 or c == n - 1:
9                    heapq.heappush(heap, (heightMap[r][c], r, c))
10                    seen[r][c] = True
11        water = 0
12        while heap:
13            level, r, c = heapq.heappop(heap)
14            for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
15                if 0 <= nr < m and 0 <= nc < n and not seen[nr][nc]:
16                    seen[nr][nc] = True
17                    water += max(0, level - heightMap[nr][nc])
18                    heapq.heappush(heap, (max(level, heightMap[nr][nc]), nr, nc))
19        return water
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(mn log(mn))

Every cell is pushed and popped once, each heap operation costs O(log(mn)).

Space

O(mn)

The visited matrix and the heap can both hold every cell.

Other approaches

Repeated relaxation (time O((mn)^2) worst case, space O(mn))

Start every inner cell at infinity, then repeatedly set level = max(height, min neighbor level) until nothing changes. Correct, but it may need many passes over the grid.

Union-find by height (time O(mn log(mn)), space O(mn))

Process cells in increasing height and union them with lower neighbors, tracking which components touch the border. It works but is harder to get right than the heap.

Common mistakes

  • Applying the 1D row and column formula to each cell. Water can escape diagonally around obstacles, so the row and column maxima overestimate the level.
  • Pushing a filled neighbor with its own height instead of max(level, height); the water surface is the wall that matters.
  • Marking cells visited when popped instead of when pushed, which adds water to the same cell more than once.
  • Forgetting that grids with one or two rows or columns cannot hold any water.

Frequently asked questions

Why does popping the lowest wall give the right level?

Every cell still in the heap is at least as high as the popped one, and the visited region is sealed off by those cells. So the popped level is the lowest point a neighbor's water could leak through, which is exactly its fill level.

How is this related to Dijkstra's algorithm?

It is Dijkstra where the cost of a path is its highest wall instead of its sum. Each cell's final level is the minimum, over all paths to the border, of the maximum height along the path.

Can the total overflow a 32-bit int?

A cell holds at most 2 * 10^4 units and there are at most 40,000 cells, so the total stays under 8 * 10^8, which fits in an int.