#42

Trapping Rain Water

Hard Opposite ends with max heights

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Bars of given heights stand side by side. Return how much rain water is trapped between them.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: how much rain sits between the bars?

Why this works: water above a bar = min(tallest on left, tallest on right) - bar. With two pointers, the side with the smaller max is already decided, so process that side.

Example: [4, 2, 0, 3, 2, 5]

leftMax 4 < rightMax 5 → water at 2: 2, at 0: 4, at 3: 1, at 2: 2total 9

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

For each bar, scanning left and right for the maximum — O(n²).