Command Palette

Search for a command to run...

← All patterns

Pattern · Pointers & Windows

Two Pointers: Opposite Ends

Start one pointer at each end and move them towards each other, using a rule to decide which one moves.

Time O(n) · Space O(1)

Taught in Module 6: Two Pointers

Think of it like this

Two people searching a sorted bookshelf from both ends: if the pair of books is too heavy, the person at the heavy end steps inwards; if too light, the other one does.

Clues that point here

  • → Sorted array or string
  • → Find a pair (or triple) with a target sum
  • → Palindrome checks
  • → "Container" or "area between two lines"
  • → Reverse in place

Not this pattern when

  • ✕ The array isn't sorted and sorting would lose the original indexes you must return (use a hash map)
  • ✕ You need all pairs, not one, in an unsorted array

The template

A skeleton to adapt. The parts in comments are what changes from problem to problem.

Two Pointers: Opposite Ends · template
int left = 0, right = arr.length - 1;
while (left < right) {
    int value = combine(arr[left], arr[right]);   // e.g. a sum
    if (value == target) return new int[]{left, right};
    if (value < target) left++;                  // need bigger: move the small side
    else right--;                                // need smaller: move the big side
}
return new int[]{-1, -1};

Common versions

  • Pair sum in a sorted array
  • 3Sum (fix one, two-pointer the rest)
  • Valid palindrome
  • Container with most water
  • Reverse an array in place

Practice problems with this pattern

Related patterns