Find all unique triplets in the array which gives the sum of zero.
Problem Statement
Examples
Input: nums = [-1, 0, 1, 2, -1, -4]
Output: [[-1, -1, 2], [-1, 0, 1]]
Explanation: Combining the input according to 3 Sum logic yields [[-1, -1, 2], [-1, 0, 1]].
Input: nums = [0, 1, 1]
Output: []
Explanation: No matching element or subarray exists, so the output is empty.
Input: nums = [0, 0, 0]
Output: [[0, 0, 0]]
Explanation: Combining the input according to 3 Sum logic yields [[0, 0, 0]].
Complexity
Time Complexity: O(N²)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
Sorting the array in O(N log N) allows solving the remainder with the two-pointer technique in O(N²). For each element nums[i], we search for pairs in the remaining subarray that sum to -nums[i]. Duplicate skipping prevents redundant triplets.
Step-by-Step Approach
- Sort
numsin ascending order. - Loop
ifrom0tonums.length - 3. - If
i > 0 && nums[i] === nums[i - 1], skip to prevent duplicates. - Use
left = i + 1andright = nums.length - 1. - While
left < right: - If
sum === 0, add[nums[i], nums[left], nums[right]], advance both pointers while skipping duplicates. - If
sum < 0,left++; ifsum > 0,right--. - Return
result.
Optimal Implementation (JavaScript)
function threeSum(nums) {
nums.sort((a, b) => a - b);
const result = [];
for (let i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] === nums[i - 1]) continue;
let left = i + 1, right = nums.length - 1;
while (left < right) {
const sum = nums[i] + nums[left] + nums[right];
if (sum === 0) {
result.push([nums[i], nums[left], nums[right]]);
while (left < right && nums[left] === nums[left + 1]) left++;
while (left < right && nums[right] === nums[right - 1]) right--;
left++;
right--;
} else if (sum < 0) left++;
else right--;
}
}
return result;
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- Array of all zeroes: returns [[0, 0, 0]].
- No valid triplet sums to 0: returns [].
- Array length < 3: returns [].