def test(fn):
= [0,1,0,2,1,0,1,3,2,1,2,1]
height = 6
actual assert actual == fn(height)
= [4,2,0,3,2,5]
height = 9
actual assert actual == fn(height)
Problem Source: Leetcode
Problem Description
Given n
non-negative integers representing an elevation map where the width of each bar is 1
, compute how much water it can trap after raining.
tests
Solution
- Time Complexity:
O(n)
- Space Complexity:
O(1)
from typing import List
def trap(height: List[int]) -> int:
= 0, len(height)-1 # start on both ends
l,r = 0
vol = height[l], height[r]
lm, rm
while l < r: # stop when pointers meet
# The side with largest max determines the bin depth
if lm < rm:
+= 1
l = max(height[l], lm)
lm += lm - height[l]
vol else:
-= 1
r = max(height[r], rm)
rm += rm - height[r]
vol return vol
test(trap)