1565. Ancestor XOR Queries

A company hierarchy is a tree on employees 0..n-1 with the CEO at node 0; edges lists its n - 1 undirected links and vals[i] is the clearance code of employee i. Each query [u, x] asks: among the employees on the chain from the CEO down to employee u (both ends included), which code w gives the largest value of x ^ vals[w]?

Return an int[] with the largest XOR value for each query, in the order the queries are given.

Walking the chain for every query works but costs depth per query. The intended offline method runs one depth-first traversal that inserts vals[u] into a counting binary trie when entering u, answers all queries of u while inside it, and removes the value when leaving. Use an iterative traversal. Target O((n + q) * 20) time and O(n * 20) space.

Example 1

Input:
n = 1edges = []vals = [5]queries = [[0,3]]
Output:
[6]
Explanation:

With a single employee the only candidate is 5, and 3 ^ 5 = 6.

Example 2

Input:
n = 3edges = [[0,1],[1,2]]vals = [1,2,4]queries = [[2,7],[1,0]]
Output:
[6,2]
Explanation:

The chain 0-1-2 holds codes 1, 2, 4; the answers are [6, 2].

Example 3

Input:
n = 4edges = [[0,1],[0,2],[0,3]]vals = [8,1,2,3]queries = [[1,6],[3,6],[0,0]]
Output:
[14,14,8]
Explanation:

Each leaf only sees the root code 8 and its own code; the answers are [14, 14, 8].

Constraints

1 ≤ n ≤ 2000; edges form a tree on 0..n-1; 0 ≤ vals[i], x < 220; 1 ≤ queries.length ≤ 2000

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O((n + q) * 20)
Space
O(n * 20)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…