407. Trapping Rain Water II
hardCompute the volume of water trapped on a 2D heightmap after rain. The 1D two-pointer trick doesn't generalize — the right answer is a min-heap walking the border inward.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an m x n integer matrix heightMap representing the height of each unit cell in a 2D elevation map, return the volume of water it can trap after raining.
Constraints
m == heightMap.lengthn == heightMap[i].length1 <= m, n <= 2000 <= heightMap[i][j] <= 2 * 10^4
Examples
Example 1
heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]4Explanation: After the rain, water is trapped between the blocks. The total volume of water trapped is 4.
Example 2
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]]10Explanation: The inner basin holds 10 units.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Hints
Progressive — try the first before opening the next.
Hint 1
Border cells trap zero water — water spills out.
Hint 2
For any interior cell, the water level above it is determined by the shortest 'wall' on every path to the boundary. That's a minimax problem.
Hint 3
Min-heap walk from the border inward. Always pop the shortest border cell — that's the weakest wall. Its unvisited neighbors are bounded by max(currentHeight, neighborHeight).
Hint 4
If neighborHeight < poppedHeight, the neighbor traps (poppedHeight - neighborHeight) water. Push the neighbor with effective height = max(currentHeight, neighborHeight).
Solution approach
Reveal approach
Push every border cell into a min-heap and mark visited. Loop: pop the shortest border (h, r, c). For each unvisited 4-neighbor (nr, nc) with height nh: if nh < h, water += h - nh (this cell sits below the weakest wall surrounding it). Push (max(h, nh), nr, nc) — the effective wall for cells beyond this one is the *higher* of h and nh, because water now has to surmount the current frontier. Mark visited. Continue until the heap empties. This is BFS/Dijkstra in spirit: you're always processing the lowest known wall, which guarantees that when you visit an interior cell, all paths to the boundary go through walls at least as high. O(mn log(mn)) time. Why not 1D's two-pointer? In 2D, 'left wall' and 'right wall' aren't well-defined — water can escape in any direction.
Complexity
- Time
- O(mn log(mn))
- Space
- O(mn)
Related patterns
- heap
- bfs
- matrix
Related problems
Asked at
Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).
- Amazon
- Meta
- Bloomberg
Practice these live with InterviewChamp.AI
Drill Trapping Rain Water II and Heaps problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →