Given a 1-indexed array of integers sorted in non-decreasing order, find two numbers that add up to target and return their indices [index1, index2] (1-indexed). Use only constant extra space.
Start at both ends. Since the array is sorted, a sum that is too small can only grow by moving l right, and a sum that is too big can only shrink by moving r left.
1function twoSum(numbers: number[], target: number): number[] {2let l = 0, r = numbers.length - 1;3while (l < r) {4const sum = numbers[l] + numbers[r];5if (sum === target) return [l + 1, r + 1];6if (sum < target) l++;7else r--;8}9return [];10}
l at the smallest value, r at the largest.
Space: play/pause · ←/→: step