Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Rain falls on a 2-D height map. Compute the trapped water volume with a min-heap that grows inward from the border.

Problem: Rain falls on a 2-D height map. Compute the trapped water volume with a min-heap that grows inward from the border.
import heapq
def trap(h):
    R, C = len(h), len(h[0]); seen = set(); pq = []
    for r in range(R):
        for c in range(C):
            if r in (0, R - 1) or c in (0, C - 1): heapq.heappush(pq, (h[r][c], r, c)); seen.add((r, c))
    water = 0
    while pq:
        lv, r, c = heapq.heappop(pq)
        for x, y in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)):
            if 0 <= x < R and 0 <= y < C and (x, y) not in seen:
                seen.add((x, y)); water += max(0, lv - h[x][y])
                heapq.heappush(pq, (max(lv, h[x][y]), x, y))
    return water
print(trap([[3,3,3,3,3],[3,1,2,1,3],[3,2,0,4,3],[3,3,1,3,3]]))
What is printed?
  1. A. 3
  2. B. 11
  3. C. 9
  4. D. 13

Correct answer: A. 3

Each inner cell fills to its 'spill height', the lowest possible maximum wall on a path to the border. The 0 at (2, 2) drains through the border gap of height 1, so it holds 1 unit; the 1s at (1, 1) and (1, 3) are enclosed by walls of height 2 and hold 1 unit each; the 2s hold nothing. Total 3.

More Coding Interview Problems questions

Exams that ask this topic