two-pointers · Problem 4 of 4

Trapping Rain Water

hard
Amazon logoAmazon
Google logoGoogle
Meta logoMeta
Goldman Sachs logoGoldman Sachs
Apple logoApple

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

trap([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]) -> 6
trap([4, 2, 0, 3, 2, 5])                   -> 9
trap([])                                   -> 0

Your solution

Runs your code and animates it without grading anything. Change the input to see what it does on a case the tests do not cover.

Running is free — Submit is what records it. Or press ⌘↩

Tests

5 cases, 1 hidden
calltypeexpectedresult
trap([0,1,0,2,1,0,1,3,2,1,2,1])standard multi-peak elevation6
trap([4,2,0,3,2,5])valley elevation9
trap([1,2,3,4,5])strictly ascending (no trap)0
trap([])empty elevation0
withheldhiddenwithheld

Hidden cases run too — their inputs aren't listed here, so aim for a general solution rather than one fitted to the cases above.

Complexity

target time
O(n)
target space
O(1)

Optimal two-pointer approach requiring a single pass and constant extra space.

Hints

Stuck? Hints open one at a time, each giving a little more away.

3 hints left