Trusted answers to developer questions

Ravi

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`

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)); } }

Try it out!

- 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.

RELATED TAGS

bitwise

CONTRIBUTOR

Ravi

RELATED COURSES

View all Courses

Keep Exploring

Related Courses