GeeksforGeeks » Algorithms
Find a pair in a sequence whose sum is another element of the same sequence.
(4 posts)-
For example if array is [1, 4, 3, 14, 24, 30 ] then your program shoul be able to find out 1 and 3 as sum of them is present in array.
Asked in Amazon
-
Sort the array of N elements.
Take the first element. Add the next element. Compare the sum with the consecutive element. If the sum is more traverse to next till you find an element equal to or greater than the sum.
Repeat the step upto N-2.Complexity O(N^2)
-
The question is a variation of the standard 3SUM problem http://en.wikipedia.org/wiki/3SUM.
And O(n^2) is the best possible solution for this.
-
#include<stdio.h> void sort(int *, int); void print_array(int *, int); void func(int *,int); int is_existing(int *,int,int,int); int main() { int a[] = {1,4,3,14,5,9,17}; printf("\n==Input Array==\n"); print_array(a,6); sort(a,6); func(a,6); return 0; } int is_existing(int *a, int count, int sum, int j) { int i; for(i=j+1;i<count;i++) { if(a[i] == sum) return 1; } return 0; } void func(int *a,int count) { int i,j,sum,result; for(i=0;i<count-2;i++) { for(j=i+1;j<count-1;j++) { sum = a[i] + a[j]; result = is_existing(a,count,sum,j); //look out for sum in a after index j if(result == 1) { printf("%d+%d=>%d ",a[i],a[j],sum); } } } printf("\n"); } void sort(int *a, int count) { int i,j,temp; do { j = 0; for (i = 0;i<count;i++) { if (a[i] > a[i+1]) { j = 1; temp = a[i]; a[i] = a[i+1]; a[i+1] = temp; } } } while (j == 1); return; } void print_array(int *a, int count) { int i; for(i=0;i<count;i++) printf("%d ",a[i]); printf("\n"); return; }
Reply
You must log in to post.