3Sum
Problem
Given an integer array nums, return all unique triplets [nums[i], nums[j], nums[k]] such that:
i,j, andkare distinctnums[i] + nums[j] + nums[k] == 0
Why The Brute Force TLEs
The direct approach checks every triple:
for i
for j
for k
That is O(n^3). It can pass many test cases, but it times out near the upper limits.
Using a Set<List<Integer>> also adds overhead:
- each valid triplet creates a list
- each list is sorted
- each list is hashed
- final result is streamed again
The main issue is still O(n^3), but the object creation makes it slower.
Optimized Idea
Sort the array first.
Then fix one number nums[i] and solve the remaining two-number problem using two pointers:
left = i + 1right = n - 1- target is
-nums[i]
If the sum is too small, move left. If the sum is too large, move right. If the sum matches, record the triplet and skip duplicates.
Complexity
| Approach | Time | Space |
|---|---|---|
| Brute force triples | O(n^3) | O(number of answers) |
| Sort + two pointers | O(n^2) | O(1) extra, excluding output |
Java Solution
import java.util.*;
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<>();
int n = nums.length;
for (int i = 0; i < n - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
if (nums[i] > 0) {
break;
}
int left = i + 1;
int right = n - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
result.add(Arrays.asList(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;
}
}
Duplicate Rules
Skip duplicate fixed values:
if (i > 0 && nums[i] == nums[i - 1]) continue;
After finding a valid triplet, skip duplicate left and right values before moving both pointers.
Key Pattern
When a problem asks for unique pairs or triplets and order does not matter:
- Sort first.
- Fix one value if needed.
- Use two pointers for the remaining pair.
- Skip duplicates at the same decision level.