Tuesday, January 05, 2010

Two numbers in set whose sum is equal to a given number

Approach 1 O(N^2) :- Try summing each number in array with all other numbers in array and if the sum is equal to given number return true. This approach in worst case will be O(n^2). In best case we can be lucky to have first two numbers in array to be such that their sum is equal to a given number.

Approach 2 O( n Log n) : Sort the numbers. Now keep two pointers one at start and one at end. pseudo code can be something as below. I havent tested this code so bear with me if it has some syntax error :)

bool checksum(int sortedArray[], int len, int required_sum)
{
int start = 0;
int end = len-1;

while(start < end)
{
if((sortedArray[start]+sortedArray[end])>required_sum)
{
end = end -1;
continue;
}

if((sortedArray[start]+sortedArray[end])<required_sum)
{
start = start +1;
continue;
}

else return true;

}

}
--
Ashish Meena

No comments: