- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 40 lines of Python from the credited upstream file 407.py.
- The implementation visibly relies on sequence storage, ordered lookup, work queue.
- No explicit loop blocks detected.
Complexity
Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def trapRainWater(self, heightMap: list[list[int]]) -> int:3 DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))4 m = len(heightMap)5 n = len(heightMap[0])6 ans = 07 minHeap = []8 seen = set()9 10 for i in range(m):11 heapq.heappush(minHeap, (heightMap[i][0], i, 0))12 heapq.heappush(minHeap, (heightMap[i][n - 1], i, n - 1))13 seen.add((i, 0))14 seen.add((i, n - 1))15 16 for j in range(1, n - 1):17 heapq.heappush(minHeap, (heightMap[0][j], 0, j))18 heapq.heappush(minHeap, (heightMap[m - 1][j], m - 1, j))19 seen.add((0, j))20 seen.add((m - 1, j))21 22 while minHeap:23 h, i, j = heapq.heappop(minHeap)24 for dx, dy in DIRS:25 x = i + dx26 y = j + dy27 if x < 0 or x == m or y < 0 or y == n:28 continue29 if (x, y) in seen:30 continue31 if heightMap[x][y] < h:32 ans += h - heightMap[x][y]33 34 heapq.heappush(minHeap, (h, x, y))35 else:36 heapq.heappush(minHeap, (heightMap[x][y], x, y))37 seen.add((x, y))38 39 return ans40