Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Trapping Rain Water

Arrays & Two-Pointershard

Given `height`, an array of non-negative bar heights each 1 unit wide, implement `trap(height)` returning how many units of water are trapped after raining.

Examples

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Input: [4,2,0,3,2,5]
Output: 9

Sample tests

Input: trap([0,1,0,2,1,0,1,3,2,1,2,1])
Output: 6
Input: trap([4,2,0,3,2,5])
Output: 9

+ 2 hidden tests run on Submit.

Hints

Common pitfalls
  • Recomputing left/right maxima inside a loop gives an O(n^2) solution that may time out on large inputs.

Learning resources

  • Wikipedia: Array data structure
Approach & explanation (try first)

Move two pointers inward from both ends. The side with the smaller current height is the limiting wall, so the water over that bar equals its running max minus its own height. This computes the answer in one O(n) pass with O(1) space.

Loading...
⌘/Ctrl + Enter

Run your code to see results.