3sum

Problem Description

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.

Intuition

We can break down this problem by fixing one element and converting it into a 2Sum problem:

  1. Fix one element as the first number
  2. Solve for the remaining elements using the 2Sum approach

Time Complexity: $O(n^2)$
Space Complexity: $O(n)$ for sorting, $O(1)$ extra space

Algorithm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int n = nums.size();
set<vector<int>> s;
vector<vector<int>> ans;
sort(nums.begin(), nums.end());

for(int i = 0; i < n - 2; i++){
int target = nums[i];
int left = i + 1;
int right = n - 1;
while(left < right){
if(nums[left] + nums[right] + target == 0) {
s.insert({target, nums[left], nums[right]});
left++;
right--;
}
else if(nums[left] + nums[right] + target < 0) {
left++;
}
else{
right--;
}
}
}

for(auto vec:s){
ans.push_back(vec);
}

return ans;
}
};