Container With Most Water – Solution & Complexity
Watch: Container With Most Water with two pointers
Start with the widest container: one pointer at each end. The area is limited by the shorter wall, so moving the taller one can never help. Always move the shorter pointer inward and track the best area. O(n) time, O(1) space.
Solution Walkthrough
Step 1: Understand the Area Formula
- Choose two vertical lines at indices
leftandright. - The width is
right - left. - The height of the water is limited by the shorter line.
- Area is
(right - left) * min(height[left], height[right]).
- Choose two vertical lines at indices
Step 2: Brute Force Idea
- Check every pair of lines and compute its area.
- Keep the maximum area found.
- This is simple but O(n²), which is too slow for large arrays.
Step 3: Use Two Pointers
- Start with the widest possible container: first and last lines.
- Compute the area, then move one pointer inward.
- Moving the taller line cannot help because the shorter line still limits the height while width shrinks.
- Therefore, always move the pointer at the shorter line.
Step 4: Update the Best Area While Moving
- At each step, calculate the current area.
- Update
bestif this area is larger. - Move
leftwhen the left line is shorter, otherwise moveright.
Step 5: Final Solution and Complexity
- The two pointers scan inward in one pass.
- Every possible useful candidate is considered without checking all pairs.
- Time complexity is O(n).
- Space complexity is O(1).