Skip to content

Commit b595448

Browse files
committed
Find unique triplets in an array such that the triplet sum = 0
1 parent eb83b47 commit b595448

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/*
2+
Given an array nums of n integers, find all unique triplets in the array which gives the sum of zero.
3+
*/
4+
#include<bits/stdc++.h>
5+
using namespace std;
6+
vector<vector<int>> threeSum(vector<int>& nums) {
7+
int n = nums.size();
8+
if(n < 3)
9+
return {};
10+
sort(nums.begin(),nums.end());
11+
vector <vector<int>> result;
12+
unordered_set<string> triplets;
13+
int i = 0;
14+
while(i < n -2){
15+
int j = i+1, k = n-1;
16+
while(j<k){
17+
int sum = nums[i] + nums[j] + nums[k];
18+
if(sum == 0){
19+
string newTriplet = to_string(nums[i]) + ":"
20+
+ to_string(nums[j]) + ":"
21+
+ to_string(nums[k]);
22+
if(triplets.find(newTriplet) == triplets.end()){
23+
triplets.insert(newTriplet);
24+
result.push_back({nums[i],nums[j],nums[k]});
25+
}
26+
j++;
27+
k--;
28+
}
29+
else if(sum > 0)
30+
k--;
31+
else if(sum < 0)
32+
j++;
33+
}
34+
i++;
35+
}
36+
return result;
37+
}
38+
39+
int main(){
40+
int n;
41+
vector <int> nums;
42+
cin>>n;
43+
for(int i = 0; i < n; i++){
44+
int input;
45+
cin>>input;
46+
nums.push_back(input);
47+
}
48+
vector <vector<int>> result = threeSum(nums);
49+
for(int i = 0; i< result.size(); i++){
50+
for(int j = 0; j< result[0].size(); j++)
51+
cout<<result[i][j]<<" ";
52+
cout<<"\n";
53+
}
54+
}
55+
//Time complexity: O(n^2), Space complexity: O(n)

0 commit comments

Comments
 (0)