VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-pairs-having-bitwise-xor-less-than-k-from-given-array/

⇱ Count pairs having Bitwise XOR less than K - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count pairs having Bitwise XOR less than K

Last Updated : 30 Nov, 2025

Given an array arr[] and an integer k, Find the number of pairs (i, j) with i < j such that arr[i] XOR arr[j] is less than k. Each valid pair is counted only once.

Examples:

Input: arr = [1, 2, 3, 5], k = 5 
Output:
Explanation: Bitwise XOR of all possible pairs that satisfy the given conditions are: 
arr[0] ^ arr[1] = 1 ^ 2 = 3 
arr[0] ^ arr[2] = 1 ^ 3 = 2 
arr[0] ^ arr[3] = 1 ^ 5 = 4 
arr[1] ^ arr[2] = 2 ^ 3 = 1 
Therefore, the required output is 4. 

Input: arr[] = [3, 5, 6, 8], k = 7 
Output: 3  
Explanation: Bitwise XOR of all possible pairs that satisfy the given conditions are: 
arr[0] ^ arr[1] = 6
arr[0] ^ arr[2] = 5
arr[1] ^ arr[2] = 3
Therefore, the required output is 3. 

[Naive Approach] By generating all pairs - O(n2) Time and O(1) Space

The 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 less than k or not. If found to be true, then increment the count of pairs having bitwise XOR less than k.


Output
3

[Expected Approach] Using Trie

Instead of explicitly forming all pairs, we insert numbers one by one into the Trie. For every new number x, before inserting it, we ask the Trie: “How many numbers inserted so far have their XOR with x less than k?”
So the Trie helps us count valid pairs without checking every combination.

How Trie Works for XOR < k?
We compare numbers bit by bit (from the most significant bit to the least). At each bit position, we look at: Bit of the current number (x) and Bit of k. Depending on the bit of k, two situations arise:

Case 1: Bit of k is 1, it means:

Numbers whose XOR with x at this bit becomes 0 still keep the total value < K. So all numbers that match the same bit as x can be counted immediately. After counting them, we can still explore numbers that differ from x at that bit, because XOR at this bit becomes 1 (which matches k) - so we need to continue checking remaining bits.

Case 2: Bit of k is 0, It means:

XOR at this bit must also be 0 to stay below k. So the only valid option is to follow the same bit as x. If a different bit is taken, XOR becomes 1 - which already exceeds k at this bit so that path is not allowed.

After completing the entire process - querying the Trie for every element and then inserting it - we will have the total count of all valid pairs whose XOR is less than k.


Output
3

Time Complexity: O(n * 32), Each number requires a 32-bit traversal for counting + insertion.
Auxiliary Space: O(n * 32)

Comment