You are given an array of integers numbers sorted in non-decreasing order and an integer target. Find the two elements whose values add up to target and return their positions as a list [index1, index2], where positions are 1-based (the first element is at position 1) and index1 < index2.
Each input has exactly one valid pair of positions. You may not use the same element twice.
Your solution must use only constant extra space.
Function Signature
def two_sum_sorted(numbers: list[int], target: int) -> list[int]:
Rules
-
Positions are 1-based. If the pair is at 0-based indices
i < j
, return
[i + 1, j + 1]
.
-
The two positions must be different, and the smaller position comes first.
-
Extra space beyond the returned list must be O(1).
Constraints
-
2 <= len(numbers) <= 3 * 10^4
-
-1000 <= numbers[i] <= 1000
-
numbers
is sorted in non-decreasing order.
-
-1000 <= target <= 1000
-
Exactly one valid pair exists.
Examples
Input: numbers = [2, 7, 11, 15], target = 9
Output: [1, 2]
2 + 7 = 9, and the values 2 and 7 are at positions 1 and 2.
Input: numbers = [2, 3, 4], target = 6
Output: [1, 3]
2 + 4 = 6, so the answer is positions 1 and 3. Adding 3 to itself also gives 6, but that would use the element at position 2 twice, which is not allowed.
Input: numbers = [-3, -1, 0, 2, 5], target = 1
Output: [2, 4]
-1 + 2 = 1, and -1 and 2 are at positions 2 and 4. No other pair of elements sums to 1.