25. Two Pointers
Move two indices through an array, usually from both ends toward the middle, to replace an O(n^2) pair search with one O(n) pass. Works when the input is sorted or has another monotonic property.
How it works
For pair with target sum in a sorted array, start with left at the smallest item and right at the largest. If the sum is too small, the only way to increase it is to move left right. If too large, move right left. Every step rules out one item for good, so the scan is linear.
Other two-pointer shapes: fast/slow pointers (linked list cycles), read/write pointers (remove duplicates in place), and pointers on two different arrays (merging).
Diagram
flowchart TD
S["sum = a at left + a at right"] --> Q{"Compare sum with target"}
Q -->|equal| F["Return the pair"]
Q -->|"too small"| L["left moves right"] --> S
Q -->|"too big"| R["right moves left"] --> S
Step-by-step trace
Input: Find two numbers in [1, 2, 4, 7, 11, 15] that add up to 15.
| Step | left | right | a[left] + a[right] | Move |
|---|---|---|---|---|
| 1 | 0 | 5 | 1 + 15 = 16 | 16 > 15: right– |
| 2 | 0 | 4 | 1 + 11 = 12 | 12 < 15: left++ |
| 3 | 1 | 4 | 2 + 11 = 13 | 13 < 15: left++ |
| 4 | 2 | 4 | 4 + 11 = 15 | match, stop |
Result: Indices (2, 4): 4 + 11 = 15.
Complexity
| Operation | Time | Space |
|---|---|---|
| Pair sum on sorted array | O(n) | O(1) |
| Same on unsorted array (sort first) | O(n log n) | O(1) extra |
Python reference implementation
def pair_with_sum(a, target):
"""Two pointers on a sorted list. Returns (i, j) with a[i] + a[j] == target, or None."""
left, right = 0, len(a) - 1
while left < right:
s = a[left] + a[right]
if s == target:
return left, right
if s < target:
left += 1 # need a bigger sum
else:
right -= 1 # need a smaller sum
return None
Common mistakes and tips
- Unsorted input with indices required? Use a hash map instead (sorting loses original positions).
- 3Sum is: sort, fix one item, then run two pointers on the rest, skipping duplicates.
The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.
| Previous: Binary Search | Next: Sliding Window |