← Home

42. Trapping Rain Water

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
42

The trick here is to name the state correctly, then let the implementation follow. For 42. Trapping Rain Water, the solution in this repository is mainly a two pointers solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers, stack, sliding window.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are trap, leftMax, tmp.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • The stack stores unfinished context, which is usually the cleanest way to handle nested or monotonic structure.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 4 ms, faster than 95.59% of C++ online submissions for Trapping Rain Water.
02//Memory Usage: 8.2 MB, less than 100.00% of C++ online submissions for Trapping Rain Water.
03class Solution {
04public:
05    int trap(vector<int>& height) {
06        int left = 0, right = 0;
07        int ans = 0;
08        int N = height.size();
09        
10        while(right < N){
11            int valley = height[left];
12            
13            //left wall should have height > 0
14            while(left < N && height[left] == 0){
15                left++;
16            }
17            //cannot find left wall
18            if(left == N) break;
19
20            //right wall should be larger than valley
21            for(right = left+1; right < N && height[right] <= valley; right++){
22                valley = min(valley, height[right]);
23            }
24            //cannot find right wall
25            if(right == N) break;
26            // cout << "left: " << left << ", right: " << right << endl;
27            
28            //we've found a valid right wall,
29            //now we want to discover higher right wall
30            //we only need to find a higher right wall when right wall is lower than left wall
31            int head = right+1;
32            if(height[left] > height[right]){
33                int last = right;
34                while(head < N && height[head] < height[left]){
35                    if(height[head] > height[last]){
36                        last = head;
37                    }
38                    head++;
39                }
40                if(head < N && height[head] >= height[left]){
41                    //found a right wall >= left wall
42                    right = head;
43                }else{
44                    //found the highest right wall > original right wall
45                    right = last;
46                }
47            }
48            
49            //calculate current trapping water amount
50            int lh = height[left], rh = height[right];
51            for(int i = left+1; i < min(right, N); i++){
52                // cout << i << ", height: " << height[i] << endl;
53                //we should take max(0, x) here!
54                ans += max(0, min(lh, rh) - height[i]);
55            }
56            // cout << left << " " << right << " " << valley << " " << ans << endl;
57
58            left = right;
59        }
60        
61        return ans;
62    }
63};
64
65//Approach 1: Brute force
66//Runtime: 312 ms, faster than 5.10% of C++ online submissions for Trapping Rain Water.
67//Memory Usage: 8.5 MB, less than 100.00% of C++ online submissions for Trapping Rain Water.
68//time: O(n^2), space: O(1)
69class Solution {
70public:
71    int trap(vector<int>& height) {
72        int ans = 0;
73        
74        for(int i = 0; i < height.size(); i++){
75            int maxLeft = 0, maxRight = 0;
76            for(int j = i; j >= 0 ; j--){
77                maxLeft = max(maxLeft, height[j]);
78            }
79            for(int j = i; j < height.size() ; j++){
80                maxRight = max(maxRight, height[j]);
81            }
82            ans += min(maxLeft, maxRight) - height[i];
83            // cout << maxLeft << " " << maxRight << " " << ans << endl;
84        }
85        
86        return ans;
87    }
88};
89
90//Approach 2: Dynamic Programming
91//Runtime: 4 ms, faster than 95.59% of C++ online submissions for Trapping Rain Water.
92//Memory Usage: 8.2 MB, less than 100.00% of C++ online submissions for Trapping Rain Water.
93//time: O(n), space: O(n)
94class Solution {
95public:
96    int trap(vector<int>& height) {
97        int N = height.size();
98        if(N == 0) return 0;
99        int ans = 0;
100        
101        vector<int> leftMax(N), rightMax(N);
102        leftMax[0] = height[0];
103        for(int i = 1; i < N; i++){
104            leftMax[i] = max(leftMax[i-1], height[i]);
105        }
106        
107        rightMax[N-1] = height[N-1];
108        for(int i = N-2; i >= 0; i--){
109            rightMax[i] = max(rightMax[i+1], height[i]);
110        }
111        
112        for(int i = 1; i < N-1; i++){
113            ans += min(leftMax[i], rightMax[i]) - height[i];
114        }
115        
116        return ans;
117    }
118};
119
120//Approach 3: Using stacks
121//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Trapping Rain Water.
122//Memory Usage: 8.5 MB, less than 100.00% of C++ online submissions for Trapping Rain Water.
123//time: O(n), space: O(n)
124class Solution {
125public:
126    int trap(vector<int>& height) {
127        int ans = 0, cur = 0;
128        stack<int> stk;
129        for(int cur = 0; cur < height.size(); cur++){
130            // cout << cur << endl;
131            // if(!stk.empty()){
132            //     cout << "stack: ";
133            //     vector<int> tmp(&stk.top()+1-stk.size(), &stk.top()+1);
134            //     for(int i = 0; i < tmp.size(); i++){
135            //         cout << tmp[i] << " ";
136            //     }
137            //     cout << endl;
138            // }
139            while(!stk.empty() && height[cur] > height[stk.top()]){
140                int top = stk.top(); stk.pop();
141                // cout << "pop: " << top << endl;
142                if(stk.empty()){
143                    break;
144                }
145                //top is bounded by previous bar in the stack and current bar   
146                int dist = cur - stk.top() - 1;
147                //the left and right walls are : stk.top(), cur
148                int bounded_height = min(height[stk.top()], height[cur]) - height[top];
149                ans += dist * bounded_height;
150                // cout << "[" << stk.top() << ", " << cur << "] " << ans << endl;
151            }
152            //the current bar is bounded by previous bar in the stack
153            stk.push(cur);
154        }
155        return ans;
156    }
157};
158
159//Approach 4: Using 2 pointers
160//Runtime: 4 ms, faster than 95.59% of C++ online submissions for Trapping Rain Water.
161//Memory Usage: 8.3 MB, less than 100.00% of C++ online submissions for Trapping Rain Water.
162//time: O(n), space: O(1)
163class Solution {
164public:
165    int trap(vector<int>& height) {
166        int N = height.size();
167        if(N == 0) return 0;
168        int left = 0, right = N-1;
169        int leftMax = 0, rightMax = 0;
170        int ans = 0;
171        while(left < right){
172            if(height[left] > leftMax){
173                leftMax = height[left];
174            }
175            if(height[right] > rightMax){
176                rightMax = height[right];
177            }
178            if(leftMax < rightMax){
179                //use leftMax to substract because leftMax is min(leftMax, rightMax)
180                ans += max(0, leftMax - height[left]);
181                // cout << "[" << left << ", " << right << "] " << leftMax << " " << rightMax << " " << ans << endl;
182                left++;
183            }else{
184                ans += max(0, rightMax - height[right]);
185                // cout << "[" << left << ", " << right << "] " << leftMax << " " << rightMax << " " << ans << endl;
186                right--;
187            }
188        }
189        return ans;
190    }
191};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.