How to find the number of unique triplets whose XOR is zero

Problem statement

Given an array of numbers with no duplicates, count the number of unique triplets (x, y, z) such that the result of their XOR is zero.

A unique triplet is a triplet where all three numbers in the triplet are unique.

Example 1

  • Input: arr=[7, 29, 32, 54, 90, 2]
  • Output: 0

Example 2

  • Input: arr=[1, 3, 5, 10, 14, 15]
  • Output: 2

Solution

The simplest method is to have three nested loops and check each one to see if the XOR of the three numbers is zero.

Code

Let’s view a code example.

public class Main{
private static int count(int[] arr){
int count = 0;
int n = arr.length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = j + 1; k < n; k++) {
if ((arr[i] ^ arr[j] ^ arr[k]) == 0) {
count++;
}
}
}
}
return count;
}
public static void main(String[] args) {
int[] arr = {7, 29, 32, 54, 90, 2};
System.out.println(count(arr));
}
}
Try it out!

Explanation

  • Lines 3–15: We define a count() function that accepts an array and uses three loops to count the number of unique triplets whose XOR is zero.
  • Lines 18–21: In the main() method, we invoke the count() function.
New on Educative
Learn any Language for FREE all September 🎉
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources