3Sum
Medium · Two Pointers
You are given an array of integers. Find all distinct triplets of elements (by value, not index) whose sum is zero and return them as a list of triplets. Each triplet should be listed only once even if the same combination of values could be formed using different indices, and the order of triplets or values within a triplet does not matter. If no such triplet exists, return an empty list.
Examples
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Why: These are the only combinations of three numbers from the array that add up to zero, ignoring order and duplicate triplets.
Input: nums = [0,1,1]
Output: []
Why: No three numbers in this array sum to zero.
Input: nums = [0,0,0]
Output: [[0,0,0]]
Why: The three zeros sum to zero and there is only one such triplet possible.
Constraints
3 <= nums.length <= 3000, -100000 <= nums[i] <= 100000
Practise it by voice
Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.
This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of 3Sum. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.