Problem-solving patterns · 12 min

Two pointers: from n² pairs to n steps

Use the order of a sorted array to rule out a value with every comparison.

01Why it matters

Do you really need to check every pair?

Given a list of prices and a gift card, is there a pair of items that spends it exactly? The obvious answer tries every pair: with nn items that is n(n−1)2\tfrac{n(n-1)}{2} pairs, about 5,000 for 100 items and 50 million for 10,000.

If the prices are sorted, you can do it in at most n−1n - 1 checks. The trick is to stop thinking about pairs and start thinking about ruling values out.

02Key parts

The pieces you will see

L and R
Two indices: L starts at the smallest value, R at the largest. They only ever move inward.
sum
A[L] + A[R], compared with the target at every step.
ruled out
A value that cannot be part of any answer, given what we know. Each step rules out exactly one.
still possible
The positions between L and R: any answer must lie entirely inside them.

03See it work

Watch values get ruled out

Each step compares one pair and rules out the smaller or the larger value, with the reason in the narration.

The reasoning is the whole algorithm:

  • If A[L] + A[R] is too small, then A[L] plus anything still possible is too small, because A[R] is the largest thing left. So A[L] can't be in any answer: move L right.
  • If the sum is too big, A[R] plus anything still possible is too big, because A[L] is the smallest thing left. So A[R] is out: move R left.

04Predict

Your turn: which pointer moves?

Make 5 predictions: step forward and answer each question before the next step plays.

0 of 5 made

05Try it

Try the edge cases

Pick "Pair at the ends" and count the checks: one. Pick "No pair" and watch L and R meet. Then make up your own sorted list and target in the input box.

06Check yourself

Check yourself

  1. Question 1 of 4

    A = [1, 4, 6, 9, 13], target 15. L = 0, R = 4: the sum is 1 + 13 = 14. What happens?

    Your answer comes back in Review in a few days, so it sticks.

  2. Question 2 of 4

    For 1,000 sorted values, at most how many sums does two pointers check?

  3. Question 3 of 4

    Why is it safe to move R left when the sum is too big?

  4. Question 4 of 4

    A = [7, 2, 9, 4] is not sorted and the target is 6. Does two pointers from the ends find 2 + 4?

07Explain it back

Say it in your own words

How do two pointers find a pair with a given sum in a sorted array without checking every pair, and why can they never miss it?

08Recap

What to remember

  • Two pointers use order to rule out one value per step, turning O(n²) pair checks into O(n).
  • The invariant: any answer lies inside [L, R].
  • The same shape solves 3Sum (fix one value, two-pointer the rest), container with most water, and removing duplicates in place.
  • Next: the sliding window keeps two pointers moving in the same direction instead of toward each other.
Back to path