Tutorialspoint
Problem
Solution
Submissions

Trapping Rain Water

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

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:
    • The elevation map is represented by the 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)
  • Space Complexity: O(1)
ArraysPwCTutorix
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Consider using two pointers approach to avoid extra space
  • For each position, the water trapped depends on the minimum of maximum heights to its left and right
  • Keep track of the left and right maximum heights as you traverse the array
  • Calculate the water amount at each position by finding the difference between the minimum of the two maxima and the current height

Steps to solve by this approach:

 Step 1: Initialize two pointers - left at the start of the array and right at the end of the array.
 Step 2: Initialize two variables leftMax and rightMax to track the maximum heights from the left and right ends.
 Step 3: Initialize a result variable to store the total trapped water.
 Step 4: Use a two-pointer approach, moving inward from both ends of the array.
 Step 5: At each step, compare leftMax and rightMax and move the pointer from the side with the smaller maximum height.
 Step 6: Update the maximum height for that side and add the trapped water at the current position.
 Step 7: Continue until the two pointers meet.

Submitted Code :