01. XOR Pairs less than K
β GFG solution to the Count Pairs with XOR Less Than K problem: efficiently count pairs whose XOR is less than k using Binary Trie data structure. π
The problem can be found at the following link: π Question Link
π§© Problem Description
Given an array arr[] and an integer k, count the number of pairs from the array such that the Bitwise XOR of each pair is less than k.
A pair (i, j) is valid if i < j and arr[i] ^ arr[j] < k.
π Examples
Example 1
Input: arr = [1, 2, 3, 5], k = 5
Output: 4
Explanation: Valid pairs with XOR < 5:
1 ^ 2 = 3
1 ^ 3 = 2
1 ^ 5 = 4
2 ^ 3 = 1
Total = 4 pairsExample 2
Input: arr[] = [3, 5, 6, 8], k = 7
Output: 3
Explanation: Valid pairs with XOR < 7:
3 ^ 5 = 6
3 ^ 6 = 5
5 ^ 6 = 3
Total = 3 pairsπ Constraints
$1 \le \text{arr.size()}, k \le 5 \times 10^4$
$1 \le \text{arr}[i] \le 5 \times 10^4$
β
My Approach
The optimal solution uses a Binary Trie data structure to efficiently count XOR pairs:
Binary Trie Approach
Trie Structure:
Build a binary trie where each node represents a bit (0 or 1).
Store 32-bit representation of numbers from MSB to LSB.
Each node maintains a count of numbers passing through it.
Query Operation:
For each element, traverse the trie to count existing numbers whose XOR is less than k.
At each bit position, compare bits of current number, k, and trie path.
If k's bit is 1, we can take the path that makes XOR smaller and count those numbers.
If k's bit is 0, we must follow the exact path to keep XOR minimal.
Insertion:
After counting pairs for current element, insert it into the trie.
This ensures we only count each pair once (avoiding duplicates).
Bit Manipulation Logic:
For bit position i: if
k[i] = 1, numbers withXOR[i] = 0are valid (< k).Count all numbers in the matching branch, then explore the opposite branch.
If
k[i] = 0, only exact matching path keeps XOR < k.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n Γ 32) β O(n), where n is the size of the array. Each element requires traversing a fixed-depth trie of 32 levels (for 32-bit integers), making it effectively linear time.
Expected Auxiliary Space Complexity: O(n Γ 32) β O(n), for storing the binary trie structure. In worst case, each number creates 32 new nodes, resulting in linear space proportional to the number of elements.
π§βπ» Code (C++)
class Solution {
public:
class T {
public:
T* c[2];
int n;
T() { c[0] = c[1] = NULL; n = 0; }
};
void add(T* r, int v) {
for (int i = 31; i >= 0; i--) {
int b = (v >> i) & 1;
if (!r->c[b]) r->c[b] = new T();
r->c[b]->n++;
r = r->c[b];
}
}
int cnt(T* r, int v, int k) {
int res = 0;
for (int i = 31; i >= 0 && r; i--) {
int bv = (v >> i) & 1, bk = (k >> i) & 1;
if (bk) {
if (r->c[bv]) res += r->c[bv]->n;
r = r->c[1 - bv];
} else r = r->c[bv];
}
return res;
}
int cntPairs(vector<int>& a, int k) {
T* r = new T();
int ans = 0;
for (int x : a) {
ans += cnt(r, x, k);
add(r, x);
}
return ans;
}
};β Code (Java)
class Solution {
class Node {
Node[] ch = new Node[2];
int cnt = 0;
}
void add(Node r, int v) {
for (int i = 31; i >= 0; i--) {
int b = (v >> i) & 1;
if (r.ch[b] == null) r.ch[b] = new Node();
r.ch[b].cnt++;
r = r.ch[b];
}
}
int query(Node r, int v, int k) {
int res = 0;
for (int i = 31; i >= 0 && r != null; i--) {
int bv = (v >> i) & 1, bk = (k >> i) & 1;
if (bk == 1) {
if (r.ch[bv] != null) res += r.ch[bv].cnt;
r = r.ch[1 - bv];
} else r = r.ch[bv];
}
return res;
}
public int cntPairs(int[] a, int k) {
Node r = new Node();
int ans = 0;
for (int x : a) {
ans += query(r, x, k);
add(r, x);
}
return ans;
}
}π Code (Python)
class Solution:
class Node:
def __init__(self):
self.ch = [None, None]
self.cnt = 0
def add(self, r, v):
for i in range(31, -1, -1):
b = (v >> i) & 1
if not r.ch[b]: r.ch[b] = self.Node()
r.ch[b].cnt += 1
r = r.ch[b]
def query(self, r, v, k):
res = 0
for i in range(31, -1, -1):
if not r: break
bv, bk = (v >> i) & 1, (k >> i) & 1
if bk:
if r.ch[bv]: res += r.ch[bv].cnt
r = r.ch[1 - bv]
else: r = r.ch[bv]
return res
def cntPairs(self, a, k):
r = self.Node()
ans = 0
for x in a:
ans += self.query(r, x, k)
self.add(r, x)
return ansπ§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated