### Archives

### Categories

Advertisements

May 28, 2008

Posted by on We are given a set of integers, and another integer . And we need to find out if there exists two integers in the set such that there sum is .

The straight forward answer is to calculate sum for each possible pair of elements in , and see if any of them matches with .

Note that the sum of the smallest element and the largest element in , will be the median of sums possible with pairs of elements in . If , is less than this sum, then the largest element of could not be in the pair we are searching for. Similarly, if is larger than the required sum, then the smallest element from will not be in the pair we are searching for. The same method could be applied to the subproblem(the remaining list).

At each stage we have to calculate the smallest and largest element in the list. We could solve this for each subproblem in , or we could sort the set initially, and then access the smallest and largest elements in . The second approach solves the problem in .

As u might have noticed, the solution is a recursive one. But it doesn’t have to be coded that way. The recursive solution could be easily converted to an iterative one, as shown below. I have skipped the much of the code, just to present heart of the method.

int sum_check(int *arr, int n, int x) { int u, l, s; u=0;l=n-1; while (u<l) { s = arr[u]+arr[l]; if (x < s) l--; else if (x > s) u++; else return 1; } return 0; }

But lets see the recursive approach also.

int sum_check_rec(int *arr, int n, int x)

{

int s = arr[0] + arr[n-1];

if (n == 1) return 0;

if (x == s) return 1;

return sum_check_rec(arr + (x~~
~~

Advertisements