Given a list of non-negative integers representing the height of vertical bars in an elevation map (each bar has width 1), compute the total amount of water that can be trapped between the bars after it rains. Water accumulates between taller bars and flows off the ends.
Examples:
Input: heights = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
Output: 6
Explanation: Water trapped at positions: index 2 (1 unit), index 4 (1 unit), index 5 (2 units), index 6 (1 unit), index 9 (1 unit) = 6 total
Input: heights = [4, 2, 0, 3, 2, 5]
Output: 9
Explanation: Total water trapped in the elevation map is 9 units
Input: heights = [1, 0, 1]
Output: 1
Explanation: One unit of water trapped in the valley between the two bars of height 1
Input: heights = [3, 0, 2, 0, 4]
Output: 7
Explanation: 3 units trapped in first valley, 1 unit partially, 3 units in second valley
Input: heights = [1, 2, 3, 4, 5]
Output: 0
Explanation: Monotonically increasing heights, no water can be trapped
Apex Code Editor
Welcome to Lightning Challenge!
Create an Account
Sign up to track your progress, earn points, and compete with others. Your solutions will be saved automatically.
Create accountHow It Works
- • Write your solution in the code editor
- • Connect your Salesforce org to test
- • Submit to check if your solution passes
- • Use hints if you get stuck
Contest Alert
🏆 #CodeEveryDay June 2026
Contest runs June 1 - 30. Complete challenges to climb the leaderboard!
Only the 30 daily challenges shown during this contest count toward points. Earlier dailies don't carry over.