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.
Example 1:
Input: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]] Output: 4 Explanation: After the rain, water is trapped between the blocks. We have two small ponds 1 and 3 units trapped. The total volume of water trapped is 4.
Example 2:
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.lengthn == heightMap[i].length1 <= m, n <= 2000 <= heightMap[i][j] <= 2 * 104When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a solid grid of blocks standing upright, and it starts raining over the whole structure so water collects in the various low spots. The brute force approach looks at every single interior spot in the grid independently to figure out how much water can pool right there.
Here's how the algorithm would work step-by-step:
def trap_rain_water_two(height_map):
if not height_map or not height_map[0]:
return 0
row_count = len(height_map)
col_count = len(height_map[0])
total_water_trapped = 0
# We only check interior cells because boundary cells cannot trap any water
for current_row in range(1, row_count - 1):
for current_col in range(1, col_count - 1):
current_height = height_map[current_row][current_col]
max_north = 0
for scan_row in range(current_row - 1, -1, -1):
if height_map[scan_row][current_col] > max_north:
max_north = height_map[scan_row][current_col]
max_south = 0
for scan_row in range(current_row + 1, row_count):
if height_map[scan_row][current_col] > max_south:
max_south = height_map[scan_row][current_col]
max_west = 0
for scan_col in range(current_col - 1, -1, -1):
if height_map[current_row][scan_col] > max_west:
max_west = height_map[current_row][scan_col]
max_east = 0
for scan_col in range(current_col + 1, col_count):
if height_map[current_row][scan_col] > max_east:
max_east = height_map[current_row][scan_col]
# Find the minimum of maximum obstacles because water spills over the lowest boundary
limiting_obstacle = min(max_north, max_south, max_west, max_east)
if limiting_obstacle > current_height:
total_water_trapped += limiting_obstacle - current_height
return total_water_trappedImagine the terrain as a solid landscape with walls of varying heights, where rain water can get trapped in the lowest basins. Instead of looking at the whole grid at once, the secret is to always process the lowest boundary wall first because water will always spill over the lowest edge before anything else.
Here's how the algorithm would work step-by-step:
import heapq
def trap_rain_water(height_map):
if not height_map or not height_map[0]:
return 0
row_count = len(height_map)
col_count = len(height_map[0])
visited_cells = [[False] * col_count for _ in range(row_count)]
boundary_min_heap = []
# We start by adding all outer boundary cells to the heap because water hitting the edge escapes immediately.
for row_index in range(row_count):
for col_index in range(col_count):
if row_index == 0 or row_index == row_count - 1 or col_index == 0 or col_index == col_count - 1:
heapq.heappush(boundary_min_heap, (height_map[row_index][col_index], row_index, col_index))
visited_cells[row_index][col_index] = True
total_water_volume = 0
row_directions = [-1, 1, 0, 0]
col_directions = [0, 0, -1, 1]
while boundary_min_heap:
current_height, current_row, current_col = heapq.heappop(boundary_min_heap)
for direction_index in range(4):
neighbor_row = current_row + row_directions[direction_index]
neighbor_col = current_col + col_directions[direction_index]
if 0 <= neighbor_row < row_count and 0 <= neighbor_col < col_count and not visited_cells[neighbor_row][neighbor_col]:
visited_cells[neighbor_row][neighbor_col] = True
# Water pools if the neighbor is lower than the current boundary wall holding it back.
if height_map[neighbor_row][neighbor_col] < current_height:
total_water_volume += current_height - height_map[neighbor_row][neighbor_col]
# The effective boundary height for the next neighbor is the max of its own height and current height.
pushed_height = max(height_map[neighbor_row][neighbor_col], current_height)
heapq.heappush(boundary_min_heap, (pushed_height, neighbor_row, neighbor_col))
return total_water_volume| Case | How to Handle |
|---|---|
| Empty or null matrix input | Return zero immediately as no water can be trapped without terrain. |
| Matrix dimensions smaller than three in either row or column | Return zero because water cannot be trapped without an inner region surrounded by borders. |
| Matrix with all identical cell heights | Return zero since no depressions exist to contain the water. |
| Terrain heights containing negative numbers and zeros | Treat values uniformly in the min-heap algorithm since only relative height differences matter for trapping water. |
| Step-like monotonically increasing or decreasing terrain | The priority queue correctly processes boundary cells from outside in, ensuring water leaks off edges with zero volume trapped. |
| Large scale matrices up to maximum constraint limits | Use a min-heap combined with a visited matrix to ensure an efficient time complexity of O(m * n * log(m + n)). |
| Extreme boundary values reaching maximum integer limits | Accumulate trapped water using standard 64-bit integers to prevent potential overflow issues. |
| Deep central basin surrounded by high walls | The greedy approach via priority queue progressively updates the effective boundary height, accurately filling and calculating the inner volume. |