Problem solution · C++

Maximum Genetic Difference Query

Maximum Genetic Difference Query: a C++ 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
85 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

  • 85 lines of C++ from the credited upstream file 1938.cpp.
  • The implementation visibly relies on sequence storage, hash lookup.
  • 6 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 · C++C++
Use this to learn the idea, then write your own version.
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);  }}; 

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 ↗