Two pointers
Two pointers is a technique that walks a sequence with two indices (or iterators) instead of nested loops. The pointers move inward, forward together, or at different speeds, turning many O(n²) pair searches into O(n).
Detailed Explanation
You are asked for two numbers in a sorted array that add to a target. The nested loop tries every pair. The two-pointer version puts i at the start and j at the end. If a[i] + a[j] is too big, decrement j. If it is too small, increment i. Each step discards an index forever, so the loop is O(n). Sorting first, if needed, is O(n log n) and still better than O(n²) for large n.
That inward walk is one pattern. Others:
- Same direction, different speed. Fast and slow pointers on a linked list: fast moves twice, slow once. If they meet, there is a cycle. If fast hits null, there is not. Finding the midpoint is the same idea.
- Window ends. A write pointer and a read pointer compact a vector in place (
remove/unique). The write pointer only advances when you keep an element. - Partition. Hoare partition in quicksort: two pointers walk toward the middle and swap inversions.
The invariant is the thing you must state. For the pair-sum: every pair you skipped cannot be the answer because the array is sorted. If you cannot state why a move is safe, you do not have two pointers; you have a bug.
C++ iterators are pointers in this sense. auto first = v.begin(), last = v.end(); --last; and then move them. Prefer indices on a vector when you need arithmetic (i + 1). Prefer iterators on a list because there is no [].
Two pointers need a structure that can move both ends cheaply. A singly linked list cannot walk backward. A hash map is usually a different technique (store complements). A sorted vector is the classic host.
Edge cases: empty range, one element, all duplicates, pointers that cross. Write the loop condition as i < j (indices) or first < last after you made last inclusive carefully. Off-by-one at the meeting point is the usual defect.
Space is O(1) extra besides the sort. That is why interviewers like the pattern: you replaced a hash set's O(n) memory with a sort plus two indices.
Code Examples
#include <cstddef>
#include <iostream>
#include <vector>
bool hasPairSum(const std::vector<int>& sorted, int target) {
std::size_t i = 0;
std::size_t j = sorted.size();
if (j < 2) return false;
--j;
while (i < j) {
int sum = sorted[i] + sorted[j];
if (sum == target) return true;
if (sum < target) ++i;
else --j;
}
return false;
}
int main() {
std::vector<int> v{1, 2, 4, 7, 11};
std::cout << std::boolalpha << hasPairSum(v, 15) << '\n'; // true (4+11)
std::cout << hasPairSum(v, 14) << '\n'; // false
}#include <iostream>
#include <vector>
int compactNonzero(std::vector<int>& v) {
std::size_t w = 0;
for (std::size_t r = 0; r < v.size(); ++r) {
if (v[r] != 0) v[w++] = v[r];
}
return static_cast<int>(w);
}
int main() {
std::vector<int> v{0, 1, 0, 2, 3};
int n = compactNonzero(v);
std::cout << n << '\n'; // prints: 3
}Common Gotchas
Using two pointers on an unsorted pair-sum
the discard argument needs order. Sort first, or use a hash set.
`unsigned` indices that decrement past 0
`j` as `size_t` with `j--` when `j == 0` wraps. Keep the `i < j` test before you decrement, or use signed indices.
Fast/slow on a list needs two hops and a null check on `fast->next`
missing the check is a null dereference.
Crossing pointers
when `i == j` you are looking at one element, not a pair. Use `i < j`.