LeetCode 11 Container With Most Water - Example and Complexity Analysis

Walkthrough and analysis

Trace height = [1, 8, 6, 2, 5, 4, 8, 3, 7].

Start: left = 0, right = 8. Heights: 1 and 7. Area = min(1, 7) × 8 = 8. Left is shorter, move left.

left = 1, right = 8. Heights: 8 and 7. Area = min(8, 7) × 7 = 49. Right is shorter, move right.

left = 1, right = 7. Heights: 8 and 3. Area = min(8, 3) × 6 = 18. Right is shorter, move right.

Continue until pointers meet. Maximum area found: 49.

Each pointer moves inward exactly once per step. Total steps: n1n - 1. That's O(n)O(n) time.

Only two pointers and one variable for max area. That's O(1)O(1) space.