Skip to content
IT glossary
AlgorithmsUpdated December 3, 2026

Two pointers

Два указателя

An algorithm technique that tracks two positions and moves them according to the problem’s rules. It often lets you scan an array, string, or list without checking every possible pair.

What are the two pointers?

A pointer here is a position you can move: usually an index into an array or string, or a reference to a node in a linked list. The useful part is the rule for moving it. For instance, when checking whether a string reads the same backward and forward, compare its first and last characters. If they match, move inward: those characters need no further checks.

Common ways to move them

  • From opposite ends: move one or both positions inward. This works for palindrome checks and for finding a target sum in a sorted array.
  • Forward with different jobs: a read index examines every item while a write index advances only when there is something to keep. This is useful for filtering an array in place.
  • Forward at different speeds: a slow reference follows one link per step and a fast reference follows two. This lets you find the middle of a linked list or detect a cycle.

Two positions alone do not make an algorithm linear. To justify linear time for an array scan, show that the positions make only O(n) moves in total and that each iteration does constant work. If one position resets for every move of the other, you may still be doing a quadratic search.

Example: find two values that add to a target

Given an array sorted in nondecreasing order, return two distinct indices, or None if there is no match:

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

Suppose the array is [1, 3, 4, 7, 10] and the target is 11. The first pair happens to work. With a target of 10, the first sum is too high: 1 is already the smallest available partner for 10, so no pair using that rightmost value can work. Move hi left. Now 1 + 7 is too low, and 7 is the largest remaining partner for 1, so move lo right. That leaves 3 + 7, a match. Each move shrinks the gap by one, giving O(n) time and O(1) extra space for the search.

What interviewers look for

Explain why a move rules out candidates without skipping a valid answer. Then state the assumptions: the input is sorted, and lo < hi ensures that the indices are distinct even if their values are equal. If you sort an unsorted input first, include the sorting cost and preserve the original indices if the task asks for them.

A sliding window also uses two positions, but they mark a contiguous range whose contents matter, often because you maintain a sum or a frequency table for that range. In the pair-sum example, only the values at the two positions contribute to the sum.