Monday, February 2, 2015

Checking whether a sum exists in array by adding two numbers

Given an array we need to find whether any two numbers in the array add up to the number given

Say the array is

{23,45,34,12,78} and number given is 57.This is possible as 45+12 add up to give 57.

Simple solutions is to use brute force technique.We will see how to solve this is lesser time complexity.

//Given an array and a sum N
int isSumExists (vector<int>a, int N)
{

     int i = 0, j = a.size() - 1;

     //sort the array
     sort (a.begin(), a.end());

     for (int i=0; i<a.size(); i++) {

            //if sum present return 1
            if (a[i] + a[j]   == N)    return 1;
            else if (a[i] + a[j] < N) i++;
            else  j--;
     }

      //control will reach here if sum is not found
      return 0;
}

No comments: