Container With Most Water
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Examples
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
The Problem
You are given an array height where height[i] represents the height of a vertical line. Find two lines that, together with the x-axis, form a container that holds the most water.
Goal: Maximize Area = width * min(height[left], height[right]).
Visualizing the Problem
Example: L at 8, R at 7. Width = 7. Height = min(8, 7) = 7. Area = 7 * 7 = 49.
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.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.
- Start Max Width: The widest possible container is bounded by the first and last line. Let's start there.
- 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 byleft. We must moveleftto hope for a taller line. - Similarly, if
rightis shorter, we must discard it and moverightinward.
- If
Algorithm Strategy
- Start with pointers at both ends:
left = 0,right = n-1. - Calculate the current area:
min(height[left], height[right]) * (right - left). - Update the maximum area found so far.
- Decision: Compare the heights of
leftandright. Move the pointer pointing to the shorter line inwards.- If
height[left] < height[right], incrementleft. - Else, decrement
right.
- If
- Repeat until the pointers meet.
Interactive Walkthrough
Start: L(1) vs R(7). Width=8. Heigth=1. Area=8. Move L (shorter).
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.- The Problem
- Visualizing the Problem
- Attempt 1: Brute Force
- The Intuition: Process of Elimination
- Algorithm Strategy
- Interactive Walkthrough
- Dry Run Table
- The Solution Template
- Edge Cases & Common Mistakes
- Summary
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
