Quant Memo
Coding/●●●●

Trapping rain water with two pointers

Asked at DE Shaw

You're given n non-negative bar heights. After rain, water pools in the dips between taller bars. The water sitting above bar i is bounded by the tallest bar to its left and the tallest bar to its right: it equals min(maxLefti,maxRighti)heighti\min(\text{maxLeft}_i, \text{maxRight}_i) - \text{height}_i (never negative).

height = [3, 0, 2, 0, 4]
-> 7           # 3 + 1 + 3 units above the three dips

Return the total trapped water. Aim for O(n)O(n) time and O(1)O(1) space, and justify why the pointer you advance is the safe one.

Show a hint

At any moment you know the running max from the left and the running max from the right. The water over one bar is set by the smaller of the two walls. Which side can you resolve without knowing the other side exactly?

Your answer

This one is open-ended. Work it through, then check your reasoning against the full solution.

More Coding questions