Print all triplets with given sum in C++


In this problem, we are given an array of unique integers and a sum. And we have to find the triplets which can form the same sum.

Let's take an example to solve the problem −

Input : array = {0 , 2 , -1 , 1, -2}
Sum = 1
Output : 1 2 -2
0 2 -1

To solve this problem, we will be finding all the triplets that provide the sum. A simple approach will be using three loops and finding the sum of the elements and return the adequate triplet.

Example

 Live Demo

#include <iostream>
using namespace std;
void Triplets(int arr[], int n, int sum){
   for (int i = 0; i < n - 2; i++) {
      for (int j = i + 1; j < n - 1; j++) {
         for (int k = j + 1; k < n; k++) {
            if (arr[i] + arr[j] + arr[k] == sum) {
               cout<<arr[i]<<"\t"<<arr[j]<<"\t"<<arr[k]<<endl;
            }
         }
      }
   }
}
// Driver code
int main(){
   int arr[] = { 0 , 2 , -1 , 1, -2 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The Triplets are : \n";
   Triplets(arr, n, 1);
   return 0;
}

Output

The Triplets are −

0 2 -1
2 1 -2

But this approach is not efficient as it will have time complexity of o(n3) for running three loops. So, we will use other techniques to solve this problem in an effective way.

One method is using hashing. In this method, we will find pairs of every element of such that they are a complement each other i.e. for the element with value x, we need an element -x.

This reduces the time complexity of the code.

Example

#include <bits/stdc++.h>
using namespace std;
void Triplets(int arr[], int n, int sum{
   for (int i = 0; i < n - 1; i++) {
      unordered_set<int> triplet;
      for (int j = i + 1; j < n; j++) {
         int third = sum - (arr[i] + arr[j]);
         if (triplet.find(third) != triplet.end())
            cout<<third<<"\t"<<arr[i]<<"\t"<<arr[j]<<endl;
         else
            triplet.insert(arr[j]);
      }
   }
}
int main(){
   int arr[] = { 0 , 2 , -1 , 1, -2 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The Triplets are : \n";
   Triplets(arr, n, 1);
   return 0;
}

Output

The Triplets are −

0 2 -1
2 1 -2

This method can be made more effective by sorting the array which will reduce the space complexity of the code.

Updated on: 17-Jan-2020

177 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements