Trapping Rain Water
How the interviewer asks it
“Given a list of bar heights, compute how much water is trapped between the bars after it rains.”
0 1 0 2 1 0 1 3 2 1 2 1
6
In the practice room your code reads the input from standard input, and Run checks it against tests like this one. Try it now in your browser, in Python or JavaScript.
Typed drills are free and unlimited: the AI scores your answer against the outline below.
What the interviewer is looking for
- You explain the core idea: water above a bar is min(highest to the left, highest to the right) minus its height.
- You go from the O(n) space prefix and suffix arrays to two pointers in O(1) space.
- You can justify why moving the pointer with the smaller max is safe, not just recite it.
- Edge cases: fewer than three bars, flat ground, strictly rising heights.
How to structure your answer
- 01
Water per bar
State the formula for one bar and check it on a small example.
- 02
Prefix and suffix maxima
Precompute the highest bar to the left and right of each position, then sum. O(n) time, O(n) space.
- 03
Two pointers
Move left and right inward, tracking leftMax and rightMax. Always advance the side with the smaller max, because that side's water level is already decided.
- 04
Test
[0,1,0,2,1,0,1,3,2,1,2,1] traps 6.
- 05
Complexity
O(n) time and O(1) extra space.
Best answers from candidates
No candidate answers yet. Type yours, and if it scores 6 or more you can show it here without your name.
Answers are shared by candidates, without names, after a privacy check. Add yours
Common mistakes
- Counting water at the edges, where it would run off.
- Moving the wrong pointer and over-counting.
- Writing the two-pointer version from memory without being able to explain it, then getting stuck on a follow-up.
Follow-up questions to expect
- Solve it with a monotonic stack and compare the approaches.
- The heights are a 2D map. How much water does it hold?
Now answer it out loud
Max will ask you this exact question, listen to your answer, push on the weak spots with follow-ups like the ones above, and score you when you finish.
Practice with MaxFree: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.
More coding interview questions
Preparing for this round? Read how to prepare for a coding interview: a four-week DSA plan.