Trapping Rain Water
How much water an elevation map holds after rain.
Problem
Given n non-negative integers representing an elevation map where each bar is 1 wide, compute how much water it can trap after raining.
- Water above a bar is limited by the shorter of the tallest walls on its left and right.
- Bars at the edges cannot hold water.
Examples
Approach
- At any index, water = min(leftMax, rightMax) - height[i]: the shorter boundary sets the level.
- Start one position at each end and keep track of the tallest wall seen so far on each side.
- If height[left] < height[right], the left side is the limiting one: a taller wall is known to exist on the right, so water at left depends only on leftMax. Update leftMax or add leftMax - height[left], then move left inward.
- Otherwise do the same from the right. Every bar is visited once, with no extra arrays.
Brute force: For each bar, scan left and right for the tallest walls - a loop inside a loop. Working out all the left and right maximums first gets you down to one pass, but costs two extra arrays.
Common mistakes
- Moving the taller side instead of the shorter one breaks the thing that makes this work: you only know the other side is at least as tall when you move the shorter one.
- Adding water before updating the max for a new tallest bar counts negative water.
Step through it
Pick an input and play the algorithm step by step. The highlighted line in the code follows each step, and you can edit the code to experiment.
Solution
The same approach in JavaScript, Python, and Java. Each is a complete program that prints the examples above - JavaScript runs here, so edit it and try your own input.
JavaScript solution
Output
Run code to see output...
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...
AI
System Design
Backend
- GraphQL8 modules · 69 lessons planned
- Core Python13 modules · 75 lessons planned
- FastAPI5 sections · 20 lessons
- Node.js14 modules · 206 lessons planned
- Node.js Performance7 chapters · 36 topics
- Event Loop Lifecycle6 phases · 3 scenarios
- Docker & Containerization11 modules · 144 lessons planned
- AWS for Developers14 modules · 219 lessons planned
- CI/CD & DevOps Automation10 modules · 134 lessons planned