Skip to main content

Posts

Showing posts with the label Triplet Sum in Array

Triplet Sum in Array

Task: Find the triplet sum in given an array of N numbers with value x, Triplet sum means find three elements in an array which sum is exactly equal to x. If it present print 1 else print 0. Example: Input: 1 5 10 1 5 3 7 6 Output: 1 // 1 + 3 + 6 = 10. Here is the Code: Program in C++: #include<iostream> #include<bits/stdc++.h> using namespace std; int tripletSum(int *a,int n,int x) {     sort(a,a+n);     //1 2 3 4 6     for(int i=0;i<=n-3;i++)     {         int j=i+1,k=n-1;         while(j<k)         {             if(a[i]+a[j]+a[k]==x) return 1;             else if(a[i]+a[j]+a[k]<x) j++;             else if(a[i]+a[j]+a[k]>x) k--;         }     }     return 0; } int main()  { int t; cin>>t; while(t--) {     int n,x;     cin>>n>>x;     int a[n];     for(int i=0;i<n;i++)     {         cin>>a[i];     }     cout<<tripletSum(a,n,x)<<endl; } return 0; } Here is the Video: