Prompt
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.
Constraints:
3 <= nums.length <= 3000-105 <= nums[i] <= 105
Examples
- Example 1:
- 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].
- Notice that the order of the output and the order of the triplets does not matter.
- Example 2:
- Input: nums = [0,1,1]
- Output: []
- Explanation: The only possible triplet does not sum up to 0.
- Example 3:
- Input: nums = [0,0,0]
- Output: 0,0,0
- Explanation: The only possible triplet sums up to 0.
Solutions
Sorted Two Pointers Solution
In C++
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> answer;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); ++i) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
int l = i + 1; int r = nums.size() - 1;
while (l < r) {
int sum = nums[l] + nums[r] + nums[i];
if (sum < 0) l++;
else if (sum > 0) r--;
else {
answer.push_back({nums[l], nums[r], nums[i]});
while (l < r && nums[l] == nums[l + 1]) l++;
while (l < r && nums[r] == nums[r - 1]) r--;
l++; r--;
}
}
}
return answer;
}In pseudocode
threeSum(nums : list<int>) -> list<list<int>> {
answer : list<list<int>>;
nums.sort(); n = nums.size;
for (i = 0; i < n; ++i) {
skip to last dupe of i pointer;
l = i + 1; r = n - 1;
while (l < r) {
sum = sum(nums[l], nums[r], nums[i]);
if (sum < 0) l++;
else if (sum > 0) r--;
else {
answer.add(list(nums[l], nums[r], nums[i]));
skip to last dupe of l pointer;
skip to last dupe of r pointer;
}
}
}
return answer;
}Explanation
The idea here is that we nest a modified version of our 167. Two Sum II - Input Array Is Sorted solution within a loop that iterates through the nonduplicates of the input array. The aforementioned problem is assumes that there is exactly one solution to we must modify the else case a bit. Namely, after we add a valid solution, we skip all duplicates on both the left and right hand side. It was not immediately obvious to me why we need the l++; r--; after the while loops in the else. My intuition told me that each while loop equals skip all the duplicates. However, each loop actually says: “Move ahead until the next element is not a duplicate”, which results in both pointers ending at the last duplicate. We give each of them one final push into nonduplicate land.
Big O Analysis
Time Complexity