Approach
Depth-first search
For Maximum Genetic Difference Query, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 86 lines of Java from the credited upstream file 1938.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 7 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class TrieNode {2 public TrieNode[] children = new TrieNode[2];3 public int count = 0;4}5 6class Trie {7 public void update(int num, int val) {8 TrieNode node = root;9 for (int i = HEIGHT; i >= 0; --i) {10 final int bit = (num >> i) & 1;11 if (node.children[bit] == null)12 node.children[bit] = new TrieNode();13 node = node.children[bit];14 node.count += val;15 }16 }17 18 public int query(int num) {19 int ans = 0;20 TrieNode node = root;21 for (int i = HEIGHT; i >= 0; --i) {22 final int bit = (num >> i) & 1;23 final int targetBit = bit ^ 1;24 if (node.children[targetBit] != null && node.children[targetBit].count > 0) {25 ans += 1 << i;26 node = node.children[targetBit];27 } else {28 node = node.children[targetBit ^ 1];29 }30 }31 return ans;32 }33 34 private static final int HEIGHT = 17;35 TrieNode root = new TrieNode();36}37 38class Solution {39 public int[] maxGeneticDifference(int[] parents, int[][] queries) {40 final int n = parents.length;41 int[] ans = new int[queries.length];42 int rootVal = -1;43 List<Integer>[] tree = new List[n];44 45 for (int i = 0; i < n; ++i)46 tree[i] = new ArrayList<>();47 48 49 Map<Integer, List<Pair<Integer, Integer>>> nodeToQueries = new HashMap<>();50 Trie trie = new Trie();51 52 for (int i = 0; i < parents.length; ++i)53 if (parents[i] == -1)54 rootVal = i;55 else56 tree[parents[i]].add(i);57 58 for (int i = 0; i < queries.length; ++i) {59 final int node = queries[i][0];60 final int val = queries[i][1];61 nodeToQueries.putIfAbsent(node, new ArrayList<>());62 nodeToQueries.get(node).add(new Pair<>(i, val));63 }64 65 dfs(rootVal, trie, tree, nodeToQueries, ans);66 return ans;67 }68 69 private void dfs(int node, Trie trie, List<Integer>[] tree,70 Map<Integer, List<Pair<Integer, Integer>>> nodeToQueries, int[] ans) {71 trie.update(node, 1);72 73 if (nodeToQueries.containsKey(node))74 for (Pair<Integer, Integer> query : nodeToQueries.get(node)) {75 final int i = query.getKey();76 final int val = query.getValue();77 ans[i] = trie.query(val);78 }79 80 for (final int child : tree[node])81 dfs(child, trie, tree, nodeToQueries, ans);82 83 trie.update(node, -1);84 }85}86