KatInterview

Rainwater Held Between Terrain Columns

Arrays & HashingAuto-graded · 23 test cases
MediumAuto-gradedArrays & Hashingtwo-pointersarraysgreedy

Last updated

Compute total rainwater stored between unit-width columns of given heights, aiming for a single pass with constant extra memory using the two-pointer technique.

A strip of terrain is made of unit-width columns placed side by side. The list terrain gives the height of each column, from left to right. Every height is a non-negative integer.

After a heavy rain, water settles in the low areas between taller columns. Water cannot flow out past the ends of the strip, so it only stays above a column if there is a taller-or-equal column somewhere on both sides of it.

For a column at index i, the water sitting directly above it reaches the height of the lower of these two values:

  • the tallest column at or to the left of i, and
  • the tallest column at or to the right of i.

The amount of water above column i is that level minus the height of column i. This is never negative.

Return the total amount of water (in unit squares) held above all columns.

A straightforward approach checks every column against both sides and takes quadratic time. Aim for a solution that runs in linear time and uses only constant extra space.

Constraints

  • 0 <= len(terrain) <= 2 * 10^4
  • 0 <= terrain[i] <= 10^5
  • The return value is a single non-negative integer.
  • Strips with fewer than 3 columns hold no water, so the answer is 0.

Examples

Example 1

Input: stored_rainwater([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1])

Output: 6

Example 2

Input: stored_rainwater([4, 2, 0, 3, 2, 5])

Output: 9

Hints

Hint 1

For a single column, the water above it depends only on the smaller of two numbers: the tallest column to its left and the tallest column to its right (both including itself).

Hint 2

Precomputing prefix maxima and suffix maxima gives an O(n) time, O(n) space solution. To remove the arrays, notice you only need to know which side's maximum is smaller, not both exact values.

Hint 3

Use two pointers from the ends, with a running maximum for each side. Always advance the pointer whose current column is lower or equal; that side's running maximum is guaranteed to be the limiting level, so its water can be finalized immediately.