Interactive Lab · DSA & Algorithms
Here's a favourite: given the heights of a row of walls, pick two of them to hold the most water. The area between walls i and j is min(height) × widththe shorter wall caps it. The brute-force answer tries every pair, O(n²). The two-pointer trick starts with the widest pair and walks inward, and here's the whole idea: at each step, move the shorter wall. Moving the taller one can only lose width while the short wall still caps the height, so it can never help. One pass, O(n). Scrub the sweep and watch the water rectangle reshape.
🎬 Watch the 90-second explainer, then trap the most water yourself below ↓
▶ The playground, scrub the two pointers as they close in
Bars are wall heights. The blue rectangle is the water held by the current L and R walls, its height is the shorter wall. The amber wall is the one we move next, the shorter wall (either one, on a tie); the green dashed line marks the best container found so far.
Two pointers is the O(n²)→O(n) move of algorithm interviews (container-with-most-water, pair sums, dedup) and real systems: merge steps in databases and merge sort, in-place array compaction, and stream intersection. The never-skips-the-answer proof you just reasoned through is the transferable skill, arguing why a greedy sweep is safe.
The code that's actually running, one pass, two pointers
Brute force checks every pair, n(n−1)/2 = 36 here, about n²/2 in general. The two-pointer sweep does just n−1 = 8 moves. Predict why dropping the shorter wall never skips the real answer: once you move past the shorter wall, any container that still used it would be narrower (less width) and still capped at that same short height, so its area can't beat the one you just measured. Nothing is lost. That single observation is the entire correctness proof. One question to settle: on a tie (both walls equal), does it matter which one you move?
The takeaway
min(h[L], h[R]) × (R − L). The tall wall is wasted height, only the short one decides how high the water sits.n − 1 steps. The double loop re-examines pairs the sweep already ruled out.