Home »
Algorithms
Find three elements in an array such that their sum is equal to given element K
Here, we are going to learn how to find three elements in an array such that their sum is equal to given element k?
Submitted by Radib Kar, on November 07, 2018
Description:
Given an array of n elements. Find three elements such that their sum is equal to given element K.
Solutions:
Brute force method: The brute force solution is to check if there are any elements whose sum is equal to K for any two input pair taken from the array. This solution requires to run three loops and the time complexity is much higher, O(n3).
Advanced algorithm with lesser time complexity
1. Sort the array.
2. for k=0:n-1 // k from 0 to n-1
for i=k+1, j=n-1 & i<j //i=k+1, j= n-1 && loop till i<j
if( array[k]+array[i]+array[j]==K) // if they sums to K
Print elements; //then print
else if(array[k]+array[i]+array[j]<K) //if sum is <K
i=i+1; // increase i since array is sorted
else //else
j=j-1; //decrease j
End for loop
End for loop
3. If no elements are found print no such elements present.
Time complexity: O(n2) ( for two for loops)
C++ implementation of above algorithm
#include<bits/stdc++.h>
using namespace std;
void findelements(int* a, int n,int K){
//sort the array using default sort library function, O(logn) generally
sort(a,a+n);
//run the first loop
for(int k=0;k<n;k++){
//i=k+1 & j=n-1 (initialized) ; run till i<j
for(int i=k+1,j=n-1;i<j;){
if(a[i]+a[j]+a[k]==K){ //if sum ==K
//print & return
printf("three elements are found to sum to %d. These are %d,%d,%d\n",K,a[k],a[i],a[j]);
return;
}
// if sum <K increment i since array is sorted & we need higher value elements
else if (a[i]+a[j]+a[k]<K)
i=i+1;
else
j=j-1; // if sum >K decrement j since array is sorted & we need lower value elements
}
}
cout<<"no such three elements can be found"<<endl; // no such element trio found
return;
}
int main(){
int K,count=0,n;
// enter array length
cout<<"enter no of elements\n";
cin>>n;
int* a=(int*)(malloc(sizeof(int)*n));
cout<<"enter elements................\n"; //fill the array
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
cout<<"enter the sum,K"<<endl;
cin>>K;
findelements(a,n,K);
return 0;
}
Output (first run)
enter no of elements
7
enter elements................
-1
5
6
9
23
28
12
enter the sum,K
28
three elements are found to sum to 28. These are -1,6,23
Output (second run)
enter no of elements
4
enter elements................
5
6
-5
7
enter the sum,K
1
no such three elements can be found