TechoSagar: Triplet Sum in Array

Search

Google Alert - jobs

Triplet Sum in Array

Given an array A[] of n numbers and another number x, determine whether or not there exist three elements in A[] whose sum is exactly x.
Expected time complexity is O(n^2).
Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is n and x, n is the size of array.
The second line of each test case contains n integers representing array elements C[i].

Output:
Print 1 if there exist three elements in A whose sum is exactly x, else 0.


Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 200
1 ≤ A[i] ≤ 1000

Example:
Input:
2
6 13
1 4 45 6 10 8
5 10

1 2 4 3 6
Output:
1

1
Get Your Code
#include<iostream>

using namespace std;

int main()
{
int t;
cin>>t;
while(t--)
{
int n,x;
cin>>n>>x;
   int i;
   int a[200];
   for(i=0; i<n; i++)
   {
    cin>>a[i];
}
int j;
for(i=0; i<n-1; i++)
{
int c=i;
for(j=i+1; j<n; j++)
{
if(a[c]>a[j])
{
c=j;
}
}
if(c!=i)
{
int temp=a[i];
a[i]=a[c];
a[c]=temp;
}
}
int k;
int ans=0;
for(i=0; i<n-2; i++)
{
for(j=i+1; j<n-1; j++)
{
for(k=j+1; k<n; k++)
{
if(a[i]+a[j]+a[k]==x)
{
ans=1;
break;
}
}
}
}
if(ans==1)
{
cout<<"1"<<endl;
}
else
cout<<"0"<<endl;
}
}


Follow us

Follow Bijendra Kumar on Facebook