Reqflow
Two Pointers·Beginner

Two Pointers: Pair Sum

Time O(n)Space O(1)
·

Given a sorted array, find two numbers that add up to a target. The brute force way checks every pair, which is quadratic. The two-pointer trick starts with one pointer at each end and moves them inward: if the sum is too large you move the right pointer left, if it is too small you move the left pointer right. Each number is visited at most once, so the whole thing runs in linear time.

Example: Find two numbers that sum to 10 in a sorted array.

When to use this

See also

← All algorithms