Find a Pair That Sums to a Target in a Sorted Array

Implement pairWithTargetSum

Given an integer array nums sorted in non-decreasing order and an integer target, find the one pair of elements whose values add up to target, and return their positions as a 1-indexed pair [index1, index2] with index1 < index2. Exactly one valid pair exists. Since the array is already sorted, you don't need extra space or a second pass — a two-pointer sweep from both ends finds the pair in a single O(n) pass.

Example 1:

Input: nums = [2,5,9,11,14], target = 20

Output: [3,4]

Example 2:

Input: nums = [-4,-1,0,3,7], target = 6

Output: [2,5]

Example 3:

Input: nums = [1,2], target = 3

Output: [1,2]

+ 4 hidden test cases run on Submit.

Constraints:

  • 2 ≤ nums.length ≤ 10⁵
  • -10⁶ ≤ nums[i] ≤ 10⁶
  • nums is sorted in non-decreasing order
  • Exactly one valid pair exists

nums =

[2, 5, 9, 11, 14]

target =

20