Free beta: 30 days of full access, no card needed.Sign up free

We use necessary cookies to run the site (sign-in and language). The contact and bug-report forms also use Google reCAPTCHA for spam protection, loaded only if you accept. Privacy policy

Field manual

Two pointers (opposite ends)

O(n)

Two indices start at the two ends of a sorted array and walk toward each other, deciding at each step which side to move.

Signals

sorted array (or you are allowed to sort)find a pair/triple with a target sumsqueeze from both ends (container, area)palindrome check

Template

function twoPointers(arr, target) {
    let lo = 0;
    let hi = arr.length - 1;
    while (lo < hi) {
        const sum = arr[lo] + arr[hi];
        if (sum === target) return [lo, hi];
        if (sum < target) lo++;
        else hi--;
    }
    return null;
}

Looks similar, isn't

  • Sliding window: A window keeps a contiguous span and grows/shrinks it under a condition. Opposite pointers converge to a single answer (a pair, an area) and never keep a span.
  • Hash set / map: Hashing finds a complement in unsorted data in O(n) time but O(n) space. Reach for two pointers only when the array is sorted and O(1) extra space matters.

n up to 1e5..1e6 and the array is sorted -> O(n): one linear pass, each pointer moves at most n steps. O(1) extra space.

Learn this pattern