Skip to content

Instantly share code, notes, and snippets.

@ms1797
Created November 12, 2018 09:26
Show Gist options
  • Save ms1797/3975212da19e21f75f8462dddf5b1d8a to your computer and use it in GitHub Desktop.
Save ms1797/3975212da19e21f75f8462dddf5b1d8a to your computer and use it in GitHub Desktop.
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.(https://www.interviewbit.com/problems/4-sum/)
vector<vector<int> > Solution::fourSum(vector<int> &A, int B) {
int N = A.size();
//mapping sum value to a vector of pair indices
unordered_map<int, vector<pair<int, int> > > Hash;
vector<vector<int> >Ans;
for(int i = 0; i < N; ++i) {
for(int j = i + 1; j < N; ++j) {
//calculate sum with i and j indices
int Sum = A[i] + A[j];
//if B- sum is already present in Hash then check for valid indices
if(Hash.find(B - Sum ) != Hash.end())
{
//get vector of pair of indices with Hash of B- Sum
vector<pair<int, int> > vec = Hash[B - Sum];
//check for all pairs with i anf j
for(int k = 0 ; k < vec.size() ; k++)
{
//we are checking that all the indices are different
if(vec[k].first != i && vec[k].first != j && vec[k].second != i
&& vec[k].second != j)
{
//push to vector
vector<int> ans;
ans.push_back(A[vec[k].first]);
ans.push_back(A[vec[k].second]);
ans.push_back(A[i]);
ans.push_back(A[j]);
//sort the vector ans to maintain the expected output
sort(ans.begin() , ans.end()) ;
//push to final result and avoids duplicates
if(find(Ans.begin() , Ans.end() , ans ) == Ans.end())
Ans.push_back(ans) ;
}
}
}
//if B- Sum not present then hash the indices i anj with sum of i and j
Hash[Sum].push_back(make_pair(i,j)) ;
}
}
//finally sort the result vector to maintain expected output
sort(Ans.begin() , Ans.end()) ;
return Ans;
}
@setu1421
Copy link

Nice solution. Just one suggestion. We will always hash the sum whether B - Sum is present or not which you are doing as well. Please update the comment above this line.

Hash[Sum].push_back(make_pair(i,j)) ;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment