Showing posts with label sum in sorted array. Show all posts
Showing posts with label sum in sorted array. Show all posts

Saturday, June 6, 2020

Finding whether a number exists as sum of two array elements in a sorted array

Given the array{-5,-2,7,8,9,10,12}
Find whether sum 8 is possible
As element no.2 (-2) and element no.7(10) are present the sum of the two is 8


Solution:  As the array is sorted, we can leverage this property and come up with an approach which is similar to binary searching

Start with two markers at start and end of the array
Sum the two numbers at start and end marker
if sum is greater than given number, decrease the end marker 
if sum is less than given number, advance the start marker
Break if desired sum is found or start becomes greater than or equal to end



Complexity: O(n)

#include <stdio.h>
int main()
{
    int a[] = {-5,-2,7,8,9,10,12};
    
    int sum =8;
    
    int found_flag = 0;
    int size = sizeof a / sizeof a[0];
    printf("\nSize of array %d", size);
    int start = 0;
    int end = size-1;
    
    while(start<=end) {
        if((a[start]+a[end])<sum) {
            start++;
        }
        else if ((a[start]+a[end]>sum)) {
            end--;
        }
        else {
            found_flag++;
            break;
        }
    }
    
    if(found_flag) {
     printf("\nElement at location(%d):%d and location(%d):%d has sum:%d", start+1,a[start],end+1,a[end],sum);
    }
    else {
        printf("\nNot found !!");
    }
    return 0;
}

Output:
Size of array 7                                                                                                               
Element at location(2):-2 and location(6):10 has sum:8