TRT
Sign in
hardAdvancedLeetCode#two pointers#running maximum

Trapping rain water

Compute the water trapped between bars after rain, with two pointers and running maximums from each side.

The Runtime Theory Team1 min read
Taught inTwo pointersPro — members onlyOn a sorted array, two indexes moving toward each other can find pairs with a given sum in one pass, because every move rules out a whole row of candidate pairs. The same argument powers three-sum, container problems and trapping rain water.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inheight = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]

out6

inheight = [4, 2, 0, 3, 2, 5]

out9

inheight = [2, 0, 2]

out2

Given bar heights of width 1, return how much water they trap after raining.

Before you code

Water above a bar is min(tallest on the left, tallest on the right) - height. Precomputing both maximums is O(n) space; two pointers avoid it.

Hints

  1. Keep left_max and right_max as the pointers move inward.
  2. If left_max <= right_max, the left bar's water is decided by left_max: add it and move left. Otherwise do the same on the right.
  3. Alternative: a monotonic stack that fills water layer by layer.

Production & complexity notes

When solving Trapping rain water on LeetCode (hard), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Two pointers to reinforce the underlying pattern.

What it practices

Moving the side whose bound is already known, from Two pointers.

Not started

Sign in to save your learning progress.

Sign in to save