Skip to content

Trapping Rain Water

HardTwo Pointers
Decode it first. Clues, constraints, pattern and plan before any code.

A list height describes an elevation map of bars, each one unit wide. After it rains, water settles in the dips between taller bars. Return how many units of water are trapped in total.

height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]   →  6
height = [4, 2, 0, 3, 2, 5]                     →  9
height = [3, 0, 3]                              →  3

Aim for O(n) time and O(1) extra space.

Constraints

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