Problem Statement
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
The solution set must not contain duplicate triplets.
Approach: Sorting + Two Pointers
We can reduce the 3Sum problem to a "Two Sum" problem by fixing one number and searching for the other two.
- Sort the array: This allows us to use two pointers and easily skip duplicates.
- Iterate: Fix
nums[i]and look for a pair innums[i+1...n-1]that sums to-nums[i]. - Skip Duplicates: To avoid duplicate triplets, skip the current
iifnums[i] == nums[i-1]. Also, skip duplicates when moving the two pointers.
Java Implementation
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < nums.length - 2; i++) {
// Skip duplicate fixed element
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1;
int right = nums.length - 1;
int target = -nums[i];
while (left < right) {
int sum = nums[left] + nums[right];
if (sum == target) {
res.add(Arrays.asList(nums[i], nums[left], nums[right]));
// Skip duplicates for left and right
while (left < right && nums[left] == nums[left + 1]) left++;
while (left < right && nums[right] == nums[right - 1]) right--;
left++;
right--;
} else if (sum < target) {
left++;
} else {
right--;
}
}
}
return res;
}
Complexity Discussion
- Time Complexity: $O(n^2)$. Sorting takes $O(n \log n)$, and the nested loops take $O(n^2)$.
- Space Complexity: $O(\log n)$ to $O(n)$ depending on the sorting implementation.
Interview Tips
- Why sort? "Sorting helps in two ways: it enables the two-pointer approach and makes it easy to identify and skip duplicate elements."
- Edge cases: Array length less than 3, all zeros, no valid triplets.