Skip to content
Decoder

Trapping Rain Water

Hard

Problem

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.

Example 1

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

Example 2

Input
height = [4, 2, 0, 3, 2, 5]
Output
9

Example 3

Input
height = [3, 0, 3]
Output
3

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

Constraints

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

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.