Problem solution · C++

Maximum XOR With an Element From Array

Maximum XOR With an Element From Array: a C++ solution using sorting and greedy selection. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Sorting and greedy selection
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

Sorting and greedy selection

For Maximum XOR With an Element From Array, the implementation first exposes a useful order, then scans that order while making locally justified choices.

  1. Choose the key that reveals the greedy or grouping structure.
  2. Sort the relevant records by that key.
  3. Scan in order, maintaining the invariant that makes each local choice safe.

Code notes

  • 85 lines of C++ from the credited upstream file 1707.cpp.
  • The implementation visibly relies on sequence storage.
  • 5 loop blocks detected.

Complexity

Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.

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 XOR With an Element From Array · C++C++
Use this to learn the idea, then write your own version.
struct TrieNode {  vector<shared_ptr<TrieNode>> children;  TrieNode() : children(2) {}}; class BitTrie { public:  BitTrie(int maxBit) : maxBit(maxBit) {}   void insert(int num) {    shared_ptr<TrieNode> node = root;    for (int i = maxBit; i >= 0; --i) {      const int bit = num >> i & 1;      if (node->children[bit] == nullptr)        node->children[bit] = make_shared<TrieNode>();      node = node->children[bit];    }  }   int getMaxXor(int num) {    int maxXor = 0;    shared_ptr<TrieNode> node = root;    for (int i = maxBit; i >= 0; --i) {      const int bit = num >> i & 1;      const int toggleBit = bit ^ 1;      if (node->children[toggleBit] != nullptr) {        maxXor = maxXor | 1 << i;        node = node->children[toggleBit];      } else if (node->children[bit] != nullptr) {        node = node->children[bit];      } else {  // There's nothing in the Bit Trie.        return 0;      }    }    return maxXor;  }  private:  const int maxBit;  shared_ptr<TrieNode> root = make_shared<TrieNode>();}; struct IndexedQuery {  int queryIndex;  int x;  int m;}; class Solution { public:  vector<int> maximizeXor(vector<int>& nums, vector<vector<int>>& queries) {    vector<int> ans(queries.size(), -1);    const int maxNumInNums = ranges::max(nums);    const int maxNumInQuery = ranges::max_element(queries, ranges::less{},                                                  [](const vector<int>& query) {      return query[0];    })->at(0);    const int maxBit = static_cast<int>(log2(max(maxNumInNums, maxNumInQuery)));    BitTrie bitTrie(maxBit);     ranges::sort(nums);     int i = 0;  // nums' index    for (const auto& [queryIndex, x, m] : getIndexedQueries(queries)) {      while (i < nums.size() && nums[i] <= m)        bitTrie.insert(nums[i++]);      if (i > 0 && nums[i - 1] <= m)        ans[queryIndex] = bitTrie.getMaxXor(x);    }     return ans;  }  private:  vector<IndexedQuery> getIndexedQueries(const vector<vector<int>>& queries) {    vector<IndexedQuery> indexedQueries;    for (int i = 0; i < queries.size(); ++i)      indexedQueries.emplace_back(i, queries[i][0], queries[i][1]);    ranges::sort(        indexedQueries, ranges::less{},        [](const IndexedQuery& indexedQuery) { return indexedQuery.m; });    return indexedQueries;  }}; 

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 ↗