01
Problem Statement
Given a 1-indexed array of integers numbers that is sorted in non-decreasing order and an integer target, find two numbers that add up to target. Return the indices of the two numbers as [index1, index2] where 1 <= index1 < index2. Exactly one solution exists; you may not use the same element twice.
- 1-indexed means the first element has index 1 (so return
[left+1, right+1]when using 0-based indices). - The array is sorted, so we can use two pointers without extra space.
02
Key Observations
- Because the array is sorted, a two-pointer approach works: put one pointer at the start (smallest) and one at the end (largest). If the sum is too small, the only way to increase it is to move the left pointer right (to a larger value). If the sum is too large, move the right pointer left (to a smaller value). So we never miss the pair.
- When
left < right: ifnumbers[left] + numbers[right] == target, we are done; if the sum is less than target,left++; elseright--. Each step eliminates a candidate and we are guaranteed to find the unique pair.
03
Approach
High-level: Use two pointers left = 0 and right = n - 1. If the sum equals target, return [left+1, right+1]. If the sum is less than target, increment left; if greater, decrement right. Repeat until the pair is found.
Steps:
left = 0,right = numbers.length - 1.- While
left < right:sum = numbers[left] + numbers[right]. Ifsum == target, return[left+1, right+1]. Ifsum < target,left++; elseright--. - (Guaranteed to find.)
04
Implementation
Java
public int[] twoSum(int[] numbers, int target) {
int left = 0, right = numbers.length - 1;
while (left < right) {
int sum = numbers[left] + numbers[right];
if (sum == target) {
return new int[]{left + 1, right + 1};
}
if (sum < target) {
left++;
}
else {
right--;
}
}
return new int[]{};
}05
Test Cases
Example 1
Input
numbers = [2,7,11,15], target = 9
Expected
[1,2]Explanation
2+7=9.
06
Complexity Analysis
- Time: O(n).
- Space: O(1).
07
Follow-ups
- Three sum: find all triplets that sum to 0.