Trapping Rain Water

Hard#42towards each other

You get the heights of bars that stand side by side, each one unit wide. Rain falls on them: how much water stays between the bars? Our example: heights [3, 0, 1, 4, 0, 2, 1, 3] — 11 units of water.

input
height: the heights of bars one unit wide, standing side by side.
returns
How much water stays between the bars after rain: above each bar, up to the lower of the tallest bars on its left and on its right.
constraints
  • 1 ≤ height.length ≤ 3000
  • 0 ≤ height[i] ≤ 10⁵
our 13 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} height
 * @return {number}
 */
function trap(height) {

}
Ctrl ↵
format
reset

saved in this browser

13 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more two pointers problems

Pattern “Two pointers” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.