learn/Algorithms/Two Pointers
ƒ(x) PatternsIntermediate interactive

Two Pointers

Two indices converging or chasing through data.

two_pointers
step 1 / 6
L
2
0
5
1
8
2
12
3
15
4
21
5
26
6
R
30
7

2 + 30 = 32 < 33 → move left pointer right.

left / right pointermatchtarget = 33
speed1×

How it works

The two-pointer pattern uses a pair of indices — moving toward each other or one chasing the other — to solve array and string problems in a single O(n) pass instead of O(n²) nested loops. Classic on sorted arrays for pair-sum and reversal.

Mental models

  • On a sorted array, move the pointer that brings the sum toward target.
  • Fast/slow pointers detect cycles and find midpoints.

Complexity

Time
O(n)
Space
O(1)

Reach for it when

  • Pair-sum on sorted arrays
  • Palindrome checks
  • In-place dedup