Container With Most Water

Asked byAmazonMicrosoftAdobeFacebookGoogleApple

Problem

Given an array of heights where each value represents a vertical line at that index, find two lines that together with the x-axis form a container holding the maximum amount of water, and return that maximum area.

Examples

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

Constraints

  • 2 <= height.length <= 10^5

Solve it in the editor. Sign in free to run your Python or JavaScript against test cases, get a verdict, and track your attempts.

Solve on FeatCode →

How to approach it: the Two Pointers pattern

Two indices move through a sorted (or sortable) structure — often from opposite ends or at different speeds — to avoid the nested loops a brute-force scan would need.

Look for this pattern when

  • The input is sorted, or can be sorted without losing information you need.
  • You're looking for a pair, triplet, or partition that satisfies a sum or comparison condition.
  • You need to compare values from both ends of a sequence (e.g. palindrome checks).

Read the full Two Pointers guide →

Video walkthroughs

Original problem on LeetCode ↗

More Two Pointers problems