Skip to content
GKgkml.dev
← Pattern lab

Two pointers

Walk two indices toward each other, or one behind the other, in a single pass.

The tell: The input is sorted (or can be sorted) and you are looking for a pair, a triple, or a partition.

Reach for it when

  • Pair summing to a target in a sorted array
  • Removing duplicates or zeros in place
  • Palindrome checks
  • Merging two sorted sequences
  • 3-sum / 4-sum after sorting

Reference implementation

pair_sum — sorted array, target sum
def pair_sum(nums: list[int], target: int) -> tuple[int, int] | None:
    """nums must be sorted ascending. Returns the two indices, or None."""
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        total = nums[lo] + nums[hi]
        if total == target:
            return lo, hi
        if total < target:
            lo += 1        # need a bigger number
        else:
            hi -= 1        # need a smaller number
    return None

Complexity: O(n) time after an O(n log n) sort, O(1) extra space.

What goes wrong

  • Using `lo <= hi` instead of `lo < hi` lets an element pair with itself.
  • Forgetting to skip duplicates in 3-sum, which produces repeated triples.
  • Sorting when the problem asks for original indices — sort (value, index) pairs instead.

Practise on

  • Two Sum II
  • 3Sum
  • Container With Most Water
  • Remove Duplicates from Sorted Array
  • Valid Palindrome