Taro Logo

Maximum XOR of Two Non-Overlapping Subtrees

#13 Most AskedHard
0 views
Topics:
TreesBit Manipulation

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:

  • 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.

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 * 104
  • edges.length == n - 1
  • 0 <= ai, bi < n
  • values.length == n
  • 1 <= values[i] <= 109
  • It is guaranteed that edges represents a valid tree.

Solution


Clarifying Questions

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:

  1. Can the node values be negative, or are they guaranteed to be non-negative integers?
  2. What is the minimum number of nodes in the tree? Can a tree have fewer than 2 nodes, and if so, what should be returned since we need two disjoint subtrees?
  3. Does 'partition the tree into two disjoint subtrees' mean we must remove a single edge from the tree to split it into exactly two connected components, or can the subtrees be non-contiguous?
  4. Are the node values and tree identifiers guaranteed to fit within standard 32-bit integer limits, or could the XOR sums exceed this range?
  5. If the tree is already a line (degenerate/skewed tree), does the definition of subtrees still apply normally?

Brute Force Solution

Approach

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:

  1. Begin by examining every single part of the tree and pretending to slice it off to form a distinct smaller subtree.
  2. Once you choose the first subtree, look at all the remaining parts of the main tree that do not overlap or share any nodes with your first choice.
  3. From those remaining parts, pick a second subtree so that you have two completely separate, non-overlapping pieces.
  4. Calculate the special combined value of these two chosen pieces using the math rule given in the problem.
  5. Repeat this process for every possible pair of non-overlapping subtrees you can make from the tree.
  6. Keep track of all the calculated values you find along the way.
  7. Finally, look through all your recorded values and pick the absolute highest one as your answer.

Code Implementation

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_found

Big(O) Analysis

Time Complexity
O(n^2) – To evaluate all possible pairs of non-overlapping subtrees, we must consider every possible choice for the first subtree out of n nodes in the tree. For each of these n initial choices, we must then explore all remaining disjoint parts of the tree to select a valid second subtree. This pairing process requires checking approximately n * n over 2 combinations of distinct subtrees. As the number of nodes n grows, the total operations scale quadratically, which simplifies to O(n^2).
Space Complexity
O(n) – To calculate subtree values and find the maximum XOR, the algorithm relies on recursive tree traversal and storage for subtree sums. The auxiliary space is primarily driven by the recursion stack frames, which can reach a maximum depth of N in the case of a skewed tree. Additionally, storing intermediate subtree sums requires an array or hash map proportional to the number of nodes, N. Combining the recursion stack and the sum storage, the total extra memory scales linearly with the input size.

Optimal Solution

Approach

The 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:

  1. Construct an adjacency list and compute the subtree sum for every node using a post-order traversal.
  2. Recognize that two subtrees are disjoint if and only if neither root is an ancestor of the other.
  3. Traverse the tree recursively starting from each child of the root node.
  4. Before adding the current node's subtree sum into a global binary Trie, query the Trie with its subtree sum to find the maximum XOR with previously processed disjoint subtrees.
  5. After processing all descendants of a node, insert that node's subtree sum into the Trie so subsequent branches can query against it.
  6. Return the maximum XOR score encountered, or zero if no two valid disjoint subtrees exist.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(n * B) – Calculating subtree sums takes O(n) time. Each node's subtree sum is queried and inserted into a Trie of depth B (where B is approximately 49 bits since node values sum up to 5 * 10^13), taking O(n * B) time in total.
Space Complexity
O(n * B) – The Trie stores up to n values with a depth of B bits, requiring O(n * B) pointers, alongside O(n) auxiliary memory for tree structures, subtree sums, and recursion stack.

Edge Cases

Tree with exactly two nodes
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
The algorithm correctly calculates zero XOR zero as zero since zero XORed with anything is the value itself.
Large integer values requiring bitwise manipulation
How to Handle:
Using standard 32-bit or 64-bit integer types prevents overflow during both subtree sum accumulation and bitwise Trie insertions.
0/38 completed