Skip to the solution
MediumDSA6 min read

Trapping Rain Water with two pointers — why does leftMax/rightMax work in O(1) space?

372 views

The problem

Question presented to candidate: "You wrote the two-pointer solution to Trapping Rain Water. Convince me it is correct: the left pointer has not seen most of the right side, so why is leftMax enough to decide the water there? Walk me through it with Python code."

What a strong answer should cover:

  • The per-bar formula: water = min(max to the left, max to the right) - h[i], and that the left pointer knows its left max exactly.
  • The key bound: the right max seen so far is a lower bound on the true right wall of L, because unseen bars can only make it taller.
  • The invariant: if leftMax <= rightMax, then level(L) = leftMax exactly, so L can be settled; otherwise settle R symmetrically.
  • Why comparing heights (h[L] < h[R]) is also correct, and what goes wrong if you move the taller side.
  • Complexity: each step settles one bar, so O(n) time; four variables, so O(1) extra space.
  • Python details: Python ints cannot overflow, so the proof is the only thing to get right; tuple assignment like side, i, used = "L", lo, left_max keeps the branch short, and a randomised test against a brute force is a few lines with plain lists.

Code / implementation expected: Optional — the two-pointer loop in Python 3 plus a short argument; a brute-force cross-check is a strong bonus.

  • two pointers
  • array
  • Meta

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonTraced two-pointer run: level used vs true level for every bar
Python3,000 random arrays: two correct rules and one wrong rule vs brute force

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 96 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you solve the coin change problem?

Continue