Problem
Givenn non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Examples
Constraints
n == height.length1 <= n <= 2 * 10^40 <= height[i] <= 10^5
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 42 with 15 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 42 # by problem number
lcpy gen -s trapping_rain_water # by problem name
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.
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Input: height = [4,2,0,3,2,5]
Output: 9
n == height.length1 <= n <= 2 * 10^40 <= height[i] <= 10^5class Solution:
# Time: O(n)
# Space: O(1)
def trap(self, height: list[int]) -> int:
if not height:
return 0
left, right = 0, len(height) - 1
left_max = right_max = water = 0
while left < right:
if height[left] < height[right]:
if height[left] >= left_max:
left_max = height[left]
else:
water += left_max - height[left]
left += 1
else:
if height[right] >= right_max:
right_max = height[right]
else:
water += right_max - height[right]
right -= 1
return water
| Time | Space |
|---|---|
| O(n) | O(1) |