#15 - 3Sum
Given an integer array nums, return all unique triplets [nums[i], nums[j], nums[k]] such that i ≠ j ≠ k and nums[i] + nums[j] + nums[k] === 0. The solution set must not contain duplicate triplets.
| Input | Output |
|---|---|
nums = [-1,0,1,2,-1,-4] | [[-1,-1,2],[-1,0,1]] |
nums = [0,1,1] | [] |
nums = [0,0,0] | [[0,0,0]] |
Solution Space
ts
/**
* Returns all unique triplets that sum to zero.
*
* @param nums Array of integers (may contain duplicates)
* @returns Array of unique triplets summing to 0
*/
export function threeSum(nums: number[]): number[][] {
const result: number[][] = [];
nums.sort((a, b) => a - b);
for (let i = 0; i < nums.length - 2; i++) {
// Skip duplicate values for the first element
if (i > 0 && nums[i] === nums[i - 1]) continue;
// Early termination: smallest possible sum already > 0
if (nums[i] > 0) break;
let left = i + 1;
let 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]]);
// Skip duplicates for both pointers
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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
Approach: sort + two-pointer – sort the array, iterate through it fixing one element, and use two pointers to find pairs that sum to the negative of the fixed element.
Time: O(n²) – outer loop O(n) × inner two-pointer scan O(n).
Space: O(1) extra – sorting is in-place; output space is not counted.
Alternative approaches:
| Approach | Idea | Time | Space |
|---|---|---|---|
| Hash-set | For each pair, check if -(a+b) exists in a set; use a Set<string> to deduplicate triplets. | O(n²) | O(n) |
| Brute force | Check all triples i < j < k. | O(n³) | O(1) |
Why sort + two-pointer is preferred:
- Sorting makes duplicate skipping trivial with simple
===checks on adjacent elements. - O(1) extra space vs. the hash-set approach which needs bookkeeping to avoid duplicate triplets.