15% off all plans & roadmaps Use code
See plansTrapping Rain Water
- LeetCode 42
- Hard
- Two Pointers
- In-place Array Modification
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^40 <= height[i] <= 10^5- Every element of
heightis an integer. - Each bar has width 1 and rests on the same baseline.
Constraints that matter
nup 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 andnup to 2 * 10^4 means the answer can approach 2 * 10^9. That still fits in a signed 32-bit int, but alongaccumulator is a cheap safeguard.height[i] >= 0means 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 >= 1means you still must handle length 1 and 2, where no water can be trapped.
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.
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
- Set
total = 0. - For each index
i, scan0..ito getleftMax. - Scan
i..n-1to getrightMax. - Add
min(leftMax, rightMax) - height[i]tototal. - Return
totalafter the last index.
Dry run
On [1,3,0,2,1,4] each index gets two scans.
| i | leftMax | rightMax | water |
|---|---|---|---|
| 0 | 1 | 4 | 0 |
| 1 | 3 | 4 | 0 |
| 2 | 3 | 4 | 3 |
| 3 | 3 | 4 | 1 |
| 4 | 3 | 4 | 2 |
| 5 | 4 | 4 | 0 |
The water column sums to 6.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(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 totalJavaTested in our runner
import java.util.*;
class Solution {
public int trap(int[] height) {
int n = height.length;
long total = 0;
for (int i = 0; i < n; i++) {
int leftMax = 0;
for (int j = 0; j <= i; j++) {
leftMax = Math.max(leftMax, height[j]);
}
int rightMax = 0;
for (int j = i; j < n; j++) {
rightMax = Math.max(rightMax, height[j]);
}
total += Math.min(leftMax, rightMax) - height[i];
}
return (int) total;
}
};C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
long long total = 0;
for (int i = 0; i < n; i++) {
int leftMax = 0;
for (int j = 0; j <= i; j++) {
leftMax = max(leftMax, height[j]);
}
int rightMax = 0;
for (int j = i; j < n; j++) {
rightMax = max(rightMax, height[j]);
}
total += min(leftMax, rightMax) - height[i];
}
return (int) total;
}
};JavaScriptTested in our runner
/**
* @param {number[]} height
* @return {number}
*/
var trap = function(height) {
const n = height.length;
let total = 0;
for (let i = 0; i < n; i++) {
let leftMax = 0;
for (let j = 0; j <= i; j++) {
leftMax = Math.max(leftMax, height[j]);
}
let rightMax = 0;
for (let j = i; j < n; j++) {
rightMax = Math.max(rightMax, height[j]);
}
total += Math.min(leftMax, rightMax) - height[i];
}
return total;
};GoTested in our runner
func trap(height []int) int {
n := len(height)
total := 0
for i := 0; i < n; i++ {
leftMax := 0
for j := 0; j <= i; j++ {
if height[j] > leftMax {
leftMax = height[j]
}
}
rightMax := 0
for j := i; j < n; j++ {
if height[j] > rightMax {
rightMax = height[j]
}
}
lower := leftMax
if rightMax < lower {
lower = rightMax
}
total += lower - height[i]
}
return total
}C#Tested in our runner
public class Solution {
public int trap(int[] height) {
int n = height.Length;
long total = 0;
for (int i = 0; i < n; i++) {
int leftMax = 0;
for (int j = 0; j <= i; j++) {
leftMax = Math.Max(leftMax, height[j]);
}
int rightMax = 0;
for (int j = i; j < n; j++) {
rightMax = Math.Max(rightMax, height[j]);
}
total += Math.Min(leftMax, rightMax) - height[i];
}
return (int) 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
- Create
leftMaxandrightMax, both of length n. - Set
leftMax[0] = height[0]and fill forward withmax(leftMax[i-1], height[i]). - Set
rightMax[n-1] = height[n-1]and fill backward withmax(rightMax[i+1], height[i]). - For each
i, addmin(leftMax[i], rightMax[i]) - height[i]. - 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]minof the two per index:[1,3,3,3,3,4]- subtract
height:[0,0,3,1,2,0]
The sum is 6.
Complexity
| Time | O(n) |
|---|---|
| Space | O(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 totalJavaTested in our runner
import java.util.*;
class Solution {
public int trap(int[] height) {
int n = height.length;
int[] leftMax = new int[n];
int[] rightMax = new int[n];
leftMax[0] = height[0];
for (int i = 1; i < n; i++) {
leftMax[i] = Math.max(leftMax[i - 1], height[i]);
}
rightMax[n - 1] = height[n - 1];
for (int i = n - 2; i >= 0; i--) {
rightMax[i] = Math.max(rightMax[i + 1], height[i]);
}
long total = 0;
for (int i = 0; i < n; i++) {
total += Math.min(leftMax[i], rightMax[i]) - height[i];
}
return (int) total;
}
}C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int trap(vector<int>& height) {
int n = height.size();
vector<int> leftMax(n), rightMax(n);
leftMax[0] = height[0];
for (int i = 1; i < n; i++) {
leftMax[i] = max(leftMax[i - 1], height[i]);
}
rightMax[n - 1] = height[n - 1];
for (int i = n - 2; i >= 0; i--) {
rightMax[i] = max(rightMax[i + 1], height[i]);
}
long long total = 0;
for (int i = 0; i < n; i++) {
total += min(leftMax[i], rightMax[i]) - height[i];
}
return (int) total;
}
};JavaScriptTested in our runner
/**
* @param {number[]} height
* @return {number}
*/
var trap = function(height) {
const n = height.length;
const leftMax = new Array(n).fill(0);
const rightMax = new Array(n).fill(0);
leftMax[0] = height[0];
for (let i = 1; i < n; i++) {
leftMax[i] = Math.max(leftMax[i - 1], height[i]);
}
rightMax[n - 1] = height[n - 1];
for (let i = n - 2; i >= 0; i--) {
rightMax[i] = Math.max(rightMax[i + 1], height[i]);
}
let total = 0;
for (let i = 0; i < n; i++) {
total += Math.min(leftMax[i], rightMax[i]) - height[i];
}
return total;
};GoTested in our runner
func trap(height []int) int {
n := len(height)
leftMax := make([]int, n)
rightMax := make([]int, n)
leftMax[0] = height[0]
for i := 1; i < n; i++ {
leftMax[i] = leftMax[i-1]
if height[i] > leftMax[i] {
leftMax[i] = height[i]
}
}
rightMax[n-1] = height[n-1]
for i := n - 2; i >= 0; i-- {
rightMax[i] = rightMax[i+1]
if height[i] > rightMax[i] {
rightMax[i] = height[i]
}
}
total := 0
for i := 0; i < n; i++ {
lower := leftMax[i]
if rightMax[i] < lower {
lower = rightMax[i]
}
total += lower - height[i]
}
return total
}C#Tested in our runner
public class Solution {
public int trap(int[] height) {
int n = height.Length;
int[] leftMax = new int[n];
int[] rightMax = new int[n];
leftMax[0] = height[0];
for (int i = 1; i < n; i++) {
leftMax[i] = Math.Max(leftMax[i - 1], height[i]);
}
rightMax[n - 1] = height[n - 1];
for (int i = n - 2; i >= 0; i--) {
rightMax[i] = Math.Max(rightMax[i + 1], height[i]);
}
long total = 0;
for (int i = 0; i < n; i++) {
total += Math.Min(leftMax[i], rightMax[i]) - height[i];
}
return (int) 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
- Start with an empty stack of indices and
total = 0. - For each index
i, while the stack is non-empty andheight[i] > height[top], pop the top as the floor. - If the stack is now empty, there is no left wall, so stop popping.
- Otherwise let
leftbe the new top. The layer width isi - left - 1, and its depth ismin(height[left], height[i]) - floor. - Add width * depth to
total. - Push
ionto the stack. - Return
total.
Dry run
On [1,3,0,2,1,4]:
| i | height | action | stack after | total |
|---|---|---|---|---|
| 0 | 1 | push | [0] | 0 |
| 1 | 3 | pop 0, stack empty, push | [1] | 0 |
| 2 | 0 | push | [1,2] | 0 |
| 3 | 2 | pop 2: width 1, depth min(3,2)-0 = 2; push | [1,3] | 2 |
| 4 | 1 | push | [1,3,4] | 2 |
| 5 | 4 | pop 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
| Time | O(n) |
|---|---|
| Space | O(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 totalJavaTested in our runner
import java.util.*;
class Solution {
public int trap(int[] height) {
Deque<Integer> stack = new ArrayDeque<>();
long total = 0;
for (int i = 0; i < height.length; i++) {
while (!stack.isEmpty() && height[i] > height[stack.peek()]) {
int floor = height[stack.pop()];
if (stack.isEmpty()) {
break;
}
int left = stack.peek();
long width = i - left - 1;
total += width * (Math.min(height[left], height[i]) - floor);
}
stack.push(i);
}
return (int) total;
}
}C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int trap(vector<int>& height) {
vector<int> st;
long long total = 0;
for (int i = 0; i < (int) height.size(); i++) {
while (!st.empty() && height[i] > height[st.back()]) {
int floor = height[st.back()];
st.pop_back();
if (st.empty()) {
break;
}
int left = st.back();
long long width = i - left - 1;
total += width * (min(height[left], height[i]) - floor);
}
st.push_back(i);
}
return (int) total;
}
};JavaScriptTested in our runner
/**
* @param {number[]} height
* @return {number}
*/
var trap = function(height) {
const stack = [];
let total = 0;
for (let i = 0; i < height.length; i++) {
while (stack.length > 0 && height[i] > height[stack[stack.length - 1]]) {
const floor = height[stack.pop()];
if (stack.length === 0) {
break;
}
const left = stack[stack.length - 1];
const width = i - left - 1;
total += width * (Math.min(height[left], height[i]) - floor);
}
stack.push(i);
}
return total;
};GoTested in our runner
func trap(height []int) int {
stack := []int{}
total := 0
for i := 0; i < len(height); i++ {
for len(stack) > 0 && height[i] > height[stack[len(stack)-1]] {
floor := height[stack[len(stack)-1]]
stack = stack[:len(stack)-1]
if len(stack) == 0 {
break
}
left := stack[len(stack)-1]
width := i - left - 1
lower := height[left]
if height[i] < lower {
lower = height[i]
}
total += width * (lower - floor)
}
stack = append(stack, i)
}
return total
}C#Tested in our runner
public class Solution {
public int trap(int[] height) {
Stack<int> stack = new Stack<int>();
long total = 0;
for (int i = 0; i < height.Length; i++) {
while (stack.Count > 0 && height[i] > height[stack.Peek()]) {
int floor = height[stack.Pop()];
if (stack.Count == 0) {
break;
}
int left = stack.Peek();
long width = i - left - 1;
total += width * (Math.Min(height[left], height[i]) - floor);
}
stack.Push(i);
}
return (int) total;
}
}
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
- Set
left = 0,right = n - 1,leftMax = 0,rightMax = 0,water = 0. - While
left < right, compareheight[left]withheight[right]. - If the left bar is no taller: if it is at least
leftMax, make it the newleftMax; otherwise addleftMax - height[left]towater. Then moveleftright. - Otherwise do the mirror on the right with
rightMax, then moverightleft. - Return
waterwhen 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.
| step | left | right | height[left] vs height[right] | leftMax | rightMax | water |
|---|---|---|---|---|---|---|
| 1 | 0 | 5 | 1 <= 4, new max | 1 | 0 | 0 |
| 2 | 1 | 5 | 3 <= 4, new max | 3 | 0 | 0 |
| 3 | 2 | 5 | 0 <= 4, add 3 - 0 | 3 | 0 | 3 |
| 4 | 3 | 5 | 2 <= 4, add 3 - 2 | 3 | 0 | 4 |
| 5 | 4 | 5 | 1 <= 4, add 3 - 1 | 3 | 0 | 6 |
| end | 5 | 5 | pointers meet | 3 | 0 | 6 |
The loop stops and returns 6.
Complexity
| Time | O(n) |
|---|---|
| Space | O(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 waterJavaTested in our runner
import java.util.*;
class Solution {
public int trap(int[] height) {
int left = 0, right = height.length - 1;
int leftMax = 0, rightMax = 0;
long water = 0;
while (left < right) {
if (height[left] <= height[right]) {
// right wall is at least as tall, so leftMax decides
if (height[left] >= leftMax) {
leftMax = height[left];
} else {
water += leftMax - height[left];
}
left++;
} else {
if (height[right] >= rightMax) {
rightMax = height[right];
} else {
water += rightMax - height[right];
}
right--;
}
}
return (int) water;
}
}C++Tested in our runner
#include <vector>
using namespace std;
class Solution {
public:
int trap(vector<int>& height) {
int left = 0;
int right = (int) height.size() - 1;
int leftMax = 0, rightMax = 0;
long long water = 0;
while (left < right) {
if (height[left] <= height[right]) {
// right wall is at least as tall, so leftMax decides
if (height[left] >= leftMax) {
leftMax = height[left];
} else {
water += leftMax - height[left];
}
left++;
} else {
if (height[right] >= rightMax) {
rightMax = height[right];
} else {
water += rightMax - height[right];
}
right--;
}
}
return (int) water;
}
};JavaScriptTested in our runner
/**
* @param {number[]} height
* @return {number}
*/
var trap = function(height) {
let left = 0;
let right = height.length - 1;
let leftMax = 0;
let rightMax = 0;
let water = 0;
while (left < right) {
if (height[left] <= height[right]) {
// right wall is at least as tall, so leftMax decides
if (height[left] >= leftMax) {
leftMax = height[left];
} else {
water += leftMax - height[left];
}
left++;
} else {
if (height[right] >= rightMax) {
rightMax = height[right];
} else {
water += rightMax - height[right];
}
right--;
}
}
return water;
};GoTested in our runner
func trap(height []int) int {
left, right := 0, len(height)-1
leftMax, rightMax := 0, 0
water := 0
for left < right {
if height[left] <= height[right] {
// right wall is at least as tall, so leftMax decides
if height[left] >= leftMax {
leftMax = height[left]
} else {
water += leftMax - height[left]
}
left++
} else {
if height[right] >= rightMax {
rightMax = height[right]
} else {
water += rightMax - height[right]
}
right--
}
}
return water
}C#Tested in our runner
public class Solution {
public int trap(int[] height) {
int left = 0, right = height.Length - 1;
int leftMax = 0, rightMax = 0;
long water = 0;
while (left < right) {
if (height[left] <= height[right]) {
// right wall is at least as tall, so leftMax decides
if (height[left] >= leftMax) {
leftMax = height[left];
} else {
water += leftMax - height[left];
}
left++;
} else {
if (height[right] >= rightMax) {
rightMax = height[right];
} else {
water += rightMax - height[right];
}
right--;
}
}
return (int) water;
}
}Common mistakes
- Adding
leftMax - height[left]before updatingleftMax. When the current bar is the new tallest, the difference is negative or stale. Checkheight[left] >= leftMaxfirst, update the max, and only add water in the else branch. - Using
min(leftMax, rightMax)as the pointer rule instead of comparingheight[left]withheight[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. Useleft < right. - Computing the brute-force maxima over
0..i-1andi+1..n-1, excluding the bar itself. Then a tall bar gives a negative result. Include indexiin both scans so the minimum is at leastheight[i]. - In the stack solution, forgetting the
if not stack: breakcheck after popping. With an empty stack there is no left wall, and readingstack[-1]fails or counts water that spills out. Break and push the current index. - In the stack solution, using the full distance
i - leftas the width instead ofi - 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 = 20000with 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,rightMaxand 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
leftMaxgives 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
Related problems
- Sort Colors · same technique: In-place Array Modification
- String Compression · same technique: In-place Array Modification
- Remove Duplicates from Sorted Array II · same technique: In-place Array Modification
- Move Pieces to Obtain a String · same technique: In-place Array Modification
- Separate Black and White Balls · same technique: In-place Array Modification
- 3Sum · same pattern: Two Pointers
- Container With Most Water · same pattern: Two Pointers
- Longest Palindromic Substring · same pattern: Two Pointers
- Remove Nth Node From End of List · same pattern: Two Pointers
- Find the Duplicate Number · same pattern: Two Pointers