Sorted Pair Sum

EasyTwo Pointers≈ 15 min

You are given a list of integers nums, sorted from smallest to largest, and an integer target. At most one pair of numbers adds up to target.

Return the indices of the pair as [i, j] with i smaller than j, or an empty list [] if no pair adds up to target.

Examples

text
nums = [1, 3, 4, 6, 8], target = 11   →  [1, 4]
nums = [-3, 0, 2, 5], target = -1     →  [0, 2]
nums = [2, 2], target = 4             →  [0, 1]
nums = [1, 2, 4, 9], target = 7       →  []

Constraints

  • Between 2 and 10,000 numbers, sorted, not necessarily distinct.
  • At most one pair adds up to target; when none does, the answer is [].
  • Use the order: aim for O(n) time and O(1) extra memory.
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 4 visible cases here, in your browser. Submit runs all 9 on the judge, 5 of them hidden, and measures how your solution scales.