15% off all plans & roadmaps Use code

See plans

Trapping Rain Water

Updated

TL;DR: Given bar heights, count the unit squares of rain water the bars hold. The water above a bar is min(tallest left, tallest right) minus its height, and two pointers compute the total in O(n) time and O(1) space.

Problem

You are given an array height of non-negative integers. Each entry is a vertical bar of width 1, and all bars stand on the same baseline. Rain falls on the bars, and water collects in the gaps between taller bars.

For a given position, the water above it depends on the tallest bar somewhere to its left and the tallest bar somewhere to its right. The two ends of the array have a missing side, so they hold no water. Return the total number of unit squares of water trapped, as an integer.

Example 1

Input: height = [3,0,2,0,4]
Output: 7
Explanation: The three low interior positions hold 3, 1 and 3 units, so the total is 7.

Example 2

Input: height = [2,0,2]
Output: 2
Explanation: The middle position sits between two bars of height 2, so it holds 2 units.

Example 3

Input: height = [1,3,0,2,1,4]
Output: 6
Explanation: The positions between the bars of height 3 and 4 hold 3, 1 and 2 units, which totals 6.

Constraints

  • 1 <= height.length <= 2 * 10^4
  • 0 <= height[i] <= 10^5
  • Every element of height is an integer.
  • Each bar has width 1 and rests on the same baseline.

Constraints that matter

  • n up to 2 * 10^4 means an O(n^2) scan does about 4 * 10^8 basic steps in the worst case, which is risky, so aim for O(n).
  • height[i] up to 10^5 and n up to 2 * 10^4 means the answer can approach 2 * 10^9. That still fits in a signed 32-bit int, but a long accumulator is a cheap safeguard.
  • height[i] >= 0 means a bar never has negative height, so the water formula min(leftMax, rightMax) - height[i] is never negative when the maxima include the bar itself.
  • n >= 1 means you still must handle length 1 and 2, where no water can be trapped.

View on LeetCode

Hints

Hint 1

This is a two pointers problem with a running-maximum twist.

Hint 2

For every index, scan left to find the tallest bar up to and including it, scan right to find the tallest bar from it onward, and add min(leftMax, rightMax) - height[i].

Solution

Intuition

This is a two pointers problem with a running-maximum twist. Start from the per-position formula: water above index i equals min(tallest bar at or left of i, tallest bar at or right of i) - height[i]. Every approach on this page computes that formula. They differ in how they get the two maxima.

Picture two people walking a row of posts from opposite ends, each keeping the tallest post they have passed. Whichever end has the shorter post is the bottleneck, so the water there is fixed by that person's running tallest post, and they step inward while the other end is already known to be at least that tall.

The brute force rescans the array for each index. You can reuse work instead. The left maximum of index i is the left maximum of i - 1 combined with height[i], so a single pass fills it. The same holds from the right.

The final step removes the two arrays. Water at a position is limited by the shorter of its two walls, so you only need to know which side is shorter, not the exact taller maximum. If height[left] <= height[right], the right side already has a wall at least as tall as the current left bar. Then leftMax alone decides the water at left, and you can finalize it and move on.

That argument is why one pass with two pointers and two integers is enough. Each step settles exactly one index, and the pointers meet after n steps.

Watch the pattern animation

Worked example

Input: height = [1, 3, 0, 2, 1, 4]
Output: 6
Explanation: The bar of height 3 at index 1 and the bar of height 4 at index 5 form walls. Between them, index 2 holds 3 units, index 3 holds 1 unit and index 4 holds 2 units. Indices 0, 1 and 5 hold nothing, so the total is 3 + 1 + 2 = 6.

Approach 1: Brute force

For every index, scan left to find the tallest bar up to and including it, scan right to find the tallest bar from it onward, and add min(leftMax, rightMax) - height[i].

This is the formula applied literally. Because each maximum includes the bar itself, the difference is never negative.

Steps

  1. Set total = 0.
  2. For each index i, scan 0..i to get leftMax.
  3. Scan i..n-1 to get rightMax.
  4. Add min(leftMax, rightMax) - height[i] to total.
  5. Return total after the last index.

Dry run

On [1,3,0,2,1,4] each index gets two scans.

ileftMaxrightMaxwater
0140
1340
2343
3341
4342
5440

The water column sums to 6.

Complexity

TimeO(n^2)
SpaceO(1)

Here n is the number of bars. The outer loop runs n times, and each iteration scans up to n elements in total across its two inner scans, so the work is about n * n. Only a few integers are stored, so extra space is constant.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def trap(self, height: List[int]) -> int:
        n = len(height)
        total = 0
        for i in range(n):
            left_max = 0
            for j in range(0, i + 1):
                left_max = max(left_max, height[j])
            right_max = 0
            for j in range(i, n):
                right_max = max(right_max, height[j])
            total += min(left_max, right_max) - height[i]
        return total

Approach 2: Prefix and suffix maximum arrays

