Problem: Maximum Genetic Difference Query

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.


Python solution:
import math
import itertools
import bisect
import collections
import string
import heapq
import functools
import sortedcontainers
from typing import List, Dict, Tuple, Iterator

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


class Trie:
  def __init__(self):
    self.root = TrieNode()
    self.kHeight = 17

  def update(self, num: int, val: int) -> None:
    node = self.root
    for i in range(self.kHeight, -1, -1):
      bit = (num >> i) & 1
      if not node.children[bit]:
        node.children[bit] = TrieNode()
      node = node.children[bit]
      node.count += val

  def query(self, num: int) -> int:
    ans = 0
    node = self.root
    for i in range(self.kHeight, -1, -1):
      bit = (num >> i) & 1
      targetBit = bit ^ 1
      if node.children[targetBit] and node.children[targetBit].count > 0:
        ans += 1 << i
        node = node.children[targetBit]
      else:
        node = node.children[targetBit ^ 1]
    return ans


class Solution:
  def maxGeneticDifference(self, parents: List[int], queries: List[List[int]]) -> List[int]:
    n = len(parents)
    ans = [0] * len(queries)
    rootVal = -1
    tree = [[] for _ in range(n)]
    nodeToQueries = collections.defaultdict(list)
    trie = Trie()

    for i, parent in enumerate(parents):
      if parent == -1:
        rootVal = i
      else:
        tree[parent].append(i)

    for i, (node, val) in enumerate(queries):
      nodeToQueries[node].append((i, val))

    def dfs(node: int) -> None:
      trie.update(node, 1)

      for i, val in nodeToQueries[node]:
        ans[i] = trie.query(val)

      for child in tree[node]:
        dfs(child)

      trie.update(node, -1)

    dfs(rootVal)
    return ans


Java solution:
class TrieNode {
  public TrieNode[] children = new TrieNode[2];
  public int count = 0;
}

class Trie {
  public void update(int num, int val) {
    TrieNode node = root;
    for (int i = HEIGHT; i >= 0; --i) {
      final int bit = (num >> i) & 1;
      if (node.children[bit] == null)
        node.children[bit] = new TrieNode();
      node = node.children[bit];
      node.count += val;
    }
  }

  public int query(int num) {
    int ans = 0;
    TrieNode node = root;
    for (int i = HEIGHT; i >= 0; --i) {
      final int bit = (num >> i) & 1;
      final int targetBit = bit ^ 1;
      if (node.children[targetBit] != null && node.children[targetBit].count > 0) {
        ans += 1 << i;
        node = node.children[targetBit];
      } else {
        node = node.children[targetBit ^ 1];
      }
    }
    return ans;
  }

  private static final int HEIGHT = 17;
  TrieNode root = new TrieNode();
}

class Solution {
  public int[] maxGeneticDifference(int[] parents, int[][] queries) {
    final int n = parents.length;
    int[] ans = new int[queries.length];
    int rootVal = -1;
    List<Integer>[] tree = new List[n];

    for (int i = 0; i < n; ++i)
      tree[i] = new ArrayList<>();

    // {node: (index, val)}
    Map<Integer, List<Pair<Integer, Integer>>> nodeToQueries = new HashMap<>();
    Trie trie = new Trie();

    for (int i = 0; i < parents.length; ++i)
      if (parents[i] == -1)
        rootVal = i;
      else
        tree[parents[i]].add(i);

    for (int i = 0; i < queries.length; ++i) {
      final int node = queries[i][0];
      final int val = queries[i][1];
      nodeToQueries.putIfAbsent(node, new ArrayList<>());
      nodeToQueries.get(node).add(new Pair<>(i, val));
    }

    dfs(rootVal, trie, tree, nodeToQueries, ans);
    return ans;
  }

  private void dfs(int node, Trie trie, List<Integer>[] tree,
                   Map<Integer, List<Pair<Integer, Integer>>> nodeToQueries, int[] ans) {
    trie.update(node, 1);

    if (nodeToQueries.containsKey(node))
      for (Pair<Integer, Integer> query : nodeToQueries.get(node)) {
        final int i = query.getKey();
        final int val = query.getValue();
        ans[i] = trie.query(val);
      }

    for (final int child : tree[node])
      dfs(child, trie, tree, nodeToQueries, ans);

    trie.update(node, -1);
  }
}


C++ solution:
struct TrieNode {
  vector<shared_ptr<TrieNode>> children;
  int count = 0;
  TrieNode() : children(2) {}
};

class Trie {
 public:
  void update(int num, int val) {
    shared_ptr<TrieNode> node = root;
    for (int i = kHeight; i >= 0; --i) {
      const int bit = (num >> i) & 1;
      if (node->children[bit] == nullptr)
        node->children[bit] = make_shared<TrieNode>();
      node = node->children[bit];
      node->count += val;
    }
  }

  int query(int num) {
    int ans = 0;
    shared_ptr<TrieNode> node = root;
    for (int i = kHeight; i >= 0; --i) {
      const int bit = (num >> i) & 1;
      const int targetBit = bit ^ 1;
      if (node->children[targetBit] && node->children[targetBit]->count) {
        ans += 1 << i;
        node = node->children[targetBit];
      } else {
        node = node->children[targetBit ^ 1];
      }
    }
    return ans;
  }

 private:
  static constexpr int kHeight = 17;
  shared_ptr<TrieNode> root = make_shared<TrieNode>();
};

class Solution {
 public:
  vector<int> maxGeneticDifference(vector<int>& parents,
                                   vector<vector<int>>& queries) {
    const int n = parents.size();
    vector<int> ans(queries.size());
    int rootVal = -1;
    vector<vector<int>> tree(n);
    // {node: (index, val)}
    unordered_map<int, vector<pair<int, int>>> nodeToQueries;
    Trie trie;

    for (int i = 0; i < parents.size(); ++i)
      if (parents[i] == -1)
        rootVal = i;
      else
        tree[parents[i]].push_back(i);

    for (int i = 0; i < queries.size(); ++i) {
      const int node = queries[i][0];
      const int val = queries[i][1];
      nodeToQueries[node].emplace_back(i, val);
    }

    dfs(rootVal, trie, tree, nodeToQueries, ans);
    return ans;
  }

 private:
  void dfs(int node, Trie& trie, const vector<vector<int>>& tree,
           const unordered_map<int, vector<pair<int, int>>>& nodeToQueries,
           vector<int>& ans) {
    trie.update(node, 1);

    if (const auto it = nodeToQueries.find(node); it != nodeToQueries.cend())
      for (const auto& [i, val] : it->second)
        ans[i] = trie.query(val);

    for (const int child : tree[node])
      dfs(child, trie, tree, nodeToQueries, ans);

    trie.update(node, -1);
  }
};