BackhardTwo Pointers Razorpay Uber

Trapping Rain Water Solution

Problem Statement

Given an array of non-negative integers representing building heights, calculate the total volume of water trapped on the rooftops after heavy rain.

Example 1
Input
[0,1,0,2,1,0,1,3,2,1,2,1]
Output
6

Explanation: Step-by-step: Given the input [0,1,0,2,1,0,1,3,2,1,2,1], we first initialize two pointers, left and right, to the start and end of the array respectively. We also initialize two variables, maxLeft and maxRight, to store the maximum height of the left and right sides of the array. We then iterate through the array from left to right, and for each element, we calculate the water trapped by taking the minimum of maxLeft and maxRight, and subtracting the current height. We add this value to the total water trapped. We repeat this process for the right to left iteration. The final output is the total water trapped, which is 6.

Example 2
Input
[4,2,0,3,2,5]
Output
9

Explanation: Step-by-step: Given the input [4,2,0,3,2,5], we first initialize two pointers, left and right, to the start and end of the array respectively. We also initialize two variables, maxLeft and maxRight, to store the maximum height of the left and right sides of the array. We then iterate through the array from left to right, and for each element, we calculate the water trapped by taking the minimum of maxLeft and maxRight, and subtracting the current height. We add this value to the total water trapped. We repeat this process for the right to left iteration. The final output is the total water trapped, which is 9.

Constraints

  • 1 <= n <= 2 * 10^4
  • 0 <= height[i] <= 10^5
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free