← Lessons

quiz vs the machine

Silver1100

Algorithms

Opposite Ends Pointers

Starting one pointer at each end and converging toward the middle.

4 min read · intro · beat Silver to climb

Converging from both ends

In the opposite ends pattern you place one pointer at the start and one at the end, then move them toward each other. Each step you inspect the pair, decide which boundary to tighten, and shrink the window from one side.

Why it works on sorted input

On a sorted array, the sum of the two boundary values tells you exactly how to move:

  • If the pair sum is too small, advance the left pointer to gain a larger value.
  • If the pair sum is too large, retreat the right pointer to gain a smaller value.
  • If it matches the target, you found the pair.

Because every step eliminates at least one candidate value, the pointers meet after at most a linear number of moves.

Other uses

The same converging motion reverses an array in place, checks whether a string is a palindrome, and computes container or trapping style problems where the limiting side should move inward.

Key idea

Two pointers starting at opposite ends converge inward, and on sorted data the comparison at the boundary tells you exactly which side to move, solving pair problems in one linear pass.

Check yourself

Answer to earn rating on the learn ladder.

1. On a sorted array, if the boundary pair sum is too small, what do you do?

2. Which task is NOT a natural fit for opposite ends pointers?