Maximum Genetic Difference Query - Problem

There is a rooted tree consisting of n nodes numbered 0 to n - 1. Each node's number denotes its unique genetic value (i.e., the genetic value of node x is x). The genetic difference between two genetic values is defined as the bitwise-XOR of their values.

You are given the integer array parents, where parents[i] is the parent for node i. If node x is the root of the tree, then parents[x] == -1.

You are also given the array queries where queries[i] = [nodei, vali]. For each query i, find the maximum genetic difference between vali and pi, where pi is the genetic value of any node that is on the path between nodei and the root (including nodei and the root). More formally, you want to maximize vali XOR pi.

Return an array ans where ans[i] is the answer to the ith query.

Input & Output

Example 1 — Basic Tree Queries
$ Input: parents = [-1,0,0,2], queries = [[3,4],[2,5]]
Output: [7,5]
💡 Note: Tree: 0 is root, 1 and 2 are children of 0, 3 is child of 2. Query [3,4]: ancestors of 3 are [3,2,0], max XOR is 4⊕3=7. Query [2,5]: ancestors of 2 are [2,0], max XOR is 5⊕0=5.
Example 2 — Single Node Tree
$ Input: parents = [-1], queries = [[0,1]]
Output: [1]
💡 Note: Only node 0 exists as root. Query [0,1]: only ancestor is node 0, so XOR is 1⊕0=1.
Example 3 — Linear Tree Path
$ Input: parents = [-1,0,1], queries = [[2,3]]
Output: [3]
💡 Note: Linear tree: 0→1→2. Query [2,3]: ancestors are [2,1,0], XOR values are 3⊕2=1, 3⊕1=2, 3⊕0=3, so maximum is 3.

Constraints

  • n == parents.length
  • 2 ≤ n ≤ 105
  • 0 ≤ parents[i] ≤ n - 1 for i ≠ root
  • parents[root] == -1
  • 1 ≤ queries.length ≤ 3 × 104
  • 0 ≤ nodei ≤ n - 1
  • 0 ≤ vali ≤ 2 × 105

Visualization

Tap to expand
Maximum Genetic Difference QueryInput Tree:0123parents = [-1,0,0,2]Queries:[3, 4][2, 5]Node, Value pairsProcess:Query [3,4]:Path: 3→2→0XOR: 4⊕3=7, 4⊕2=6, 4⊕0=4Max: 7Query [2,5]:Path: 2→0XOR: 5⊕2=7, 5⊕0=5Max: 7Output: [7, 5][7, 5]
Understanding the Visualization
1
Input
Tree structure from parents array and queries with [node, value]
2
Process
For each query, find all ancestors and compute maximum XOR
3
Output
Array of maximum XOR values for each query
Key Takeaway
🎯 Key Insight: Use trie data structure to efficiently find maximum XOR by choosing opposite bits at each level
Asked in
Google 25 Amazon 18 Microsoft 15 Apple 12
12.5K Views
Medium Frequency
~35 min Avg. Time
485 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen