Neural Mastery
← Practice
Container With Most Watermedium

Container With Most Water

medium Coding Interview Patterns 15–20 min

NumPy allowed · plain Python earns 10 bonus points

Interactive
Two Pointers & Sliding Window, Step by Step
Pattern
1
L
2
3
4
6
R
arr[L]=1 + arr[R]=6 = 7 vs target 6 -> too big, move R left
Step 1 / 3
Both modes run the exact algorithm described on the linked practice problem, one real step at a time -- not a pre-rendered animation. Edit the input and every step recomputes live.

Implement the greedy two-pointer solution to Container With Most Water -- the classic proof that checking every pair (O(n^2)) is unnecessary once you see WHY moving the shorter pointer is always the only move worth making.

Related Skills

Task

Implement max_area(heights): start with pointers at both ends. At each step, compute the area between them, then move whichever pointer points at the SHORTER line inward (moving the taller one can only ever decrease or maintain the width-limited-by-the-short-side area).

Function Signature

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

Examples

Example 1: Classic Example
Input: heights = [1, 8, 6, 2, 5, 4, 8, 3, 7]
Output: 49
Explanation: Lines at height 8 and 7, width 7
Example 2: Two Elements Only
Input: heights = [1, 1]
Output: 1

Constraints

  • Libraries are allowed; a plain-Python solution earns 10 bonus points.
  • Area = min(heights[l], heights[r]) * (r - l) for pointers l < r.
  • Must run in O(n) time (a single two-pointer pass, not all pairs).
Python3Saved ✓
def max_area(heights: list[int]) -> int:
"""heights[i] is the height of a vertical line at position i. Return
the maximum area of water a pair of these lines (plus the x-axis
between them) can contain: area = min(heights[i], heights[j]) *
abs(i - j)."""
# Your implementation here
pass

Case 1: Classic Example
Input: heights = [1, 8, 6, 2, 5, 4, 8, 3, 7]
Expected: 49
Case 2: Two Elements Only
Input: heights = [1, 1]
Expected: 1