trapping rain water solution

main
Luca Lombardo 1 year ago
parent fc0b4598c1
commit 193f667011

@ -0,0 +1,8 @@
[package]
name = "trapping-rain-water"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

@ -0,0 +1,46 @@
> **Problem**: https://leetcode.com/problems/trapping-rain-water/
# Comments on the solution
The strategy used to solve this problem is the two-pointer approach. We use two pointers, one at the beginning and one at the end of the array. We also keep track of the maximum height of the left and right sides. We then move the pointers towards each other, updating the maximum height as we go. If the maximum height of the left side is less than the maximum height of the right side, we know that we can trap water on the left side. Similarly, if the maximum height of the right side is less than the maximum height of the left side, we know that we can trap water on the right side. We keep adding the trapped water to the result until the pointers meet.
### Complexity analysis
* **Time complexity:** `O(n)` since we are iterating over the array once.
* **Space complexity:** `O(1)` since we are not using any extra space.
---
### Rust solution
```rust
fn trap(height: Vec<i32>) -> i32 {
if height.len() == 0 {
return 0;
}
let (mut l, mut r) = (0, height.len() - 1);
let (mut l_max, mut r_max) = (height[l], height[r]);
let mut res = 0;
while l < r {
match l_max.cmp(&r_max) {
Ordering::Less => {
l += 1;
l_max = std::cmp::max(l_max, height[l]);
res += l_max - height[l];
},
_ => {
r -= 1;
r_max = std::cmp::max(r_max, height[r]);
res += r_max - height[r];
}
}
}
res
}
```
### Leetcode result
![](https://i.imgur.com/jzsT7bu.png)

@ -0,0 +1,36 @@
use std::cmp::Ordering;
fn trap(height: Vec<i32>) -> i32 {
// base case
if height.len() == 0 {
return 0;
}
let (mut l, mut r) = (0, height.len() - 1); // left and right pointer
let (mut l_max, mut r_max) = (height[l], height[r]); // left and right max height of current pointer
let mut res = 0;
while l < r { // loop until left and right pointer meet
match l_max.cmp(&r_max) { // compare left and right max height
Ordering::Less => { // if left max height is less than right max height means we can trap water in left side
l += 1; // move left pointer
l_max = std::cmp::max(l_max, height[l]); // update left max height
res += l_max - height[l]; // add water
},
_ => { // if right max height is less than left max height means we can trap water in right side
r -= 1; // move right pointer
r_max = std::cmp::max(r_max, height[r]); // update right max height
res += r_max - height[r]; // add water
}
}
}
res
}
fn main() {
let height = vec![0,1,0,2,1,0,1,3,2,1,2,1];
let res = trap(height);
println!("res = {}", res);
}
Loading…
Cancel
Save