You get an array height of non-negative integers. Each number is the height of a bar one unit wide, and the bars stand side by side with no gaps.
Rain falls on the bars and fills every dip it can without spilling over the sides. Return how many units of water stay on top of the bars.
Example 1
Input: height = [3, 0, 2, 0, 4] Output: 7 Why: the walls 3 and 4 hold water up to 3: 3 + 1 + 3 above the inner bars
2 more examples and the constraints
Example 2
Input: height = [1, 0, 2, 1, 0, 1, 3] Output: 5 Why: 1 unit at index 1, then 1 + 2 + 1 between the 2 and the 3
Example 3
Input: height = [5, 4, 1] Output: 0 Why: the bars only go down, so every drop runs off the right edge
Constraints
- 1 ≤ length of height ≤ 20,000
- 0 ≤ height[i] ≤ 100,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Scan both ways from every barO(n²)
- Tallest-so-far arraysO(n)
- Two pointersO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 20,000 bars | Verdict |
|---|---|---|---|
| Scan both ways from every bar | O(n²) | Mention it, then move on | |
| Tallest-so-far arrays | O(n) | Passes; uses two extra arrays | |
| Two pointers | O(n) | Best; O(1) extra space |
n = number of bars.
Edge cases to test
- One or two bars. There is no dip with walls on both sides, so the answer is 0.
- Only rising or only falling. [1, 2, 3, 4] or [5, 4, 1]: the water runs off one edge, so 0.
- Walls of different heights. [2, 0, 6] holds 2, not 6: the lower wall sets the level.
- Large totals. 20,000 bars of height up to 100,000 can hold almost 2 billion units, which still fits in a 32-bit int.
Common mistakes
- Using the taller wall instead of the shorter one, which overfills every dip.
- Leaving the bar itself out of its own maxima, which can make the water negative.
- Moving the pointer on the taller side, where the cap is not known yet.
How to talk through it
- 1Clarify. Are all heights non-negative and every bar one unit wide? Can the array have a single bar?
- 2Find the formula. Water at i is min(tallest on the left, tallest on the right) minus height[i].
- 3Give the brute force. Scan both ways from each bar; say it is O(n²) and that the scans repeat.
- 4Drop the arrays. Precompute both maxima in O(n), then explain why two pointers only need the lower side.
- 5Test out loud. Run [3, 0, 2, 0, 4] and a falling array like [5, 4, 1].
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?