Two Sum II - Input Array Is Sorted
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 numbersindex1 and numbersindex2 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 so that there is exactly one solution, and you may not use the same element twice. Start pointers at both ends and converge them inward based on whether the current sum is too small or too large.
Constraints
- 2 ≤ numbers.length ≤ 3 × 104
- -1000 ≤ numbersi ≤ 1000
- numbers is sorted in non-decreasing order.
- -1000 ≤ target ≤ 1000
- The tests are generated such that there is exactly one solution.
Example
numbers = [2, 7, 11, 15], target = 9[1, 2]Explanation numbers0 + numbers1 = 2 + 7 = 9, so index1 = 1 and index2 = 2 (1-indexed).
Converge two pointers from both ends
left=2 (idx 0), right=15 (idx 3): sum = 17 > 9, move right inward.
What happens in this step
Steps to visualize
- Point left at the first element and right at the last.
- Compute the sum of the two pointed-at values.
- If the sum is too small, move left one step right to increase it.
- If the sum is too large, move right one step left to decrease it.
- Stop the moment the sum equals target and return the 1-indexed positions.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
left=2 (idx 0), right=15 (idx 3): sum = 17 > 9, move right inward.
What happens in this step
Solution
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];
} else if (sum < target) {
left++;
} else {
right--;
}
}
return [];
}- Time
- O(n)
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
numbers = [2, 7, 11, 15], target = 9 | [1, 2] | example from the docstring |
numbers = [1, 2], target = 3 | [1, 2] | smallest valid input: only two elements |
numbers = [-7, -3, 4, 9, 15], target = 6 | [2, 4] | negative and positive numbers mixed in the same array |
numbers = [-5, -2, -1, 3, 8], target = -6 | [1, 3] | a negative target value |
numbers = [0, 0, 3, 4], target = 0 | [1, 2] | duplicate values that themselves sum to the target |
numbers = [1, 3, 3, 6], target = 6 | [2, 3] | duplicate non-zero values that are the unique solution |