Target Sum Pairs
EasyHash Set · Cisco
Given an integer array nums and an integer target, find every distinct pair of values [a, b] with a <= b and a + b == target, where a and b come from two different positions in nums.
- Pairs are distinct by value, not by position: if
[2, 5]can be formed in several ways it is still listed once. - A pair of equal values
[v, v]requiresvto appear at least twice innums.
Return the pairs sorted in ascending order by a (since a + b is fixed, this also orders them by b). Return an empty list if there are none. Do not modify nums.
Example 1
- Input:
- nums = [4, 1, 6, 3, 3, 5, 2, 7, 3], target = 6
- Output:
- [[1, 5], [2, 4], [3, 3]]
- Explanation
- 1 + 5, 2 + 4 and 3 + 3 all make 6. The value 3 appears three times, but
[3, 3]is listed once. 6 and 7 have no partner, since 0 and -1 are not in the array.
Example 2
- Input:
- nums = [5, 5, -2, 12, 0, 10], target = 10
- Output:
- [[-2, 12], [0, 10], [5, 5]]
- Explanation
- -2 pairs with 12, 0 with 10, and the two 5s pair with each other. Sorted by first value, that gives -2, 0, 5.
Example 3
- Input:
- nums = [3], target = 6
- Output:
- []
- Explanation
- A single 3 cannot be used twice, so there is no pair.
Constraints
0 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9-2 * 10^9 <= target <= 2 * 10^9