Skip to content

Latest commit

 

History

History
53 lines (38 loc) · 1.58 KB

index.md

File metadata and controls

53 lines (38 loc) · 1.58 KB

42. Trapping Rain Water

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.

Example 1:

Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.

Example 2:

Input: height = [4,2,0,3,2,5] Output: 9

Constraints

n == height.length 1 <= n <= 2 * 10^4 0 <= height[i] <= 10^5

Solution

class Solution:
    def trap(self, height: List[int]) -> int:
        left, right = 0, len(height) - 1
        left_max, right_max = 0, 0
        trapped_water = 0

        while left < right:
            if height[left] < height[right]:
                if height[left] >= left_max:
                    left_max = height[left]
                else:
                    trapped_water += left_max - height[left]
                left += 1
            else:
                if height[right] >= right_max:
                    right_max = height[right]
                else:
                    trapped_water += right_max - height[right]
                right -= 1

        return trapped_water

Thoughts

Strightforward no trick question, just had to cover all edge case in code. But took a lot longer than I thought it would take.

The time complexity of this solution is O(n), where n is the number of elements in the input array, because each element is visited at most once. The space complexity is O(1), as no additional data structures are used.