Problem Statement
(Source) Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1]
, return 6
.
The above elevation map 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. Thanks Marcos for contributing this image!
Tags: Array
, Stack
, Two Pointers
.
Solution - Two Pointers
The idea is very simple. Begin scan from beginning and end of array. Compare value of left and right pointer, hold the greater one and move the other to inner array. Compute passed area when pointer gets inner. (mo10)
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
if not height or len(height) < 3:
return 0
res = 0
n = len(height)
left, right = 0, n - 1
lower = min(height[left], height[right])
while left < right:
if height[left] < height[right]:
lower = max(lower, height[left])
res += (lower - height[left])
left += 1
else:
lower = max(lower, height[right])
res += (lower - height[right])
right -= 1
return res
Complexity Analysis:
- Time Complexity: O(n) .
- Space Complexity: O(1) .