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.
Because the array is sorted, we can make intelligent decisions:
- Sum too large → shrink from the right (move
rightleft) - Sum too small → grow from the left (move
leftright)
- 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.
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
| Signal | Use 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.