I am trying to find four number sum for a given array. The task is to find all quadruplets in the array that sum up to the target sum and return a two-dimensional array of all these quadruplets in no particular order. If no four unique numbers sum up to the target sum, the function should return an empty array.
I tried following code seems to work fine but I get one additional quadruple because of duplicate element.
function fourSum([1,2,3,4,5,6,7],10) {
var hash = {};
var quadruples = [];
for(var i=0; i<array.length; i++){
for(var j=0; j<array.length;j++){
var Q = 0;
var P = 0;
if(i<j){
Q = array[i]+array[j];
if(hash[(targetSum - Q)]){
for(var k=0; k< hash[(targetSum - Q)].length; k++){
var combination = [hash[(targetSum - Q)][k][0] , hash[(targetSum - Q)][k][1] ,array[i], array[j]];
quadruples.push(combination);
}
}
}
if(i>j){
P = array[i]+array[j];
if(hash[P]){
hash[P].push([array[i], array[j]]);
}else{
hash[P] = [[array[i], array[j]]];
}
}
}
}
return quadruples;
}
This returns me following: {[2, 1, 2, 5], [2, 1, 3, 4]} which is incorrect because in [2, 1, 2, 5], we have 2 two time. I am unable to find out where I am wrong in my code.