This problem follows the Two Pointers / Prefix Max pattern, commonly found in the Two Pointers category. Recognizing this pattern is key to solving it efficiently in an interview setting.
Track maxLeft and maxRight. Water at each position = min(maxL, maxR) - height.
Water at any position depends on the minimum of the tallest bars on its left and right. By processing from the shorter side, you always know one bound is satisfied.
left = 0, right = n - 1
maxLeft = 0, maxRight = 0, result = 0
while left < right:
if height[left] < height[right]:
maxLeft = max(maxLeft, height[left])
result += maxLeft - height[left]
left++
else:
maxRight = max(maxRight, height[right])
result += maxRight - height[right]
right--
return resultPractice Trapping Rain Water and similar Two Pointers problems with flashcards. Build pattern recognition through active recall.
Practice this problem