ToolMight Logo
HardTwo PointersTwo Pointers Max BoundariesPrefix/Suffix Max

Trapping Rain Water

Calculate total trapped water between elevation bars. Compare O(n)-space prefix/suffix max arrays with O(1)-space converging two pointers.

Optimal Time
O(n)
Optimal Space
O(1)
Primary Pattern
Two Pointers Max Boundaries
Visualizer
Open Interactive View →

Problem Statement

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

Examples & Constraints

Example 1
Input: height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
Output: 6
Explanation: 6 units of water collect in the valleys bounded by bars [1, 2] and [2, 3] and [3, 2].
Example 2
Input: height = [4, 2, 0, 3, 2, 5]
Output: 9
Explanation: Bars of height 4 and 5 bound 2 + 4 + 1 + 2 = 9 units across indices 1..4.
Constraints
  • n == height.length
  • 1 <= n <= 2 * 10^4
  • 0 <= height[i] <= 10^5

Pattern Recognition & Core Invariant

How to Spot This Pattern

When the contribution at index i depends on the maximum height to both its left and right, either precompute prefix/suffix max arrays or converge pointers from the lower outer wall.

Core Invariant

At any position i, trapped water equals max(0, min(leftMax[i], rightMax[i]) - height[i]); whenever maxLeft < maxRight, the water level above the left pointer is locked regardless of taller bars further inside.

Solution Approaches & Complexity

ApproachTimeSpaceNotes
1. Prefix & Suffix Max Arrays
O(n)O(n)Precompute the tallest bar to the left and right of every index in two passes, then sum min(leftMax[i], rightMax[i]) - height[i].
2. Two Pointers with Running Max Boundaries (O(1) Space)Optimal
O(n)O(1)Converge left and right pointers while tracking maxLeft and maxRight. The trapped water at the lower boundary is min(maxLeft, maxRight) - height[i], computed in O(1) auxiliary space.

1. Prefix & Suffix Max Arrays

TimeO(n)
SpaceO(n)

Precompute the tallest bar to the left and right of every index in two passes, then sum min(leftMax[i], rightMax[i]) - height[i].

Time ComplexityO(n)

Three linear passes over the n elevation bars.

Space ComplexityO(n)

Stores leftMax and rightMax arrays of size n.

How It Works

Deriving the Bottleneck Directly

Above every index i, water rises up to the shorter of the tallest wall on its left and tallest wall on its right:

water[i] = min(leftMax[i], rightMax[i]) - height[i]

Precomputing those boundaries explicitly takes three clean passes:

  1. Forward scan builds leftMax[i] = max(leftMax[i - 1], height[i]).
  2. Backward scan builds rightMax[i] = max(rightMax[i + 1], height[i]).
  3. Final pass accumulates min(leftMax[i], rightMax[i]) - height[i].

Step-by-Step Dry Run

Execution Trace·Step 1 of 3
1Compute Prefix leftMax

For [4, 2, 0, 3, 2, 5], running left maxima become [4, 4, 4, 4, 4, 5].

State:leftMax = [4, 4, 4, 4, 4, 5]
Strengths
  • +Direct translation of the water-level formula
  • +Easy to verify and debug
Trade-offs
  • -Allocates O(n) extra arrays where O(1) space is achievable

Reference Implementation

Complete implementation for Prefix & Suffix Max Arrays in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
def trap_arrays(height: list[int]) -> int:
n = len(height)
if n == 0:
return 0
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])
return sum(min(left_max[i], right_max[i]) - height[i] for i in range(n))
if __name__ == "__main__":
print("Trapped:", trap_arrays([4, 2, 0, 3, 2, 5]))

2. Two Pointers with Running Max Boundaries (O(1) Space)

Optimal
TimeO(n)
SpaceO(1)

Converge left and right pointers while tracking maxLeft and maxRight. The trapped water at the lower boundary is min(maxLeft, maxRight) - height[i], computed in O(1) auxiliary space.

Time ComplexityO(n)

Each step moves either the left or right pointer by one bar. The two pointers traverse the array of length N in a single pass.

Space ComplexityO(1)

Operates strictly in-place with four primitive scalar variables (left, right, maxLeft, maxRight). Zero auxiliary arrays allocated.

How It Works

The Water Level Formula

At any index i, the water held directly above the bar is:
water[i] = max(0, min(max_left, max_right) - height[i])

Where max_left is the tallest bar to the left of i, and max_right is the tallest bar to the right of i.


The Two-Pointer Optimization: Eliminating Arrays

A standard dynamic programming solution computes two auxiliary arrays (leftMax and rightMax) in O(n) space.

However, notice:

  • If maxLeft < maxRight, the water trapped above left is strictly bounded by `maxLeft`! It does not matter how much taller maxRight gets in the future; the bottleneck is already determined by maxLeft.
  • Conversely, if maxRight <= maxLeft, the water trapped above right is strictly bounded by `maxRight`.

