42. Trapping Rain Water

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.

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;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.