Beginner 5 min

Two pointers

Two pointers keep track of two useful positions while you scan data.

How it works

Trace the candidates you can rule out after each move. When the sum is too small, the current left item cannot work with any smaller right item. When it is too large, the current right item cannot work with any larger left item. Each step removes one position from consideration, so the scan is linear.

Walk through an example

For a sorted list [1, 3, 6, 8] and target 9, start at the ends. The sum is 9, so you found a pair. If the sum is too small, move the left pointer toward larger values.

What to watch for

That movement rule depends on sorted input. With unsorted data, a lookup set can preserve original positions and still find a pair.

Code example

def has_pair(a, target):
    left, right = 0, len(a) - 1
    while left < right:
        total = a[left] + a[right]
        if total == target: return True
        if total < target: left += 1
        else: right -= 1
    return False

Check your understanding

Which distinct pair reaches the target?

See the example and explanation
Worked example
Given [1, 2, 5, 8], target 7
Answer 2 + 5

Start with 1 + 8 = 9 and move right to 5. Then 1 + 5 = 6, so move left to 2 to get 7.

Open practice problem
Next lessonSliding windows