Tutorialspoint
Problem
Solution
Submissions

Trapping Rain Water

Certification: Advanced Level Accuracy: 100% Submissions: 1 Points: 15

Write a Java program to compute how much water can be trapped after rain, given an array of non-negative integers representing an elevation map where the width of each bar is 1. The amount of water that can be trapped depends on the heights of the surrounding bars.

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].
    • 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) where n is the size of the height array
  • Space Complexity: O(1)
ArraysSnowflakeD. E. Shaw
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 the two-pointer technique to solve this problem efficiently
  • Initialize left and right pointers at the start and end of the array
  • Keep track of the maximum height seen so far from both left and right sides
  • Move the pointer from the side with the smaller height towards the center
  • For each position, calculate water trapped as the difference between the minimum of left and right maximum heights and the current height
  • Be careful with edge cases where no water can be trapped

Steps to solve by this approach:

 Step 1: Check edge cases - if the array is null or has less than 3 elements, no water can be trapped.

 Step 2: Initialize left and right pointers at the beginning and end of the array.
 Step 3: Initialize leftMax and rightMax variables to track maximum heights seen from left and right.
 Step 4: While left pointer is less than right pointer, move the pointer from the side with smaller maximum height.
 Step 5: If the current height is greater than the maximum height on that side, update the maximum height.
 Step 6: Otherwise, add the trapped water at the current position (difference between the max height and current height).
 Step 7: Return the total trapped water.

Submitted Code :