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]
Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2.
Input: numbers = [2,3,4], target = 6
Output: [1,3]
Explanation: The sum of 2 and 4 is 6. Therefore, index1 = 1, index2 = 3.
Input: numbers = [-1,0], target = -1
Output: [1,2]
Explanation: The sum of -1 and 0 is -1. Therefore, index1 = 1, index2 = 2.
Since the array is already sorted, we can use two pointers to efficiently find the pair. Unlike the original Two Sum problem which requires a hash map, the sorted property allows us to use O(1) space.
The key insight is:
This is a classic Two Pointers pattern problem with these characteristics:
left = 0 and right = length - 1currentSum = numbers[left] + numbers[right]currentSum == target: Return [left + 1, right + 1] (1-indexed)currentSum < target: Move left++ (need larger number)currentSum > target: Move right-- (need smaller number)1class Solution {
2 public int[] twoSum(int[] numbers, int target) {
3 // Initialize two pointers at both ends
4 int left = 0;
5 int right = numbers.length - 1;
6
7 // Continue until we find the answer
8 while (left < right) {
9 int currentSum = numbers[left] + numbers[right];
10
11 if (currentSum == target) {
12 // Found the pair! Return 1-indexed positions
13 return new int[]{left + 1, right + 1};
14 } else if (currentSum < target) {
15 // Sum too small, need larger number
16 left++;
17 } else {
18 // Sum too large, need smaller number
19 right--;
20 }
21 }
22
23 // Should never reach here per problem constraints
24 return new int[]{-1, -1};
25 }
26}
27