#1707
Maximum XOR With an Element From Array
HardArrayBit ManipulationTrieBit ManipulationTrieSorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n + q log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n + q log n)Space O(n)
The optimal solution uses a Trie to efficiently store the binary representations of the numbers in nums. This allows us to quickly find the best number to maximize the XOR for each query, significantly reducing the time complexity.
⚙️
Algorithm
5 steps- 1Step 1: Sort nums to facilitate efficient searching.
- 2Step 2: Build a Trie from the binary representations of nums.
- 3Step 3: For each query, filter nums to only those <= m using binary search.
- 4Step 4: Use the Trie to find the maximum XOR for the filtered nums with x.
- 5Step 5: Return the results for all queries.
solution.py45 lines
1class TrieNode:
2 def __init__(self):
3 self.children = {}
4 self.value = None
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(31, -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.value = num
18
19 def maxXor(self, num):
20 node = self.root
21 max_xor = 0
22 for i in range(31, -1, -1):
23 bit = (num >> i) & 1
24 toggled_bit = 1 - bit
25 if toggled_bit in node.children:
26 max_xor |= (1 << i)
27 node = node.children[toggled_bit]
28 else:
29 node = node.children.get(bit, None)
30 return max_xor
31
32def maximizeXor(nums, queries):
33 nums.sort()
34 trie = Trie()
35 for num in nums:
36 trie.insert(num)
37 answer = []
38 for x, m in queries:
39 max_xor = -1
40 for num in nums:
41 if num > m:
42 break
43 max_xor = max(max_xor, trie.maxXor(x))
44 answer.append(max_xor)
45 return answerℹ
Complexity note: The sorting step takes O(n log n), and each query involves a binary search and Trie operations, leading to a total complexity of O(n log n + q log n).
- 1Maximizing XOR involves understanding how bits interact; toggling bits can lead to higher values.
- 2Using data structures like Trie can significantly optimize search operations for bit manipulation problems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.