167 - Two Sum II - Input Array Is Sorted
Wednesday, 16 September 2026
Two pointers from both ends of the sorted array, dropping whichever end can no longer be part of the pair.
Problem
Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find
two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length.
Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.
The tests are generated such that there is exactly one solution. You may not use the same element twice.
Your solution must use only constant extra space.
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Input: numbers = [2,3,4], target = 6
Output: [1,3]
Input: numbers = [-1,0], target = -1
Output: [1,2] Constraints:
2 <= numbers.length <= 3 * 10^4-1000 <= numbers[i] <= 1000numbersis sorted in non-decreasing order.-1000 <= target <= 1000- The tests are generated such that there is exactly one solution.
Approach
Start with l at the first element and r at the last, and look at sum = numbers[l] + numbers[r].
sum == target: found it, return{l + 1, r + 1}.sum < target:numbers[r]is the largest value still in range, and even that isn’t enough fornumbers[l]. Sonumbers[l]can’t be in the answer with any element. Drop it:l++.sum > target:numbers[l]is the smallest value still in range, and even that is too much fornumbers[r]. Sonumbers[r]can’t be in the answer. Drop it:r--.
numbers = [2, 7, 11, 15], target = 9
l = 0, r = 3 -> 2 + 15 = 17 > 9 -> r--
l = 0, r = 2 -> 2 + 11 = 13 > 9 -> r--
l = 0, r = 1 -> 2 + 7 = 9 -> return [1, 2] class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int l = 0, r = numbers.size() - 1;
while (l < r) {
int sum = numbers[l] + numbers[r];
if (sum == target) return {l + 1, r + 1};
if (sum < target) l++;
else r--;
}
return {};
}
}; - time:
O(n)— every step moves one pointer inward, so at mostn - 1steps - space:
O(1)— just the two pointers