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
arr=[7, 29, 32, 54, 90, 2]
0
Example 2
arr=[1, 3, 5, 10, 14, 15]
2
The simplest method is to have three nested loops and check each one to see if the XOR of the three numbers is zero.
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));}}
count()
function that accepts an array and uses three loops to count the number of unique triplets whose XOR is zero.main()
method, we invoke the count()
function.