Taro Logo

Trapping Rain Water II

#2 Most AskedHard
0 views
Topics:
ArraysGraphsDynamic ProgrammingGreedy Algorithms

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.length
  • n == heightMap[i].length
  • 1 <= m, n <= 200
  • 0 <= heightMap[i][j] <= 2 * 104

Solution


Clarifying Questions

When 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:

  1. What are the dimensions of the 2D elevation map, and can the grid be non-rectangular or jagged?
  2. Can the elevation values be negative, or are they guaranteed to be non-negative integers?
  3. What should be returned if the grid dimensions are smaller than 3x3, such that no water can possibly be trapped?
  4. Are cells on the outer boundary of the grid considered to have a height of zero for trapping water, or do they immediately leak all water off the edge?
  5. Is there a possibility of disjoint pools or complex multi-level basins that share boundaries, and how should water sharing between them be calculated?

Brute Force Solution

Approach

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:

  1. Pick a starting interior spot on the grid where water could potentially pool.
  2. Pretend you are standing at that chosen spot and look outward in every horizontal and vertical direction toward the outer edge of the grid.
  3. Find the tallest obstacle blocking your view in each of those four directions.
  4. Identify the shortest among those tallest obstacles, because that limits how high the water can rise before spilling over.
  5. Compare the height of that limiting obstacle to the height of your chosen spot to see how deep the pooled water will be.
  6. If the limiting obstacle is taller than your spot, calculate the difference as the amount of trapped water at this location.
  7. If the limiting obstacle is shorter than or equal to your spot, note that no water can be trapped here.
  8. Repeat this entire process for every single interior spot in the grid.
  9. Add up the water collected at all the spots to get the total amount of trapped rainwater.

Code Implementation

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_trapped

Big(O) Analysis

Time Complexity
O(r^2 * c^2) – The input size is defined by the grid dimensions, with r rows and c columns, giving approximately r times c interior spots to evaluate. For each of these interior spots, we scan outward in four directions toward the outer edge, which takes an amount of operations proportional to the total dimensions r plus c. Evaluating every interior spot means we multiply the number of spots by the cost of scanning, leading to roughly r times c times (r plus c) operations. In the worst case where r and c are roughly equal to n, this formula approximates n cubed operations, simplifying to a cubic time complexity.
Space Complexity
O(M * N) – To implement the boundary-shrinking and visiting process described in the steps, the algorithm requires a 2D boolean grid of size M by N to keep track of visited locations, preventing redundant processing of interior spots. Additionally, a priority queue or min-heap is used to store boundary blocks, which in the worst-case scenario can hold up to 2M + 2N minus 4 elements along the perimeter. Defining the total number of cells as N equals M times M, the visited grid and priority queue dominate the auxiliary memory. Combining these structures results in a total extra space complexity that scales linearly with the total number of grid cells.

Optimal Solution

Approach

Imagine 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:

  1. Begin by placing guards all along the outer edge of the landscape, since any water hitting the very border would simply spill off the edge and escape.
  2. Identify the single lowest guard from your active group, because that specific point is the weakest link holding back water.
  3. Look inward from that lowest guard to inspect its immediate neighbor that hasn't been checked yet.
  4. If the neighbor is lower than the current guard, it means water can pool right there, and the amount of trapped water is calculated by the difference in their heights.
  5. If the neighbor is taller, no water gets trapped, but it now acts as a brand new wall.
  6. Add this neighbor to your group of active guards, pretending it now has the height of either itself or the previous guard, whichever is taller, to represent water already filling the space.
  7. Repeat this process of always pulling out the lowest guard and checking its unvisited neighbors until the entire landscape has been explored.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(R * C * log(R * C)) – Given a grid with R rows and C columns, step 1 visits all boundary cells and adds them to a priority queue, costing O(R + C). Steps 2 through 7 process each of the total R * C cells exactly once by extracting the minimum boundary element in logarithmic time, which takes O(log(R * C)) per cell. Summing these extractions across all cells results in approximately (R * C) * log(R * C) total operations. Letting n represent the total number of cells in the grid, this simplifies to O(n log n).
Space Complexity
O(M * N) – To implement the strategy of always processing the lowest boundary wall, we maintain a min-heap priority queue and a two-dimensional visited boolean matrix that scale with the dimensions of the grid. Let N be the total number of cells in the landscape, meaning M and N rows and columns. The min-heap stores at most all the boundary cells, while the visited matrix keeps track of every single cell in the grid. Consequently, these auxiliary data structures consume memory proportional to the total number of cells, resulting in a space complexity of O(N).

Edge Cases

Empty or null matrix input
How to Handle:
Return zero immediately as no water can be trapped without terrain.
Matrix dimensions smaller than three in either row or column
How to Handle:
Return zero because water cannot be trapped without an inner region surrounded by borders.
Matrix with all identical cell heights
How to Handle:
Return zero since no depressions exist to contain the water.
Terrain heights containing negative numbers and zeros
How to Handle:
Treat values uniformly in the min-heap algorithm since only relative height differences matter for trapping water.
Step-like monotonically increasing or decreasing terrain
How to Handle:
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
How to Handle:
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
How to Handle:
Accumulate trapped water using standard 64-bit integers to prevent potential overflow issues.
Deep central basin surrounded by high walls
How to Handle:
The greedy approach via priority queue progressively updates the effective boundary height, accurately filling and calculating the inner volume.
0/38 completed