Learning pathsPricingChecking sign-in…
Array and string patterns

Two pointers

Use order to eliminate impossible candidates.

Two pointers are useful when moving a boundary can safely discard candidates, not merely because the input is an array.

Mechanism and state

For Container With Most Water, compare the two boundary heights. Holding the shorter line fixed while moving its partner inward reduces width and cannot raise the limiting height. Measure the current area, then discard the shorter boundary. For sorted Two Sum, a sum below target discards the smaller boundary because pairing it with any smaller partner cannot reach the target. These are two different elimination arguments.

Why the pattern works

State which candidates remain between the boundaries and why every discarded candidate is dominated or impossible. Initialization includes all candidates. A move must strictly reduce the interval without discarding an unaccounted improvement. Termination leaves no pair. Nested loops are not required: a total of n-1 boundary moves gives linear work.

Work through an example

On heights [1,2,4,3], (0,3) gives 3, then move left. (1,3) gives 4, then move left. (2,3) gives 3, then move right. The answer stays 4; moving the taller boundary at the first step could lose it. Two pointers also implement a different invariant in reversal: positions outside the current interval already have their symmetric destinations. Swapping the two endpoints and shrinking restores reversed blocks for Rotate Array; this is not the container elimination proof.

Where the reasoning fails

Sorting an arbitrary array can lose original indices or change a geometric problem. Do not sort container heights: their positions are part of the contract. Use long before multiplying width by height.

Reconstruct the reasoning

For each pointer move, explain the entire set of pairs it discards. Then find an input where moving the other boundary loses the optimum.

Apply this foundation

Your study notes