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.
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
The distinct triplets are [-1,0,1] and [-1,-1,2].
Input: nums = [0,1,1]
Output: []
Explanation: The only possible triplet does not sum up to 0.
Input: nums = [0,0,0]
Output: [[0,0,0]]
Explanation: The only possible triplet sums up to 0.
The key insight is to reduce 3Sum to a Two Sum problem. By fixing one number and using two pointers for the remaining two numbers, we can find all valid triplets efficiently.
Main Ideas:
i) and find two other elements that sum to -nums[i]This is a Two Pointers pattern combined with:
nums in ascending orderi
nums[i] > 0 (no way to get sum = 0)i to avoid duplicate tripletsi, use two pointers:
left = i + 1, right = length - 1sum = nums[i] + nums[left] + nums[right]sum == 0: Add triplet, skip duplicates for left and rightsum < 0: Move left++sum > 0: Move right--1class Solution {
2 public List<List<Integer>> threeSum(int[] nums) {
3 List<List<Integer>> result = new ArrayList<>();
4
5 // Sort array to enable two-pointer technique
6 Arrays.sort(nums);
7
8 // Iterate through array, fixing first element
9 for (int i = 0; i < nums.length - 2; i++) {
10 // Skip positive numbers (can't sum to 0)
11 if (nums[i] > 0) break;
12
13 // Skip duplicates for first element
14 if (i > 0 && nums[i] == nums[i - 1]) continue;
15
16 // Two pointers for remaining elements
17 int left = i + 1;
18 int right = nums.length - 1;
19
20 while (left < right) {
21 int sum = nums[i] + nums[left] + nums[right];
22
23 if (sum == 0) {
24 // Found a triplet
25 result.add(Arrays.asList(nums[i], nums[left], nums[right]));
26
27 // Skip duplicates for left pointer
28 while (left < right && nums[left] == nums[left + 1]) {
29 left++;
30 }
31
32 // Skip duplicates for right pointer
33 while (left < right && nums[right] == nums[right - 1]) {
34 right--;
35 }
36
37 // Move both pointers
38 left++;
39 right--;
40 } else if (sum < 0) {
41 // Sum too small, need larger number
42 left++;
43 } else {
44 // Sum too large, need smaller number
45 right--;
46 }
47 }
48 }
49
50 return result;
51 }
52}
53