Open In App

Number of unique triplets whose XOR is zero

Last Updated : 10 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given N numbers with no duplicates, count the number of unique triplets (ai, aj, ak) such that their XOR is 0. A triplet is said to be unique if all of the three numbers in the triplet are unique. 

Examples: 

Input : a[] = {1, 3, 5, 10, 14, 15};
Output :
Explanation : {1, 14, 15} and {5, 10, 15} are the 
                        unique triplets whose XOR is 0. 
                       {1, 14, 15} and all other combinations of 
                        1, 14, 15 are considered as 1 only.

Input : a[] = {4, 7, 5, 8, 3, 9};
Output : 1
Explanation : {4, 7, 3} is the only triplet whose XOR is 0 

Naive Approach: A naive approach is to run three nested loops, the first runs from 0 to n, the second from i+1 to n, and the last one from j+1 to n to get the unique triplets. Calculate the XOR of ai, aj, ak, check if it equals 0. If so, then increase the count. 

Below is the implementation of the above idea:

C++




// CPP program to count the number of
// unique triplets whose XOR is 0
#include <bits/stdc++.h>
using namespace std;
 
// function to count the number of
// unique triplets whose xor is 0
int countTriplets(int a[], int n)
{
 
    // stores the count of unique triplets
    int count = 0;
 
    // traverse for all i, j, k pairs such that k>j>i
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            for (int k = j + 1; k < n; k++) {
 
                int xorr = a[i] ^ a[j] ^ a[k];
 
                // if xor of a[i], a[j] and a[k] is 0,
                // increase count by 1
                if (xorr == 0)
                    count++;
            }
        }
    }
 
    return count;
}
 
// Driver code
int main()
{
    int a[] = { 1, 3, 5, 10, 14, 15 };
    int n = sizeof(a) / sizeof(a[0]);
    cout << countTriplets(a, n);
    return 0;
}


Java




// JAVA program to count the number of
// unique triplets whose XOR is 0
 
public class GFG {
    // function to count the number of
    // unique triplets whose xor is 0
    static int countTriplets(int a[], int n)
    {
 
        // stores the count of unique triplets
        int count = 0;
 
        // traverse for all i, j, k pairs such that k>j>i
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                for (int k = j + 1; k < n; k++) {
 
                    int xorr = a[i] ^ a[j] ^ a[k];
 
                    // if xor of a[i], a[j] and a[k] is 0,
                    // increase count by 1
                    if (xorr == 0)
                        count++;
                }
            }
        }
 
        return count;
    }
    public static void main(String[] args)
    {
        int a[] = { 1, 3, 5, 10, 14, 15 };
        int n = 6;
        System.out.println(countTriplets(a, n));
    }
}


Python3




# Python program to count the number of
# unique triplets whose XOR is 0
class GFG :
   
    # function to count the number of
    # unique triplets whose xor is 0
    @staticmethod
    def  countTriplets( a,  n) :
       
        # stores the count of unique triplets
        count = 0
         
        # traverse for all i, j, k pairs such that k>j>i
        i = 0
        while (i < n - 1) :
            j = i + 1
            while (j < n) :
                k = j + 1
                while (k < n) :
                    xorr = a[i] ^ a[j] ^ a[k]
                     
                    # if xor of a[i], a[j] and a[k] is 0,
                    # increase count by 1
                    if (xorr == 0) :
                        count += 1
                    k += 1
                j += 1
            i += 1
        return count
    @staticmethod
    def main( args) :
        a = [1, 3, 5, 10, 14, 15]
        n = 6
        print(GFG.countTriplets(a, n))
     
if __name__=="__main__":
    GFG.main([])
     
    # This code is contributed y aadityaburujwale.


C#




using System;
class GFG {
 
  static int countTriplets(int[] a, int n)
  {
 
    // stores the count of unique triplets
    int count = 0;
 
    // traverse for all i, j, k pairs such that k>j>i
    for (int i = 0; i < n - 1; i++) {
      for (int j = i + 1; j < n; j++) {
        for (int k = j + 1; k < n; k++) {
 
          int xorr = a[i] ^ a[j] ^ a[k];
 
          // if xor of a[i], a[j] and a[k] is 0,
          // increase count by 1
          if (xorr == 0)
            count++;
        }
      }
    }
 
    return count;
  }
 
