Find Unique Target-Sum Pairs
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: easy
Interview Round: Technical Screen
Quick Answer: This question evaluates array-processing skills, correctness in handling duplicate values, and the ability to identify unique value pairs whose sums meet a numeric constraint, with attention to edge cases and result deduplication.
Part 1: Find All Unique Target-Sum Pairs
Constraints
- 0 <= len(nums) <= 200000
- -10^9 <= nums[i] <= 10^9
- -10^9 <= target <= 10^9
Examples
Input: ([1, 2, 3, 4, 2, 3], 5)
Expected Output: [[1, 4], [2, 3]]
Explanation: The pairs that sum to 5 are (1,4) and (2,3). Even though 2 and 3 appear multiple times, [2, 3] is included only once.
Input: ([2, 2, 2, 2], 4)
Expected Output: [[2, 2]]
Explanation: There are many index combinations, but only one unique value pair: [2, 2].
Input: ([], 7)
Expected Output: []
Explanation: An empty array has no pairs.
Input: ([-2, -1, 0, 1, 2, 3], 1)
Expected Output: [[-2, 3], [-1, 2], [0, 1]]
Explanation: These are all unique pairs whose sums equal 1, already sorted lexicographically.
Input: ([5], 5)
Expected Output: []
Explanation: A single element cannot form a pair.
Hints
- Sort the array first. Then compare the sum of the leftmost and rightmost values to the target.
- When you find a valid pair, skip over repeated values on both sides so the same pair is not added again.
Part 2: Find All Unique Target-Sum Triplets
Constraints
- 0 <= len(nums) <= 3000
- -10^9 <= nums[i] <= 10^9
- -10^9 <= target <= 10^9
Examples
Input: ([-1, 0, 1, 2, -1, -4], 0)
Expected Output: [[-1, -1, 2], [-1, 0, 1]]
Explanation: The only unique triplets summing to 0 are [-1, -1, 2] and [-1, 0, 1].
Input: ([0, 0, 0, 0], 0)
Expected Output: [[0, 0, 0]]
Explanation: Although there are multiple ways to pick three zeroes, they all form the same triplet [0, 0, 0].
Input: ([1, 2, 3, 4], 50)
Expected Output: []
Explanation: No three values sum to 50.
Input: ([], 0)
Expected Output: []
Explanation: An empty array cannot contain any triplet.
Input: ([1, 1, 2, 2, 3, 3, 4], 8)
Expected Output: [[1, 3, 4], [2, 2, 4], [2, 3, 3]]
Explanation: The unique triplets that sum to 8 are [1, 3, 4], [2, 2, 4], and [2, 3, 3].
Hints
- Sort the array and fix one value at a time. For the remaining part of the array, use two pointers to find complementary pairs.
- To avoid duplicate triplets, skip repeated values both for the fixed index and after finding a valid triplet.