LeetCode 42: Trapping Rain Water Solution
Master LeetCode problem 42 (Trapping Rain Water), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
42. Trapping Rain Water
Problem Explanation
Explanation
To solve this problem, we can use a two-pointer approach. We initialize two pointers left
and right
at the beginning and end of the array respectively. We also maintain two variables leftMax
and rightMax
to keep track of the maximum height encountered from the left and right sides so far.
At each step, we compare the heights at the left
and right
pointers. If height[left] < height[right]
, then we update leftMax
and calculate the water trapped at the left
pointer using leftMax - height[left]
. Similarly, if height[left] >= height[right]
, we update rightMax
and calculate the water trapped at the right
pointer using rightMax - height[right]
.
We continue this process until the left
pointer crosses the right
pointer.
The time complexity of this approach is O(n) where n is the number of elements in the input array. The space complexity is O(1) as we are using only a constant amount of extra space.
Solution Code
class Solution {
public int trap(int[] height) {
int left = 0, right = height.length - 1;
int leftMax = 0, rightMax = 0;
int totalWater = 0;
while (left < right) {
if (height[left] < height[right]) {
if (height[left] >= leftMax) {
leftMax = height[left];
} else {
totalWater += leftMax - height[left];
}
left++;
} else {
if (height[right] >= rightMax) {
rightMax = height[right];
} else {
totalWater += rightMax - height[right];
}
right--;
}
}
return totalWater;
}
}
Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 42 (Trapping Rain Water)?
This page provides optimized solutions for LeetCode problem 42 (Trapping Rain Water) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 42 (Trapping Rain Water)?
The time complexity for LeetCode 42 (Trapping Rain Water) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 42 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 42 in Java, C++, or Python.