
Problem
Solution
Submissions
Trapping Rain Water
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C program to calculate how much water can be trapped after raining given n non-negative integers representing an elevation map where the width of each bar is 1. Given an array of non-negative integers representing an elevation map, 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:
- The elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1].
- Water can be trapped at indices where there are higher bars on both sides.
- Total water trapped = 6 units
- The elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1].
Example 2
- Input: height = [4,2,0,3,2,5]
- Output: 9
- Explanation:
- The elevation map is [4,2,0,3,2,5].
- Water gets trapped between the bars.
- Total water trapped = 9 units
- The elevation map is [4,2,0,3,2,5].
Constraints
- n == height.length
- 1 ≤ n ≤ 2 * 10^4
- 0 ≤ height[i] ≤ 3 * 10^4
- Time Complexity: O(n)
- 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 two pointers approach from both ends of the array
- Keep track of maximum height seen so far from left and right
- Move the pointer with smaller maximum height
- Calculate trapped water at each position using the minimum of left and right maximums
- Continue until both pointers meet