Pattern 2 of 18 · Foundations

Two Pointers

Two indices moving through a sorted structure to avoid nested loops.

Two indices move through a sorted (or sortable) structure — often from opposite ends or at different speeds — to avoid the nested loops a brute-force scan would need.

Key concepts

  • Opposite-direction pointers: start at both ends, move inward based on a comparison — classic for sorted-array sum problems.
  • Same-direction (fast/slow) pointers: one pointer scans ahead while the other tracks a valid window or position.
  • Works because sorting (or an inherent order) lets you discard whole ranges instead of testing every pair.

When to use it

  • The input is sorted, or can be sorted without losing information you need.
  • You're looking for a pair, triplet, or partition that satisfies a sum or comparison condition.
  • You need to compare values from both ends of a sequence (e.g. palindrome checks).

Tips

  • Sorting first costs O(n log n) but often unlocks an O(n) two-pointer pass — usually a net win over O(n²).
  • When a condition is too big or too small, move the pointer that can fix it — don't move both blindly.
  • Skip duplicate values explicitly when the problem asks for unique results (e.g. 3Sum).

Practice problems (5)

Blind 75 (3):

More from Blind 150 (2):

See the full roadmap →