Back to DSA track
DSA Topic

Two Pointers

A reliable linear-scan pattern for arrays and strings where progress comes from moving one boundary at a time instead of rechecking every pair.

Turns many nested scans into a single directional pass
Works best when pointer movement has a clear monotonic rule
Gets easier once you name the invariant before writing code

How to think about it

Two pointers is less about having two indices and more about using structure to avoid wasteful comparisons. Once you can prove that moving one side cannot hide a better answer, the search space collapses quickly.

That is why the pattern keeps showing up in interview arrays and strings. Sorted input, palindrome checks, deduplication, and interval-style reasoning all create situations where a careful boundary move preserves previous work.

Signals that the pattern fits

  • You are scanning an array or string from one or both ends.
  • The answer depends on relative comparisons between elements.
  • The input is already sorted, or sorting would make the movement rule obvious.
  • You can explain exactly why moving one pointer never discards a valid better answer.

Movement models

Opposite-end pointers

Start one pointer on each side when outer comparisons matter or the structure is sorted.

  • Great for pair sum in a sorted array
  • Useful for palindrome checks and width-based tradeoffs
  • Each move should be justified by whether the current pair is too small, too large, or already valid

Same-direction pointers

Let one pointer read while the other tracks the next clean write position or compacted region.

  • Shows up in duplicate removal and partition-style tasks
  • The write pointer marks what the processed prefix already guarantees
  • Most bugs disappear once you state what the prefix represents after every step

Quick review checklist

  • Is the input sorted, or can it be sorted without breaking the problem?
  • What exact event moves the left pointer?
  • What exact event moves the right or write pointer?
  • What invariant remains true after every move?