Skip to content
StackDecode
Array techniquesAnimated

Two Pointer Technique

Move two indexes towards each other (or together) instead of nesting loops.

Time

O(n)

Extra space

O(1)

Use it for

Sorted arrays, pair sums, palindromes.

How it works

  1. The array must be sorted. Put one pointer at the start and one at the end.
  2. Add the two values. If the sum is too small, move the left pointer right (to a bigger value).
  3. If the sum is too big, move the right pointer left.
  4. If it matches, done. Each pointer only moves one way, so it takes O(n) instead of O(n²).

Watch it run

Loading animation…