Two PointersArraysStringsSorted DataO(n) Optimization

Two Pointers — The Complete Guide

Master the Two Pointers pattern from first principles. Learn to recognize it instantly, evolve brute-force into optimal solutions, and confidently solve interview questions.

35 min read10 sections
01

Intuition from Scratch

Why does this pattern exist?

Imagine you have a sorted list of numbers and someone asks: "Find two numbers that add up to 15." The brute-force way is to check every possible pair — pick the first number, then scan the rest. That's O(n²). Painfully slow for large inputs.

But wait — the list is sorted. That's a massive clue. If you place one finger at the start (smallest number) and another at the end (largest number), you can make intelligent decisions:

  • Sum too small? Move the left finger right (need a bigger number)
  • Sum too big? Move the right finger left (need a smaller number)
  • Sum just right? Found it.

Each step eliminates an entire row or column of possibilities. You never go backwards. One pass, O(n). That's the Two Pointers pattern — using two indices that move strategically to avoid redundant work.

Analogies to Build Intuition

📖

The Dictionary Search

Looking for a word in a physical dictionary. You open to the middle — too far? Go left. Not far enough? Go right. Two Pointers is like having two bookmarks, one near the front and one near the back, and moving them inward based on what you find.

🤝

Two People Walking Toward Each Other

Imagine two people at opposite ends of a hallway. They walk toward each other, each adjusting their speed based on a condition. They'll eventually meet in the middle. That's the opposite-direction variant — you process the entire array in one pass.

🏃

The Slow and Fast Runner

Two runners on a track, one fast and one slow. If the track has a loop, the fast runner will eventually lap the slow one — that's how you detect cycles. If there's no loop, the fast runner reaches the end first — that's how you find the middle.

What kind of problems does it solve?

Two Pointers is your go-to when:

  • You're working with a sorted array or string
  • You need to find pairs or triplets with a specific property
  • You need to partition or rearrange elements in-place
  • You need to compare or merge two sequences
  • You want to reduce O(n²) brute force to O(n)

The core insight

Two Pointers works because each pointer movement eliminates possibilities that you'd otherwise check in a nested loop. The sorted order (or some other structural property) guarantees that skipped possibilities can't contain the answer.

1 / 11