CodingNodes / Two Pointers / Two Sum II Input Array Is Sorted System design Space play · ←→ step · R restart

Problem

You are given an array numbers sorted in non-decreasing order and an integer target. Find two different positions whose values add up to target.

Return the two positions as [a, b] with a < b, counting positions from 1, not 0. Exactly one valid pair exists, and you may not use the same element twice. Use only constant extra space.

Constraints

  • 2 ≤ numbers.length ≤ 3 · 10⁴
  • −1000 ≤ numbers[i] ≤ 1000, sorted non-decreasing
  • −1000 ≤ target ≤ 1000
  • Exactly one solution exists

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(1)

Time: Each step moves left right or right left, so there are at most n - 1 steps before the pointers meet.

Space: Only two indexes and one running sum are stored.

Because the array is sorted, the ends give the extremes. Add numbers[left] and numbers[right]. If the sum is too small, only moving left right can raise it. If it is too big, only moving right left can lower it. This never skips a valid pair.