Skip to content

Trapping Rain Water

Add up the rain water trapped between the bars of an elevation map, with two pointers and O(1) space.

HardTwo Pointers
Solve on LeetCode

The problem

You get an array height of non-negative integers, where each value is the height of a bar of width 1 in an elevation map. After it rains, water collects in the dips between the bars. Return the total number of units of water that stay trapped.

Input height = [3, 0, 2, 0, 4]

Output 7

The water stands 3 deep above index 1, 1 deep above index 2 and 3 deep above index 3.

Input height = [4, 1, 3, 0, 1]

Output 3

2 units sit above index 1. Above index 3 the level is capped at 1 by the short bar on the right, so only 1 unit stays there.

Key constraint: Up to 20,000 bars; the intended answer is O(n) time, and O(1) extra space is possible.

How to spot the pattern

  • The water above each bar depends on the tallest bar to its left and the tallest bar to its right.
  • Whichever side has the lower maximum decides the water level, so you can settle that side first.

The idea

The water above bar i is min(tallest on the left, tallest on the right) - height[i]. Walk two pointers inward and keep leftMax and rightMax, the tallest bars seen from each end. If leftMax < rightMax, the bar at left has its level settled by leftMax alone, because some bar on the right is already taller, so add its water and move left inward. Otherwise do the same on the right side.

Brute force: For each bar, scan left and right to find the tallest bar on each side, which takes O(n^2) time.

Step by step

  1. 1Set left = 0, right = n - 1, and leftMax = rightMax = total = 0.
  2. 2While left < right, update leftMax with height[left] and rightMax with height[right].
  3. 3If leftMax < rightMax, add leftMax - height[left] to total and move left right.
  4. 4Otherwise add rightMax - height[right] to total and move right left.
  5. 5Return total when the pointers meet.

See the pattern move

The two pointers pattern on a small example. Step through it, or press play.

Code

class Solution:
    def trap(self, height: List[int]) -> int:
        left, right = 0, len(height) - 1
        left_max = right_max = total = 0
        while left < right:
            left_max = max(left_max, height[left])
            right_max = max(right_max, height[right])
            if left_max < right_max:
                # the right side has a taller bar, so left_max sets the level here
                total += left_max - height[left]
                left += 1
            else:
                total += right_max - height[right]
                right -= 1
        return total

Complexity

Time

O(n)

Space

O(1)

Each step settles one bar and moves one pointer, so there are n - 1 steps and only a handful of variables.

Watch out for

  • Using the taller side's maximum: the water level is capped by the lower of the two maximums, never the higher one.
  • Adding water before updating the maximum with the bar's own height, which can make the amount negative.
  • Thinking only the nearest bars matter: the level depends on the tallest bar on each side, however far away it is.

Follow-up questions

Is there an easier version to explain first?

Yes: fill maxLeft[i] and maxRight[i] in two passes, then add min(maxLeft[i], maxRight[i]) - height[i] for every i. It is O(n) time and O(n) space, and the two-pointer version simply removes the two arrays.

Can a stack solve it?

A stack of bars with decreasing heights also works in O(n): when a taller bar arrives, pop the shorter ones and add the water that sits above each of them, layer by layer. It belongs to the same family as Largest Rectangle in Histogram.

In Hinglish

Har bar ke upar paani = dono taraf ki sabse oonchi bar mein se chhoti wali minus us bar ki height; jis side ka max chhota ho, pehle wahi side settle karo.

Related problems