Apply opposite-direction pointers to find a target pair in a sorted array.
Find the target pair in the sorted array. JavaScript and Python start array indices at 0. The answer counts positions starting at 1, so add 1 to each index when you return it.
Use constant extra space
Find the pair with two pointers and O(1) extra space without building a lookup map. Use the array's sorted order to decide which pointer should move after each sum. Handle negative and duplicate values.
Run the examples before submitting.
Given an array of integers sorted in non-decreasing order and a target, find two elements at distinct indices whose sum equals the target. Their values may be equal.
Return their positions as [index1, index2] in ascending order, counting the first position as 1.
2 ≤ numbers.length ≤ 30,000Results appear here after a run.
Start left at the first element and right at the last. If the sum is too small, even the largest remaining partner falls short for numbers[left], so move left one step right. If the sum is too large, even the smallest remaining partner makes the sum too large for numbers[right], so move right one step left.
In the figure, the values 2 and 11 match the target at zero-based indices 1 and 4. They are the second and fifth elements, so [left + 1, right + 1] gives [2, 5].
function twoSumSorted(numbers, target) {
let left = 0;
let right = numbers.length - 1;
while (left < right) {
const sum = numbers[left] + numbers[right];
if (sum === target) return [left + 1, right + 1];
if (sum < target) left++;
else right--;
}
return [];
}| Measure | Complexity | Explanation |
|---|---|---|
| Time | O(n) | Each check either returns the answer or moves one pointer inward. There are at most n - 1 checks. |
| Auxiliary space | O(1) | Only two pointer indices and the current sum are stored. |