Intuition First: Closing In From Both Ends#

Picture a long shelf of books arranged by price, and you want two of them that together cost exactly ₹500. One friend starts at the cheap end, another at the expensive end. If their two books total too much, the friend at the expensive end steps inward to something cheaper. If it's too little, the cheap-end friend steps up to something pricier. They keep walking toward each other until the prices add up — or they meet in the middle and give up.

Because the shelf is sorted, every single step rules out a whole range of pairs at once. That's the magic: a check-every-pair search that would take O(N²) collapses into one inward walk of O(N).


The Core Idea#

Two Pointers is a technique, not a single algorithm. You maintain two index variables — left and right — and move them toward each other (or in the same direction) to avoid nested loops.

Instead of O(N²) brute force, you get O(N) by exploiting the structure of the data.


The Classic Problem: Pair Sum in a Sorted Array#

Given a sorted array and a target sum, find two indices whose values add up to the target.

text
Loading editor…

Because the array is sorted, we can make intelligent decisions:

  • Sum too large → shrink from the right (move right left)
  • Sum too small → grow from the left (move left right)
Loading editor…
  • Time Complexity: O(N) — each pointer moves at most N steps total
  • Space Complexity: O(1) — just two index variables

Interactive Lab#

See how the left and right pointers converge.


Other Two-Pointer Patterns#

Same-Direction (Fast & Slow)#

Used for problems like "remove duplicates" or cycle detection in linked lists.

python
Loading editor…

Partition (used in Quick Sort)#

One pointer from the left finds a large element; one from the right finds a small element. They swap until they cross.


When to Reach for Two Pointers#

SignalUse Two Pointers?
Sorted array + pair/triplet sum✓ Yes
Remove duplicates in-place✓ Yes
Palindrome check✓ Yes
Unsorted array + exact pair✗ Use hash map instead

Key Takeaway#

Two Pointers replaces a nested loop (O(N²)) with two synchronized pointers (O(N)) whenever the data has enough structure to tell you which pointer to move. Sorting the array first — even if O(N log N) — is often worth it because the two-pointer pass saves more.