Best XOR Between a Value and Any Ancestor in a Tree
Last updated: November 29, 2026
Quick Overview
Each node of a rooted tree has an integer label equal to its index; for queries (node, v), return the maximum of v XOR label over all nodes on the path from the root to the given node.
0
0
0 solved
Each node of a rooted tree has an integer label equal to its index; for queries (node, v), return the maximum of v XOR label over all nodes on the path from the root to the given node.
A hard Google onsite problem combining tree traversal with a binary trie. The interviewer checks offline grouping of queries by node, a DFS that inserts on entry and removes on exit using counts, and an iterative traversal to avoid recursion limits.
What the Interviewer Expects
- Group queries by node so each is answered when DFS reaches it
- Maintain a binary trie of the current root-to-node path
- Use per-node counts so removal on backtrack is correct
- Walk greedily for the opposite bit only where count is positive
- Implement DFS iteratively
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you answer queries online without grouping?
- What if the query asks for the subtree instead of the path?
- How would a persistent trie answer these online?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: parents where parents[i] is the parent of node i and the root has parent -1; node i's label is i. queries is a list of (node, v). Output: for each query, the max v ^ label(u) ov...
High-Level Design
If we visit the tree in DFS order and keep a data structure holding exactly the labels on the current root-to-node path, each query at a node becomes a plain max-XOR query. A binary trie with a count ...