</>

42. Trapping Rain Water

Hard NeetCode 150
Two Pointers Time O(N) Space O(1)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Two Pointers
Time
O(N)
Space
O(1)

Standard Solution (C++)

SummaryGiven an array of bar heights representing an elevation map, compute the total volume of rainwater that can be trapped between the bars after it rains.

Approach
  • Use two pointers starting at each end of the array, tracking the running max height seen from the left (maxL) and from the right (maxR).
  • The water above any bar is bounded by the shorter of the two sides, so process the pointer on the side with the smaller max: the water contribution is max - height[pointer].
  • Advance the chosen pointer inward, updating the running max before the next iteration.
  • This greedy invariant guarantees the limiting wall has already been seen, so no look-ahead is needed — one O(n) pass suffices with O(1) extra space.
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
    int trap(vector<int>& height) {
        int left = 0, right = static_cast<int>(height.size()) - 1;
        int maxL = 0, maxR = 0;
        int water = 0;

        while (left < right) {
            // Update running maxima before deciding contribution
            maxL = max(maxL, height[left]);
            maxR = max(maxR, height[right]);

            // The weaker side determines water level; process that pointer
            if (maxL <= maxR) {
                water += maxL - height[left];   // always >= 0 by definition of maxL
                ++left;
            } else {
                water += maxR - height[right];  // always >= 0 by definition of maxR
                --right;
            }
        }

        return water;
    }
};
Time O(n) Space O(1)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
    int trap(vector<int>& height) {
        int n=height.size();
        int left=0, right=n-1;
        int maxLeft=height[0], maxRight=height[n-1];
        int sum=0;

        if(n<=2)
            return 0;

        while(left<right){
            if(maxLeft<maxRight){
                int cur=maxLeft-height[left];
                if(cur>0)
                    sum+=cur;
                ++left;
            }
            else{ // maxLeft>=maxRight
                int cur=maxRight-height[right];
                if(cur>0)
                    sum+=cur;
                --right;
            }
            maxLeft=std::max(maxLeft,height[left]);
            maxRight=std::max(maxRight,height[right]);
        }

        return sum;
    }
};

// Time Complexity: O(N)
// Space Complexity: O(1)
Time O(N) Space O(1)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern