D · Pupil · 15 min

Two Pointers: Shrink the Search

When a range or a pair has a monotonic invariant, you can walk two indices in O(n) instead of checking O(n²) pairs.

The two-pointer method is an invariant wearing running shoes. You keep two indices — often left and right — and you only move them forward. Each element enters and leaves the window a constant number of times, so the whole scan is linear.

It is not a magic pair of indices. It works when there is a reason you never need to move a pointer backwards.

Sorted two-sum, one pass after sortjs
function twoSumSorted(a, target) {
  let L = 0;
  let R = a.length - 1;
  while (L < R) {
    const s = a[L] + a[R];
    if (s === target) return [L, R];
    if (s < target) L++;
    else R--;
  }
  return null;
}

TRACE

a = [1, 2, 4, 7, 11, 15], target = 15. Watch L and R.

Start

L = 0 (1), R = 5 (15). Sum = 16 > 15. R moves left.

16 is too big → R--

1 / 4

Sliding windows are two pointers plus a payload: the sum of the window, a frequency map, the number of unique characters, a max deque. You expand right every step, and you shrink left while the window is illegal. Same O(n) tax.

CHECK

Why does two-pointer pair-sum fail on an unsorted array?

CHECK

You want the longest subarray with sum ≤ k on an array of positive numbers. After adding a[right] makes the sum too big, what do you do?

Checks 0/2

Next lesson