Algo-Sim › Two Pointers

Trapping Rain Water

Hard · Two Pointers · step through it in Java, Python and C++ on your own input

Compute how much rain water the bars trap, in O(n) time and O(1) space.

Problem

Bars of width 1 stand side by side with heights height[i]. After it rains, water collects in the dips between taller bars. Return the total units of water held.

Constraints

Edge cases to test

Follow-up questions

What are the other O(n) ways?
Prefix maxima from both sides (O(n) space), or a monotonic stack that fills water layer by layer (O(n) space). Two pointers need O(1).
What about a 2D height map?
A min-heap of boundary cells, flooding inward from the lowest one (LC 407): O(mn log(mn)).

Solution

Java

public int trap(int[] height) {
    int left = 0, right = height.length - 1;
    int leftMax = 0, rightMax = 0, water = 0;
    while (left < right) {
        if (height[left] < height[right]) {
            leftMax = Math.max(leftMax, height[left]);
            water += leftMax - height[left];
            left++;
        } else {
            rightMax = Math.max(rightMax, height[right]);
            water += rightMax - height[right];
            right--;
        }
    }
    return water;
}

Python

def trap(height):
    left, right = 0, len(height) - 1
    left_max = right_max = water = 0
    while left < right:
        if height[left] < height[right]:
            left_max = max(left_max, height[left])
            water += left_max - height[left]
            left += 1
        else:
            right_max = max(right_max, height[right])
            water += right_max - height[right]
            right -= 1
    return water

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int trap(vector<int> &height) {
        int left = 0, right = int(height.size()) - 1;
        int leftMax = 0, rightMax = 0, water = 0;
        while (left < right) {
            if (height[left] < height[right]) {
                leftMax = std::max(leftMax, height[left]);
                water += leftMax - height[left];
                left++;
            } else {
                rightMax = std::max(rightMax, height[right]);
                water += rightMax - height[right];
                right--;
            }
        }
        return water;
    }
};

More Two Pointers problems