What if you could instantly know how much rainwater a city's buildings trap without guessing?
Why Trapping Rain Water Problem in DSA Rust?
Imagine you have a row of different height walls after a rainstorm. You want to find out how much water is trapped between these walls. Doing this by looking at each wall and guessing the water trapped is like trying to count drops in a puddle by eye.
Manually calculating trapped water is slow and error-prone because you must consider the highest walls on both sides for every position. It's easy to miss spots or double count, especially when walls vary a lot in height.
The Trapping Rain Water algorithm quickly calculates trapped water by using two pointers or arrays to track the highest walls from left and right. This way, it finds trapped water at each position without guessing, making the process fast and accurate.
let mut total_water = 0; for i in 1..heights.len()-1 { let left_max = heights[..=i].iter().max().unwrap(); let right_max = heights[i..].iter().max().unwrap(); let water = (*left_max).min(*right_max) - heights[i]; if water > 0 { total_water += water; } }
let mut left = 0; let mut right = heights.len() - 1; let mut left_max = 0; let mut right_max = 0; let mut total_water = 0; while left < right { if heights[left] < heights[right] { if heights[left] >= left_max { left_max = heights[left]; } else { total_water += left_max - heights[left]; } left += 1; } else { if heights[right] >= right_max { right_max = heights[right]; } else { total_water += right_max - heights[right]; } right -= 1; } }
This algorithm enables fast and precise calculation of trapped water, even for very large and complex wall height arrays.
City planners use this concept to estimate how much rainwater can be collected or trapped in urban areas with buildings of different heights, helping design better drainage systems.
Manual counting is slow and error-prone for varying wall heights.
The algorithm uses two pointers to track max heights efficiently.
It calculates trapped water quickly and accurately for each position.
Practice
Solution
Step 1: Understand the problem context
The problem involves an array representing heights of bars where water can be trapped between them.Step 2: Identify what is asked
We need to find how much water can be trapped after raining, which depends on the heights and gaps between bars.Final Answer:
The total amount of water that can be trapped between the bars after raining -> Option AQuick Check:
Trapping Rain Water = Total trapped water [OK]
- Confusing trapped water with total height sum
- Ignoring gaps between bars
- Only finding tallest bar instead of trapped water
Solution
Step 1: Identify Rust vector syntax
In Rust, vectors are created using vec![elements], which is dynamic and growable.Step 2: Check each option
let heights = vec![0,1,0,2,1,0,1,3,2,1,2,1]; uses vec! macro correctly; B is an array, C is a tuple, D is invalid syntax.Final Answer:
let heights = vec![0,1,0,2,1,0,1,3,2,1,2,1]; -> Option BQuick Check:
vec! macro creates vector [OK]
- Using array syntax instead of vector
- Using tuple parentheses instead of brackets
- Using curly braces which are invalid here
fn trap(height: Vec<i32>) -> i32 {
let mut left = 0;
let mut right = height.len() - 1;
let mut left_max = 0;
let mut right_max = 0;
let mut water = 0;
while left < right {
if height[left] < height[right] {
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;
}
}
water
}
fn main() {
let heights = vec![0,1,0,2,1,0,1,3,2,1,2,1];
println!("{}", trap(heights));
}Solution
Step 1: Understand two-pointer approach in code
The code uses two pointers from left and right, tracking max heights and accumulating trapped water.Step 2: Trace the example input
For input [0,1,0,2,1,0,1,3,2,1,2,1], the trapped water calculated is 6 units.Final Answer:
6 -> Option AQuick Check:
Two-pointer trap water = 6 [OK]
- Miscounting trapped water units
- Confusing left_max and right_max updates
- Off-by-one errors in pointer movement
fn trap(height: Vec<i32>) -> i32 {
let mut left = 0;
let mut right = height.len();
let mut left_max = 0;
let mut right_max = 0;
let mut water = 0;
while left < right {
if height[left] < height[right] {
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;
}
}
water
}Solution
Step 1: Check initialization of right pointer
right is set to height.len(), which is out of bounds for indexing (max index is len()-1).Step 2: Correct right initialization
right should be height.len() - 1 to point to the last valid index.Final Answer:
right should be initialized to height.len() - 1 -> Option DQuick Check:
Indexing error fixed by right = len()-1 [OK]
- Using len() as index causes runtime panic
- Changing loop condition incorrectly
- Starting max heights at wrong values
[4,2,0,3,2,5], what is the total trapped rain water using the two-pointer approach?Solution
Step 1: Analyze heights and max boundaries
Left max starts at 4, right max at 5. Water trapped depends on min(left_max, right_max) minus current height.Step 2: Calculate trapped water step-by-step
Positions: - index 1: min(4,5)=4, height=2, trapped=2 - index 2: min(4,5)=4, height=0, trapped=4 - index 3: min(4,5)=4, height=3, trapped=1 - index 4: min(4,5)=4, height=2, trapped=2 Total trapped water = 2+4+1+2 = 9 units. Verified with two-pointer simulation.Final Answer:
9 -> Option CQuick Check:
Two-pointer trap water for [4,2,0,3,2,5] = 9 [OK]
- Adding trapped water incorrectly at edges
- Confusing left_max and right_max updates
- Forgetting to move pointers properly
Ready to prove it?
Pass the test and this pattern moves unknown
