progress

~/problems / Two pointers

Container with Most Water

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

Write max_area(heights: list[int]) -> int.

heights[i] is the height of a vertical wall standing at x-coordinate i. Choose two walls i < j; together with the floor they hold water up to the shorter wall, so the amount is (j - i) * min(heights[i], heights[j]). Return the largest possible amount. Walls in between do not get in the way.

Example: heights = [3, 1, 2, 5, 2, 4] gives 15 (walls at 0 and 5: width 5, height 3).

Six walls of heights 3, 1, 2, 5, 2 and 4; the walls at positions 0 and 5 hold water 5 wide and 3 high, area 15, the largest possible

Another example: [4, 4] gives 4.

Constraints: 2 <= len(heights) <= 10^5, 0 <= heights[i] <= 10^4.

⭐ Bonus: trying all pairs is O(n²) and still passes; the speed test earns a star in O(n). Start with the widest pair and move one pointer inward each step. Which side can you safely drop?

Topic: Two pointers. Sorted input + moving ends inward; skip duplicates; pairs and triples.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc