Optimal Python Solution for Trapping Rain Water (Interview Script)
2025-09-26
The Logic
- The bottleneck is avoiding nested scans for left and right maximums at every index.
- Use a two-pointer technique to maintain left and right boundaries in a single pass.
- Water trapped at an index is determined by the minimum of the two boundaries minus the current height.
Implementation / Diagram
Key Invariant
At every step, the side with the smaller boundary determines the trapped water because it is the limiting factor.
def trap(height):
left, right = 0, len(height) - 1
left_max, right_max = 0, 0
water = 0
while left < right:
if height[left] < height[right]:
left_max = max(left_max, height[left])
water += left_max - height[left]
left += 1
else:
right_max = max(right_max, height[right])
water += right_max - height[right]
right -= 1
return water
⏵ The honest play
You've read the playbook.
Now make sure you pass the live OA.
Knowing the patterns isn't the same as solving them under a timer with a proctor watching. StealthCoder is the hedge: an AI overlay invisible during screen share. It reads the problem on screen and surfaces a working solution in under 2 seconds. Made for the engineer who has done the work but might still blank with a webcam pointed at him. Works on HackerRank, CodeSignal, CoderPad, and Karat.
Hedge your live OA
Invisible during screen share