Find all unique triplets summing to zero
Company: NVIDIA
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: This question evaluates array-based algorithm design, handling of duplicate results, and analysis of time and space complexity when producing unique triplets that sum to zero.
Constraints
- 0 <= len(nums) <= 3000
- -100000 <= nums[i] <= 100000
Examples
Input: ([-1, 0, 1, 2, -1, -4],)
Expected Output: [[-1, -1, 2], [-1, 0, 1]]
Explanation: The only unique triplets that sum to zero are [-1, -1, 2] and [-1, 0, 1].
Input: ([0, 0, 0, 0],)
Expected Output: [[0, 0, 0]]
Explanation: Even though there are multiple ways to choose three zeros, they all form the same triplet, so it appears once.
Hints
- Sorting the array helps you avoid duplicates and makes it possible to use a two-pointer scan.
- Fix one number, then look for two remaining numbers whose sum equals its negation.