KatInterview

407. Trapping Rain Water II

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to calculate the total volume of rainwater that can be trapped on a 2D elevation map represented by an m x n matrix. This is a 2D extension of the classic "Trapping Rain Water" problem.

Solution

Trapping Rain Water II in Python

import heapq

class Solution:
    def trapRainWater(self, heightMap: list[list[int]]) -> int:
        if not heightMap or not heightMap[0]:
            return 0
        
        m, n = len(heightMap), len(heightMap[0])
        if m < 3 or n < 3:
            return 0

        visited = [[False for _ in range(n)] for _ in range(m)]
        pq = []  # Min-heap

        # Add all border cells to the priority queue and mark them as visited
        for i in range(m):
            for j in range(n):
                if i == 0 or i == m - 1 or j == 0 or j == n - 1:
                    heapq.heappush(pq, (heightMap[i][j], i, j))
                    visited[i][j] = True

        total_water = 0
        dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]

        # Process cells from the priority queue, starting with the lowest height
        while pq:
            h, r, c = heapq.heappop(pq)

            # Explore neighbors
            for dr, dc in dirs:
                nr, nc = r + dr, c + dc

                # Check bounds and if the neighbor has been visited
                if 0 <= nr < m and 0 <= nc < n and not visited[nr][nc]:
                    # The water level is determined by the current wall height 'h'.
                    # If the neighbor is lower, it traps water.
                    if heightMap[nr][nc] < h:
                        total_water += h - heightMap[nr][nc]
                    
                    # The neighbor becomes part of the wall. Its effective height is the max
                    # of its own height and the water level that reached it.
                    heapq.heappush(pq, (max(h, heightMap[nr][nc]), nr, nc))
                    visited[nr][nc] = True
        
        return total_water

Trapping Rain Water II in Java

class Solution {
    public int trapRainWater(int[][] heightMap) {
        if (heightMap == null || heightMap.length == 0 || heightMap[0].length == 0) {
            return 0;
        }
        
        int m = heightMap.length;
        int n = heightMap[0].length;
        
        if (m < 3 || n < 3) {
            return 0;
        }

        // Min-heap to store cells [height, row, col]
        PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
        boolean[][] visited = new boolean[m][n];

        // Add all border cells to the priority queue and mark them as visited
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 || i == m - 1 || j == 0 || j == n - 1) {
                    pq.offer(new int[]{heightMap[i][j], i, j});
                    visited[i][j] = true;
                }
            }
        }

        int totalWater = 0;
        int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

        // Process cells from the priority queue, starting with the lowest height
        while (!pq.isEmpty()) {
            int[] cell = pq.poll();
            int h = cell[0];
            int r = cell[1];
            int c = cell[2];

            // Explore neighbors
            for (int[] dir : dirs) {
                int nr = r + dir[0];
                int nc = c + dir[1];

                // Check bounds and if the neighbor has been visited
                if (nr >= 0 && nr < m && nc >= 0 && nc < n && !visited[nr][nc]) {
                    // The water level is determined by the current wall height 'h'.
                    // If the neighbor is lower, it traps water.
                    if (heightMap[nr][nc] < h) {
                        totalWater += h - heightMap[nr][nc];
                    }
                    
                    // The neighbor becomes part of the wall. Its effective height is the max
                    // of its own height and the water level that reached it.
                    pq.offer(new int[]{Math.max(h, heightMap[nr][nc]), nr, nc});
                    visited[nr][nc] = true;
                }
            }
        }

        return totalWater;
    }
}

Trapping Rain Water II in C++

class Solution {
public:
    int trapRainWater(vector<vector<int>>& heightMap) {
        if (heightMap.empty() || heightMap[0].empty()) {
            return 0;
        }
        
        int m = heightMap.size();
        int n = heightMap[0].size();
        
        if (m < 3 || n < 3) {
            return 0;
        }

        // Min-heap to store cells {height, row, col}
        priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<tuple<int, int, int>>> pq;
        vector<vector<bool>> visited(m, vector<bool>(n, false));

        // Add all border cells to the priority queue and mark them as visited
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (i == 0 || i == m - 1 || j == 0 || j == n - 1) {
                    pq.push({heightMap[i][j], i, j});
                    visited[i][j] = true;
                }
            }
        }

        int totalWater = 0;
        int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

        // Process cells from the priority queue, starting with the lowest height
        while (!pq.empty()) {
            auto [h, r, c] = pq.top();
            pq.pop();

            // Explore neighbors
            for (auto& dir : dirs) {
                int nr = r + dir[0];
                int nc = c + dir[1];

                // Check bounds and if the neighbor has been visited
                if (nr >= 0 && nr < m && nc >= 0 && nc < n && !visited[nr][nc]) {
                    // The water level is determined by the current wall height 'h'.
                    // If the neighbor is lower, it traps water.
                    if (heightMap[nr][nc] < h) {
                        totalWater += h - heightMap[nr][nc];
                    }
                    
                    // The neighbor becomes part of the wall. Its effective height is the max
                    // of its own height and the water level that reached it.
                    pq.push({max(h, heightMap[nr][nc]), nr, nc});
                    visited[nr][nc] = true;
                }
            }
        }

        return totalWater;
    }
};

