42. Trapping Rain Water
Asked at 70Amazon88Bloomberg80Microsoft78Google74Meta64Apple63Goldman Sachs100Rakuten100Snowflake86Media.net76Nvidia71Infosys66tcs57ThousandEyes100Zenefits100X97Zoho94Walmart Labs93Samsung92Urban Company89ServiceNow88Tekion88Hive87Wix87Sigmoid87PornHub87Squarepoint Capital85Zopsmart84IMC83Moloco81TikTok79Tesla78Qualcomm76Visa75Adobe74Zeta74Airbnb73HashedIn72Nutanix71Paytm71Navi70HCL69Mindtickle69Swiggy69Flipkart68Publicis Sapient68BitGo68Huawei67Intel66CrowdStrike65Docusign64PhonePe64EPAM Systems60DE Shaw58Yandex57Dell57Citadel57Sprinklr54Accenture54Oracle52Capgemini52Grammarly51Roblox51ByteDance50OpenAI49IBM44Intuit43PayPal42Salesforce41Uber35
Problem
height is an elevation map of bars, each 1 unit wide. Return how many units of rain water it traps after raining.
Example: [0,1,0,2,1,0,1,3,2,1,2,1] → 6
Constraints: n ≤ 2·10⁴.
Water at i = min(maxLeft, maxRight) - h[i]. With two pointers, the side with the smaller running max is the bottleneck, so its water is already determined: process that side and move inward.
█
█ ~ ~ ~ █ █ ~ █
█ ~ █ █ ~ █ █ █ █ █ █ (~ = trapped water)
height 0 1 0 2 1 0 1 3 2 1 2 1
water . . 1 . 1 2 1 . . 1 . . total = 6
Complexity: O(n) time, O(1) space.
class Solution:
def trap(self, height: List[int]) -> int:
l, r = 0, len(height) - 1
lmax = rmax = water = 0
while l < r:
if height[l] < height[r]:
lmax = max(lmax, height[l])
water += lmax - height[l]
l += 1
else:
rmax = max(rmax, height[r])
water += rmax - height[r]
r -= 1
return water
assert Solution().trap([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]) == 6
assert Solution().trap([4, 2, 0, 3, 2, 5]) == 9
class Solution {
public int trap(int[] height) {
int l = 0, r = height.length - 1, lmax = 0, rmax = 0, water = 0;
while (l < r) {
if (height[l] < height[r]) {
lmax = Math.max(lmax, height[l]);
water += lmax - height[l++];
} else {
rmax = Math.max(rmax, height[r]);
water += rmax - height[r--];
}
}
return water;
}
}
func trap(height []int) int {
l, r := 0, len(height)-1
lmax, rmax, water := 0, 0, 0
for l < r {
if height[l] < height[r] { // the left side is bounded by lmax
lmax = max(lmax, height[l])
water += lmax - height[l]
l++
} else {
rmax = max(rmax, height[r])
water += rmax - height[r]
r--
}
}
return water
}