Tutorialspoint
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
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
Constraints
  • n == height.length
  • 1 ≤ n ≤ 2 * 10^4
  • 0 ≤ height[i] ≤ 3 * 10^4
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysFacebookWalmart
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

  • 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

Steps to solve by this approach:

 Step 1: Initialize two pointers at the beginning (left = 0) and end (right = n-1) of array
 Step 2: Initialize leftMax and rightMax to track maximum heights seen from respective sides
 Step 3: Compare heights at left and right pointers to determine which side to process
 Step 4: If current height is greater than or equal to respective max, update the max
 Step 5: If current height is less than respective max, add trapped water (max - current height)
 Step 6: Move the pointer from the side with smaller height towards center
 Step 7: Continue until both pointers meet and return total trapped water

Submitted Code :