Imagine you're a geneticist studying a unique species where each organism has a genetic value equal to its ID number. These organisms form a family tree (rooted tree) where each organism has exactly one parent, except for the ancient ancestor at the root.
You need to answer queries about genetic compatibility between organisms. For each query, you're given an organism and a test genetic value. You want to find the maximum genetic difference (calculated using XOR operation) between the test value and any ancestor of the given organism (including the organism itself).
Input:
parents: Array whereparents[i]is the parent of organismi, or-1ifiis the rootqueries: Array of[node, val]pairs - find max XOR betweenvaland any ancestor ofnode
Output: Array of maximum genetic differences for each query
Example: If organism 3 has ancestors [1, 0] and we query with value 5, we calculate 5 XOR 3 = 6, 5 XOR 1 = 4, 5 XOR 0 = 5, so the answer is max(6,4,5) = 6.
Input & Output
Visualization
Time & Space Complexity
DFS visits each node once, each Trie operation takes log(MAX_VAL) time where MAX_VAL is maximum possible value
Trie storage for N nodes, each with log(MAX_VAL) bits, plus recursion stack
Constraints
- 1 โค parents.length โค 105
- 0 โค parents[i] โค parents.length - 1
- parents[i] โ i
- 1 โค queries.length โค 3 ร 104
- 0 โค nodei โค parents.length - 1
- 0 โค vali โค 2 ร 105
- Exactly one element of parents is -1