Taro Logo

Maximum Genetic Difference Query

#10 Most AskedHard
0 views
Topics:
TreesBit ManipulationRecursion

There is a rooted tree consisting of n nodes numbered 0 to n - 1. Each node's number denotes its unique genetic value (i.e. the genetic value of node x is x). The genetic difference between two genetic values is defined as the bitwise-XOR of their values. You are given the integer array parents, where parents[i] is the parent for node i. If node x is the root of the tree, then parents[x] == -1.

You are also given the array queries where queries[i] = [nodei, vali]. For each query i, find the maximum genetic difference between vali and pi, where pi is the genetic value of any node that is on the path between nodei and the root (including nodei and the root). More formally, you want to maximize vali XOR pi.

Return an array ans where ans[i] is the answer to the ith query.

Example 1:

Input: parents = [-1,0,1,1], queries = [[0,2],[3,2],[2,5]]
Output: [2,3,7]
Explanation: The queries are processed as follows:
- [0,2]: The node with the maximum genetic difference is 0, with a difference of 2 XOR 0 = 2.
- [3,2]: The node with the maximum genetic difference is 1, with a difference of 2 XOR 1 = 3.
- [2,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.

Example 2:

Input: parents = [3,7,-1,2,0,7,0,2], queries = [[4,6],[1,15],[0,5]]
Output: [6,14,7]
Explanation: The queries are processed as follows:
- [4,6]: The node with the maximum genetic difference is 0, with a difference of 6 XOR 0 = 6.
- [1,15]: The node with the maximum genetic difference is 1, with a difference of 15 XOR 1 = 14.
- [0,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.

Constraints:

  • 2 <= parents.length <= 105
  • 0 <= parents[i] <= parents.length - 1 for every node i that is not the root.
  • parents[root] == -1
  • 1 <= queries.length <= 3 * 104
  • 0 <= nodei <= parents.length - 1
  • 0 <= vali <= 2 * 105

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. What is the maximum value of the node identifiers, and what are the value ranges for the query integers and the number of nodes/queries?
  2. Can the tree contain multiple disconnected components (a forest), or is it guaranteed to be a single valid rooted tree?
  3. For a given query $(node, val)$, are the query values and node values guaranteed to be non-negative integers?
  4. If a node has no descendants other than itself, does the search correctly fall back to just evaluating the node itself against the query value?
  5. Should the results in the returned array strictly correspond to the original order of the queries provided in the input list?

Brute Force Solution

Approach

Imagine you have a family tree of people and a list of specific challenges, where each challenge asks you to pick a person, look at their family tree lineage up to the root, and find a special number to combine with them to get the highest possible result. The brute force approach involves checking every single ancestor along the lineage for every single challenge, trying all possible pairs to see which combination yields the maximum value.

Here's how the algorithm would work step-by-step:

  1. Read the first challenge, which gives you a starting person and a target number.
  2. Look at the starting person and find everyone in their direct family line leading all the way up to the top of the tree.
  3. Take the target number from the challenge and combine it with the first person in that family line using the special rule.
  4. Remember the result of this combination.
  5. Repeat the combination process for every other person in that same family line.
  6. Compare all the results you just calculated and find the highest one for this specific challenge.
  7. Write down that highest result as the answer for the current challenge.
  8. Move on to the next challenge on your list and repeat the entire process from the beginning.
  9. Do this for every single challenge until you have found the best possible answer for all of them.

Code Implementation

def max_genetic_difference(parent_pointers, query_list):
    # We map each node to its queries to process them efficiently along the tree paths
    answer_storage = [0] * len(query_list)

    for query_index, (start_node, target_value) in enumerate(query_list):
        current_pointer = start_node
        maximum_result = 0

        while current_pointer != -1:
            bitwise_result = target_value ^ current_pointer
            if bitwise_result > maximum_result:
                maximum_result = bitwise_result
            current_pointer = parent_pointers[current_pointer]

        answer_storage[query_index] = maximum_result

    # We return the list of maximum values found for every single query processed
    return answer_storage

Big(O) Analysis

Time Complexity
O(n * m) – For each of the m queries or challenges, we traverse the direct family line of a person from the starting node all the way up to the root, which in the worst case visits n nodes in the tree. For every single ancestor in this lineage, we perform a constant-time combination step with the target number. This leads to approximately m * n total operations, which simplifies to O(n * m) where n is the number of nodes in the tree and m is the number of queries.
Space Complexity
O(N * log(MAX_VAL)) – The auxiliary space is driven by a Trie data structure used to store and query numbers along the ancestor path, where each node has at most two children and the depth corresponds to the bit-length of the maximum possible value. Additionally, recursion stack frames for the tree traversal and the output storage require space proportional to the number of nodes and queries, respectively. As the number of tree nodes and queries grows, the Trie and recursion depth scale efficiently, leading to an overall auxiliary space complexity bound by the number of nodes times the bit-length.

Optimal Solution

Approach

The problem asks for the maximum XOR genetic difference between a given query value and any node value along the path from a specified node to the root. We can process queries offline by grouping them by their target node. A depth-first search traverses the tree while dynamically maintaining the current root-to-node path in a prefix bit Trie.

Here's how the algorithm would work step-by-step:

  1. Construct the tree adjacency list from the parents array and identify the root node.
  2. Group the input queries by their respective target nodes to allow offline processing.
  3. Implement a binary Trie that supports adding a value, removing a value using reference counts, and finding the maximum XOR for a given number.
  4. Perform a depth-first traversal starting from the root, inserting each visited node's genetic value into the Trie.
  5. Answer all queries attached to the current node using the Trie's maximum XOR query function.
  6. Backtrack by removing the current node's value from the Trie after exploring all its subtrees and return the collected answers.

Code Implementation

import sys

# Increase recursion depth for deep tree traversals
sys.setrecursionlimit(300000)

class TrieNode:
    def __init__(self):
        self.children = [None, None]
        self.count = 0

def max_genetic_difference(parents, queries):
    num_nodes = len(parents)
    tree = [[] for _ in range(num_nodes)]
    root_node = -1
    
    # Build adjacency list representing the tree and find the root
    for child_node, parent_node in enumerate(parents):
        if parent_node == -1:
            root_node = child_node
        else:
            tree[parent_node].append(child_node)
            
    node_queries = [[] for _ in range(num_nodes)]
    for query_index, (query_node, query_val) in enumerate(queries):
        node_queries[query_node].append((query_val, query_index))
        
    trie_root = TrieNode()
    max_bit = 18
    
    def insert_val(value, delta):
        curr_node = trie_root
        for bit_pos in range(max_bit, -1, -1):
            bit = (value >> bit_pos) & 1
            if curr_node.children[bit] is None:
                curr_node.children[bit] = TrieNode()
            curr_node = curr_node.children[bit]
            curr_node.count += delta
            
    def query_max_xor(value):
        curr_node = trie_root
        result_xor = 0
        for bit_pos in range(max_bit, -1, -1):
            bit = (value >> bit_pos) & 1
            desired_bit = 1 - bit
            if curr_node.children[desired_bit] is not None and curr_node.children[desired_bit].count > 0:
                result_xor |= (1 << bit_pos)
                curr_node = curr_node.children[desired_bit]
            else:
                curr_node = curr_node.children[bit]
        return result_xor
        
    answers = [0] * len(queries)
    
    # Traverse the tree offline while maintaining values along the path in a Trie
    def dfs(curr_node):
        insert_val(curr_node, 1)
        for query_val, query_index in node_queries[curr_node]:
            answers[query_index] = query_max_xor(query_val)
        for neighbor in tree[curr_node]:
            dfs(neighbor)
        insert_val(curr_node, -1)
        
    dfs(root_node)
    return answers

Big(O) Analysis

Time Complexity
O((N + Q) * B) – Here N is the number of nodes in the tree, Q is the number of queries, and B is the number of bits needed (around 19 bits for values up to 2 * 10^5). Each node is inserted and deleted from the Trie once taking O(B) time, and each query traverses the Trie of depth B taking O(B) time.
Space Complexity
O(N * B + Q) – The Trie stores at most the path length elements, requiring at most O(N * B) nodes in the worst case. Storing the tree representation, offline query lists, and the recursion stack also requires O(N + Q) space.

Edge Cases

Tree consists of a single node with no children
How to Handle:
The node itself is evaluated as the only valid descendant, returning the XOR of that node's value with the query integer.
Deeply skewed tree forming a single long linked list
How to Handle:
Using an iterative approach or optimizing recursion depth prevents stack overflow errors during DFS traversal.
Query node has no descendants other than itself
How to Handle:
The Trie will only contain the query node's value when computing the maximum XOR, correctly returning that single result.
Query values are extremely large up to the maximum integer limit
How to Handle:
Bitwise operations and the binary Trie implementation process all 30 or 32 bits correctly without precision loss.
Multiple queries target the exact same node with different values
How to Handle:
Sorting queries offline and grouping them by node allows the Trie to be updated and queried efficiently without redundant traversal.
Values in the tree and queries are all zeros
How to Handle:
The XOR operations naturally compute zero, and the Trie handles zero-bit paths correctly without missing branches.
Large number of nodes and queries reaching maximum constraints
How to Handle:
Offline processing of queries combined with an insert-and-rollback or global Trie approach ensures optimal time complexity.
Disconnected nodes or multiple trees provided in input
How to Handle:
The problem guarantees a single connected tree rooted at the given node, ensuring the DFS correctly reaches all descendants.
0/38 completed