Back to ArraysPair with Given Sum in Sorted Array
Medium

Pair with Given Sum in Sorted Array

MediumRecommendedTwo Pointers

Given an array sorted in non-decreasing order and a target sum, return the two values that add up to the target — or an empty array if no such pair exists.

Examples

Example 1

Input:
nums = [1,3,5,7,9], target = 10
Output:
[1,9]

Explanation: The two endpoints already sum to the target, so the pointers find them immediately with no movement needed.

Example 2

Input:
nums = [1,2,3,9], target = 8
Output:
[]

Explanation: No two values in the array sum to 8, so an empty array signals that no pair exists.

Example 3

Input:
nums = [1,1,2,3], target = 2
Output:
[1,1]

Explanation: Two different indices holding the same value still count as a valid pair.

Constraints

  • 2 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • nums is sorted in non-decreasing order
  • -10^9 <= target <= 10^9

Follow-up

How would the two-pointer sweep need to change if you had to return every distinct pair that sums to the target, not just one?

Loading editor…

Code execution is coming soon.