Trapping Rain Water II in TypeScript

type Cell = {
    height: number;
    r: number;
    c: number;
};

class MinPriorityQueue {
    private heap: Cell[] = [];

    // Using comparator on height
    private compare(a: Cell, b: Cell): number {
        return a.height - b.height;
    }

    private getParentIndex(i: number): number {
        return Math.floor((i - 1) / 2);
    }

    private getLeftChildIndex(i: number): number {
        return 2 * i + 1;
    }

    private getRightChildIndex(i: number): number {
        return 2 * i + 2;
    }

    private swap(i: number, j: number): void {
        [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];
    }

    private siftUp(i: number): void {
        let parentIndex = this.getParentIndex(i);
        while (i > 0 && this.compare(this.heap[i], this.heap[parentIndex]) < 0) {
            this.swap(i, parentIndex);
            i = parentIndex;
            parentIndex = this.getParentIndex(i);
        }
    }

    private siftDown(i: number): void {
        let minIndex = i;
        const leftIndex = this.getLeftChildIndex(i);
        if (leftIndex < this.heap.length && this.compare(this.heap[leftIndex], this.heap[minIndex]) < 0) {
            minIndex = leftIndex;
        }
        const rightIndex = this.getRightChildIndex(i);
        if (rightIndex < this.heap.length && this.compare(this.heap[rightIndex], this.heap[minIndex]) < 0) {
            minIndex = rightIndex;
        }
        if (i !== minIndex) {
            this.swap(i, minIndex);
            this.siftDown(minIndex);
        }
    }

    public push(cell: Cell): void {
        this.heap.push(cell);
        this.siftUp(this.heap.length - 1);
    }

    public pop(): Cell | undefined {
        if (this.heap.length === 0) return undefined;
        this.swap(0, this.heap.length - 1);
        const popped = this.heap.pop();
        if (this.heap.length > 0) {
            this.siftDown(0);
        }
        return popped;
    }

    public isEmpty(): boolean {
        return this.heap.length === 0;
    }
}

function trapRainWater(heightMap: number[][]): number {
    if (!heightMap || heightMap.length === 0 || heightMap[0].length === 0) {
        return 0;
    }

    const m = heightMap.length;
    const n = heightMap[0].length;

    if (m < 3 || n < 3) {
        return 0;
    }

    const pq = new MinPriorityQueue();
    const visited = Array.from({ length: m }, () => Array(n).fill(false));

    // Add all border cells to the priority queue and mark them as visited
    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            if (i === 0 || i === m - 1 || j === 0 || j === n - 1) {
                pq.push({ height: heightMap[i][j], r: i, c: j });
                visited[i][j] = true;
            }
        }
    }

    let totalWater = 0;
    const dirs = [[-1, 0], [1, 0], [0, -1], [0, 1]];

    // Process cells from the priority queue, starting with the lowest height
    while (!pq.isEmpty()) {
        const cell = pq.pop()!;
        const { height: h, r, c } = cell;

        // Explore neighbors
        for (const [dr, dc] of dirs) {
            const nr = r + dr;
            const nc = c + dc;

            // Check bounds and if the neighbor has been visited
            if (nr >= 0 && nr < m && nc >= 0 && nc < n && !visited[nr][nc]) {
                // The water level is determined by the current wall height 'h'.
                // If the neighbor is lower, it traps water.
                if (heightMap[nr][nc] < h) {
                    totalWater += h - heightMap[nr][nc];
                }

                // The neighbor becomes part of the wall. Its effective height is the max
                // of its own height and the water level that reached it.
                pq.push({ height: Math.max(h, heightMap[nr][nc]), r: nr, c: nc });
                visited[nr][nc] = true;
            }
        }
    }

    return totalWater;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.