Maintained by Vikas Dulgunde, software engineer
You are handed a list of non-negative integers. Each value is the height of a vertical bar, and every bar is one unit wide. Picture the bars sitting side by side to form a jagged skyline.
When rain falls, water collects in the low spots between taller bars. A position holds water only when there is something taller than it on both its left and its right, and the depth at that position is set by the shorter of those two walls.
Your job is to add up the trapped water across every position and return that single number. If the profile only rises, only falls, or is flat, no water is held and the answer is zero.
Heights can repeat, can be zero, and the array can be empty. You do not modify the input; you just measure how much it would retain.
Water settles in the dips formed by the taller bars on either side. Summing the depth held at each column gives 6 units.
The 5 on the right and the 4 on the left act as walls. The columns at heights 2, 0, 3, 2 fill up to the height of the shorter enclosing wall, totaling 9.
The profile strictly rises, so no column has a taller bar on its right. Nothing is trapped.
Visible test cases
For one column, the water sitting on top of it equals min(tallest bar to its left, tallest bar to its right) minus its own height, clamped at zero.
Precomputing the running maximum from the left and from the right lets you answer every column in one pass each, trading O(n) space for O(n) time.
You can drop the two extra arrays: walk inward from both ends, always advancing the side whose current bar is shorter, because that side's running max is the true limiting wall.
Water above a column is bounded by the shorter of the tallest wall to its left and the tallest wall to its right. Compute those two walls directly for every column.
The repeated left and right scans are wasted work. Precompute, for every index, the tallest bar at or before it and the tallest bar at or after it.
Keep a pointer at each end with a running max for each side. Whichever side currently has the shorter bar is the limiting wall, so its running max is final and you can settle that column right away.