Trapping Rain Water
LeetCode 42 · ಕಠಿಣ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
water[i] = min(maxLeft, maxRight) − height[i].
ನಾನು Trapping Rain Water (LeetCode 42) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Two Pointers ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಕಠಿಣ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Water above a bar is limited by the shorter of the tallest bar to its left and the tallest to its right. Precomputing both maxima works; the two-pointer version processes the side with the lower wall, because that side's bound is already known.
Approach
- 1
Prefix maxima from the left and suffix maxima from the right.
- 2
Sum min(left, right) − height over all bars.
- 3
Two pointers: the lower side decides — add left_max − height or update the max, then move inward.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ · ಮೊದಲ ಆಲೋಚನೆಯಿಂದ ಅಂತಿಮ ಪರಿಹಾರದವರೆಗೆ
Two helper arrays.
Resolve the lower side first.
Prefix / suffix maximaPythonO(n) time · O(n) space
class Solution:
def trap(self, height: List[int]) -> int:
n = len(height)
left_arr =[0]*n
right_arr =[0]*n
left_max=float("-inf")
right_max=float("-inf")
for i in range(n):
left_max=max(left_max,height[i])
left_arr[i]=left_max
for j in range(n-1,-1,-1):
right_max=max(right_max,height[j])
right_arr[j]=right_max
water =0
for i in range(n):
water+=min(left_arr[i],right_arr[i])-height[i]
return waterTwo pointersPythonO(n) time · O(1) space
class Solution:
def trap(self, height: List[int]) -> int:
n = len(height)
left=0
right=n-1
water = 0
left_max = float("-inf")
right_max = float("-inf")
while left<right:
if height[left]<height[right]:
if height[left]<left_max:
water+=left_max-height[left]
else:
left_max=max(left_max,height[left])
left+=1
else:
if height[right]<right_max:
water+=right_max-height[right]
else:
right_max=max(right_max,height[right])
right-=1
return waterTrapping Rain Water — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Trapping Rain Water ಹಿಂದಿನ intuition ಏನು?
Water above a bar is limited by the shorter of the tallest bar to its left and the tallest to its right. Precomputing both maxima works; the two-pointer version processes the side with the lower wall, because that side's bound is already known.
Trapping Rain Water (LeetCode 42) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Prefix maxima from the left and suffix maxima from the right. 2. Sum min(left, right) − height over all bars. 3. Two pointers: the lower side decides — add left_max − height or update the max, then move inward.
Trapping Rain Water ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(n). Space: O(1) with two pointers. (Accepted approach: Two pointers.)
Trapping Rain Water ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
The pointer on the lower side is safe to resolve; the other side's max can only be higher.
Trapping Rain Water ಅನ್ನು ಪರಿಹರಿಸಲು ಒಂದಕ್ಕಿಂತ ಹೆಚ್ಚು ಮಾರ್ಗಗಳಿವೆಯೇ?
Prefix / suffix maxima (O(n) time · O(n) space): Two helper arrays. Two pointers (O(n) time · O(1) space): Resolve the lower side first.