← Back to Patterns
Arrays & Sliding WindowMedium

Two Pointers

Use two indices moving inward or in tandem to reduce O(n²) to O(n).

How it works

The Two Pointers technique uses two index variables that move through a data structure — typically an array or string — in a coordinated way. Instead of using nested loops (O(n²)), you place one pointer at the start and one at the end, then move them toward each other based on a condition. This works because the array is sorted (or has a specific structure), so moving a pointer in one direction always makes progress toward the solution. There are two main variants: (1) Opposite ends — pointers start at both ends and converge inward, useful for pair-sum and palindrome problems. (2) Same direction — a fast and slow pointer (or leader/follower), useful for in-place removal, cycle detection, and partitioning.

Interactive Playground

1L35791113RL=1 R=13 sum=14

Place left pointer at start, right pointer at end of sorted array.

Speed

When to use

  • Sorted array with pair/triple sum problems
  • In-place partitioning or removal
  • Palindrome checking or string comparison

Tips

1Sort the array first if it is not already sorted — Two Pointers only works correctly on sorted data.
2For in-place removal, use a write pointer (slow) and a read pointer (fast): copy valid elements to the write position.
3For triple sum, fix one element with a loop, then run Two Pointers on the remaining subarray.
4When both pointers meet, you've exhausted all possibilities — this is the termination condition.

Common Mistakes

!Forgetting to sort the input — Two Pointers on unsorted data produces wrong results.
!Moving both pointers at the same time when only one should move based on the comparison.
!Off-by-one errors when checking palindromes — use `left < right`, not `left <= right`.
!Not handling duplicates in pair/triple sum — skip duplicate values after finding a valid pair.
💡 Key Insight:One pointer chases, the other flees — or both converge from opposite ends.