Container with Most Water - Two Pointers Pattern
Container with Most Water in Java using the Two Pointers pattern: problem statement, approach, template, complexity, and interview tips.
Container with Most Water
Problem Statement
Given the heights of vertical lines, find two lines that together with the x-axis hold the most water.
Pattern: Two Pointers
Move two indices through the data, usually from both ends or in the same direction, to avoid a nested loop.
Use this pattern when the input is sorted (or can be sorted) and you search for pairs, or you must compact or compare from both ends.
Approach
- Decide where each pointer starts and which direction it moves.
- At each step compare the pointed values and move the pointer that can improve the answer.
- Stop when the pointers meet or cross.
Pattern Template (Java)
int left = 0, right = n - 1;
while (left < right) {
// evaluate nums[left] and nums[right]
// move the pointer that can still improve the answer
}
Adapt this template to the exact rules of Container with Most Water: decide what state you track, what condition moves the loop forward, and what the final answer is.
Complexity
O(n) time and O(1) extra space after sorting; sorting adds O(n log n).
Interview Tips
- Say out loud why moving a pointer can never skip the best answer.
- Skip duplicates explicitly when the problem asks for unique results.
- Start with a brute-force idea, state its complexity, then explain how the Two Pointers pattern improves it.
- Walk through a small example and at least one edge case (empty input, a single element, duplicates).
Related Problems
Continue Learning
Parent: DSA Interview Learning Path | Previous: 3Sum | Next: Remove Duplicates From Sorted Array
Was this guide helpful?
CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.