Two Pointers
Two pointers is a technique that walks an array with a pair of indices that move toward a goal, often from both ends or as a slow runner and a fast runner. Many O(n^2) pair scans become O(n).
Detailed Explanation
The naive way to ask "do two numbers in this sorted array sum to t?" is a nested loop. The two-pointer way puts i at the start and j at the end. If a[i] + a[j] == t, you are done. If the sum is too small, increment i. If too large, decrement j. Each step discards an index for good, so the loop is O(n) after the sort.
The same skeleton reverses an array in place (i up, j down, swap). It partitions around a pivot in quicksort. It removes duplicates from a sorted array by a write pointer and a read pointer. It finds a cycle in a linked list with Floyd's tortoise and hare: one pointer advances by one, the other by two, and they meet if a cycle exists.
The invariant is what you prove. For the pair-sum, everything left of i is too small to use with any remaining j, and everything right of j is too large. If you cannot state what the two indices mean after each move, you do not have the algorithm yet; you have two for loops.
C details are index types and overlap. Use size_t and be careful when j would go below zero: a half-open or a j + 1 test is safer than j-- on 0. When the pointers address the same array and you write through one, the other sees the write. That is usually the point. When they address two arrays, you are merging, which is the last step of mergesort and the first step of many "sorted intersection" problems.
Two pointers is not a data structure. It is a way to spend O(1) extra memory and O(n) time on a problem whose obvious form is quadratic. If the array is unsorted and sorting would change the answer (indices of a pair in the original order), you need a hash table instead.
Code Examples
#include <stdio.h>
/* Assumes a is sorted ascending. Returns 1 if a pair sums to t. */
static int has_pair(const int *a, int n, int t)
{
int i = 0, j = n - 1;
while (i < j) {
int sum = a[i] + a[j];
if (sum == t) {
return 1;
}
if (sum < t) {
i++;
} else {
j--;
}
}
return 0;
}
int main(void)
{
int a[] = { 1, 2, 4, 7, 11 };
printf("%d %d\n", has_pair(a, 5, 11), has_pair(a, 5, 12));
/* prints: 1 0 */
return 0;
}#include <stdio.h>
/* Floyd cycle check. */
struct Node { int v; struct Node *next; };
static int has_cycle(struct Node *head)
{
struct Node *slow = head, *fast = head;
while (fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
return 1;
}
}
return 0;
}
int main(void)
{
struct Node a = { 1, NULL }, b = { 2, NULL }, c = { 3, NULL };
a.next = &b;
b.next = &c;
c.next = &b;
printf("%d\n", has_cycle(&a)); /* prints: 1 */
return 0;
}Common Gotchas
`j--` when `j` is `size_t` and `j == 0` wraps
keep the loop condition `i < j` and only decrement after you know `j > i`.
Pair-sum requires a sorted array
sorting first is `O(n log n)` and loses original indices.
Integer overflow in `a[i] + a[j]`
use a wider type or compare with subtraction carefully.
Fast/slow on a list still dereferences `fast->next`
the `fast && fast->next` guard is not optional.