InterviewPrepKit

Home / Coding / Two Pointers

Container With Most Water

medium Original β†—
Solving tips
  • Start pointers at both ends (widest container) and always move the pointer at the SHORTER line inward; that greedy elimination gives O(n).
  • Exchange-argument justification: area is capped by the shorter wall, so any pair keeping it and narrowing is provably no better, letting you discard it.
  • Compute area = width * min(heights) every step before moving, since the optimum can appear mid-sweep and never recur.
  • O(n) time, O(1) space; on a tie moving either pointer is safe. Don't confuse with Trapping Rain Water (only two lines form this container).

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.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.