Trapping Rain Water II

HardHeapheap

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

heightMap is an m x n grid where each cell holds the height of a unit-square column. After heavy rain, water settles on top of the columns; water can flow to any of the four edge-adjacent cells and drains away off the grid's border. Return the total volume of water that stays trapped. Aim for O(m * n * log(m * n)) time.

Examples

Input: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]
Output: 4
In the middle row, the cell of height 1 holds 2 units and the two cells of height 2 hold 1 unit each.
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
The whole interior fills to level 3: 8 cells hold 1 unit and the centre holds 2.

Constraints

  • m == heightMap.length
  • n == heightMap[i].length
  • 1 <= m, n <= 200
  • 0 <= heightMap[i][j] <= 2 * 10^4

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More heap problems