Problem solution · Java

Maximum Genetic Difference Query

Maximum Genetic Difference Query: a Java solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Depth-first search
Source
walkccc LeetCode Solutions
Length
86 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

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.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeMaximum Genetic Difference Query · JavaJava
Use this to learn the idea, then write your own version.
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);  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