Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

4Sum.cpp #376

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions c++/4Sum.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
int n = nums.size();
sort(nums.begin(), nums.end());
set<vector<int>> set;
vector<vector<int>> output;
for(int i=0; i<n-3; i++){
for(int j=i+1; j<n-2; j++){
long long newTarget = (long long)target - (long long)nums[i] - (long long)nums[j];
int low = j+1, high = n-1;
while(low < high){
if(nums[low] + nums[high] < newTarget){
low++;
}
else if(nums[low] + nums[high] > newTarget){
high--;
}
else{
set.insert({nums[i], nums[j], nums[low], nums[high]});
low++; high--;
}
}
}
}
for(auto it : set){
output.push_back(it);
}
return output;
}
};






/*

Time Complexity : O(N^3), Here Three nested loop creates the time complexity. Where N is the size of the
array(nums).

Space Complexity : O(1), Constant space. Extra space is only allocated for the Vector(output), however the
output does not count towards the space complexity.

Solved using Array(Three Nested Loop) + Sorting. Optimized Approach.