Skip to content

Commit 97f1f4a

Browse files
committed
Added solution 2 for 0042-trapping-rain-water-2.md
1 parent 81e4e4b commit 97f1f4a

File tree

1 file changed

+266
-0
lines changed

1 file changed

+266
-0
lines changed
+266
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,266 @@
1+
# 42. Trapping Rain Water
2+
LeetCode problem: [42. Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/)
3+
4+
## LeetCode problem description
5+
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.
6+
7+
```
8+
-----------------------------------------------------------------------------------------------------------
9+
[Example 1]
10+
11+
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
12+
Output: 6
13+
14+
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1].
15+
In this case, 6 units of rain water (blue section) are being trapped.
16+
-----------------------------------------------------------------------------------------------------------
17+
[Example 2]
18+
19+
Input: height = [4,2,0,3,2,5]
20+
Output: 9
21+
-----------------------------------------------------------------------------------------------------------
22+
[Constraints]
23+
24+
n == height.length
25+
1 <= n <= 2 * 10000
26+
0 <= height[i] <= 100000
27+
-----------------------------------------------------------------------------------------------------------
28+
```
29+
30+
## Thoughts
31+
This problem can be solved using **Monotonic Stack**.
32+
33+
### Solution 2
34+
This solution will follow **Monotonic Stack**'s common rule: **only calculating when `pop()` is happening**.
35+
36+
This common rule can be applied to calculating result for most of the **Monotonic Stack** problems.
37+
38+
Sometimes it could be hard to understand, but it does work.
39+
40+
![](../images/0042.png)
41+
42+
### Solution 1
43+
Please click [42. Trapping Rain Water (solution 1)](./0042-trapping-rain-water.md) to see it.
44+
45+
### Complexity
46+
* Time: `O(n)`.
47+
* Space: `O(n)`.
48+
49+
## Java
50+
```java
51+
class Solution {
52+
public int trap(int[] heights) {
53+
var result = 0;
54+
var indexStack = new Stack<Integer>();
55+
56+
for (var i = 0; i < heights.length; i++) {
57+
while (!indexStack.empty() && heights[indexStack.peek()] < heights[i]) {
58+
var poppedIndex = indexStack.pop();
59+
60+
if (indexStack.empty()) {
61+
break;
62+
}
63+
64+
var leftHeight = heights[indexStack.peek()];
65+
var rightHeight = heights[i];
66+
var heightGap = Math.min(leftHeight, rightHeight) - heights[poppedIndex];
67+
var width = i - indexStack.peek() - 1;
68+
result += heightGap * width;
69+
}
70+
71+
indexStack.push(i);
72+
}
73+
74+
return result;
75+
}
76+
}
77+
```
78+
79+
## Python
80+
```python
81+
class Solution:
82+
def trap(self, heights: List[int]) -> int:
83+
result = 0
84+
index_stack = []
85+
86+
for i, height in enumerate(heights):
87+
while index_stack and heights[index_stack[-1]] < height:
88+
popped_index = index_stack.pop()
89+
90+
if not index_stack:
91+
break
92+
93+
left_height = heights[index_stack[-1]]
94+
right_height = height
95+
height_gap = min(left_height, right_height) - heights[popped_index]
96+
width = i - index_stack[-1] - 1
97+
result += height_gap * width
98+
99+
index_stack.append(i)
100+
101+
return result
102+
```
103+
104+
![](../images/0042.png)
105+
106+
## C++
107+
```cpp
108+
class Solution {
109+
public:
110+
int trap(vector<int>& heights) {
111+
auto result = 0;
112+
stack<int> index_stack;
113+
114+
for (auto i = 0; i < heights.size(); i++) {
115+
auto previous_height = 0;
116+
117+
while (!index_stack.empty() && heights[index_stack.top()] < heights[i]) {
118+
auto popped_index = index_stack.top();
119+
index_stack.pop();
120+
121+
if (index_stack.empty()) {
122+
break;
123+
}
124+
125+
auto left_height = heights[index_stack.top()];
126+
auto right_height = heights[i];
127+
auto height_gap = min(left_height, right_height) - heights[popped_index];
128+
auto width = i - index_stack.top() - 1;
129+
result += height_gap * width;
130+
}
131+
132+
index_stack.push(i);
133+
}
134+
135+
return result;
136+
}
137+
};
138+
```
139+
140+
## JavaScript
141+
```javascript
142+
var trap = function (heights) {
143+
let result = 0
144+
const indexStack = []
145+
146+
heights.forEach((height, i) => {
147+
while (indexStack.length > 0 && heights[indexStack.at(-1)] < height) {
148+
const poppedIndex = indexStack.pop()
149+
150+
if (indexStack.length === 0) {
151+
break
152+
}
153+
154+
const leftHeight = heights[indexStack.at(-1)]
155+
const rightHeight = heights[i]
156+
const heightGap = Math.min(leftHeight, rightHeight) - heights[poppedIndex]
157+
const width = i - indexStack.at(-1) - 1
158+
result += heightGap * width;
159+
}
160+
161+
indexStack.push(i)
162+
})
163+
164+
return result
165+
};
166+
```
167+
168+
![](../images/0042.png)
169+
170+
## C#
171+
```c#
172+
public class Solution {
173+
public int Trap(int[] heights) {
174+
var result = 0;
175+
var indexStack = new Stack<int>();
176+
177+
for (var i = 0; i < heights.Length; i++) {
178+
while (indexStack.Count > 0 && heights[indexStack.Peek()] < heights[i]) {
179+
var poppedIndex = indexStack.Pop();
180+
181+
if (indexStack.Count == 0) {
182+
break;
183+
}
184+
185+
var leftHeight = heights[indexStack.Peek()];
186+
var rightHeight = heights[i];
187+
var heightGap = Math.Min(leftHeight, rightHeight) - heights[poppedIndex];
188+
var width = i - indexStack.Peek() - 1;
189+
result += heightGap * width;
190+
}
191+
192+
indexStack.Push(i);
193+
}
194+
195+
return result;
196+
}
197+
}
198+
```
199+
200+
## Go
201+
```go
202+
func trap(heights []int) int {
203+
result := 0
204+
indexStack := []int{}
205+
206+
for i, height := range heights {
207+
for len(indexStack) > 0 && heights[indexStack[len(indexStack) - 1]] < height {
208+
poppedIndex := indexStack[len(indexStack) - 1]
209+
indexStack = indexStack[:len(indexStack) - 1]
210+
211+
if len(indexStack) == 0 {
212+
break
213+
}
214+
215+
leftIndex := indexStack[len(indexStack) - 1]
216+
leftHeight := heights[leftIndex]
217+
rightHeight := heights[i]
218+
heightGap := min(leftHeight, rightHeight) - heights[poppedIndex]
219+
width := i - leftIndex - 1
220+
result += heightGap * width
221+
}
222+
223+
indexStack = append(indexStack, i)
224+
}
225+
226+
return result
227+
}
228+
```
229+
230+
![](../images/0042.png)
231+
232+
## Ruby
233+
```ruby
234+
def trap(heights = [])
235+
result = 0
236+
index_stack = []
237+
238+
heights.each_with_index do |height, i|
239+
while !index_stack.empty? && heights[index_stack.last] <= height
240+
popped_index = index_stack.pop
241+
242+
break if index_stack.empty?
243+
244+
left_height = heights[index_stack.last]
245+
right_height = heights[i]
246+
height_gap = [ left_height, right_height ].min - heights[popped_index]
247+
width = i - index_stack.last - 1
248+
result += height_gap * width
249+
end
250+
251+
index_stack << i
252+
end
253+
254+
result
255+
end
256+
```
257+
258+
## Rust
259+
```rust
260+
// Welcome to create a PR to complete the code of this language, thanks!
261+
```
262+
263+
## Other languages
264+
```
265+
// Welcome to create a PR to complete the code of this language, thanks!
266+
```

0 commit comments

Comments
 (0)