Given an array **arr[]**of size N and an integer K, the task is to count the number of pairs from the given array such that the Bitwise XOR of each pair is greater than K.


Input:_ arr = {1, 2, 3, 5} , K = 2_

Output:_ 4_


Bitwise XOR of all possible pairs that satisfy the given conditions are:

arr[0] ^ arr[1] = 1 ^ 2 = 3

arr[0] ^ arr[3] = 1 ^ 5 = 4

arr[1] ^ arr[3] = 2 ^ 5 = 7

arr[0] ^ arr[3] = 3 ^ 5 = 6

Therefore, the required output is 4.

Input:_ arr[] = {3, 5, 6,8}, K = 2_

Output:_ 6_

Naive Approach: The simplest approach to solve this problem is to traverse the given array and generate all possible pairs of the given array and for each pair, check if bitwise XOR of the pair is greater than K or not. If found to be true, then increment the count of pairs having bitwise XOR greater than K. Finally, print the count of such pairs obtained.

Time Complexity:O(N2)

Auxiliary Space:O(1)

Efficient Approach: The problem can be solved using Trie. The idea is to iterate over the given array and for each array element, count the number of elements present in the Trie whose bitwise XOR with the current element is greater than K and insert the binary representation of the current element into the Trie. Finally, print the count of pairs having bitwise XOR greater than K. Follow the steps below to solve the problem:

  • Create a Trie having root node, say root to store the binary representation of each element of the given array.
  • Traverse the given array, and count the number of elements present in the Trie whose bitwise XOR with the current element is greater than K and insert the binary representation of the current element.
  • Finally, print the count of pairs that satisfies the given condition.


Count pairs having bitwise XOR greater than K from a given array
10.25 GEEK