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.

The elevation map is represented by an array height where height[i] is the height of the bar at position i.

Example: For heights [0,1,0,2,1,0,1,3,2,1,2,1], the trapped water would be 6 units.

Input & Output

Example 1 — Classic Case
$ Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
💡 Note: Water gets trapped in valleys: at indices 2 (1 unit), 5 (2 units), 6 (1 unit), 9 (1 unit), 10 (1 unit) for total of 6 units
Example 2 — Simple Valley
$ Input: height = [3,0,2,0,4]
Output: 7
💡 Note: Water gets trapped in valleys: at position 1 (3 units), position 2 (1 unit), and position 3 (3 units), for a total of 7 units
Example 3 — No Water
$ Input: height = [3,2,1]
Output: 0
💡 Note: Decreasing heights cannot trap any water - water would flow off the right side

Constraints

  • n == height.length
  • 1 ≤ n ≤ 2 × 104
  • 0 ≤ height[i] ≤ 3 × 104

Visualization

Tap to expand
Trapping Rain Water INPUT 0 1 2 3 Elevation Water height[] = [0,1,0,2,1,0,1,3,2,1,2,1] n = 12 bars width = 1 each Find trapped water ALGORITHM STEPS 1 Two Pointer Setup left=0, right=n-1 leftMax=0, rightMax=0 2 Compare Heights If h[left] < h[right]: process left side 3 Calculate Water water += max - h[i] Update max if needed 4 Move Pointers left++ or right-- Until left meets right Two Pointer Approach L ... R O(n) time, O(1) space FINAL RESULT 1 1 2 1 1 Water Trapped: Index 2: 1 unit Index 4: 1 unit Index 5: 2 units Index 6: 1 unit Index 9: 1 unit Total: 1+1+2+1+1 = 6 Output: 6 Key Insight: Water at any position = min(leftMax, rightMax) - height[i]. The two-pointer technique works because we always process from the side with smaller max height. This guarantees the water level is bounded by that smaller max, achieving O(n) time with O(1) space. TutorialsPoint - Trapping Rain Water | Two Pointer Optimal Approach
Asked in
Amazon 85 Google 72 Facebook 68 Microsoft 58 Apple 45
1.9M Views
Very High Frequency
~25 min Avg. Time
25.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen