Skip to content

Instantly share code, notes, and snippets.

@Divay9Sharma
Created July 21, 2020 13:14
Show Gist options
  • Select an option

  • Save Divay9Sharma/4aef9a459574cdf7760ba0504766c2f2 to your computer and use it in GitHub Desktop.

Select an option

Save Divay9Sharma/4aef9a459574cdf7760ba0504766c2f2 to your computer and use it in GitHub Desktop.
Find all four sum numbers - hashing
using namespace std;
struct Location{
int i;
int j;
};
bool distinct(int a, int b, int c, int d){
if(a!=b&&a!=c&&a!=d)
if(b!=c&&b!=d)
if(c!=d)
return 1;
return 0;
}
int main() {
int T;
scanf("%d",&T);
while(T--){
int N,sum,flag=0;
scanf("%d%d",&N,&sum);
int array[N];
for(int i=0;i<N;i++)
scanf("%d",&array[i]);
sort(array,array+N);
unordered_map <string,int> mp;
string current="";
int sizeOfTwoSum = ((N-1)*N)/2;
int TwoSum[sizeOfTwoSum],k=0;
//Sum of all Pairs
Location L[sizeOfTwoSum];
for(int i=0;i<N;i++)
for(int j=i+1;j<N;j++){
TwoSum[k]=array[i]+array[j];
//printf("TwoSum[k++]:%d\n",TwoSum[k]);
L[k].i=i;
L[k].j=j;
k++;
}
int a,b,c,d;
for(int i=0;i<sizeOfTwoSum;i++)
for(int j=i+1;j<sizeOfTwoSum;j++){
if(TwoSum[i]+TwoSum[j]==sum){
a=L[i].i, b=L[i].j, c=L[j].i, d=L[j].j;
int temp[] = {array[L[i].i], array[L[i].j], array[L[j].i], array[L[j].j]};
sort(temp,temp+4);
current = to_string(temp[0])+to_string(temp[1])+to_string(temp[2])+to_string(temp[3]);
if(mp[current]==0&&distinct(a,b,c,d)){
printf("%d %d %d %d $",temp[0],temp[1],temp[2],temp[3]);
mp[current]++;
flag=1;
}
}
}
if(flag==0)
printf("-1");
printf("\n");
}
return 0;
}
@Divay9Sharma
Copy link
Author

Given an array A of size N, find all combination of four elements in the array whose sum is equal to a given value K. For example, if the given array is {10, 2, 3, 4, 5, 9, 7, 8} and K = 23, one of the quadruple is “3 5 7 8” (3 + 5 + 7 + 8 = 23). The output should contain only unique quadrples For example, if input array is {1, 1, 1, 1, 1, 1} and K = 4, then output should be only one quadrple {1, 1, 1, 1}.

Input:
2
5 3
0 0 2 1 1
7 23
10 2 3 4 5 7 8
Output:
0 0 1 2 $
2 3 8 10 $2 4 7 10 $3 5 7 8 $

The idea is to first take sum of each pair and store it in the hash table. Then iterate over this hash table and for each x, search in the table if k-x exist. If it does then their exist a 4 combination sum. Check that these 2 pairs do not have any common index. Then sort them and store them in a string. A set of strings is maintained to avoid repeating the same 4 combinations.

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