forked from tanus786/CP-Codes-HackOctober-Fest-2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
4Sum.cpp
49 lines (43 loc) · 1.4 KB
/
4Sum.cpp
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
int n = nums.size();
//start & end pointers
int s, e;
//initializing answer vector
vector<vector<int>> ans;
//initializing set
set<vector<int>> st;
sort(nums.begin(), nums.end());
//Edge Case
if(n < 4){
return ans;
}
// fixing first element of quadruplets
for(int i = 0; i < n; i++){
// fixing second element of quadruplets
for(int j = i+1; j < n; j++){
// now we are left with 2SUM problem
//intializing start and end
s = j + 1;
e = n - 1;
while(s < e){
if((long) nums[i] + nums[j] + nums[s] + nums[e] == target){
st.insert({nums[i], nums[j], nums[s], nums[e]});
s++, e--;
}
else if((long) nums[i] + nums[j] + nums[s] + nums[e] > target){
e--;
}
else{
s++;
}
}
}
}
// storing elements of set into ans
for(auto i: st)
ans.push_back(i);
return ans;
}
};