Container With Most Water

Two vertical lines and the x-axis form a container. Area is width × the shorter height, so always move the shorter pointer inward — the taller one can never improve by shrinking width.

Category
Two Pointers
Time complexity
O(n)
Space complexity
O(1)

Pseudocode

lo ← 0, hi ← n−1
area ← min(h[lo],h[hi]) × (hi−lo)
track best area
move the shorter side inward

Reference implementation

lo, hi, best = 0, n-1, 0
while lo < hi:
    best = max(best, min(h[lo], h[hi]) * (hi-lo))
    if h[lo] < h[hi]: lo += 1
    else: hi -= 1

Open the interactive Container With Most Water visualisation →