Loading TechCookies content…
Two-pointer is the first pattern that feels like an insight. Given a sorted array, you need to find a pair of values with some property (e.g., sum to a target). Brute force checks every pair: O(n²).
The insight: sorted order makes pointer movement predictable. If the sum is too small, only a larger left value can help. If too large, only a smaller right value can help. No useful pair is ever skipped.
This converts O(n²) into O(n) with just two integer variables.
The signal to recognise this pattern:
let left = 0, right = arr.length - 1;
while (left < right) {
const val = compute(arr[left], arr[right]);
if (val === target) return [left, right];
if (val < target) left++; // need a bigger value
else right--; // need a smaller value
}
Trace it on arr = [1, 3, 5, 8, 11], target = 13:
| left | right | sum | decision |
|---|---|---|---|
| 0 (1) | 4 (11) | 12 | too small → left++ |
| 1 (3) | 4 (11) | 14 | too large → right-- |
| 1 (3) | 3 (8) | 11 | too small → left++ |
| 2 (5) | 3 (8) | 13 | ✓ found — return [2, 3] |
Four iterations instead of checking all ten pairs.