Trapping Rain Water (LeetCode 42): Solution and Explanation
Given bar heights for an elevation map where each bar has width 1, compute how many units of rainwater stay trapped between the bars after it rains.
Watch it run step by step
Try your own input and write the code →Intuition
Focus on a single position i. The water above it rises until it would spill over either side, so its level is the smaller of the tallest bar anywhere to its left and the tallest bar anywhere to its right. The water at i is that level minus height[i], or zero if the bar itself is taller. The total is the sum over all positions. Computing the two maxima from scratch for every position is O(n²).
The first speedup is precomputation. One left-to-right pass builds leftMax[i], and one right-to-left pass builds rightMax[i]. Then a third pass sums min(leftMax[i], rightMax[i]) - height[i]. That is O(n) time but needs two extra arrays. The question is whether you really need both maxima exactly for every index.
You do not, because only the smaller one matters. Put pointers at both ends and track leftMax (the tallest bar seen from the left so far) and rightMax (the tallest from the right). If leftMax < rightMax, then for the next position on the left, its true right maximum is at least rightMax, which is already bigger than leftMax. So its water level is exactly leftMax, and you can settle that position now without knowing anything else about the right side. The symmetric argument handles the right pointer when rightMax is the smaller one. Each step settles one position, giving O(n) time and O(1) space.
Approach: Two pointers with running maxima
- Return 0 for an empty input. Set
l = 0,r = len(height) - 1,leftMax = height[l],rightMax = height[r]andres = 0. - While
l < r, compareleftMaxandrightMax. - If
leftMax < rightMax, advancel, updateleftMax = max(leftMax, height[l]), and addleftMax - height[l]tores. - Otherwise, move
rleft, updaterightMax = max(rightMax, height[r]), and addrightMax - height[r]tores. - Updating the max before adding means the added amount is never negative; a new tallest bar contributes zero.
- Return
reswhen the pointers meet.
Step-by-step example
height = [4, 2, 0, 3, 2, 5]
- Start: l = 0, r = 5, leftMax = 4, rightMax = 5, res = 0.
- 4 < 5, so l = 1. leftMax stays 4, add 4 - 2 = 2. res = 2.
- 4 < 5, so l = 2. Add 4 - 0 = 4. res = 6.
- 4 < 5, so l = 3. Add 4 - 3 = 1. res = 7.
- 4 < 5, so l = 4. Add 4 - 2 = 2. res = 9.
- 4 < 5, so l = 5, which equals r. Height 5 updates leftMax to 5 and adds 0. The loop ends and the answer is 9.
Code: Python, Java, C++
1class Solution:
2 def trap(self, height: List[int]) -> int:
3 if not height: return 0
4 l, r = 0, len(height) - 1
5 leftMax, rightMax = height[l], height[r]
6 res = 0
7
8 while l < r:
9 if leftMax < rightMax:
10 l += 1
11 leftMax = max(leftMax, height[l])
12 res += leftMax - height[l]
13 else:
14 r -= 1
15 rightMax = max(rightMax, height[r])
16 res += rightMax - height[r]
17 return res1class Solution {
2 public int trap(int[] height) {
3 if (height.length == 0) return 0;
4 int l = 0, r = height.length - 1;
5 int leftMax = height[l], rightMax = height[r];
6 int res = 0;
7
8 while (l < r) {
9 if (leftMax < rightMax) {
10 l++;
11 leftMax = Math.max(leftMax, height[l]);
12 res += leftMax - height[l];
13 } else {
14 r--;
15 rightMax = Math.max(rightMax, height[r]);
16 res += rightMax - height[r];
17 }
18 }
19 return res;
20 }
21}1class Solution {
2public:
3 int trap(vector<int>& height) {
4 if (height.empty()) return 0;
5 int l = 0, r = height.size() - 1;
6 int leftMax = height[l], rightMax = height[r];
7 int res = 0;
8
9 while (l < r) {
10 if (leftMax < rightMax) {
11 l++;
12 leftMax = max(leftMax, height[l]);
13 res += leftMax - height[l];
14 } else {
15 r--;
16 rightMax = max(rightMax, height[r]);
17 res += rightMax - height[r];
18 }
19 }
20 return res;
21 }
22};Time and space complexity
O(n)
Each iteration moves exactly one pointer inward by one, so the loop runs n - 1 times with constant work.
O(1)
Only the two pointers, the two running maxima and the total are stored.
Other approaches
Prefix and suffix max arrays (time O(n), space O(n))
Precompute leftMax[i] and rightMax[i] in two passes, then sum min(leftMax[i], rightMax[i]) - height[i]. It is the easiest version to explain and verify, at the cost of two arrays.
Monotonic stack (time O(n), space O(n))
Keep a stack of indices with decreasing heights. When a taller bar arrives, pop the bottom of a basin and add the water bounded by the new bar and the bar beneath it on the stack. It fills water in horizontal layers rather than per column.
Common mistakes
- Adding
leftMax - height[l]before updatingleftMax. If the new bar is taller, the result is negative and the total goes wrong. - Moving the pointer on the side with the larger max. The argument only holds for the side whose max is smaller, because that max is the binding limit.
- Using the tallest bar between the pointers instead of the tallest bar seen from that side. Water depends on the maxima from the edges, not on bars in the unexplored middle.
- Forgetting the empty input check, which makes
height[0]throw on an empty list.
Frequently asked questions
Why does the two pointer approach work for Trapping Rain Water?
Water at a position depends on the smaller of its left and right maxima. When leftMax < rightMax, the left position's right maximum is at least rightMax, so its level is exactly leftMax and it can be settled immediately.
What is the formula for trapped water at each index?
It is min(maxLeft, maxRight) - height[i], where the maxima include the bar itself. Including the bar guarantees the result is never negative.
Can Trapping Rain Water be solved in O(1) space?
Yes. The two pointer method keeps only two running maxima instead of full prefix and suffix arrays.
Stack or two pointers for Trapping Rain Water?
Both are O(n) time. Two pointers use constant space and less code. The monotonic stack is worth knowing because the same idea solves Largest Rectangle in Histogram.