  // Driver's code
  public static void Main(string[] args)
  {
    int[] a = { 1, 3, 5, 10, 14, 15 };
    int n = 6;
 
    // Function call
    Console.Write(countTriplets(a, n));
  }
}
 
// This code is contributed garg28harsh.


Javascript




// Javascript program to count the number of
// unique triplets whose XOR is 0
 
    // function to count the number of
    // unique triplets whose xor is 0
    function countTriplets(a, n)
{
 
    // stores the count of unique triplets
    let count = 0;
 
    // traverse for all i, j, k pairs such that k>j>i
    for (let i = 0; i < n - 1; i++) {
        for (let j = i + 1; j < n; j++) {
            for (let k = j + 1; k < n; k++) {
 
                let xorr = a[i] ^ a[j] ^ a[k];
 
                // if xor of a[i], a[j] and a[k] is 0,
                // increase count by 1
                if (xorr == 0)
                    count++;
            }
        }
    }
 
    return count;
}
 
// Driver code
let a = [ 1, 3, 5, 10, 14, 15 ];
let n = 6;
console.log(countTriplets(a, n));
 
// This code is contributed by garg28harsh.


Output

2

Time Complexity: O(n3), as we will be using nested loops for traversing n3 times.
Auxiliary Space: O(1), as we will not use extra space.

Efficient Approach: An efficient approach is to use one of the properties of XOR: the XOR of two of the same numbers gives 0. So we need to calculate the XOR of unique pairs only, and if the calculated XOR is one of the array elements, then we get the triplet whose XOR is 0. Given below are the steps for counting the number of unique triplets:

Below is the complete algorithm for this approach:  

  1. With the map, mark all the array elements.
  2. Run two nested loops, one from i-n-1, and the other from i+1-n to get all the pairs.
  3. Obtain the XOR of the pair.
  4. Check if the XOR is an array element and not one of ai or aj.
  5. Increase the count if the condition holds.
  6. Return count/3 as we only want unique triplets. Since i-n and j+1-n give us unique pairs but not triplets, we do a count/3 to remove the other two possible combinations.

Below is the implementation of the above idea:  

C++




// CPP program to count the number of
// unique triplets whose XOR is 0
#include <bits/stdc++.h>
using namespace std;
 
// function to count the number of
// unique triplets whose xor is 0
int countTriplets(int a[], int n)
{
    // To store values that are present
    unordered_set<int> s;
    for (int i = 0; i < n; i++)
        s.insert(a[i]);
     
    // stores the count of unique triplets
    int count = 0;
     
    // traverse for all i, j pairs such that j>i
    for (int i = 0; i < n-1; i++) {
        for (int j = i + 1; j < n; j++) {
 
          // xor of a[i] and a[j]
          int xr = a[i] ^ a[j];
     
          // if xr of two numbers is present,
          // then increase the count
          if (s.find(xr) != s.end() && xr != a[i] &&
                                       xr != a[j])
            count++;
        }
    }
     
    // returns answer
    return count / 3;
}
 
// Driver code to test above function
int main()
{
    int a[] = {1, 3, 5, 10, 14, 15};
    int n = sizeof(a) / sizeof(a[0]);  
    cout << countTriplets(a, n);   
    return 0;
}


Java




// Java program to count
// the number of unique
// triplets whose XOR is 0
import java.io.*;
import java.util.*;
 
class GFG
{
    // function to count the
    // number of unique triplets
    // whose xor is 0
    static int countTriplets(int []a,
                             int n)
    {
        // To store values
        // that are present
        ArrayList<Integer> s =
                  new ArrayList<Integer>();
        for (int i = 0; i < n; i++)
            s.add(a[i]);
         
        // stores the count
        // of unique triplets
        int count = 0;
         
        // traverse for all i,
        // j pairs such that j>i
        for (int i = 0; i < n; i++)
        {
            for (int j = i + 1;
                     j < n; j++)
            {
     
            // xor of a[i] and a[j]
            int xr = a[i] ^ a[j];
         
            // if xr of two numbers
            // is present, then
            // increase the count
            if (s.contains(xr) &&
                xr != a[i] && xr != a[j])
                count++;
            }
        }
         
        // returns answer
        return count / 3;
    }
     
