Browse curriculum

FAANGPrep Sprint

Container With Most Water

Pick the two vertical lines that, with the x-axis as the floor, hold the most water between them.

Examples

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

The best pair is the line of height 8 at index 1 and the line of height 7 at index 8: they stand 7 apart and the shorter is 7 tall, so they hold 7 × 7 = 49.

The Problem

height[i] is the height of a vertical line standing at position i. Choose two of the lines so that, with the x-axis as the floor, the container they form holds as much water as possible.

Goal: Maximize Area = width * min(height[left], height[right]).

Visualizing the Problem

The container is formed by two vertical lines, and its water level is limited by the shorter one. The figure below outlines the water between the two pointers at that level.

Attempt 1: Brute Force

The naive solution is to simply check every pair of lines and calculate the area.

  • Check line 0 with line 1, then line 0 with line 2...
  • Then line 1 with line 2, line 1 with line 3...

Why it fails: This requires nested loops, resulting in O(n^2) time complexity. For a large input, this will time out.

The Intuition: Process of Elimination

Start Wide, Then Eliminate.

  1. Start Max Width: The widest possible container is bounded by the first and last line. Let's start there.
  2. The Decision: We want to find a higher line to potentially get more area. But we can only move one pointer at a time.
    • If height[left] < height[right], the left line is the bottleneck. Moving the right pointer in would only decrease width, and height is still limited by left. We must move left to hope for a taller line.
    • Similarly, if right is shorter, we must discard it and move right inward.

Algorithm Strategy

  1. Start with pointers at both ends: left = 0, right = n-1.
  2. Calculate the current area: min(height[left], height[right]) * (right - left).
  3. Update the maximum area found so far.
  4. Decision: Compare the heights of left and right. Move the pointer pointing to the shorter line inwards.
    • If height[left] < height[right], increment left.
    • Else, decrement right.
  5. Repeat until the pointers meet.

Interactive Walkthrough

9 LINES

MEASURE PAIR

i

j

1

0

8

1

6

2

2

3

5

4

4

5

8

6

3

7

7

8

Area

1

Best

1

Checks

1

 

Lines 0 and 1: width 1 × height 1 = 1 — a new best

Next

Lines 0 and 2: width 2 × height 1 = 2 — a new best

Heights

Compare Every pair with Two pointers on the same heights: the pointer scan moves the shorter line inward each time and still finds the best area, computing far fewer areas (Checks).