#1803

Count Pairs With XOR in a Range

Hard
ArrayBit ManipulationTrieBit ManipulationTrieSliding Window
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log(max_num))
Space
O(1)
O(n)
💡

Intuition

Time O(n log(max_num))Space O(n)

Using a Trie data structure allows us to efficiently count pairs whose XOR values fall within a specified range. This approach leverages the properties of binary representation and the Trie structure to reduce the time complexity significantly.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a Trie to store the binary representations of numbers.
  2. 2Step 2: For each number in nums, insert it into the Trie.
  3. 3Step 3: For each number, calculate the number of valid pairs by traversing the Trie to count how many numbers produce an XOR within the range [low, high].
  4. 4Step 4: Use a helper function to count the valid pairs for a given number based on the Trie.
  5. 5Step 5: Return the total count of nice pairs.
solution.py39 lines
1class TrieNode:
2    def __init__(self):
3        self.children = {}
4        self.count = 0
5
6class Trie:
7    def __init__(self):
8        self.root = TrieNode()
9
10    def insert(self, num):
11        node = self.root
12        for i in range(15, -1, -1):
13            bit = (num >> i) & 1
14            if bit not in node.children:
15                node.children[bit] = TrieNode()
16            node = node.children[bit]
17            node.count += 1
18
19    def countPairs(self, num, low, high):
20        return self._count(num, low, 0, 15) - self._count(num, high + 1, 0, 15)
21
22    def _count(self, num, limit, node, bit):
23        if node is None or bit < 0:
24            return 0
25        if limit < 0:
26            return 0
27        bit_num = (num >> bit) & 1
28        if (limit >> bit) & 1:
29            return node.count + self._count(num, limit, node.children.get(bit_num), bit - 1) + self._count(num, limit, node.children.get(1 - bit_num), bit - 1)
30        else:
31            return self._count(num, limit, node.children.get(bit_num), bit - 1)
32
33def countPairs(nums, low, high):
34    trie = Trie()
35    count = 0
36    for num in nums:
37        count += trie.countPairs(num, low, high)
38        trie.insert(num)
39    return count

Complexity note: The time complexity is O(n log(max_num)) because we insert each number into the Trie and count pairs based on the binary representation, where max_num is the maximum value in nums. The space complexity is O(n) due to the storage of the Trie nodes.

  • 1Using a Trie can significantly reduce the time complexity for counting pairs based on bitwise operations.
  • 2Understanding the properties of XOR and its binary representation is crucial for optimizing the solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.