Top Interview 150
To solve LeetCode 42: Trapping Rain Water, we need to calculate the total amount of water that can be trapped between elevation heights after it rains. This problem is best tackled using one of the following methods:
π Problem Description
Input: An array height where each element represents an elevation bar.
Output: The total units of water trapped.
π‘ Examples
Example 1
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: Water trapped is shown in the diagram.
Example 2
Input: height = [4,2,0,3,2,5]
Output: 9
Explanation: Water trapped in valleys.
π Solution Approach
Two-Pointer Approach
This method uses O(n)
time complexity and O(1)
space complexity.
Implementation
var trap = function(height) {
let left = 0, right = height.length - 1;
let leftMax = 0, rightMax = 0;
let waterTrapped = 0;
while (left < right) {
if (height[left] < height[right]) {
if (height[left] >= leftMax) {
leftMax = height[left];
} else {
waterTrapped += leftMax - height[left];
}
left++;
} else {
if (height[right] >= rightMax) {
rightMax = height[right];
} else {
waterTrapped += rightMax - height[right];
}
right--;
}
}
return waterTrapped;
};
π How It Works
- Initialization:
- Two pointers:
left
andright
starting at the two ends of the array.
- Two pointers:
-
leftMax
andrightMax
to store the maximum height seen so far from the left and right. - Process:
- Compare
height[left]
andheight[right]
. - If
height[left]
is smaller, calculate water trapped usingleftMax
. - Otherwise, calculate water trapped using
rightMax
. - Move the pointer inward.
- Compare
- Calculation:
- If the current bar is smaller than
leftMax
orrightMax
, it traps water.
- If the current bar is smaller than
π Complexity Analysis
- > Time Complexity:
O(n)
Single traversal of the height array. - > Space Complexity:
O(1)
, No additional space is used.
π Dry Run
Input: height = [4,2,0,3,2,5]
π Learn More
Read the detailed walkthrough and explanation of the two-pointer approach on my Dev.to post:
π Candy - JavaScript Solution
How would you optimize this further? Letβs discuss below! π
Top comments (1)
Follow Me on GitHub π
If you found this solution helpful, check out more of my projects and solutions on my GitHub profile.
Don't forget to follow for more updates!