Algo-Sim › Two Pointers
Trapping Rain Water
Hard · Two Pointers · step through it in Java, Python and C++ on your own input
Compute how much rain water the bars trap, in O(n) time and O(1) space.
Problem
Bars of width 1 stand side by side with heights height[i]. After it rains, water collects in the dips between taller bars. Return the total units of water held.
Constraints
- 1 ≤ height.length ≤ 2 · 10⁴
- 0 ≤ height[i] ≤ 10⁵
- Target O(n) time and O(1) extra space
Edge cases to test
- Fewer than three bars:
0 - A strictly increasing or decreasing profile:
0 - Flat stretches between walls
Follow-up questions
- What are the other O(n) ways?
- Prefix maxima from both sides (O(n) space), or a monotonic stack that fills water layer by layer (O(n) space). Two pointers need O(1).
- What about a 2D height map?
- A min-heap of boundary cells, flooding inward from the lowest one (LC 407): O(mn log(mn)).
Solution
Java
public int trap(int[] height) {
int left = 0, right = height.length - 1;
int leftMax = 0, rightMax = 0, water = 0;
while (left < right) {
if (height[left] < height[right]) {
leftMax = Math.max(leftMax, height[left]);
water += leftMax - height[left];
left++;
} else {
rightMax = Math.max(rightMax, height[right]);
water += rightMax - height[right];
right--;
}
}
return water;
}Python
def trap(height):
left, right = 0, len(height) - 1
left_max = right_max = water = 0
while left < right:
if height[left] < height[right]:
left_max = max(left_max, height[left])
water += left_max - height[left]
left += 1
else:
right_max = max(right_max, height[right])
water += right_max - height[right]
right -= 1
return waterC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int trap(vector<int> &height) {
int left = 0, right = int(height.size()) - 1;
int leftMax = 0, rightMax = 0, water = 0;
while (left < right) {
if (height[left] < height[right]) {
leftMax = std::max(leftMax, height[left]);
water += leftMax - height[left];
left++;
} else {
rightMax = std::max(rightMax, height[right]);
water += rightMax - height[right];
right--;
}
}
return water;
}
};
More Two Pointers problems
- Valid Palindrome (Easy)
- Valid Palindrome II (Easy)
- Two Sum II - Input Array Is Sorted (Medium)
- Remove Duplicates from Sorted Array (Easy)
- Move Zeroes (Easy)
- Container With Most Water (Medium)
- Sort Colors (Medium)
- Merge Sorted Array (Easy)
- Rotate Array (Medium)
- Next Permutation (Medium)
- 3Sum (Medium)