#1938
Maximum Genetic Difference Query
HardArrayHash TableBit ManipulationDepth-First SearchTrieTrieBit Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n + q * 32) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n + q * 32)Space O(n)
The optimal solution uses a Trie to store the XOR values of all nodes on the path from each queried node to the root. This allows for efficient retrieval of the maximum XOR value for each query by leveraging the properties of binary numbers.
⚙️
Algorithm
3 steps- 1Step 1: Construct a Trie to store the XOR values of nodes as we traverse from each node to the root.
- 2Step 2: For each query, insert the XOR values into the Trie while traversing to the root.
- 3Step 3: For each query, search the Trie to find the maximum XOR value with the given value.
solution.py42 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 toggle_bit = 1 - bit
25 if toggle_bit in node.children:
26 max_xor |= (1 << i)
27 node = node.children[toggle_bit]
28 else:
29 node = node.children[bit]
30 return max_xor
31
32
33def maxGeneticDifference(parents, queries):
34 trie = Trie()
35 results = []
36 for node in range(len(parents)):
37 xor_value = node
38 trie.insert(xor_value)
39 for node, val in queries:
40 max_xor = trie.maxXor(val)
41 results.append(max_xor)
42 return resultsℹ
Complexity note: The time complexity is O(n + q * 32) where n is the number of nodes and q is the number of queries. Each insertion into the Trie takes O(32) time, and we do this for each node, plus we query the Trie for each query.
- 1Using a Trie can significantly optimize the retrieval of maximum XOR values.
- 2Understanding bit manipulation is crucial for solving XOR-related problems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.