Algorithm-Day07-Trapping-Rain-Water-lc-42
π§© Problem Description
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] |
π‘ Brute Force (Too Slow)
For each index i
, calculate:
- The max height to the left
- The max height to the right
- Water at
i
=min(leftMax, rightMax) - height[i]
But this takes O(nΒ²) time.
π‘ Optimized Approach 1: Precomputed Arrays (Prefix Max)
We use two arrays:
leftMax[i]
: max height to the left (includingi
)rightMax[i]
: max height to the right (includingi
)
Then compute trapped water at each index.
π’ Java Code (Prefix Max)
1 | class Solution { |
β± Complexity
- Time: O(n)
- Space: O(n)
π‘ Optimized Approach 2: Two Pointers (Space O(1))
We use two pointers (left
, right
) and two variables (leftMax
, rightMax
) to simulate the process:
- Always move the pointer with lower height
- Update
leftMax
orrightMax
and calculate trapped water accordingly
π’ Java Code (Two Pointers)
1 | class Solution { |
β± Complexity
- Time: O(n)
- Space: O(1)
βοΈ Summary
- This is a classic two-pointer technique problem with a space optimization.
- The intuition is that water is bounded by the shorter side.
- First solve using prefix arrays to build understanding, then optimize to two pointers.