Algorithm:

  1. Initialize left = 0, right = n - 1.
  2. Initialize maxLeft = 0, maxRight = 0, and totalWater = 0.
  3. While left < right:
  • If height[left] < height[right]:
  • If height[left] >= maxLeft, update maxLeft = height[left].
  • Else, add maxLeft - height[left] to totalWater.
  • Advance left++.
  • Else:
  • If height[right] >= maxRight, update maxRight = height[right].
  • Else, add maxRight - height[right] to totalWater.
  • Decrement right--.
  1. Return totalWater.

Step-by-Step Dry Run

Execution Trace·Step 1 of 4
1Initial Pointers

height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]. left = 0 (val 0), right = 11 (val 1). maxLeft = 0, maxRight = 0.

State:left = 0right = 11total = 0
Strengths
  • +Optimal O(n) single pass runtime
  • +O(1) auxiliary space without requiring extra prefix/suffix arrays
Trade-offs
  • -The logic condition (advancing based on height[left] < height[right]) requires careful proof

Reference Implementation

Complete implementation for Two Pointers with Running Max Boundaries (O(1) Space) in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
def trap(height: list[int]) -> int:
if not height:
return 0
left, right = 0, len(height) - 1
max_left, max_right = 0, 0
total_water = 0
while left < right:
if height[left] < height[right]:
if height[left] >= max_left:
max_left = height[left]
else:
total_water += max_left - height[left]
left += 1
else:
if height[right] >= max_right:
max_right = height[right]
else:
total_water += max_right - height[right]
right -= 1
return total_water
if __name__ == "__main__":
test1 = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
test2 = [4, 2, 0, 3, 2, 5]
print("test1 trapped water:", trap(test1))
print("test2 trapped water:", trap(test2))
Interactive Visualizer

Trace Array & Matrix mechanics in memory

Step through custom inputs in the Array & Matrix visualizer to inspect pointer updates, array shifts, and call-stack state alongside Trapping Rain Water.

Open Array & Matrix visualizer

Frequently Asked Questions

Why can we determine trapped water with only one side's maximum?

When height[left] < height[right], we already have a right boundary at right strictly taller than height[left]. Because maxLeft only grows from values below height[right] whenever the left pointer moves, min(maxLeft, maxRight) is guaranteed to equal maxLeft.

How does Two Pointers compare to the Monotonic Stack approach?

A monotonic decreasing stack sums trapped water horizontally layer by layer (O(n) time, O(n) space). Two Pointers sums vertically bar by bar in a single pass with O(1) extra space.

What breaks if we check `maxLeft < maxRight` instead of `height[left] < height[right]`?

When maxLeft hasn't been updated for the current bar yet, comparing height[left] < height[right] ensures we always step away from whichever outer edge currently limits water height; comparing stale maxLeft vs maxRight can still work if updated first, but keeping height[left] < height[right] avoids out-of-sync updates.

Edge Cases & Implementation Pitfalls

Boundary Test Cases to Verify

  • Fewer than 3 bars ([], [5], [4, 2]) trap 0 units of water.
  • Monotonically increasing or decreasing heights ([1, 2, 3, 4] or [4, 3, 2, 1]) trap 0 units.
  • Valleys of height 0 bounded by nonzero walls trap full wall minimum across empty slots.
  • Flat plateaus at top or bottom.

Common Bugs to Avoid

  • Checking `height[left] < height[right]` only conceptually, or advancing BOTH pointers in one iteration instead of only the lower side.
  • Subtracting current height from maxLeft without first updating `maxLeft = max(maxLeft, height[left])`, leading to negative water values.
  • Confusing width-1 trapping per bar (this problem) with 2-wall area (Container With Most Water).

Interview Follow-Up Variations

  • Solve horizontally layer-by-layer using a Monotonic Decreasing Stack in O(n) time and O(n) space.
  • Trapping Rain Water II (2D matrix elevation map): replace two pointers with a Min-Heap boundary flood starting from the perimeter cells.

Related Problems

All problems
MediumTwo Pointers

Container With Most Water

Find two vertical walls bounding maximum water volume. Compare quadratic pair enumeration against O(n) greedy two-pointer elimination.

Pattern: Two Pointers Inward Convergence
O(n) · O(1)
Solve
EasyArrays & Hashing

Two Sum

Find indices of two array elements summing to target. Compare O(n²) brute-force scanning against O(n) one-pass complement lookup with a Hash Map.

Pattern: Hash Map
O(n) · O(n)
Solve
EasyTwo Pointers

Valid Palindrome

Check whether a string reads identically forward and backward over alphanumeric characters. Compare build-and-reverse against O(1)-space converging pointers.

Pattern: Two Pointers Converging
O(n) · O(1)
Solve