Two pointers on unsorted data: Trapping Rain Water, on compiled LeetCode lists for OpenAI and Airbnb
Trapping Rain Water is on the compiled LeetCode company lists for OpenAI and Airbnb (2 sources). Given bar heights, how much water sits between them after rain? For the heights [3, 0, 2, 0, 4, 1, 0, 2]:
Predict
Bar heights 3, 0, 2, 0, 4, 1, 0, 2. How much water sits between them after rain?
Heights 3, 0, 2, 0, 4, 1, 0, 2
01234567
water at each spot
03130120
a barwater
Total water: 10.
The water above a bar is the lower of the tallest bar to its left and the tallest to its right, minus its own height.
Put a pointer at each end. Whichever side has the lower bar is settled. The other side already has something at least that tall, so the water there depends only on the tallest bar seen from its own side.
def trapped(heights): lo, hi = 0, len(heights) - 1 left_max = right_max = water = 0 while lo < hi: if heights[lo] < heights[hi]: left_max = max(left_max, heights[lo]) water += left_max - heights[lo] lo += 1 else: right_max = max(right_max, heights[hi]) water += right_max - heights[hi] hi -= 1 return waterprint(trapped([3, 0, 2, 0, 4, 1, 0, 2]))
10
It's the same rule as at the start of the lesson: each step settles one end for good.
Write water_at: the water above each spot of heights, from the tallest bar on each side. It's the rule that makes the two pointers safe.
Pick an answer above to see the rest
Instructions
1
Write water_at(heights): for each spot, the lower of the tallest bar from the start up to it and the tallest from it to the end, minus its own height.
2
Build the tallest-so-far from the left in one pass and from the right in another, both counting the spot itself.