Two Sum II Input Array Is Sorted
Medium · Two Pointers
You are given a list of integers that is already sorted in non-decreasing order, along with a target value. Find the two distinct positions (1-indexed) whose values add up exactly to the target, and return them as a two-element list with the smaller index first. You may assume exactly one valid pair exists, and you cannot use the same element twice.
Examples
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Why: numbers[0] + numbers[1] = 2 + 7 = 9, so the 1-indexed positions are 1 and 2.
Input: numbers = [2,3,4], target = 6
Output: [1,3]
Why: numbers[0] + numbers[2] = 2 + 4 = 6, giving positions 1 and 3.
Input: numbers = [-1,0], target = -1
Output: [1,2]
Why: numbers[0] + numbers[1] = -1 + 0 = -1, giving positions 1 and 2.
Constraints
2 <= numbers.length <= 3*10^4, -1000 <= numbers[i] <= 1000, numbers is sorted in non-decreasing order, -1000 <= target <= 1000, exactly one valid answer exists
Practise it by voice
Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.
Practise Two Sum II Input Array Is Sorted
This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Two Sum II Input Array Is Sorted. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.