    // Driver code
    public static void main(String srgs[])
    {
        int []a = {1, 3, 5,
                   10, 14, 15};
        int n = a.length;
        System.out.print(countTriplets(a, n));
    }
}
 
// This code is contributed by
// Manish Shaw(manishshaw1)


Python3




# Python 3 program to count the number of
# unique triplets whose XOR is 0
 
# function to count the number of
# unique triplets whose xor is 0
def countTriplets(a, n):
     
    # To store values that are present
    s = set()
    for i in range(n):
        s.add(a[i])
     
    # stores the count of unique triplets
    count = 0
     
    # traverse for all i, j pairs such that j>i
    for i in range(n):
        for j in range(i + 1, n, 1):
             
            # xor of a[i] and a[j]
            xr = a[i] ^ a[j]
             
            # if xr of two numbers is present,
            # then increase the count
            if (xr in s and xr != a[i] and
                            xr != a[j]):
                count += 1;
         
    # returns answer
    return int(count / 3)
 
# Driver code
if __name__ == '__main__':
    a = [1, 3, 5, 10, 14, 15]
    n = len(a)
    print(countTriplets(a, n))
     
# This code is contributed by
# Surendra_Gangwar


C#




// C# program to count
// the number of unique
// triplets whose XOR is 0
using System;
using System.Collections.Generic;
 
class GFG
{
    // function to count the
    // number of unique triplets
    // whose xor is 0
    static int countTriplets(int []a,
                             int n)
    {
        // To store values
        // that are present
        List<int> s = new List<int>();
        for (int i = 0; i < n; i++)
            s.Add(a[i]);
         
        // stores the count
        // of unique triplets
        int count = 0;
         
        // traverse for all i,
        // j pairs such that j>i
        for (int i = 0; i < n; i++)
        {
            for (int j = i + 1;
                     j < n; j++)
            {
     
            // xor of a[i] and a[j]
            int xr = a[i] ^ a[j];
         
            // if xr of two numbers
            // is present, then
            // increase the count
            if (s.Exists(item => item == xr) &&
                   xr != a[i] && xr != a[j])
                count++;
            }
        }
         
        // returns answer
        return count / 3;
    }
     
    // Driver code
    static void Main()
    {
        int []a = new int[]{1, 3, 5,
                            10, 14, 15};
        int n = a.Length;
        Console.Write(countTriplets(a, n));
    }
}
 
// This code is contributed by
// Manish Shaw(manishshaw1)


Javascript




<script>
    // javascript program to count
    // the number of unique
    // triplets whose XOR is 0
 
    // function to count the
    // number of unique triplets
    // whose xor is 0
    function countTriplets(a , n) {
        // To store values
        // that are present
        var s = [];
        for (i = 0; i < n; i++)
            s.push(a[i]);
 
        // stores the count
        // of unique triplets
        var count = 0;
 
        // traverse for all i,
        // j pairs such that j>i
        for (i = 0; i < n; i++) {
            for (j = i + 1; j < n; j++) {
 
                // xor of a[i] and a[j]
                var xr = a[i] ^ a[j];
 
                // if xr of two numbers
                // is present, then
                // increase the count
                if (s.includes(xr) && xr != a[i] && xr != a[j])
                    count++;
            }
        }
 
        // returns answer
        return count / 3;
    }
 
    // Driver code
    var a = [ 1, 3, 5, 10, 14, 15 ];
    var n = a.length;
    document.write(countTriplets(a, n));
 
// This code contributed by Rajput-Ji
</script>


Output

2

Time Complexity: O(N*N), as we are using a loop to traverse N*N times.
Auxiliary Space: O(N), as we are using extra space for set s.



Similar Reads

