1. Problem Statement (Simple Explanation):
You’re given an array height of length n:
Each height[i] is a non-negative integer representing a bar’s height.
The width of each bar is 1.
Imagine this array as an elevation map. You must compute how many units of water can be trapped between the bars after raining.
2. Examples:
Example 1:
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Visualization shows 6 units of trapped water.
Output: 6
Example 2:
Input: height = [4,2,0,3,2,5]
Trapped water:
Between 4 and 3: 2 units above index 1, 4 units above index 2 (total 6).
Between 3 and 5: 1 unit above index 4, 2 units above index 3 (total 3).
Total: 6 + 3 = 9.
Output: 9
3. Intuition:
At any position i, the water height is:
water_at_i = min(max_left[i], max_right[i]) - height[i]
where:
max_left[i] = max height on the left of i including i.
max_right[i] = max height on the right of i including i.
Water can only be trapped where both sides have taller bars than the current height.
Brute force would compute max_left and max_right for each i in O(n²).
We can do it in O(n) time, O(1) extra space with the two-pointer technique.
4. Approach – Two Pointers (O(n) Time, O(1) Space):
Key Idea:
Use two pointers:
left starting at 0
right starting at n-1
Maintain:
leftMax = highest bar seen so far from the left
rightMax = highest bar seen so far from the right
At each step:
Compare height[left] and height[right]:
If height[left] < height[right]:
Then leftMax is the limiting factor for left side.
If height[left] >= leftMax, update leftMax.
Else water trapped at left = leftMax - height[left].
Move left++.
Else:
Symmetric logic for right using rightMax.
Move right--.
Why this works:
If height[left] < height[right], then for any i at left, the right side is guaranteed to have a bar >= height[right] ≥ height[left], so the water level is determined by leftMax.
Similarly for the other side.
Algorithm (Step-by-Step):
Initialize:
left = 0
right = n - 1
leftMax = 0
rightMax = 0
water = 0
While left < right:
If height[left] < height[right]:
If height[left] >= leftMax:
leftMax = height[left]
Else:
water += leftMax - height[left]
left++
Else:
If height[right] >= rightMax:
rightMax = height[right]
Else:
water += rightMax - height[right]
right--
Return water.
Pseudo-code:
Time: O(n) (each index visited at most once).
Space: O(1) extra.
5. Java code:
6. C code:
8. Python code:
9. JavaScript code:






Comments
Post a Comment