Trapping Rain Water II - 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.

Water can flow from one cell to another if the height difference allows it. Water will flow out if it can reach the boundary of the matrix.

Example: If we have a heightMap like [[3,3,3],[3,2,3],[3,3,3]], the center cell with height 2 can trap 1 unit of water (making effective height 3).

Input & Output

Example 1 — Simple Basin
$ Input: heightMap = [[3,3,3,3,4],[3,2,2,3,4],[3,2,1,3,4],[4,4,4,4,4]]
Output: 5
💡 Note: The basin in the middle can trap water. Cell (2,2) with height 1 can hold water up to level 3 (trapped: 2). Cells (1,1), (1,2), (2,1) with height 2 can hold water up to level 3 (trapped: 1 each). Total: 2 + 1 + 1 + 1 = 5.
Example 2 — No Water Trapped
$ Input: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]
Output: 4
💡 Note: Some interior cells can trap water where they are surrounded by higher cells that create barriers to the boundary.
Example 3 — Single Cell
$ Input: heightMap = [[5]]
Output: 0
💡 Note: Single cell cannot trap any water as it's also a boundary cell.

Constraints

  • m == heightMap.length
  • n == heightMap[i].length
  • 1 ≤ m, n ≤ 200
  • 0 ≤ heightMap[i][j] ≤ 2 × 104

Visualization

Tap to expand
Trapping Rain Water II INPUT 2D Elevation Map (4x5) 3 3 3 3 4 3 2 2 3 4 3 2 1 3 4 4 4 4 4 4 Low (can trap water) Boundary/High heightMap = [[3,3,3,3,4], [3,2,2,3,4], [3,2,1,3,4], [4,4,4,4,4]] ALGORITHM STEPS 1 Init Min-Heap Add all boundary cells to heap with heights Heap: [(3,0,0),(3,0,1), (4,0,4),(4,3,0)...] 2 Process Min Height Pop smallest height cell from heap each time 3 Check Neighbors For each unvisited neighbor: water = max(0, curr - nbr) 4 Update and Add Add neighbor to heap with max(curr_h, nbr_h) Cell(2,2) h=1, water_level=3 Water trapped = 3-1 = 2 Repeat for all inner cells FINAL RESULT Water Trapped Visualization +1 water +1 water +1 water +2 water +0 +0 Water Calculation Cell(1,1): 3-2 = 1 Cell(1,2): 3-2 = 1 Cell(2,1): 3-2 = 1 Cell(2,2): 3-1 = 2 +2 more Output: 7 Total water trapped Key Insight: Use a Min-Heap to process boundary cells from lowest to highest. Water at any cell is determined by the minimum height path to the boundary. By processing cells in height order (BFS with priority), we ensure water levels propagate correctly inward. Time: O(mn log(mn)), Space: O(mn) TutorialsPoint - Trapping Rain Water II | Optimal Min-Heap BFS Solution
Asked in
Google 25 Amazon 20 Facebook 15 Microsoft 10
25.0K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen