
Problem
Solution
Submissions
Trapping Rain Water
Certification: Advanced Level
Accuracy: 100%
Submissions: 1
Points: 15
Write a Java program to compute how much water can be trapped after rain, given an array of non-negative integers representing an elevation map where the width of each bar is 1. The amount of water that can be trapped depends on the heights of the surrounding bars.
Example 1
- Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
- Output: 6
- Explanation:
- The elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1].
- In this case, 6 units of rain water are being trapped.
Example 2
- Input: height = [4,2,0,3,2,5]
- Output: 9
- Explanation:
- The elevation map is represented by array [4,2,0,3,2,5].
- In this case, 9 units of rain water are being trapped.
Constraints
- n == height.length
- 1 <= n <= 2 * 10^4
- 0 <= height[i] <= 10^5
- Time Complexity: O(n) where n is the size of the height array
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
| Lang | Status | Date | Code |
|---|---|---|---|
| You do not have any submissions for this problem. | |||
| User | Lang | Status | Date | Code |
|---|---|---|---|---|
| No submissions found. | ||||
Solution Hints
- Use the two-pointer technique to solve this problem efficiently
- Initialize left and right pointers at the start and end of the array
- Keep track of the maximum height seen so far from both left and right sides
- Move the pointer from the side with the smaller height towards the center
- For each position, calculate water trapped as the difference between the minimum of left and right maximum heights and the current height
- Be careful with edge cases where no water can be trapped