~/problems / Two pointers

Container with Most Water

medium ~25 min

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). [4, 4] gives 4.

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

Trying all pairs is O(n²) and too slow for the large test. 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