QuestionsDSA

Container With Most Water

Two PointersMediumDSA

Given heights[], each a vertical line, find two lines that together with the x-axis hold the most water. Return the max area.

What it tests

Greedy two-pointer reasoning: why moving the shorter side is always safe.

Approach & answer

Start pointers at both ends. Area = min(h[i], h[j]) × width. Always move the SHORTER line inward — moving the taller can only lower or keep the height while shrinking width, so it can never beat the current best. Moving the shorter one is the only move with upside: it discards a line that already capped the area, giving a shorter-but-possibly-taller pairing a chance. This greedy 'the limiting side is the one to abandon' argument is the crux; brute force is O(n²) and this proves you can skip almost all pairs safely.

Use this technique when

Maximize/minimize something between two ends of an array where width shrinks as you move in.

Complexity

Time O(n) · Space O(1)

References

js