Trapping Rain Water

IF
AlgoAxiomStaff Engineers
JSTS
Hard20 mins

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

Examples

Example 1:

Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]

Output: 6

Explanation: The elevation map [0,1,0,2,1,0,1,3,2,1,2,1] traps 6 units of rain water. Water fills the valleys between the bars: 1 unit between indices 1-3, 4 units between indices 3-7, and 1 unit between indices 8-10.

Example 2:

Input: height = [4,2,0,3,2,5]

Output: 9

Explanation: Water fills the gap between the tall bars at indices 0 and 5, trapping 2 + 4 + 1 + 2 = 9 units total.

Example 3:

Input: height = [1,0,1]

Output: 1

Explanation: One unit of water is trapped between the two bars of height 1.

Constraints

  • n == height.length
  • 1 <= n <= 2 * 10⁴
  • 0 <= height[i] <= 10⁵
Source: Two Pointers pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle