Kth Smallest Path XOR Sum Problem
Description
LeetCode Problem 3590.
You are given an undirected tree rooted at node 0 with n nodes numbered from 0 to n - 1. Each node i has an integer value vals[i], and its parent is given by par[i].
The path XOR sum from the root to a node u is defined as the bitwise XOR of all vals[i] for nodes i on the path from the root node to node u, inclusive.
You are given a 2D integer array queries, where queries[j] = [u_j, k_j]. For each query, find the k_j^th smallest distinct path XOR sum among all nodes in the subtree rooted at u_j. If there are fewer than k_j distinct path XOR sums in that subtree, the answer is -1.
Return an integer array where the j^th element is the answer to the j^th query.
In a rooted tree, the subtree of a node v includes v and all nodes whose path to the root passes through v, that is, v and its descendants.
Example 1:
Input: par = [-1,0,0], vals = [1,1,1], queries = [[0,1],[0,2],[0,3]]
Output: [0,1,-1]
Explanation:

Path XORs:
- Node 0: 1
- Node 1: 1 XOR 1 = 0
- Node 2: 1 XOR 1 = 0
Subtree of 0: Subtree rooted at node 0 includes nodes [0, 1, 2] with Path XORs = [1, 0, 0]. The distinct XORs are [0, 1].
Queries:
- queries[0] = [0, 1]: The 1st smallest distinct path XOR in the subtree of node 0 is 0.
- queries[1] = [0, 2]: The 2nd smallest distinct path XOR in the subtree of node 0 is 1.
- queries[2] = [0, 3]: Since there are only two distinct path XORs in this subtree, the answer is -1.
Output: [0, 1, -1]
Example 2:
Input: par = [-1,0,1], vals = [5,2,7], queries = [[0,1],[1,2],[1,3],[2,1]]
Output: [0,7,-1,0]
Explanation:

Path XORs:
- Node 0: 5
- Node 1: 5 XOR 2 = 7
- Node 2: 5 XOR 2 XOR 7 = 0
Subtrees and Distinct Path XORs:
- Subtree of 0: Subtree rooted at node 0 includes nodes [0, 1, 2] with Path XORs = [5, 7, 0]. The distinct XORs are [0, 5, 7].
- Subtree of 1: Subtree rooted at node 1 includes nodes [1, 2] with Path XORs = [7, 0]. The distinct XORs are [0, 7].
- Subtree of 2: Subtree rooted at node 2 includes only node [2] with Path XOR = [0]. The distinct XORs are [0].
Queries:
- queries[0] = [0, 1]: The 1st smallest distinct path XOR in the subtree of node 0 is 0.
- queries[1] = [1, 2]: The 2nd smallest distinct path XOR in the subtree of node 1 is 7.
- queries[2] = [1, 3]: Since there are only two distinct path XORs, the answer is -1.
- queries[3] = [2, 1]: The 1st smallest distinct path XOR in the subtree of node 2 is 0.
Output: [0, 7, -1, 0]
Constraints:
1 <= n == vals.length <= 5 * 10^40 <= vals[i] <= 10^5par.length == npar[0] == -10 <= par[i] < nforiin[1, n - 1]1 <= queries.length <= 5 * 10^4queries[j] == [u_j, k_j]0 <= u_j < n1 <= k_j <= n- The input is generated such that the parent array
parrepresents a valid tree.
Solution
Approach: Small-to-Large Merging of Binary Tries
Compute the XOR of the path from the root to every node. A query asks for the k-th smallest distinct value among the path XORs in a subtree.
Keep, for every subtree, a binary trie of its distinct path XORs where each trie node stores how many distinct values lie below it. Process the nodes from the leaves up: start from a trie holding the node's own value, and merge each child's trie into it, always inserting the values of the smaller trie into the larger one and skipping values that already exist. Once a node's trie is complete, answer its queries by walking down the trie using the counts (go left if k fits in the left count, otherwise subtract it and go right); if k exceeds the total count the answer is -1.
Complexity: O(n log n * B) time for the merges, where B = 17 is the bit width of the values, and O(n log n * B) space in the worst case.
class Solution:
def kthSmallest(self, par: List[int], vals: List[int], queries: List[List[int]]) -> List[int]:
n = len(par)
B = 17 # path XOR sums are below 2^17
g = [[] for _ in range(n)]
for i in range(1, n):
g[par[i]].append(i)
order = [0]
for u in order:
order.extend(g[u])
px = vals[:]
for u in order:
for v in g[u]:
px[v] ^= px[u]
# binary trie pool: node 0 is the null node; cnt = number of distinct values below
c0, c1, cnt = [0], [0], [0]
def new_node():
c0.append(0)
c1.append(0)
cnt.append(0)
return len(cnt) - 1
def exists(root, x):
node = root
for b in range(B - 1, -1, -1):
node = c1[node] if (x >> b) & 1 else c0[node]
if not node:
return False
return True
def add(root, x):
node = root
cnt[node] += 1
for b in range(B - 1, -1, -1):
ch = c1 if (x >> b) & 1 else c0
if not ch[node]:
ch[node] = new_node()
node = ch[node]
cnt[node] += 1
def collect(root):
res = []
stack = [(root, B - 1, 0)]
while stack:
node, b, prefix = stack.pop()
if b < 0:
res.append(prefix)
continue
if c0[node]:
stack.append((c0[node], b - 1, prefix))
if c1[node]:
stack.append((c1[node], b - 1, prefix | (1 << b)))
return res
def kth(root, k):
node, res = root, 0
for b in range(B - 1, -1, -1):
left = cnt[c0[node]]
if k <= left:
node = c0[node]
else:
k -= left
res |= 1 << b
node = c1[node]
return res
qs = [[] for _ in range(n)]
for i, (u, k) in enumerate(queries):
qs[u].append((k, i))
ans = [-1] * len(queries)
root = [0] * n
for u in reversed(order):
r = new_node()
add(r, px[u])
for v in g[u]:
if cnt[r] < cnt[root[v]]:
r, root[v] = root[v], r
for x in collect(root[v]):
if not exists(r, x):
add(r, x)
root[v] = 0
root[u] = r
for k, i in qs[u]:
if k <= cnt[r]:
ans[i] = kth(r, k)
return ans