Maximum XOR of Two Non-Overlapping Subtrees - Problem

There is an undirected tree with n nodes labeled from 0 to n - 1. You are given the integer n and a 2D integer array edges of length n - 1, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.

The root of the tree is the node labeled 0. Each node has an associated value. You are given an array values of length n, where values[i] is the value of the ith node.

Select any two non-overlapping subtrees. Your score is the bitwise XOR of the sum of the values within those subtrees.

Return the maximum possible score you can achieve. If it is impossible to find two non-overlapping subtrees, return 0.

Note that:

  • The subtree of a node is the tree consisting of that node and all of its descendants.
  • Two subtrees are non-overlapping if they do not share any common node.

Input & Output

Example 1 — Basic Tree
$ Input: n = 6, edges = [[0,1],[1,3],[1,4],[0,2],[2,5]], values = [2,8,3,6,2,5]
Output: 24
💡 Note: We can select subtree rooted at node 1 (sum = 8+6+2 = 16) and subtree rooted at node 2 (sum = 3+5 = 8). XOR: 16 ⊕ 8 = 24
Example 2 — Small Tree
$ Input: n = 3, edges = [[0,1],[0,2]], values = [4,3,1]
Output: 0
💡 Note: Any two non-overlapping subtrees would be single nodes. Maximum XOR is 3 ⊕ 1 = 2, but since we need subtrees, best is 0
Example 3 — Linear Tree
$ Input: n = 4, edges = [[0,1],[1,2],[2,3]], values = [1,1,1,1]
Output: 3
💡 Note: Select subtree at node 0 (sum=1) and subtree at node 3 (sum=1). But better: node 1 subtree (sum=3) and node 3 (sum=1). XOR: 3 ⊕ 1 = 2. Actually, best is subtree [0,1,2] = 3 and node 3 = 1, giving 3 ⊕ 1 = 2. Wait, let me recalculate: we can have subtree starting at 1 (includes 2,3) = 3, and node 0 = 1, giving 3 ⊕ 1 = 2. Or subtree at 0 (includes 1,2,3) = 4 but then no second subtree. Best is subtree 1,2 = 2 and subtree 3 = 1, giving 2 ⊕ 1 = 3

Constraints

  • 2 ≤ n ≤ 5 × 104
  • edges.length == n - 1
  • 0 ≤ ai, bi < n
  • ai ≠ bi
  • 1 ≤ values[i] ≤ 109
  • The given edges form a valid tree

Visualization

Tap to expand
Maximum XOR of Two Non-Overlapping SubtreesInput Tree2Node 08Node 13Node 26Node 32Node 45Node 5Selected SubtreesSubtree 1Sum = 8+6+2 = 16Subtree 2Sum = 3+5 = 883625ResultXOR Calculation16 ⊕ 8 = 24Binary: 10000 ⊕ 01000Maximum XOR: 24Two non-overlapping subtrees with maximum XOR of their sums
Understanding the Visualization
1
Input Tree
Tree with node values and edges
2
Find Subtrees
Identify all possible non-overlapping subtree pairs
3
Maximum XOR
Calculate XOR of subtree sums and find maximum
Key Takeaway
🎯 Key Insight: Use DFS to generate all subtree sums, then find maximum XOR efficiently with Trie
Asked in
Google 12 Amazon 8 Microsoft 6
8.9K Views
Medium Frequency
~35 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen