
Problem
Solution
Submissions
Trapping Rain Water Problem
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a C++ program to solve the Trapping Rain Water problem. Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Example 1
- Input: height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
- Output: 6
- Explanation:
- Step 1: We have to find the maximum height to the left of each position.
- Step 2: We have to find the maximum height to the right of each position.
- Step 3: For each position, calculate water trapped = min(left_max, right_max) - height[i].
- Step 4: Sum all trapped water amounts to get the total water trapped (6 units).
Example 2
- Input: height = [4, 2, 0, 3, 2, 5]
- Output: 9
- Explanation:
- Step 1: We have to find the maximum height to the left of each position.
- Step 2: We have to find the maximum height to the right of each position.
- Step 3: For each position, calculate water trapped = min(left_max, right_max) - height[i].
- Step 4: Sum all trapped water amounts to get the total water trapped (9 units).
Constraints
- 1 ≤ height.length ≤ 2 * 10^4
- 0 ≤ height[i] ≤ 10^5
- Time Complexity: O(n) where n is the length 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
- Water can be trapped at a position only if there are higher bars on both sides
- The amount of water trapped is determined by the minimum of maximum heights on both sides
- Use a two-pointer approach to track the maximum heights from both sides
- Move the pointer from the side with a smaller maximum height
- Be careful with edge cases where no water can be trapped