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!
How 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 September 2026 (Sep 16–30)Sponsored by FLXBL
Contest runs September 16 - 30. Complete challenges to climb the leaderboard!
Prizes 1 & 2: Salesforce certification exam voucher — won by random drawing, where every point is a ticket. see all prizes
Only the 15 daily challenges shown during this contest count toward points. Earlier dailies don't carry over.