Container With Most Water
MediumNeetCode 150Top Interview 150 Two PointersFlipkarttcsAmazonBloombergPubMaticWorkdayProblem
The array height describes vertical walls standing on a line: wall i has height
height[i] and sits at position i.
Pick any two walls. Together with the ground they form a container whose width is the distance between the walls and whose water level is the shorter of the two. Return the largest amount of water (width × level) any pair can hold. The container cannot be tilted.
Constraints
- 2 ≤ height.length ≤ 10⁵
- 0 ≤ height[i] ≤ 10⁴
Examples: pick one to animate
Solutions
Time: Each step moves one pointer inward, so the loop runs at most n - 1 times.
Space: Only the two indexes, the current area and the best area are stored.
Start with the widest container. Its level is limited by the shorter wall, so keeping that wall and shrinking the width can only make things worse. Move the pointer on the shorter wall inward in the hope of finding a taller one, and track the best area seen.