Skip to main content

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++:

  1. #include<iostream>
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4. int tripletSum(int *a,int n,int x)
  5. {
  6.     sort(a,a+n);
  7.     //1 2 3 4 6
  8.     for(int i=0;i<=n-3;i++)
  9.     {
  10.         int j=i+1,k=n-1;
  11.         while(j<k)
  12.         {
  13.             if(a[i]+a[j]+a[k]==x) return 1;
  14.             else if(a[i]+a[j]+a[k]<x) j++;
  15.             else if(a[i]+a[j]+a[k]>x) k--;
  16.         }
  17.     }
  18.     return 0;
  19. }
  20. int main()
  21.  {
  22. int t;
  23. cin>>t;
  24. while(t--)
  25. {
  26.     int n,x;
  27.     cin>>n>>x;
  28.     int a[n];
  29.     for(int i=0;i<n;i++)
  30.     {
  31.         cin>>a[i];
  32.     }
  33.     cout<<tripletSum(a,n,x)<<endl;
  34. }
  35. return 0;
  36. }

Here is the Video: