Trapping Rain Water

Hard Two Pointers AI round

height is a row of walls, one unit wide each, standing side by side in the order of the list. Each number is the height of one wall, and none is negative.

Rain falls on the row. The water over a wall rises to the lower of two heights: the tallest wall at or before it, and the tallest wall at or after it (the wall itself counts). If that is no more than the wall's own height, there is no water over it. Water runs off past the first and last walls.

Return the total amount of water the row holds, counting one unit of water for each unit of width and each unit of height.

Example 1

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

The wall of 3 on the left is the lower of the two sides, so the water stands 3 units high: 3 units over the first 0, 1 unit over the 2 and 3 units over the second 0, for 7 in all. The 4 on the right is never filled to its top.

Example 2

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

Example 3

Input: height = [5,1,1,4]
Output: 6

Constraints

  • 1 ≤ height.length ≤ 10⁵
  • 0 ≤ height[i] ≤ 10⁴

Watch the explanation

More Two Pointers

All Two Pointers problems