TRT
Sign in
mediumAdvancedLeetCode#converging pointers#move the bottleneck

Container with most water

Find two lines that hold the most water, moving the pointer at the shorter line inward each step.

The Runtime Theory Team1 min read
Taught inTwo pointersPro — members onlyOn a sorted array, two indexes moving toward each other can find pairs with a given sum in one pass, because every move rules out a whole row of candidate pairs. The same argument powers three-sum, container problems and trapping rain water.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inheight = [1, 8, 6, 2, 5, 4, 8, 3, 7]

out49

inheight = [1, 1]

out1

inheight = [4, 3, 2, 1, 4]

out16

Lines of the given heights stand at each index. Choose two that, with the x-axis, form a container holding the most water, and return that amount.

Before you code

Area is width times the shorter height. Starting from the widest pair, the only move that could find a bigger area is to discard the shorter line.

Hints

  1. Start with the two ends and compute the area.
  2. Move the pointer at the shorter line inward; on a tie, either.
  3. Track the maximum. O(n) time.

Production & complexity notes

When solving Container with most water on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Two pointers to reinforce the underlying pattern.

What it practices

Discarding the limiting element, from Two pointers.

Not started

Sign in to save your learning progress.

Sign in to save