Skip to content
GKgkml.dev
← Problem set
#167MediumTwo pointers

Two Sum II — Input Array Is Sorted

The tell: Sorted input and a target pair, with O(1) space demanded.

How you get there

  1. 1Sorted order means the sum moves predictably as either pointer moves.
  2. 2If the sum is too small the only way up is to advance the left pointer.
  3. 3If it is too large, retreat the right pointer. Neither ever needs to backtrack.

Solution

Python
def two_sum(numbers: list[int], target: int) -> list[int]:
    lo, hi = 0, len(numbers) - 1
    while lo < hi:
        total = numbers[lo] + numbers[hi]
        if total == target:
            return [lo + 1, hi + 1]     # problem uses 1-based indices
        if total < target:
            lo += 1
        else:
            hi -= 1
    return []
Time
O(n)
Space
O(1)

What goes wrong

Using `lo <= hi` allows an element to pair with itself.