Two pointers
Two indices walking one array, turning O(n²) scans into O(n).
Before you start
The brute-force way to find two numbers that add to a target is to try every pair: for each element, check it against every other one. That is n²/2 comparisons.
But if the array is **sorted**, you know something extra — and the two-pointer technique cashes that in. Put one pointer at each end. Their sum is either too small, too big, or exactly right, and in each case you know precisely which pointer to move.
Every move eliminates an entire set of pairs without checking them. The array is scanned once, giving O(n) — and it only works because sortedness makes the elimination provably safe.
target = 14
greyed cells are eliminated21 possible pairs. We will look at far fewer than that.
Step 1 of 7. The target is 14. A sorted array of seven values. The question: do any two of them sum to **14**? Brute force would check 21 pairs. Two pointers will answer in at most 7 steps.
Step 01 / 07
The target is 14
A sorted array of seven values. The question: do any two of them sum to **14**?
Brute force would check 21 pairs. Two pointers will answer in at most 7 steps.
/* Find a pair summing to target, in a SORTED array. */bool two_sum(int a[], int n, int target) { int lo = 0, hi = n - 1; while (lo < hi) { int sum = a[lo] + a[hi]; if (sum == target) return true; if (sum < target) lo++; /* need bigger → move left up */ else hi--; /* need smaller → move right down */ } return false;}/* The O(n²) version this replaces: */bool two_sum_slow(int a[], int n, int target) { for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (a[i] + a[j] == target) return true; return false;}