Two Sum II – Input Array Is Sorted
Problem
The array is sorted in ascending order. Return the 1-based indices of the two numbers that add up to target (exactly one solution exists), using O(1) extra space.
Example 1
Input: numbers = [2, 7, 11, 15], target = 9 Output: [1, 2]
Test cases
Case 1
Input: [2,7,11,15], 9 Expected: [1,2]
Case 2
Input: [2,3,4], 6 Expected: [1,3]
Case 3
Input: [-1,0], -1 Expected: [1,2]
View solutionHide solution1 approach
1. Two pointers from both ends
Time O(n)Space O(1)
Sum too small → move left up; too big → move right down. Sorting guarantees nothing is skipped. Answer is 1-indexed.
function twoSum(numbers, target) { let l = 0, r = numbers.length - 1; while (l < r) { const s = numbers[l] + numbers[r]; if (s === target) return [l + 1, r + 1]; s < target ? l++ : r--; } return [];}