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]]
Input: nums = []
Output: []
Input: nums = [0]
Output: []
Q: What should be returned if there are no such triplets? A: An empty list should be returned.
Q: Can the input include duplicate numbers? A: Yes, the input can contain duplicate numbers, but the solution must not contain duplicate triplets.
Q: Should the triplets be returned in any specific order? A: No, the order of the triplets does not matter.
To solve the 3Sum problem, we can use a two-pointer approach with sorting:
Sort the Array: First, sort the input array. This makes it easier to avoid duplicates and use the two-pointer technique.
Iterate through the Array: For each element in the array (with the index i
), treat it as the first element of the triplet and use two pointers to find pairs that add up to the negative of the first element.
i
(left
) and one at the end of the array (right
).left
pointer to the right and the right
pointer to the left based on the sum of nums[i] + nums[left] + nums[right]
.import java.util.*;
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
// Skip duplicates for the first element.
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1;
int right = nums.length - 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]));
// Skip duplicates for the second element.
while (left < right && nums[left] == nums[left + 1]) left++;
// Skip duplicates for the third element.
while (left < right && nums[right] == nums[right - 1]) right--;
left++;
right--;
} else if (sum < 0) {
left++;
} else {
right--;
}
}
}
return result;
}
}
O(n log n)
O(n)
O(n)
Therefore, the overall time complexity is O(n^2)
.
O(n)
auxiliary space if the sort implementation uses a non-in-place algorithm. However, most in-place sorts like QuickSort would use O(log n)
auxiliary space.O(n^2)
space in the worst case if there are many triplets.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?