Tutorialspoint
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)
ArraysFunctions / MethodsIBMeBay
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

  • 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

Steps to solve by this approach:

 Step 1: Initialize two pointers, left at the beginning and right at the end of the array
 Step 2: Initialize two variables, leftMax and rightMax, to track the maximum heights seen from both sides
 Step 3: While left pointer is less than right pointer, compare the heights at both pointers
 Step 4: Update the maximum height seen from the left and right sides
 Step 5: If the left bar is smaller, calculate water trapped at this position as leftMax - height[left]
 Step 6: If the right bar is smaller, calculate water trapped at this position as rightMax - height[right]
 Step 7: Move the pointer of the smaller height inward and continue until pointers meet

Submitted Code :