All unique triplets that sum up to a given value in C++



Unique Triplets that Sum up to a Given Value

In this article, we will discuss different approaches to find all the unique triplets that sum up to the given value. Before that, first understand the given problem.

We have been given an integer array with N elements, along with a target value. Our task is to find unique or distinct triplets (i.e., three numbers) from an array, whose sum is the same as the target value.

Let's take a scenario to understand the problem in a better way:

Scenario 1

Input: arr ={1, 2, 3, 4, 5, 6, 7} and  S = 10
Output: Triplets are: (1, 3, 6), (1, 4, 5), (2, 3, 5)
Explanation: Here, 1+ 3 + 6 = 10 , 1+ 4+ 5 = 10 and 2 +3 + 5 = 10
As there are 3 triplets whose sum is equal to  S.

Scenario 2

Input: arr ={-3, 0, 2, 3, -2} and S = 0
Output: Triplets are: (-3, 0, 3) and (2, 0, -2)
Explanation: Here, -3 + 0 + 3 = 0 and 2 + 0 + (-2) = 0
As there are 2 triplets whose sum is equal to S.

Different Ways to Find Unique Triplets

There are various ways to find unique triplets from an array that sum up to a given value:

  • Using loops (Brute Force)
  • Using Two-Pointer Approach
  • Using Hashing

Let's understand the above approaches one by one:

Using loops (Brute Force)

To find the unique triplets from the given array, we need to check all possible combinations of three numbers using three nested loops and add them to check sum is equal to the target value or not. This is a brute force approach as we go through all possible triplets and verify their sum.

Algorithm

Following is an algorithm to find triplets whose sum is up to the target value using a brute force approach:

  • Declare and initialize an array and a target value.
  • Iterate using three nested loops to find all possible combinations of a triplet (i.e., i, j, k).
  • For each triplet, check whether the sum of the triplet is equal to the target value or not.
  • If the sum is equal, we have to check if this triplet is already stored or not; if not, print it.
  • Else, if no such triplet is found, return an empty array.

Example

Following is a program to find unique triplets whose sum is up to the target value:

#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
int main() {
   vector < int > arr = { 1, 2, 3, 4, 5, 0, -1 };
   int target = 10;
   set < vector < int >> uniqueTriplets;
   for (int i = 0; i < arr.size(); i++) {
      for (int j = i + 1; j < arr.size(); j++) {
         for (int k = j + 1; k < arr.size(); k++) {
            if (arr[i] + arr[j] + arr[k] == target) {
               vector < int  >triplet = {
                  arr[i],
                  arr[j],
                  arr[k]
               };
               sort(triplet.begin(), triplet.end()); // Sort to avoid duplicates
               uniqueTriplets.insert(triplet);
            }
         }
      }
   }
   if (uniqueTriplets.empty()) {
      cout << "No unique triplets found." << endl;
   } else {
      cout << "Triplets with sum " << target << " are:\n";
      for (auto triplet: uniqueTriplets) {
         for (int num: triplet) {
            cout << num << " ";
         }
         cout << endl;
      }
   }
   return 0;
}

Following is the output of the above code:

Triplets with sum 10 are:
1 4 5 
2 3 5

Two-pointer Approach

The two-pointer approach uses two pointers or variables (i.e., left and right) to iterate through a list or array. These pointers can move toward each other or in the same direction, depending on the type of problem.

To find unique triplets from an array, one pointer starts at the beginning of array and other at the end, and they move towards each other.

Algorithm

Following algorithm to find triplets whose sum is up to the target value using a two-pointer approach:

  • Declare and initialize an array and a target value.

  • First, sort the given array in ascending order.

  • Now, fix the first element of the array using a loop from i = 0 to n - 3.

  • For each fixed element, initialize two pointers(i.e., left and right): left = i + 1, and right = n - 1.

  • Now, check arr[i] + arr[left] + arr[right] == target value.

  • If the sum is less than the target value, move the left pointer forward.

  • If the sum is more than the target value, move the right pointer backward.

  • If no triplets are found, return "No such triplets found" on the console to the user.

Example

