What Is the Two Pointers Technique?
Two Pointers moves two indices over a sorted array — from both ends, or in the same direction — to find an answer in O(n). The point is to turn the O(n²) double loop over all pairs into a single O(n) scan.
A classic example: find two numbers that sum to target in a sorted array. The left pointer starts at 0 and the right at the end.
Why Is It O(n)?
The array being sorted is the key.
- •If the pointed-to sum is greater than target → shrink the largest candidate, so
right-- - •If the sum is less than target → you need a larger value, so
left++ - •If the sum equals target → answer found
Thanks to this monotonicity (shrinking one side lowers the sum, growing it raises the sum), you never need to revisit a discarded candidate. Each pointer moves in only one direction, so the whole thing is O(n).
How It Works
Step 1. Set left = 0, right = n - 1.
Step 2. Compute sum = arr[left] + arr[right].
Step 3. If sum == target you're done; if sum > target then right--; if sum < target then left++.
Step 4. Repeat steps 2–3 while left < right.
The AlgoNote visualization shows the two pointers closing inward based on the sum, step by step.
Time and Space Complexity
| Complexity | |
|---|---|
| Time | O(n) (plus O(n log n) if not sorted) |
| Space | O(1) |
Walking Through an Example
arr = [1, 2, 4, 7, 11], target = 9.
- •left=0(1), right=4(11): sum 12 > 9 → right--
- •left=0(1), right=3(7): sum 8 < 9 → left++
- •left=1(2), right=3(7): sum 9 = 9 → answer
(2, 7)
Variations
- •Same-direction two pointers: both start on one side and grow/shrink a window — the sliding window.
- •3-sum: fix one element and run two pointers on the other two.
- •Dedup/merge: scan two sorted arrays simultaneously.
Common Mistakes
- •Ignoring the sorted assumption: using it on an unsorted array breaks monotonicity and gives wrong answers.
- •Boundary condition: choose
left < right(or<=) to match the problem so you don't reuse one element twice. - •Duplicate pairs: if you must find all pairs, advance both pointers appropriately after a hit to skip duplicates.
See It in Action on AlgoNote
Watch how the left and right pointers move as the sum compares to target, step by step on AlgoNote.