Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Two pointers

Rain water trapped between walls

Hard · Target 25 minutes · Two pointers

height[i] is the height of a wall of width 1 at position i. After rain, water collects between the walls. Return the total amount of water held, in units of area.

Examples

InputOutputWhy
height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]6
height = [4, 2, 0, 3, 2, 5]9Water levels 4, 4, 4, 4 over the four inner columns: 2 + 4 + 1 + 2.

Constraints

  • 1 ≤ n ≤ 2 × 10⁴
  • 0 ≤ height[i] ≤ 10⁵

Hints

Hint 1

Think one column at a time. How high does the water stand above column i?

Hint 2

It stands at min(tallest wall to the left, tallest wall to the right), including column i itself. Two arrays of prefix and suffix maxima give O(n) time and O(n) memory.

Hint 3

With pointers at both ends, keep the highest wall seen from the left and from the right. Whichever side has the lower maximum: that maximum is the water level at that pointer, whatever lies between.

Where people lose marks

  • Moving the pointer on the side with the taller wall: the level there is not yet known, because the other side's maximum is the limit.
  • Updating the running maximum after adding water instead of before, which can add a negative amount at a new tallest wall.
  • Summing in a 32-bit integer: n × max height reaches 2 × 10⁹ at these limits, close to overflow.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.