What's slow: the brute force recomputes a maximum from scratch for every index, even though neighbouring indices share almost the same prefix.

The insight that fixes it: the prefix maximum at i equals max(prefix[i-1], height[i]). One left-to-right pass fills a leftMax array, and one right-to-left pass fills a rightMax array. Then every index is answered by a lookup.

Steps

  1. Create leftMax and rightMax, both of length n.
  2. Set leftMax[0] = height[0] and fill forward with max(leftMax[i-1], height[i]).
  3. Set rightMax[n-1] = height[n-1] and fill backward with max(rightMax[i+1], height[i]).
  4. For each i, add min(leftMax[i], rightMax[i]) - height[i].
  5. Return the sum.

Dry run

On [1,3,0,2,1,4]:

  • leftMax = [1,3,3,3,3,4]
  • rightMax = [4,4,4,4,4,4]
  • min of the two per index: [1,3,3,3,3,4]
  • subtract height: [0,0,3,1,2,0]

The sum is 6.

Complexity

TimeO(n)
SpaceO(n)

Here n is the number of bars. Each of the three passes touches every index exactly once, so the time is about 3n steps. The two helper arrays each hold n integers, so extra space is 2n, which is O(n).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def trap(self, height: List[int]) -> int:
        n = len(height)
        left_max = [0] * n
        right_max = [0] * n
        left_max[0] = height[0]
        for i in range(1, n):
            left_max[i] = max(left_max[i - 1], height[i])
        right_max[n - 1] = height[n - 1]
        for i in range(n - 2, -1, -1):
            right_max[i] = max(right_max[i + 1], height[i])
        total = 0
        for i in range(n):
            total += min(left_max[i], right_max[i]) - height[i]
        return total

Approach 3: Monotonic stack

What's slow: the prefix and suffix arrays fix the time but still cost O(n) memory, and they compute water one column at a time.

The insight that fixes it: water can also be counted in horizontal layers. Keep a stack of indices whose heights are non-increasing. When a bar h is taller than the stack top, the top is a floor. The new stack top is the left wall and h is the right wall, so one layer of water fills the gap above that floor.

This approach still uses O(n) space, so it does not beat the arrays on memory. Interviewers ask for it, and the layer view is a different way to see the problem.

Steps

  1. Start with an empty stack of indices and total = 0.
  2. For each index i, while the stack is non-empty and height[i] > height[top], pop the top as the floor.
  3. If the stack is now empty, there is no left wall, so stop popping.
  4. Otherwise let left be the new top. The layer width is i - left - 1, and its depth is min(height[left], height[i]) - floor.
  5. Add width * depth to total.
  6. Push i onto the stack.
  7. Return total.

Dry run

On [1,3,0,2,1,4]:

iheightactionstack aftertotal
01push[0]0
13pop 0, stack empty, push[1]0
20push[1,2]0
32pop 2: width 1, depth min(3,2)-0 = 2; push[1,3]2
41push[1,3,4]2
54pop 4: width 1, depth min(2,4)-1 = 1; pop 3: width 3, depth min(3,4)-2 = 1; pop 1, stack empty; push[5]6

The total is 6.

Complexity

TimeO(n)
SpaceO(n)

Here n is the number of bars. Each index is pushed once and popped at most once, so the loop body runs at most 2n times in total even though a while sits inside the for. The stack can hold all n indices at once, for example on strictly decreasing heights, so space is O(n).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def trap(self, height: List[int]) -> int:
        stack = []
        total = 0
        for i, h in enumerate(height):
            while stack and h > height[stack[-1]]:
                floor = height[stack.pop()]
                if not stack:
                    break
                left = stack[-1]
                width = i - left - 1
                total += width * (min(height[left], h) - floor)
            stack.append(i)
        return total
In-place Array Modification pattern infographic for Trapping Rain Water

Solution pattern

In-place Array Modification

Part of Two Pointers

Approach 4: Two pointersOptimalIn-place Array Modification

What's slow: both previous linear solutions keep O(n) extra memory, either two arrays or a stack. Most of that memory is never needed at once.

The insight that fixes it: water at an index depends on the shorter of its two walls. Put one pointer at each end and compare height[left] with height[right].

If the left bar is no taller, the right side already holds a wall at least that tall, so leftMax decides the water at left. Settle that index and move left inward. Otherwise do the mirror case on the right. Two running maxima replace both arrays.

Steps

  1. Set left = 0, right = n - 1, leftMax = 0, rightMax = 0, water = 0.
  2. While left < right, compare height[left] with height[right].
  3. If the left bar is no taller: if it is at least leftMax, make it the new leftMax; otherwise add leftMax - height[left] to water. Then move left right.
  4. Otherwise do the mirror on the right with rightMax, then move right left.
  5. Return water when the pointers meet.

Dry run

On [1,3,0,2,1,4], with left = 0, right = 5 at the start. The right bar is 4 throughout, so only the left side moves.

