Reading preferences
Concept

Two Pointers

Use two positions to make progress through an ordered row.

two pointers, sorted, pairs, search

Two fingers on a row

Put one finger at each end of a sorted row of number cards. If the two cards add to too little, move the left finger to a larger card. If they add to too much, move the right finger to a smaller card.

A pointer here is simply a position in the row, not a physical arrow. The two-pointer pattern keeps two positions and moves them using a rule that does not throw away a possible answer.

Why use it and where it helps

Two pointers can find a pair with a target sum in a sorted row without checking every pair. Related techniques compare two sequences or move a slow and fast position through a sequence. Each problem needs its own movement rule.

Follow an example

Find two values that sum to 9 in [1, 2, 4, 7, 11].

LeftRightSumDecision
11112Too large; move right left
178Too small; move left right
279Found a pair

If even the smallest remaining value plus 11 is too large, no remaining pair using 11 can work. The same reasoning applies to a too-small left value.

See the reasoning

Follow the example one step at a time

Find a pair summing to 9 in a sorted row. This is a prepared teaching demonstration, not live code execution.

Check the ends

[1, 2, 4, 7, 11]
 L            R
1 + 11 = 12

12 is too large. With the smallest remaining value, 11 is already too big, so move the right pointer left.

Python illustration

def find_pair(numbers, target):
    left, right = 0, len(numbers) - 1
    while left < right:
        total = numbers[left] + numbers[right]
        if total == target:
            return (numbers[left], numbers[right])
        if total < target:
            left += 1
        else:
            right -= 1
    return None


print(find_pair([1, 2, 4, 7, 11], 9))
print(find_pair([], 9))

Prepared output — not live execution:

(2, 7)
None

The input must already be sorted in nondecreasing order. This returns one pair of values from distinct positions, or None, not all pairs or their original indices. Duplicate values can form a pair if they occupy two positions.

Time, space, and common mistakes

Each step moves one pointer inward, so this search takes O(n) time and O(1) extra space for n items. Sorting unsorted input first has its own cost and can change positions. Do not apply these movement rules to an unsorted row.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. Why must this pair-search example receive a sorted row?
2. If the end values sum to less than the target which pointer moves?
3. If the end values sum to more than the target which pointer moves?
4. What happens when fewer than two items are provided?

References and further reading