#11

Container With Most Water

MediumTwo PointersHas vizArrayTwo Pointers
Related studio

Problem

You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).

Find two lines that together with the x-axis form a container that holds the most water.

Return the maximum amount of water a container can store.

Notice that you may not slant the container.

Example 1

Input: height = [1,8,6,2,5,4,8,3,7]

Output: 49

The lines at index 1 and 8 form the max container.

Example 2

Input: height = [1,1]

Output: 1

Only one possible container.

Constraints

  • n == height.length
  • 2 <= n <= 10^5
  • 0 <= height[i] <= 10^4
Loading visualization…

Explanation

Container With Most Water is a Medium interview problem tagged [Array, Two Pointers]. The winning approach is typically **Two Pointers**.

Intuition

Each pointer only moves forward/backward once, guaranteeing O(n) after any required sort.

Approach

Place two indices and move them based on a comparison or invariant (sorted order, palindrome symmetry, partition).

  1. Establish the invariant (e.g., array sorted).
  2. Initialize L and R.
  3. Move the pointer that improves the condition.
  4. Handle duplicates carefully if uniqueness is required.

Solution

Curated solution in C#, Python, Java, JavaScript, and C++ — switch languages with the tabs.

Exact solutionTwo Pointers

Edge cases

  • •Empty or single-element input
  • •Duplicates and ties
  • •Maximum constraints / overflow
  • •Disconnected or unreachable states (for graphs)

Complexity

Time: O(n log n) or O(n)

Space: O(n)

Before coding, restate the problem, name the pattern (Two Pointers), and write the invariant or DP state in one sentence.

Learn the topic

Got it?

Mark #11 Container With Most Water as understood when the pattern clicks.