Maximum XOR of Two Non-Overlapping Subtrees - Problem
Given an undirected tree with n nodes labeled from 0 to n-1, find the maximum XOR of the sums of values from two non-overlapping subtrees.
You are provided with:
- An integer
nrepresenting the number of nodes - A 2D array
edgesof length n-1 whereedges[i] = [ai, bi]indicates an edge between nodes ai and bi - An array
valueswherevalues[i]is the value associated with the i-th node
The tree is rooted at node 0. Your task is to select any two non-overlapping subtrees and calculate the bitwise XOR of their sums. Two subtrees are non-overlapping if they share no common nodes.
Goal: Return the maximum possible XOR score. If no two non-overlapping subtrees exist, return 0.
Input & Output
example_1.py โ Basic Tree
$
Input:
n = 6, edges = [[0,1],[0,2],[1,3],[1,4],[2,5]], values = [4,6,1,3,1,2]
โบ
Output:
16
๐ก Note:
Select subtree rooted at node 1 (sum = 6+3+1 = 10) and subtree rooted at node 2 (sum = 1+2 = 3). XOR = 10 ^ 3 = 9. However, selecting subtree at node 1 (sum = 10) and single node 5 (sum = 2) gives XOR = 10 ^ 2 = 8. The optimal is selecting subtree at node 3 (sum = 3) and the remaining tree gives better result.
example_2.py โ Linear Tree
$
Input:
n = 3, edges = [[0,1],[1,2]], values = [5,3,7]
โบ
Output:
12
๐ก Note:
Select subtree rooted at node 1 (sum = 3+7 = 10) and single node 0 (sum = 5). XOR = 10 ^ 5 = 15. Alternatively, select node 2 (sum = 7) and node 0 (sum = 5) for XOR = 7 ^ 5 = 2. The maximum is 15.
example_3.py โ Single Node
$
Input:
n = 1, edges = [], values = [10]
โบ
Output:
0
๐ก Note:
Only one node exists, so we cannot select two non-overlapping subtrees. Return 0.
Visualization
Tap to expand
Understanding the Visualization
1
Build Network Tree
Construct the tree structure and establish parent-child relationships
2
Calculate Segment Values
Use DFS to compute total value for each network segment (subtree)
3
Smart XOR Matching
Use Trie to efficiently find best XOR pairs without checking all combinations
4
Optimize Locally
Check XOR between child segments at each node for additional optimization
Key Takeaway
๐ฏ Key Insight: The Trie data structure transforms an O(nยฒ) brute force approach into an O(n log S) optimal solution by enabling efficient maximum XOR queries during tree traversal.
Time & Space Complexity
Time Complexity
O(n log S)
O(n) for DFS traversal, O(log S) for each Trie operation where S is maximum sum value
โก Linearithmic
Space Complexity
O(n log S)
O(n) for recursion stack, O(n log S) for Trie storage
โก Linearithmic Space
Constraints
- 1 โค n โค 5 ร 104
- edges.length == n - 1
- 0 โค ai, bi < n
- ai โ bi
- edges represents a valid tree
- 1 โค values[i] โค 109
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code