AceYourInterviews
Checking sign-in…

14. Two Sum in a Sorted Array

IntermediateSorted two-pointer elimination

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.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Eliminate small and large endpoint sums

[-5,-2,0,7,9]
5
[1,3]