Skip to content
Preptima
mediumCodingMidSeniorStaff

Given the heights of a row of bars, work out how much rainwater is trapped between them. Do it in constant extra space.

5 min readUpdated 2026-08-15Target archetype: Big Tech, Enterprise Captive, Product Startup

Answer

Short answer

Water above a bar is the smaller of the tallest bar to its left and the tallest to its right, minus its own height. Walking inwards from both ends and always advancing the shorter side works because that side's running maximum is the binding constraint there, whatever heights remain unseen in the middle.

Was this answer helpful?

Likely follow-ups

  • Give me the same answer with prefix and suffix maximum arrays first. What does the two-pointer version save?
  • Solve it with a monotonic stack instead. What does the stack hold, and when do you pop?
  • The bars form a two-dimensional grid of heights. Does either technique survive?
  • Return the water column by column rather than the total. Does anything have to change?

Related questions