Skip to main content

Count the Triplets

Task: Given an array of distinct elements, Find the number of triplets. Triplet means two elements sum is equals to third element.

Example:
Input:
1
4
1 5 3 2
Output:
2 // 1 + 2 = 3 and 2 + 3 = 5.

Here is the Code:
Program in C++:

  1. #include<iostream>
  2. #include<bits/stdc++.h>
  3. int countTheTriplets(int *a,int n)
  4. {
  5.     sort(a,a+n);
  6.     //1 2 3 5
  7.     int j,k,c=0;
  8.     for(int i=0;i<n-2;i++)
  9.     {
  10.         j=i+1;
  11.         k=j+1;
  12.         while(k<n)
  13.         {
  14.             if(a[i]+a[j]==a[k])
  15.             {
  16.                 c++;
  17.                 j++;
  18.                 //k--;
  19.             }
  20.             else if(a[i]+a[j]<a[k])
  21.             {
  22.                 j++;
  23.                 k--;
  24.             }
  25.             k++; 
  26.         }
  27.     }
  28.     if(c==0)
  29.     {
  30.         return -1;
  31.     }
  32.     else
  33.     {
  34.         return c;
  35.     }
  36. }
  37. int main()
  38.  {
  39. int t;
  40. cin>>t;
  41. while(t--)
  42. {
  43.     int n;
  44.     cin>>n;
  45.     int a[n];
  46.     for(int i=0;i<n;i++)
  47.     {
  48.         cin>>a[i];
  49.     }
  50.     cout<<countTheTriplets(a,n)<<endl;
  51. }
  52. return 0;
  53. }
  54. //Updated Version Code
  55. class Solution{
  56. public:
  57. int countTriplet(int a[], int n)
  58. {
  59.     // Your code goes here
  60.     sort(a,a+n);
  61.     //1 2 3 5
  62.     int j,k,c=0;
  63.     for(int i=0;i<n-2;i++)
  64.     {
  65.         j=i+1;
  66.         k=j+1;
  67.         while(k<n)
  68.         {
  69.             if(a[i]+a[j]==a[k])
  70.             {
  71.                 c++;
  72.                 j++;
  73.                 //k--;
  74.             }
  75.             else if(a[i]+a[j]<a[k])
  76.             {
  77.                 j++;
  78.                 k--;
  79.             }
  80.             k++; 
  81.         }
  82.     }
  83.     return c;
  84. }
  85. };

Here is the Video: