Pattern visualizer
Container With Most Water
Start with the widest possible container and walk the two walls toward each other. Water is capped by the SHORTER wall, so moving the taller one can never help — width shrinks and the cap stays. Moving the shorter wall is the only move that might find something taller, which is why one pass safely covers every candidate pair. Animated on: Walls of heights [1, 8, 6, 2, 5, 4, 8, 3, 7] — pick the two that trap the most water: area = width × shorter wall..
Opposite-ends two pointers — always move the shorter wall
Walls at both ends: l on height 1, r on height 7. Width 8 is the widest any container will ever be — from here width only shrinks, so every move must gamble on finding a taller wall.
1FUNCTION maxArea(height):2 set l to 0, r to (length of height) - 1, best to 03 WHILE l < r:4 area = (r - l) * the shorter of height[l] and height[r]5 best = the larger of best and area6 IF height[l] < height[r]: move l one step right7 ELSE: move r one step left8 RETURN best
← / → step · space play · Home restart