Find the Number of Unique Triplets Whose XOR is Zero using C++


In this article, we will discuss counting the number of unique triplets (x, y, z) in a given array of unique numbers where their XOR is 0. Thus, triplets should be unique where all the three elements are unique and would count all the combinations of triplets for example −

Input : arr[ ] = { 5, 6, 7, 1, 3 }
Output : 2
Explanation : triplets are { 5, 6, 3 } and { 6, 7, 1 } whose XOR is zero.

Input : arr[ ] = { 3, 6, 8, 1, 5, 4 , 12}
Output : 3
Explanation : Triplets are { 3, 6, 5 }, { 1, 5, 4 } and { 4, 8, 12 } whose XOR is zero.

Approach to find The Solution

We know XOR of the same values always gives zero. So we find unique triplets, an optimistic approach can be applied, which is finding XOR of two values from an array and storing the result, and searching for the value that equals the result in the array. Also, the value of the result should not be equal to any value in pairs. Look for the

Example

#include <bits/stdc++.h>
using namespace std;

int main () {
   int arr[] = { 3, 6, 8, 1, 5, 4, 12 };
   int n = sizeof (arr) / sizeof (arr[0]);
   int result;
   // count variable to keep count of pairs.
   int count = 0;
   // creating a set to store unique numbers .
   unordered_set < int >values;
   // inserting values in set.
   for (int i = 0; i < n; i++)
      values.insert (arr[i]);


   // traverse for all pairs to calculate XOR.
   for (int i = 0; i < n - 1; i++) {
      for (int j = i + 1; j < n; j++) { // finding xor of i, j pair.
         int XR = arr[i] ^ arr[j];

         // checking if XOR value of pair present in array
         // and value should not be in pairs.
         if (values.find (XR) != values.end () && XR != arr[i] &&
            XR != arr[j])
            count++;
      }

   }
   // storing result
   result = count / 3;
   cout << "Number of unique triplets : " << result;
   return 0;
}

Output

Number of unique triplets : 3

Explanation of the above code

  • Creating a set of unordered_set < int >values; to store unique numbers of a given array.
  • Using for() loop to insert values in set using values.insert (arr[i]).
  • Using two nested loops to traverse through all the pairs and calculating their XOR value.
  • Then, search the XOR value in the array and increment the count if the value is found in an array and not in pairs.
  • Storing the result as count / 3 would count triplets' three combinations, and we require unique triplets.

Conclusion

This article discussed finding the number of triplets having XOR value 0; we discussed an optimistic approach to find unique triplets. We also discussed the C++ program to solve the problem. However, we can write this program in any other programming language like Java, C, Python, etc. We hope you find this article helpful.

Updated on: 26-Nov-2021

345 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements