Measure Rainwater Held Between Bars

Quick Overview

Calculate the total rainwater retained between unit-width bars from an elevation array, including separate basins and water that escapes at the ends.

Measure Rainwater Held Between Bars

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: hard

Interview Round: Other

### Problem The array `heights` describes a row of adjacent vertical bars on level ground. Bar `i` has height `heights[i]`, and every bar is one unit wide. Return the total volume of rainwater that remains between the bars after rainfall. Water that can escape past either end of the row is not retained. Measure the result in unit squares of the side profile. ### Examples **Example 1** ```text Input: heights = [4,0,2,0,4] Output: 10 ``` The three interior positions hold `4`, `2`, and `4` units of water, respectively. **Example 2** ```text Input: heights = [1,3,2,4] Output: 1 ``` Only the bar of height `2` has space above it that is enclosed on both sides. That space holds one unit. ### Constraints - `1 <= heights.length <= 2 * 10^4` - `0 <= heights[i] <= 10^5`

Overview: Calculate the total rainwater retained between unit-width bars from an elevation array, including separate basins and water that escapes at the ends.

Amazon logo
Amazon
Date not reported
hardSoftware EngineerOtherCoding & Algorithms
0
0

Problem

The array heights describes a row of adjacent vertical bars on level ground. Bar i has height heights[i], and every bar is one unit wide.

Return the total volume of rainwater that remains between the bars after rainfall. Water that can escape past either end of the row is not retained. Measure the result in unit squares of the side profile.

Examples

Example 1

Input: heights = [4,0,2,0,4]
Output: 10

The three interior positions hold 4, 2, and 4 units of water, respectively.

Example 2

Input: heights = [1,3,2,4]
Output: 1

Only the bar of height 2 has space above it that is enclosed on both sides. That space holds one unit.

Constraints

  • 1 <= heights.length <= 2 * 10^4
  • 0 <= heights[i] <= 10^5