Skip to the solution
HardDSA7 min read

How do you solve the trapping rain water problem?

818 views

The problem

Question presented to candidate: "You are given a list of non-negative integers where each number is the height of a bar of width 1. Write a Python function that computes how many units of rain water are trapped between the bars."

What a strong answer should cover:

  • The per-bar formula: water[i] = min(max height to the left, max height to the right) - h[i], with both maxima including i.
  • A progression of solutions: brute force O(nยฒ); prefix/suffix max arrays O(n) time and O(n) space; monotonic stack; two pointers O(n) time and O(1) space.
  • Why two pointers is correct: settle the lower side, because the other side already has a wall at least that tall.
  • Edge cases: fewer than 3 bars, monotonic arrays, flat arrays.
  • Python details: itertools.accumulate(h, max) builds the prefix-max array in one line, slicing like max(h[:i + 1]) hides an O(n) copy, and a negative index such as h[-1] silently reads the last bar instead of failing.

Clarifying questions expected:

  • Can heights be negative, and are bars all width 1?
  • Is O(n) extra space acceptable?

Code / implementation expected: Yes โ€” trap(height: list[int]) -> int with two pointers, in Python 3.

  • arrays
  • two-pointers

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

7 min read ยท 11 sections

Python code

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

PythonTwo pointers on nine height maps
PythonPer-bar water, four methods compared, brute force vs two pointers work

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 138 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 nextHard

How do you solve the word ladder problem?

Continue