Practice · Two pointers · 3 of 5

Pair Sum in a Sorted List

You are given a list of integers nums, sorted from smallest to largest (equal neighbours are allowed), and an integer target. Find two different positions i and j whose numbers add up to target, and return them as [i, j] with i < j. Indices count from 0.

At least one such pair exists; if several do, any one of them is accepted. Try to use only a constant amount of extra memory.

Example 1

Input
nums = [1, 3, 4, 6, 9], target = 10
Output
[0, 4]
1 + 9 is 10. [2, 3] (4 + 6) would be accepted too.

Example 2

Input
nums = [-5, -2, -2, 7], target = -4
Output
[1, 2]
Equal numbers at two different positions are fine.

Constraints

  • nums holds 2 to 3 × 10⁴ numbers, sorted in non-decreasing order.
  • Every number is between −10⁹ and 10⁹.
  • At least one pair adds up to target.