InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Two Pointers

Container With Most Water

medium Original ↗ 00:00

Problem

You are given an integer array height where height[i] is the height of a vertical line drawn at x-coordinate i. Pick two of these lines; together with the x-axis they form an open-topped container. The water it can hold is limited by the shorter of the two lines:

area = (distance between the lines) * min(height of the two lines)

Return the maximum water any pair of lines can contain. The container must stay upright — lines cannot be tilted — and water above the shorter line spills out.

Examples

  • height = [1,8,6,2,5,4,8,3,7]49 Lines at indices 1 and 8 (heights 8 and 7): width 8 - 1 = 7, limited by height 7 → 7 * 7 = 49.
  • height = [1,1]1 Only one pair exists: width 1, height 1.
  • height = [4,3,2,1,4]16 The two 4s at the ends: 4 * 4 = 16 beats every closer pair.

Constraints

  • 2 <= height.length <= 10^5
  • 0 <= height[i] <= 10^4
  • With n = 10^5, checking all ~5 * 10^9 pairs is too slow — an O(n) or O(n log n) approach is required.

Think about it first

Hint 1 Area is width times the smaller height. Starting from the widest possible container (first and last lines), any other pair is *narrower* — so a better pair must make up for the lost width with more height.
Hint 2 With pointers at both ends, moving either one shrinks the width by 1. Moving the pointer at the **taller** line can never help — the area is capped by the shorter line, which is still there (or worse), and the width just shrank.
Hint 3 So the shorter line's pointer is the only one worth moving: every pairing that included it has been implicitly considered and beaten. Track the best area while the pointers converge — `O(n)` total.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug