Approach
Depth-first search
For Maximum Genetic Difference Query, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 71 lines of Python from the credited upstream file 1938.py.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class TrieNode:2 def __init__(self):3 self.children: list[TrieNode | None] = [None] * 24 self.count = 05 6 7class Trie:8 def __init__(self):9 self.root = TrieNode()10 self.HEIGHT = 1711 12 def update(self, num: int, val: int) -> None:13 node = self.root14 for i in range(self.HEIGHT, -1, -1):15 bit = (num >> i) & 116 if not node.children[bit]:17 node.children[bit] = TrieNode()18 node = node.children[bit]19 node.count += val20 21 def query(self, num: int) -> int:22 ans = 023 node = self.root24 for i in range(self.HEIGHT, -1, -1):25 bit = (num >> i) & 126 targetBit = bit ^ 127 if node.children[targetBit] and node.children[targetBit].count > 0:28 ans += 1 << i29 node = node.children[targetBit]30 else:31 node = node.children[targetBit ^ 1]32 return ans33 34 35class Solution:36 def maxGeneticDifference(37 self,38 parents: list[int],39 queries: list[list[int]],40 ) -> list[int]:41 n = len(parents)42 ans = [0] * len(queries)43 rootVal = -144 tree = [[] for _ in range(n)]45 nodeToQueries = collections.defaultdict(list) 46 trie = Trie()47 48 for i, parent in enumerate(parents):49 if parent == -1:50 rootVal = i51 else:52 tree[parent].append(i)53 54 for i, (node, val) in enumerate(queries):55 nodeToQueries[node].append((i, val))56 57 def dfs(node: int) -> None:58 trie.update(node, 1)59 60 61 for i, val in nodeToQueries[node]:62 ans[i] = trie.query(val)63 64 for child in tree[node]:65 dfs(child)66 67 trie.update(node, -1)68 69 dfs(rootVal)70 return ans71