Problem · Array

Trapping Rain Water

Learn this problem
MediumInMobi logoInMobiFULLTIMEONSITE INTERVIEW

Problem statement

You are given an array heights, where heights[i] is the height of the ith bar in an elevation map. Every bar has width 1.

Return the total amount of rainwater that can be trapped between the bars.

Function

trapRainWater(heights: long[]) → long

Examples

Example 1

heights = [3,0,0,2,0,4]return = 10

The bars trap 3 + 3 + 1 + 3 = 10 units of water at indices 1, 2, 3, and 4.

Example 2

heights = [8,1,8,2,4]return = 9

The first basin traps 7 units above the bar of height 1, and the last basin traps 2 units above the bar of height 2.

Constraints

  • 0 <= heights.length <= 10^6
  • 0 <= heights[i] <= 10^9
  • The answer fits in a signed long.

More InMobi problems

drafts saved locally
public long trapRainWater(long[] heights) {
    // write your code here
}
heights[3,0,0,2,0,4]
expected10
checking account