awelgorithms

The two pointers pattern: how to spot it

Updated

Two pointers walk the input from two places at once, usually the two ends of a sorted array or string, and each step rules out a whole set of answers. That is how an O(n²) pair search becomes O(n).

When to reach for it

The usual shape

left, right = 0, len(items) - 1
while left < right:
    total = items[left] + items[right]
    if total == target:
        return left, right
    if total < target:
        left += 1               # need bigger: drop the smallest
    else:
        right -= 1              # need smaller: drop the largest

4 LeetCode two pointers problems, easiest first

  1. Valid Palindrome easy

    Skip junk, lowercase, then close the gap. Mismatch is the answer.

  2. Two Sum II medium

    Sorted input: too small, advance left; too large, retreat right.

  3. 3Sum medium

    Sort, fix i, then two-sum the suffix. Skip duplicates at every pointer.

  4. Container With Most Water medium

    Area is limited by the shorter wall. Move that end; the other cannot help yet.

Skills these problems use

Each one has a free lesson with worked examples and a drill.

All two pointers lessons

check which skills you have 10 minutes, free, no account.

Other patterns