InferenceAI

Enter at least two characters to search.

Start free

Rainwater Between Bars

hardTwo Pointers40 min50 XP

heights describes an elevation map where each bar has width 1. Return the total units of rainwater trapped after it rains.

The water above bar ii is

wi=max⁡(0,  min⁡(max⁡k≤ihk,  max⁡k≥ihk)−hi)w_i = \max\Big(0,\; \min\big(\max_{k \le i} h_k,\; \max_{k \ge i} h_k\big) - h_i\Big)

Requirements

  • Run in O(n)O(n) time and O(1)O(1) extra space with two pointers.

Examples

EXAMPLE WALKTHROUGHclassic map

A guided view of the published example, not a trace of your code.

INPUT[[0,1,0,2,1,0,1,3,2,1,2,1]]
TASKrainwater_between_bars()
EXPECTED OUTPUT6

Start with the input values shown in this example.

Example 1 of 3

Input: heights = [0,1,0,2,1,0,1,3,2,1,2,1]

Output: 6

Explanation: classic map

Input: heights = [4,2,0,3,2,5]

Output: 9

Explanation: deep basin

Input: heights = []

Output: 0

Explanation: empty

Hint 1

Water above a bar depends on the tallest bar to its left and to its right.

Hint 2

With two pointers, the side with the lower running maximum is the one you can settle.

Topics

DSATwo PointersPython