KatInterview

Puddles in a Valley: Water Volume Between Terrain Columns

Arrays & HashingAuto-graded · 25 test cases
MediumAuto-gradedArrays & Hashingtwo-pointersprefix-maxarrays

Last updated

Tests whether a candidate can compute trapped water volume across a height profile using the two-pointer O(1)-space technique.

Puddles in a Valley: Water Volume Between Terrain Columns

Imagine a cross-section of uneven terrain represented as a row of vertical columns, each exactly one unit wide, standing flush against one another on level ground. After a rainstorm, water fills the low-lying gaps between taller columns. Any water that has no taller column blocking it on one side simply drains away off the edge of the terrain.

Given the column heights from left to right, return the total volume of water that remains pooled in the terrain, counted in unit squares.

Rules

  • Each column at index i has width 1 and height terrain[i]. A height of 0 means the ground is bare at that position.
  • A unit square of water sitting at position i at vertical level y (occupying the band from y to y + 1) is retained if and only if: terrain[i] <= y, there exists at least one column strictly taller than y somewhere to the left of i, and there exists at least one column strictly taller than y somewhere to the right of i.
  • Water that does not satisfy both conditions drains off. There are no walls or barriers beyond the leftmost and rightmost columns.
  • Return the total count of retained unit squares across all positions and all levels.

Constraints

  • 1 <= len(terrain) <= 10^5
  • 0 <= terrain[i] <= 10^5
  • The answer fits in a Python integer (it stays below 10^10, but may exceed 2^31 − 1).

Examples

Example 1

Input: trapped_water([3, 0, 2, 0, 4])

Output: 7

Example 2

Input: trapped_water([1, 2, 3, 2, 1])

Output: 0

Example 3

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

Output: 6

Hints

Hint 1

For any single column, the water it can hold is determined by the tallest column to its left and the tallest column to its right. What formula relates those two values to the water at that column?

Hint 2

A straightforward approach precomputes a left-max array and a right-max array in O(n) time and O(n) space. Can you derive the two-pointer technique from that?

Hint 3

With two pointers starting at opposite ends, you only need to process the side whose current bar is shorter. Ask yourself: if the left bar is shorter than the right bar, what does that tell you about the binding constraint on the left column?