Trapping Rain Water

Pattern: Two pointers

hard

Water above a bar is set by the shorter of the tallest walls on its two sides. Two pointers that always move the shorter side compute it in one pass.

The problem

You are given the heights of bars of width 1 standing side by side. After rain, water collects between taller bars. Return how many units of water are trapped. For example, [4, 2, 0, 3, 2, 5] traps 9 units, and [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1] traps 6.

The function name trap matches LeetCode. Use the link above for the exact statement and a picture.

Think first

  • How high can water stand above one particular bar? What two things decide it?
  • If you knew, for every bar, the tallest bar to its left and the tallest to its right, how would you get the answer?
  • When the left wall is shorter than the right wall, do you need to know the exact right maximum?

Hints

    Brute force, and why it fails

    For each bar, scan left and right for the tallest bars: O(n²). Precomputing both maximums in arrays is O(n) time but O(n) memory. Two pointers do it in O(n) time with O(1) memory.

    The key insight

    The water level at a bar depends only on the shorter of its two tallest walls. Whenever one side's current bar is shorter than the other side's, that side's running maximum is the true limit, so it can be settled right away.

    Dry run

    40left
    21 
    02 
    33 
    24 
    55right
    leftMax0
    rightMax0
    water0

    height = [4, 2, 0, 3, 2, 5]. left starts at the first bar and right at the last. 4 is less than 5, so the left side is the limiting one.

    Step 1 of 5

    The plan

    left = 0, right = n - 1
    leftMax = rightMax = 0
    water = 0
    while left < right:
        if height[left] < height[right]:
            leftMax = max(leftMax, height[left])
            water = water + leftMax - height[left]
            left = left + 1
        else:
            rightMax = max(rightMax, height[right])
            water = water + rightMax - height[right]
            right = right - 1
    return water
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    Each bar is settled once by one of the pointers, and only four numbers are stored.

    Edge cases

    • Fewer than three bars: no water.
    • Increasing heights such as [1, 2, 3]: no water, since nothing holds it on the right of each bar.
    • [3, 0, 3]: 3 units in the middle.
    I've built my logic, show the code

    Java

    class Solution {
        public int trap(int[] height) {
            int left = 0;
            int right = height.length - 1;
            int leftMax = 0;                        // tallest bar seen from the left so far
            int rightMax = 0;                       // tallest bar seen from the right so far
            int water = 0;
            while (left < right) {
                if (height[left] < height[right]) {
                    leftMax = Math.max(leftMax, height[left]);
                    water += leftMax - height[left];    // the right side is at least as tall, so leftMax decides
                    left++;
                } else {
                    rightMax = Math.max(rightMax, height[right]);
                    water += rightMax - height[right];
                    right--;
                }
            }
            return water;
        }
    }

    C++

    class Solution {
    public:
        int trap(vector<int>& height) {
            int left = 0;
            int right = static_cast<int>(height.size()) - 1;
            int leftMax = 0;                        // tallest bar seen from the left so far
            int rightMax = 0;                       // tallest bar seen from the right so far
            int water = 0;
            while (left < right) {
                if (height[left] < height[right]) {
                    leftMax = max(leftMax, height[left]);
                    water += leftMax - height[left];    // the right side is at least as tall, so leftMax decides
                    left++;
                } else {
                    rightMax = max(rightMax, height[right]);
                    water += rightMax - height[right];
                    right--;
                }
            }
            return water;
        }
    };

    Python

    class Solution:
        def trap(self, height: list[int]) -> int:
            left, right = 0, len(height) - 1
            left_max = right_max = 0                # tallest bars seen from each side so far
            water = 0
            while left < right:
                if height[left] < height[right]:
                    left_max = max(left_max, height[left])
                    water += left_max - height[left]    # the right side is at least as tall, so left_max decides
                    left += 1
                else:
                    right_max = max(right_max, height[right])
                    water += right_max - height[right]
                    right -= 1
            return water

    Common mistakes

    • Using the taller side's maximum instead of the shorter side's.
    • Updating the running maximum after adding water instead of before, which can add a negative amount.
    • Moving the taller side's pointer, which settles a bar before its true limit is known.

    Similar problems