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 nonoverlapping subtrees, return 0.
Note that:
Example 1:
Input: n = 6, edges = [[0,1],[0,2],[1,3],[1,4],[2,5]], values = [2,8,3,6,2,5] Output: 24 Explanation: Node 1's subtree has sum of values 16, while node 2's subtree has sum of values 8, so choosing these nodes will yield a score of 16 XOR 8 = 24. It can be proved that is the maximum possible score we can obtain.
Example 2:
Input: n = 3, edges = [[0,1],[1,2]], values = [4,6,1] Output: 0 Explanation: There is no possible way to select two non-overlapping subtrees, so we just return 0.
Constraints:
2 <= n <= 5 * 104edges.length == n - 10 <= ai, bi < nvalues.length == n1 <= values[i] <= 109edges represents a valid tree.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
To find the maximum XOR of two non-overlapping subtrees, the brute force approach involves exploring every possible way to pick two completely separate chunks of the tree, calculating their combined values, and comparing everything.
Here's how the algorithm would work step-by-step:
class Solution:
def max_xor_two_subtrees(self, node_count: int, tree_edges: list, node_weights: list) -> int:
adjacency_list = [[] for _ in range(node_count)]
for parent_node, child_node in tree_edges:
adjacency_list[parent_node].append(child_node)
adjacency_list[child_node].append(parent_node)
subtree_sums = [0] * node_count
def compute_subtree_sums(current_node: int, parent_node: int) -> int:
total_sum = node_weights[current_node]
for neighbor_node in adjacency_list[current_node]:
if neighbor_node != parent_node:
total_sum += compute_subtree_sums(neighbor_node, current_node)
subtree_sums[current_node] = total_sum
return total_sum
compute_subtree_sums(0, -1)
subtree_intervals = []
traversal_timer = 0
def dfs_timer(current_node: int, parent_node: int):
nonlocal traversal_timer
entry_time = traversal_timer
traversal_timer += 1
for neighbor_node in adjacency_list[current_node]:
if neighbor_node != parent_node:
dfs_timer(neighbor_node, current_node)
exit_time = traversal_timer
subtree_intervals.append((entry_time, exit_time, subtree_sums[current_node]))
dfs_timer(0, -1)
# We check all pairs to guarantee we explore every possible combination of non-overlapping pieces
maximum_xor_found = 0
total_subtrees = len(subtree_intervals)
for first_index in range(total_subtrees):
for second_index in range(first_index + 1, total_subtrees):
first_entry, first_exit, first_sum = subtree_intervals[first_index]
second_entry, second_exit, second_sum = subtree_intervals[second_index]
# Non-overlapping subtrees must not share ancestor-descendant containment relationships
is_disjoint = (first_exit <= second_entry) or (second_exit <= first_entry)
if is_disjoint:
current_xor = first_sum ^ second_sum
if current_xor > maximum_xor_found:
maximum_xor_found = current_xor
# Final answer is the absolute highest XOR value found among all valid non-overlapping subtree pairs
return maximum_xor_foundThe problem asks for the maximum XOR sum of two non-overlapping subtrees in a given tree. Two subtrees rooted at two distinct nodes are non-overlapping if neither is an ancestor of the other. We can compute the sum of values in each subtree and use a bitwise Trie to efficiently query the maximum XOR against all previously visited independent subtrees.
Here's how the algorithm would work step-by-step:
def max_xor_two_subtrees(n: int, edges: list[list[int]], values: list[int]) -> int:
import sys
sys.setrecursionlimit(200000)
adjacency = [[] for _ in range(n)]
for node_u, node_v in edges:
adjacency[node_u].append(node_v)
adjacency[node_v].append(node_u)
subtree_sums = [0] * n
traversal_order = []
parent_node = [-1] * n
dfs_stack = [0]
visited = [False] * n
visited[0] = True
# Traverse the tree iteratively to determine child relationships and processing order
while dfs_stack:
current_node = dfs_stack.pop()
traversal_order.append(current_node)
for neighbor in adjacency[current_node]:
if not visited[neighbor]:
visited[neighbor] = True
parent_node[neighbor] = current_node
dfs_stack.append(neighbor)
for current_node in reversed(traversal_order):
subtree_sums[current_node] = values[current_node]
for neighbor in adjacency[current_node]:
if neighbor != parent_node[current_node]:
subtree_sums[current_node] += subtree_sums[neighbor]
trie_root = {}
max_xor_result = 0
bitwise_depth = 48
def insert_trie(number_value: int) -> None:
current_dict = trie_root
for bit_index in range(bitwise_depth, -1, -1):
current_bit = (number_value >> bit_index) & 1
if current_bit not in current_dict:
current_dict[current_bit] = {}
current_dict = current_dict[current_bit]
def query_max_xor(number_value: int) -> int:
if not trie_root:
return 0
current_dict = trie_root
accumulated_xor = 0
for bit_index in range(bitwise_depth, -1, -1):
current_bit = (number_value >> bit_index) & 1
opposite_bit = 1 - current_bit
if opposite_bit in current_dict:
accumulated_xor |= (1 << bit_index)
current_dict = current_dict[opposite_bit]
else:
current_dict = current_dict[current_bit]
return accumulated_xor
# Perform a depth-first search to query and update the Trie with subtree sums outside the current branch
def solve_dfs(current_node: int) -> None:
nonlocal max_xor_result
if trie_root:
candidate_xor = query_max_xor(subtree_sums[current_node])
if candidate_xor > max_xor_result:
max_xor_result = candidate_xor
for neighbor in adjacency[current_node]:
if neighbor != parent_node[current_node]:
solve_dfs(neighbor)
insert_trie(subtree_sums[current_node])
# Traverse children of the root to avoid comparing the full tree with its descendants
for root_child in adjacency[0]:
if root_child != parent_node[0]:
solve_dfs(root_child)
return max_xor_result
| Case | How to Handle |
|---|---|
| Tree with exactly two nodes | The tree must be partitioned into the single root node and the single child node, yielding the XOR of their respective values. |
| Nodes with negative values | Subtree sums must account for negative integers, and bitwise XOR operations on negative numbers in languages like Java use two's complement representation. |
| Skewed line graph tree structure | Deep recursion for linear trees requires a language with sufficient stack depth or an iterative post-order traversal to prevent stack overflow errors. |
| Large tree exceeding standard time limits | An efficient bottom-up dynamic programming approach combined with a Trie data structure ensures optimal O(N log MAX_VAL) time complexity. |
| All node values are zero | The algorithm correctly calculates zero XOR zero as zero since zero XORed with anything is the value itself. |
| Large integer values requiring bitwise manipulation | Using standard 32-bit or 64-bit integer types prevents overflow during both subtree sum accumulation and bitwise Trie insertions. |