Following is an example to find unique triplets whose sum is up to the target value using a two-pointer approach:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
   vector <int>arr = {1,2,3,4,5,-1,0,6};
   int target = 10;
   sort(arr.begin(), arr.end());
   int n = arr.size();
   bool found = false;
   cout << "Unique triplets with sum " << target << " are:\n";
   for (int i = 0; i < n - 2; i++) {
      if (i > 0 && arr[i] == arr[i - 1]) continue;
      int left = i + 1;
      int right = n - 1;
      while (left < right) {
         int sum = arr[i] + arr[left] + arr[right];
         if (sum == target) {
            cout << arr[i] << ", " << arr[left] << ", " << arr[right] << "\n";
            found = true;
            while (left < right && arr[left] == arr[left + 1]) left++;
            while (left < right && arr[right] == arr[right - 1]) right--;
            left++;
            right--;
         } else if (sum < target) {
            left++;
         } else {
            right--;
         }
      }
   }
   if (!found) {
      cout << "No such triplets found.\n";
   }
   return 0;
}

Following is the output of the above program:

Unique triplets with sum 10 are:
-1, 5, 6
0, 4, 6
1, 3, 6
1, 4, 5
2, 3, 5

Using Hashing

Hashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access.

We can find all the possible triplets using nested loops (as discussed in the brute force approach) and store the results in a hash set. Later, we can access the hash set to check whether a particular element has already occurred or not.

Algorithm

Following is the algorithm to find triplets whose sum is up to the target value using hashing:

  • Declare a set result to store unique triplets.

  • Iterate given array index i from 0 to n - 1 to fix the first element of triplet(i.e., arr[i]).

  • For each fixed arr[i], declare an empty set named as seen to store the already iterated or visited values to avoid duplicates.

  • Also, iterate the array index j from i + 1 to n - 1 to find all possible second elements (i.e., arr[j]).

  • Now, for each pair (arr[i], arr[j]) we will compute the third number (i.e., third = target - arr[i] - arr[j]).

  • If the third number already exists in the set seen, it means we can form a triplet (i.e., arr[i], arr[j], third) and insert that triplet in the set result.

  • If third number is not exists in the set seen, insert arr[j] in the set seen.

  • After iterating all elements, return all triplets that are stored in the set result.

Example

Let's see the following program to find unique triplets whose sum is up to the target value:

#include <iostream>
#include <vector>
#include <unordered_set>
#include <set>
#include <algorithm>
using namespace std;
vector < vector < int >> findUniqueTriplets(vector < int > & arr, int target) {
   int n = arr.size();
   set < vector < int >> uniqueTriplets;
   for (int i = 0; i < n; i++) {
      unordered_set < int > hashSet;
      for (int j = i + 1; j < n; j++) {
         int third = target - arr[i] - arr[j];
         if (hashSet.find(third) != hashSet.end()) {
            vector < int > triplet = {
               arr[i],
               arr[j],
               third
            };
            sort(triplet.begin(), triplet.end());
            uniqueTriplets.insert(triplet);
         }
         hashSet.insert(arr[j]);
      }
   }
   return vector < vector < int >> (uniqueTriplets.begin(), uniqueTriplets.end());
}
int main() {
   vector < int > arr = {12,3,6,1,6,9};
   int target = 24;
   vector < vector < int >> result = findUniqueTriplets(arr, target);
   if (result.empty()) {
      cout << "No triplets found" << endl;
   } else {
      cout << "Unique triplets whose sum is " << target << ":" << endl;
      for (int i = 0; i < result.size(); i++) {
         cout << result[i][0] << " " << result[i][1] << " " << result[i][2] << endl;
      }
   }
   return 0;
}

Following is the output of the above program:

Unique triplets whose sum is 24:
3 9 12
6 6 12

Comparison of the Complexities

The following is a table that compares the time complexities for the above different approaches:

Approach Time Complexity Space Complexity
Brute Force O(n3) O(n)
Two-pointer approach O(n2) O(1)
Hashing O(n2) O(n + k)
Manisha Chand
Manisha Chand

Words That Decode Code

Updated on: 2025-07-31T15:40:28+05:30

416 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements