Trapping rain water

Each bar traps water up to the shorter of the tallest wall on its left and its right, tracked with two pointers.

Time O(n)Space O(1)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

The water above a bar is bounded by the shorter of the tallest wall to its left and to its right. Whichever side currently has the lower wall has a known, final cap, so resolve that side and move inward; the taller side can only matter later.

Code

public static int Trap(int[] h) {
    int l = 0, r = h.Length - 1, leftMax = 0, rightMax = 0, water = 0;
    while (l < r) {
        if (h[l] < h[r]) {
            leftMax = Math.Max(leftMax, h[l]);
            water += leftMax - h[l];
            l++;
        } else {
            rightMax = Math.Max(rightMax, h[r]);
            water += rightMax - h[r];
            r--;
        }
    }
    return water;
}
static int trap(int[] h) {
    int l = 0, r = h.length - 1, leftMax = 0, rightMax = 0, water = 0;
    while (l < r) {
        if (h[l] < h[r]) {
            leftMax = Math.max(leftMax, h[l]);
            water += leftMax - h[l];
            l++;
        } else {
            rightMax = Math.max(rightMax, h[r]);
            water += rightMax - h[r];
            r--;
        }
    }
    return water;
}
int trap(const vector<int>& h) {
    int l = 0, r = (int)h.size() - 1, leftMax = 0, rightMax = 0, water = 0;
    while (l < r) {
        if (h[l] < h[r]) {
            leftMax = max(leftMax, h[l]);
            water += leftMax - h[l];
            l++;
        } else {
            rightMax = max(rightMax, h[r]);
            water += rightMax - h[r];
            r--;
        }
    }
    return water;
}
def trap(h: list[int]) -> int:
    l, r, left_max, right_max, water = 0, len(h) - 1, 0, 0, 0
    while l < r:
        if h[l] < h[r]:
            left_max = max(left_max, h[l])
            water += left_max - h[l]
            l += 1
        else:
            right_max = max(right_max, h[r])
            water += right_max - h[r]
            r -= 1
    return water

Tips

In the .NET library

A simpler O(n)-space version precomputes a leftMax array and a rightMax array first, then combines them in a second pass. This two-pointer version does the same job in O(1) space.