Trapping Rain Water

50 min · trap()

After a storm, a jagged rooftop can hold surprising pockets of water. The trick is measuring every pocket without pouring the rain into a simulation.

An elevation map is an array where height[i] gives the height of a one-unit-wide vertical bar at position i. Given that map, return the total number of water units trapped between the bars after rain falls.

A few ground rules:

  • Every height is a non-negative integer.
  • Water can escape past either end of the array.
  • A position holds water only when taller boundaries exist on both sides.
  • Return the combined volume above all positions, not the water at just one position.

Constraints

  • 0 <= height.length <= 20_000
  • 0 <= height[i] <= 10_000
  • The total trapped water is at most 200_000_000, safely within the judge's integer range.

Hints

Solve one position first

For one index, find the tallest bar on its left and the tallest bar on its right. The shorter boundary decides the waterline; subtract the current bar's height.

Stop rediscovering the same walls

A prefix maximum is the tallest bar seen so far from the left; a suffix maximum is the same idea from the right. Storing both removes the repeated scans. Can you keep only the boundary information needed at this moment?

Trust the lower side

Put one pointer at each end. When the left bar is no taller than the right bar, the right side already supplies a sufficient boundary for the left position, so update left_max, add any water there, and move left inward. Mirror that rule on the other side.

Follow-up

Can you reach O(n) time and O(1) extra space without building prefix or suffix arrays?

Visible cases

Examples

Example 1

ready
Input
height = [
  0,
  1,
  0,
  2,
  1,
  0,
  1,
  3,
  2,
  1,
  2,
  1
]
Expected
6
Why
the separate pockets hold 1 + 1 + 2 + 1 + 1 units

Example 2

ready
Input
height = [
  5,
  4,
  3,
  2,
  1
]
Expected
0
Why
a descending slope has no right wall to hold water

Example 3

ready
Input
height = [
  4,
  2,
  0,
  3,
  2,
  5
]
Expected
9
Why
the outer and inner walls create several connected pockets

Interview signal

Asked at

AmazonGoogleGoldman Sachs
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite