Maximum XOR of two numbers || Interview Approach
class Solution {
public:
    int findMaximumXOR(vector<int>& nums) {
        int i,j;
        int mask=0,max=0;
        for(i=31;i>=0;i--){
            mask=mask|(1<<i);
            set<int> s;
            for(j=0;j<nums.size();j++){
                s.insert((nums[j] & mask));
            }
            int candidate=max|(1<<i);
            for(int prefix:s){
                if(s.find(prefix^candidate)!=s.end()){
                    max=candidate;
                    break;
                }
            }
        }
        return max;
    }
};

Explanation: A number in memory is represented as a set bits (0 or 1).
For a 32 bit number we have 32 bits in memory, so in order to find the largest possible value of an XOR operation, the value of XOR should have most of the bits set (i.e. 1) starting from the left to right.Here, the desired order of set bits is left to right just because we need largest possible value.
For example:
Binary Representation of 2 is 0010
Binary Representation of 8 is 1000
So, we can observe that both 2 and 8 have one set bit but the set bit of eight is more left than set bit of 2 and hence 8 > 2.
So the desired order will be left to right.
Now, for getting the maximum number of set bits starting from leftmost bit, we use mask to keep the prefix of every number of i’th bit.Now bitwise and of mask and array element will give the prefix of the number. These prefixes will be stored in a set in order to ignore the repeated values.
Now we use the important property of XOR:
A ^ B = C
A ^ C = B
In similar fashion, we can say that
prefix ^ set = candidate
prefix ^ candidate = set
Here, we can consider candidate as one of the possible answers.
So, candidate= max |(1<<i) gives the maximum possible output we can get in the i’th iteration. Hence, if xor of any two elements in the set s is equal to max , we update the max to candidate.

Time Complexity: O(nlog(m))
Space Complexity: O(log(m))

Hope you like the code, please give an upvote!
Thanks for reading till the end!

Comments (0)