You get a list of wall heights, height. Wall i stands at position i on the ground and is height[i] tall.
Choose any two walls. Together with the ground they form an open tank, and the water level can rise only as high as the shorter of the two walls. The amount of water is that level times the distance between the walls. Return the largest amount any pair can hold. Walls between the two do not block anything, and you cannot tilt the tank.
Example 1
Input: height = [3, 7, 2, 6, 4, 5] Output: 20 Why: walls 7 and 5 are 4 apart; the water is 5 deep, 5 × 4 = 20
2 more examples and the constraints
Example 2
Input: height = [4, 4] Output: 4 Why: the only pair, 1 apart and 4 deep
Example 3
Input: height = [1, 0, 0, 9, 0, 1] Output: 5 Why: the two end walls are short but 5 apart: 1 × 5 = 5
Constraints
- 2 ≤ length of height ≤ 100,000
- 0 ≤ height[i] ≤ 10,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Brute forceO(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 100,000 walls | Verdict |
|---|---|---|---|
| Brute force | O(n²) | Mention it, then move on | |
| Two pointers | O(n) | Best; one pass, no extra memory |
n = how many walls there are.
Edge cases to test
- Only two walls. [4, 4] has one pair, so the answer is 4 × 1 = 4.
- A wall of height 0. Any pair that uses it holds nothing. [0, 10000] gives 0.
- Short walls far apart. [1, 0, 0, 9, 0, 1] gives 5 from the two ends, not anything with the 9.
- Equal heights. Moving either pointer is fine; the code moves
hion a tie.
Common mistakes
- Moving the taller wall. That keeps the short wall, which can only lose width, and it skips the real answer.
- Using the taller wall for the water level instead of the shorter one.
- Using k − i + 1 for the width. The distance between positions 1 and 5 is 4.
How to talk through it
- 1Clarify. Do the walls in between matter? Can a height be 0? Do I return the amount or the pair?
- 2Give the brute force. Measure every pair; say it is O(n²) and too slow for 100,000 walls.
- 3Find what to throw away. The shorter of the two end walls cannot beat the current tank with any narrower partner.
- 4Code the two pointers. Measure, update the best, move the shorter side. Say why a tie is safe.
- 5Test out loud. Run the two-wall case and the case with a zero wall before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?