Problem : Given an array of integers intArray[] and another integer sum, find how many pairs of numbers in the given array will sum up to the given sum.
This problem is one of the most sought after question in interviews. There may be slight variations of this problem. There are many ways to solve this problem. The most efficient solution considering both time and space complexity is the one discussed below -
/**
This problem is one of the most sought after question in interviews. There may be slight variations of this problem. There are many ways to solve this problem. The most efficient solution considering both time and space complexity is the one discussed below -
/**
* This will find how many pairs of numbers in the given array sum
* up to the given number.
*
* @param array - array of integers
* @param sum - The sum
* @return int - number of pairs.
*/
public static int sumOfSubset(int[] array, int sum)
{
// This has a complexity of O ( n lg n )
Arrays.sort(array);
int pairCount = 0;
int leftIndex = 0;
int rightIndex = array.length - 1;
// The portion below has a complextiy of
// O ( n ) in the worst case.
while (array[rightIndex] >= sum)
{
rightIndex--;
}
while (leftIndex islessthan rightIndex) {
{
if (array[leftIndex] + array[rightIndex] == sum)
{
pairCount++;
leftIndex++;
rightIndex--;
}
else if(array[leftIndex] + array[rightIndex] islessthan sum)
leftIndex++;
}
else
{
rightIndex--;
}
}
return pairCount;
}
This algorithm has an overall running complexity of O (n lg n) and a space complexity of O (1) since sorting is done in place and we are not using any other memory.
Comments