Problem solution · C++

Maximum XOR of Two Numbers in an Array

Maximum XOR of Two Numbers in an Array: a C++ solution using hash-based lookup. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Hash-based lookup
Source
walkccc LeetCode Solutions
Length
36 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

Hash-based lookup

For Maximum XOR of Two Numbers in an Array, the implementation stores previously seen values or frequencies in a hash table for direct membership and lookup operations.

  1. Decide the key that represents the information needed later.
  2. Update its count or stored state while scanning the input.
  3. Use constant-time expected lookups to detect matches or assemble the result.

Code notes

  • 36 lines of C++ from the credited upstream file 421.cpp.
  • The implementation visibly relies on sequence storage, hash lookup.
  • 3 loop blocks detected.

Complexity

Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.

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 of Two Numbers in an Array · C++C++
Use this to learn the idea, then write your own version.
class Solution { public:  int findMaximumXOR(vector<int>& nums) {    const int maxNum = ranges::max(nums);    if (maxNum == 0)      return 0;    const int maxBit = static_cast<int>(log2(maxNum));    int ans = 0;    int prefixMask = 0;  // Grows like: 10000 -> 11000 -> ... -> 11111.     // If ans is 11100 when i = 2, it means that before we reach the last two    // bits, 11100 is the maximum XOR we have, and we're going to explore if we    // can get another two 1s and put them into `ans`.    for (int i = maxBit; i >= 0; --i) {      prefixMask |= 1 << i;      unordered_set<int> prefixes;      // We only care about the left parts,      // If i = 2, nums = {1110, 1011, 0111}      //    -> prefixes = {1100, 1000, 0100}      for (const int num : nums)        prefixes.insert(num & prefixMask);      // If i = 1 and before this iteration, the ans is 10100, it means that we      // want to grow the ans to 10100 | 1 << 1 = 10110 and we're looking for      // XOR of two prefixes = candidate.      const int candidate = ans | 1 << i;      for (const int prefix : prefixes)        if (prefixes.contains(prefix ^ candidate)) {          ans = candidate;          break;        }    }     return ans;  }}; 

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 ↗