C++ Program for Number of unique triplets whose XOR is zero
Given N numbers with no duplicates, count the number of unique triplets (ai, aj, ak) such that their XOR is 0. A triplet is said to be unique if all of the three numbers in the triplet are unique. Examples: Input : a[] = {1, 3, 5, 10, 14, 15}; Output : 2 Explanation : {1, 14, 15} and {5, 10, 15} are the unique triplets whose XOR is 0. {1, 14, 15} a
3 min read
Java Program for Number of unique triplets whose XOR is zero
Given N numbers with no duplicates, count the number of unique triplets (ai, aj, ak) such that their XOR is 0. A triplet is said to be unique if all of the three numbers in the triplet are unique. Examples: Input : a[] = {1, 3, 5, 10, 14, 15}; Output : 2 Explanation : {1, 14, 15} and {5, 10, 15} are the unique triplets whose XOR is 0. {1, 14, 15} a
3 min read
Python3 Program for Number of unique triplets whose XOR is zero
Given N numbers with no duplicates, count the number of unique triplets (ai, aj, ak) such that their XOR is 0. A triplet is said to be unique if all of the three numbers in the triplet are unique. Examples: Input : a[] = {1, 3, 5, 10, 14, 15}; Output : 2 Explanation : {1, 14, 15} and {5, 10, 15} are the unique triplets whose XOR is 0. {1, 14, 15} a
3 min read
Javascript Program for Number of unique triplets whose XOR is zero
Given N numbers with no duplicates, count the number of unique triplets (ai, aj, ak) such that their XOR is 0. A triplet is said to be unique if all of the three numbers in the triplet are unique. Examples: Input : a[] = {1, 3, 5, 10, 14, 15}; Output : 2 Explanation : {1, 14, 15} and {5, 10, 15} are the unique triplets whose XOR is 0. {1, 14, 15} a
3 min read
Count of triplets whose XOR has even set bits in range [L, R] for Q queries
Given an array arr[] of size N, and an array Q[] consisting of M queries of type {L, R}, the task is to print the count of triplets whose XOR has an even number of set bits in the range [L, R], for each of the M queries. Examples: Input: arr[] = {1, 2, 3, 4, 5}, N = 5, Q[] = {{1, 4}, {3, 4}}, M = 2Output: 3 0Explanation:Perform the query as followi
13 min read
Count all triplets from given Array whose bitwise XOR is equal to K
Given an array arr[] which contains N positive integers and an integer K. The task is to count all triplets whose XOR is equal to the K. i.e arr[ i ] ^ arr[ j ] ^ arr[ k ] = X where 0 ≤ i &lt; j &lt; k &lt; N ( 0 based indexing) Examples: Input: arr[] = { 2, 1, 3, 7, 5, 4}, K = 5Output: 2Explanation: In the above array there are two triplets whose
17 min read
Number of unique pairs whose bitwise XOR and OR are same
Given an integer N, the task is to find the number of pairs (say {a, b})from 1 to N (both inclusive) that satisfies the condition: a and b are distinct elements. The values of a | b and a ^ b are equal and a( a | b ) = b( a ^ b ) - ( a | b ) also holds true. Examples: Input: N=5Output:1Explanation: If we consider a=3 and b=4, then a | b = 7 and a ^
9 min read
Print all the root-to-leaf paths of a Binary Tree whose XOR is non-zero
Given a Binary Tree, the task is to print all root-to-leaf paths of this tree whose xor value is non-zero. Examples: Input: 10 / \ 10 3 / \ 10 3 / \ / \ 7 3 42 13 / 7 Output: 10 3 10 7 10 3 3 42 Explanation: All the paths in the given binary tree are : {10, 10} xor value of the path is = 10 ^ 10 = 0 {10, 3, 10, 7} xor value of the path is = 10 ^ 3
11 min read
All pairs whose xor gives unique prime
Given an array arr[], the task is to count all the pairs whose xor gives the unique prime, i.e. no two pairs should give the same prime.Examples: Input: arr[] = {2, 3, 4, 5, 6, 7, 8, 9} Output: 6 (2, 5), (2, 7), (2, 9), (4, 6), (4, 7) and (4, 9) are the only pairs whose XORs are primes i.e. 7, 5, 11, 2, 3 and 13 respectively.Input: arr[] = {10, 12,
6 min read
Count of subarrays in range [L, R] having XOR + 1 equal to XOR (XOR) 1 for M queries
Given an array, arr[] of N positive integers and M queries which consist of two integers [Li, Ri] where 1 ? Li ? Ri ? N. For each query, find the number of subarrays in range [Li, Ri] for which (X+1)=(X?1) where X denotes the xor of a subarray. Input: arr[]= {1, 2, 9, 8, 7}, queries[] = {{1, 5}, {3, 4}}Output: 6 1Explanation: Query 1: L=1, R=5: sub
12 min read