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
.
Notice that the solution set must not contain duplicate triplets.
The solution uses a two-pointer technique combined with sorting to efficiently find triplets. Here's the step-by-step approach:
- Sort the input array first - this is crucial for avoiding duplicates and using the two-pointer technique effectively
- Iterate through the array with index i as the first number of the triplet
- For each i, use two pointers (left and right) to find pairs that sum to -nums[i]
- Skip duplicate values of i to avoid duplicate triplets
- The array must be sorted first
- Duplicate handling is critical for correct results
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;
int left = i + 1, 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;
}
}
- Time Complexity: O(n²) where n is the length of input array
- Space Complexity: O(1) excluding the space required for output
For input array: [-1, 0, 1, 2, -1, -4]
- After sorting: [-4, -1, -1, 0, 1, 2]
- First iteration: i = -4, looking for pairs that sum to 4
- Second iteration: i = -1 (first occurrence), looking for pairs that sum to 1
- Skip second -1 to avoid duplicates
- Continue with remaining elements
The solution will find all unique triplets: [[-1, -1, 2], [-1, 0, 1]]