stepleftrightheight[left] vs height[right]leftMaxrightMaxwater
1051 <= 4, new max100
2153 <= 4, new max300
3250 <= 4, add 3 - 0303
4352 <= 4, add 3 - 2304
5451 <= 4, add 3 - 1306
end55pointers meet306

The loop stops and returns 6.

Complexity

TimeO(n)
SpaceO(1)

Here n is the number of bars. Every iteration moves exactly one pointer one step inward, and the pointers start n - 1 apart, so the loop runs n - 1 times. The state is two pointers, two maxima and one total, so space is constant.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def trap(self, height: List[int]) -> int:
        left, right = 0, len(height) - 1
        left_max = right_max = 0
        water = 0
        while left < right:
            if height[left] <= height[right]:
                # right wall is at least as tall, so left_max decides
                if height[left] >= left_max:
                    left_max = height[left]
                else:
                    water += left_max - height[left]
                left += 1
            else:
                if height[right] >= right_max:
                    right_max = height[right]
                else:
                    water += right_max - height[right]
                right -= 1
        return water

Common mistakes

  • Adding leftMax - height[left] before updating leftMax. When the current bar is the new tallest, the difference is negative or stale. Check height[left] >= leftMax first, update the max, and only add water in the else branch.
  • Using min(leftMax, rightMax) as the pointer rule instead of comparing height[left] with height[right]. The comparison of the two current bars is what proves the opposite wall is tall enough. Branch on the bars, then use the maximum on the side you are settling.
  • Writing the loop as while left <= right. When the pointers meet, that bar has no wall on at least one side relative to the other pointer, and it adds nothing. Use left < right.
  • Computing the brute-force maxima over 0..i-1 and i+1..n-1, excluding the bar itself. Then a tall bar gives a negative result. Include index i in both scans so the minimum is at least height[i].
  • In the stack solution, forgetting the if not stack: break check after popping. With an empty stack there is no left wall, and reading stack[-1] fails or counts water that spills out. Break and push the current index.
  • In the stack solution, using the full distance i - left as the width instead of i - left - 1. The walls themselves are not water columns. Subtract one.

Edge cases

  • [5] (length 1): no walls on either side, so the answer is 0.
  • [2,0] (length 2): the ends hold nothing, so the answer is 0.
  • [1,2,3,4,5] (strictly increasing): water slides off, so the answer is 0. The same holds for strictly decreasing input.
  • [3,3,3] (all equal): there are no gaps, so the answer is 0.
  • [2,0,2]: the single interior bar holds 2 units, so the answer is 2.
  • n = 20000 with a bar of 100000 at each end and zeros between: the answer is 19998 * 100000 = 1999800000, which fits in a 32-bit int but shows why a wide accumulator is a good habit.

Follow-ups interviewers ask

Can you do it in O(1) extra space?
Yes, that is the two-pointer approach. It keeps leftMax, rightMax and the running total, and each step settles one index by comparing the two current bars. No array or stack is needed.
Why is it safe to settle the left index when height[left] <= height[right]?
The right pointer's bar is a wall at least as tall as the left bar, so the true right maximum of the left index is at least that tall. The shorter wall is therefore the left side, and leftMax gives the exact water. The mirror argument covers the right side.
What if the array is huge and does not fit in memory?
The two-pointer version needs random access from both ends, so it needs the array on disk with seekable reads. Alternatively, stream the data once to find the position of the global maximum. Then a left-to-right pass up to that position and a right-to-left pass back to it each need only one running maximum, so memory stays O(1) with two sequential reads.

Trapping Rain Water FAQ

What is the time complexity of Trapping Rain Water?

The optimal solution runs in O(n) time, where n is the number of bars. The brute force is O(n^2) because it scans for maxima at every index. The prefix-array, stack and two-pointer versions are all O(n).

Why use two pointers for Trapping Rain Water?

Water at a bar is limited by its shorter wall. Two pointers let you identify the shorter side by comparing the current bars, so you can finalize one index per step with only two running maxima. That removes the need to store a maximum for every index.

Can Trapping Rain Water be solved in O(1) extra space?

Yes. The two-pointer solution uses a fixed number of integers: two pointers, two maxima and the total. It reads the input but never changes it.

How does the stack solution for LeetCode 42 work?

It keeps indices of bars in non-increasing height order. When a taller bar arrives, it pops a floor bar and uses the new top as the left wall. The layer of water has width i - left - 1 and depth min(wall heights) - floor. It costs O(n) time and O(n) space.

Why does the answer never need a negative check?

Each maximum includes the bar itself, so min(leftMax, rightMax) is at least height[i]. In the two-pointer version you only add water in the branch where the bar is below its running maximum, so the added value is always positive.

Is the Trapping Rain Water answer safe in a 32-bit int?

Yes. With at most 20000 bars of height at most 100000, the water total stays below about 2 * 10^9, under the 32-bit limit of about 2.147 * 10^9. Using a 64-bit accumulator internally costs nothing and removes the doubt.

Asked at

See which companies ask this — Pro

Practise it