Find all quadruplets summing to target
Company: Snapchat
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates competency in array algorithms, combinatorial search, and handling duplicates with index-uniqueness constraints, and falls under the Coding & Algorithms domain.
Constraints
- 0 <= len(nums) <= 2000
- -10^9 <= nums[i] <= 10^9
- -10^9 <= target <= 10^9
- Values may be negative and may repeat
- The number of returned quadruplets is manageable for the test data
Examples
Input: ([1, 0, -1, 0, -2, 2], 0)
Expected Output: [[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
Explanation: These are the three unique quadruplets that sum to 0.
Input: ([], 0)
Expected Output: []
Explanation: An empty array cannot provide four distinct indices.
Input: ([0, 0, 0, 0, 0], 0)
Expected Output: [[0, 0, 0, 0]]
Explanation: Although there are multiple ways to choose indices, there is only one unique quadruplet by value.
Input: ([2, 2, 2], 8)
Expected Output: []
Explanation: The values could sum to 8 only with four 2s, but there are only three elements, so four distinct indices are impossible.
Input: ([-2, -1, -1, 0, 0, 1, 1, 2], 0)
Expected Output: [[-2, -1, 1, 2], [-2, 0, 0, 2], [-2, 0, 1, 1], [-1, -1, 0, 2], [-1, -1, 1, 1], [-1, 0, 0, 1]]
Explanation: The array contains duplicates, so quadruplets like [-1, -1, 1, 1] are valid, but each unique value combination appears only once.
Hints
- Handle duplicates by thinking in terms of value counts rather than raw indices.
- A quadruplet can be viewed as two pairs whose sums add up to target. Store valid value-pairs by their sum, then combine complementary sums carefully.