Trapping rain between the bars
Bars of given heights sit shoulder to shoulder. After rain, water pools in every dip that is walled in on both sides.
heights = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
-> 6 # total units of trapped water
Return the total trapped water. The naive "for each bar, scan for its tallest wall on each side" is ; aim for .
Show a hint
Water sits on top of a low bar only up to the shorter of the tallest walls to its left and right. A monotonic stack can settle each trapped layer the moment its right wall appears.
Your answer
This one is open-ended. Work it through, then check your reasoning against the full solution.