The problem. Given an integer array nums, return all the unique triplets [a, b, c] taken from three different positions such that a + b + c = 0. The answer must not contain the same triplet twice, and the order of the triplets doesn't matter.
Input: nums = [-1, 0, 1, 2, -1, -4]
Output: [[-1, -1, 2], [-1, 0, 1]]
Input: nums = [0, 1, 1]
Output: []
Input: nums = [0, 0, 0]
Output: [[0, 0, 0]]There are two separate challenges here: finding triplets that sum to 0 fast, and making sure each triplet appears once, even when the array has repeated values.
Three nested loops try every combination of three positions. To drop duplicates, sort each triplet that works and keep it in a set.
function threeSum(nums) { const found = new Set(); // sorted triplets as "a,b,c", so duplicates collapse const n = nums.length; for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { for (let k = j + 1; k < n; k++) { if (nums[i] + nums[j] + nums[k] === 0) { found.add([nums[i], nums[j], nums[k]].sort((a, b) => a - b).join(",")); } } } } return [...found].map((key) => key.split(",").map(Number));}Time O(n³), space O(m) for the m triplets in the set. With 3,000 numbers (LeetCode's limit) that's about 4.5 billion triplets — far too slow.
Once nums[i] is fixed, we need two later numbers that add up to -nums[i] — that's Two Sum. As j walks forward, a hash set of the values between i and j tells us in O(1) whether the third number, -nums[i] - nums[j], has already appeared.
function threeSum(nums) { const found = new Set(); // sorted triplets as "a,b,c", so duplicates collapse for (let i = 0; i < nums.length; i++) { const seen = new Set(); // values between i and j for (let j = i + 1; j < nums.length; j++) { const need = -nums[i] - nums[j]; // the third value that makes 0 if (seen.has(need)) { found.add([nums[i], nums[j], need].sort((a, b) => a - b).join(",")); } seen.add(nums[j]); } } return [...found].map((key) => key.split(",").map(Number));}Time O(n²), space O(n + m). One whole loop is gone. But we still lean on hashing twice — a set per i to find the third number, and another set to throw away duplicate triplets.
Sort the array first. Two good things happen at once:
nums[i], the pair can be found with two pointers instead of a hash set: left starts just after i, right at the end. Sum too small? Only a bigger left value helps: left++. Too big? right--.nums[i] equals the value before it, every triplet it could start has already been found. After recording a triplet, also step left past copies of the same value.Watch the duplicate skips: the second -1 as i is skipped entirely. Try [0, 0, 0, 0], or an input with no answer.
Time O(n²), space O(1) extra, apart from the sort and the output. Sorting costs O(n log n), and each fixed i squeezes the rest of the array once. A small extra speed-up: once nums[i] > 0, every later number is positive too, so you can break.
O(n³)Three nested loops: about n³/6 triplets.
O(m)The set holding the m unique triplets found.
Here m is the number of triplets found. The optimal and best solutions share O(n²) time — the best one wins by dropping both hash sets, which makes it faster in practice and lighter on memory.
[0, 1, 1] returns [].[0, 0, 0, 0] returns [[0, 0, 0]] exactly once.[-2, 0, 0, 2, 2] returns [[-2, 0, 2]] once, not twice.[]; the loop never starts.The same "fix one, squeeze the rest" structure solves 3Sum Closest and 4Sum (fix two, squeeze the rest: O(n³)).
O(n²)For each of the n fixed numbers, one O(n) pass with O(1) set lookups.
O(n + m)A set of up to n values per pass, plus the m triplets.
O(n²)The sort is O(n log n); then each fixed i squeezes the rest once in O(n).
O(1)Only pointers, beyond the sort and the output.