☰ All problems

21. Trapping Rain Water

You are given an array height of non-negative integers describing a skyline of bars, each 1 unit wide, placed side by side: bar i is height[i] units tall.

After heavy rain, water collects in the dips between bars. Return the total number of units of water the skyline traps. Water spills off both ends of the array.

Example 1
Input: height = [3,0,2,0,4]
Output: 7

Explanation: Water rises to level 3 between the outer bars: 3 + 1 + 3 = 7 units over positions 1, 2 and 3.

Example 2
Input: height = [2,1,3,0,1,2]
Output: 4

Explanation: One unit above position 1, then 2 + 1 units above positions 3 and 4 (capped by the final bar of height 2).

Example 3
Input: height = [1,2,3,4]
Output: 0

Explanation: The bars only get taller, so there is no dip to hold water.

Constraints

  • 1 <= height.length <= 2 * 10^4
  • 0 <= height[i] <= 10^5
💡 Hint 1

The water above bar i is min(tallest bar to its left, tallest bar to its right) - height[i] (counting bar i itself on both sides).

💡 Hint 2

Precomputing the left and right maxima in two arrays gives an O(n) time, O(n) space solution.

💡 Hint 3

For O(1) space, use two pointers. Whichever side has the smaller maximum so far is the bottleneck, so the water over that pointer is already known.

/**
 * @param {number[]} height
 * @return {number}
 */
function trap(height) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc