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
- 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.
Use this to learn the idea, then write your own version.
1struct TrieNode {2 vector<shared_ptr<TrieNode>> children;3 int count = 0;4 TrieNode() : children(2) {}5};6 7class Trie {8 public:9 void update(int num, int val) {10 shared_ptr<TrieNode> node = root;11 for (int i = kHeight; i >= 0; --i) {12 const int bit = (num >> i) & 1;13 if (node->children[bit] == nullptr)14 node->children[bit] = make_shared<TrieNode>();15 node = node->children[bit];16 node->count += val;17 }18 }19 20 int query(int num) {21 int ans = 0;22 shared_ptr<TrieNode> node = root;23 for (int i = kHeight; i >= 0; --i) {24 const int bit = (num >> i) & 1;25 const int targetBit = bit ^ 1;26 if (node->children[targetBit] && node->children[targetBit]->count) {27 ans += 1 << i;28 node = node->children[targetBit];29 } else {30 node = node->children[targetBit ^ 1];31 }32 }33 return ans;34 }35 36 private:37 static constexpr int kHeight = 17;38 shared_ptr<TrieNode> root = make_shared<TrieNode>();39};40 41class Solution {42 public:43 vector<int> maxGeneticDifference(vector<int>& parents,44 vector<vector<int>>& queries) {45 const int n = parents.size();46 vector<int> ans(queries.size());47 int rootVal = -1;48 vector<vector<int>> tree(n);49 50 unordered_map<int, vector<pair<int, int>>> nodeToQueries;51 Trie trie;52 53 for (int i = 0; i < parents.size(); ++i)54 if (parents[i] == -1)55 rootVal = i;56 else57 tree[parents[i]].push_back(i);58 59 for (int i = 0; i < queries.size(); ++i) {60 const int node = queries[i][0];61 const int val = queries[i][1];62 nodeToQueries[node].emplace_back(i, val);63 }64 65 dfs(rootVal, trie, tree, nodeToQueries, ans);66 return ans;67 }68 69 private:70 void dfs(int node, Trie& trie, const vector<vector<int>>& tree,71 const unordered_map<int, vector<pair<int, int>>>& nodeToQueries,72 vector<int>& ans) {73 trie.update(node, 1);74 75 if (const auto it = nodeToQueries.find(node); it != nodeToQueries.cend())76 for (const auto& [i, val] : it->second)77 ans[i] = trie.query(val);78 79 for (const int child : tree[node])80 dfs(child, trie, tree, nodeToQueries, ans);81 82 trie.update(node, -1);83 }84};85