Skip to content

1938. Maximum Genetic Difference Query 👍

  • Time: $O(n + q)$
  • Space: $O(n + q)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
struct TrieNode {
  vector<TrieNode*> children;
  int count = 0;
  TrieNode() : children(2) {}
};

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

  int query(int num) {
    int ans = 0;
    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:
  constexpr static int kHeight = 17;
  TrieNode root;
};

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 (nodeToQueries.count(node))
      for (const auto query : nodeToQueries.at(node)) {
        const int i = query.first;
        const int val = query.second;
        ans[i] = trie.query(val);
      }

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

    trie.update(node, -1);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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 = kHeight; 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 = kHeight; 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 kHeight = 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 (var 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);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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 = defaultdict(list)  # {node: (index, val)}
    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)

      # answer queries for node
      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