14. Two Sum in a Sorted Array
Choose two distinct positions in the already sorted array whose values add up to the target. Use the existing order of the values rather than rearranging the input.
Repeated values can form an answer when they occupy separate positions. Follow the documented index convention and missing-answer representation for this course.
Example 1
Input
nums=[1,3,5,8], target=9
Output
[0,3]
Explanation: 1+8 is nine using distinct zero-based positions.
Example 2
Input
nums=[2,2], target=4
Output
[0,1]
Explanation: Equal values are valid when they occupy different positions.
Constraints
0 <= nums.length <= 105-231 <= nums[i] <= 231 - 1-263 <= target <= 263 - 1- nums is sorted in nondecreasing order. Return zero-based increasing indices, or an empty array if no pair exists.
Hints
Hint 1
What is the largest partner available for the current left value?
Hint 2
If even that sum is too small, can left occur in a solution?
Hint 3
Move left on small sums and right on large sums.
Submissions
Your recent submissions for this problem.
Checking sign-in…
Discussion
Ask a question or share an approach. Posts are public; avoid personal information and mark solution spoilers clearly.
No discussion yet. Start the conversation with a question about this problem.
Checking sign-in…
Run your code to check the sample cases, or submit it to check the full validation suite.
Eliminate small and large endpoint sums
[-5,-2,0,7,9]
5
[1,3]