#3590

Kth Smallest Path XOR Sum

Hard
ArrayTreeDepth-First SearchOrdered SetHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Utilize DFS to compute path XORs while merging results from child nodes efficiently using a union-find approach.

⚙️

Algorithm

3 steps
  1. 1Step 1: Perform DFS from the root, maintaining a set of XOR sums for each node.
  2. 2Step 2: Use union-find to merge child XOR sets into the parent set during the DFS.
  3. 3Step 3: For each query, retrieve the k-th smallest XOR sum from the merged results.
solution.py18 lines
1def kth_smallest_path_xor(par, vals, queries):
2    from collections import defaultdict
3    def dfs(node, current_xor, results):
4        current_xor ^= vals[node]
5        results.add(current_xor)
6        for child in tree[node]:
7            dfs(child, current_xor, results)
8    tree = defaultdict(list)
9    for i in range(len(par)):
10        if par[i] != -1:
11            tree[par[i]].append(i)
12    answers = []
13    for u, k in queries:
14        results = set()
15        dfs(u, 0, results)
16        distinct_sums = sorted(results)
17        answers.append(distinct_sums[k-1] if k <= len(distinct_sums) else -1)
18    return answers

Complexity note: DFS visits each node once, and merging results is efficient, leading to O(n) complexity overall.

  • 1Understanding tree structure is crucial.
  • 2XOR properties can simplify path calculations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.