Example 1
- Input
- numbers = [2,7,11,15], target = 9
- Output
- [1,2]
Values 2 and 7 at 1-based positions 1 and 2 sum to 9, the only valid pair.
Given a 1-indexed array numbers sorted in non-decreasing order and an integer target, find the two positions whose values add up to target and return them as [index1, index2]. Exactly one solution exists, no element may be used twice, and only constant extra space may be used.
Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers that add up to a specific integer target.
Return the two indices, each increased by one, as [index1, index2] with index1 < index2. Exactly one solution exists, the same element may not be used twice, and the solution must use only constant extra space.
2 <= numbers.length <= 3 * 10^4-1000 <= numbers[i] <= 1000numbers is sorted in non-decreasing order.-1000 <= target <= 1000Values 2 and 7 at 1-based positions 1 and 2 sum to 9, the only valid pair.
Values 2 and 4 at 1-based positions 1 and 3 sum to 6.
Values -1 and 0 at 1-based positions 1 and 2 sum to -1.
The two equal values occupy distinct positions and form the unique valid pair. Using one occurrence twice would be invalid.
The endpoint sum 1 + 6 is too small, so discard 1. Then 2 + 6 = 8 gives one-based indices 2 and 4.
Sorted order makes each sum comparison a safe elimination. In [2, 7, 11, 15] with target 9, the smallest plus largest is 17. Even the smallest value is too large to pair with 15, so 15 cannot participate; remove that endpoint. Repeating this leaves 2 and 7. Return their positions as 1 and 2 because the answer uses one-based indexing. Equal values may form the pair if they occupy different positions.
Reveal Brute Force: intuition, complexity, and code
1-based positions, so each pointer needs + 1 on the way out.On sorted input, opposite endpoints bound all remaining pair sums. Each comparison safely removes one impossible endpoint, yielding a linear scan with constant storage; this is elimination by order, not binary search.