# Maximum XOR of Two Numbers in an Array in C++

Suppose we have a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai < 231. We have to find the maximum result of ai XOR aj, where 0 ≤ i, j < n. So if the input is like [3,10,5,15,2,8], then the output will be 28. The max result will be 5 XOR 25 = 28.

To solve this, we will follow these steps −

• Define insertNode(), this will take val and head

• for i in range 31 to 0

• bit := val / (2^i) AND 1

• if child[bit] of curr is null, then child[bit] of curr := new node

• curr := child[bit] of curr

• Define find() method. This will take val and head as input

• curr := head, ans := 0

• for i in range 31 to 0

• bit := val / (2^i) AND 1

• if child[bit] of curr is null, then ans := ans OR (2^1)/p>

• curr := child[bit] of curr

• return ans

• From the main method, do the following −

• ans := 0

• n := size of nums

• for i in range 0 to n – 1, insertNode(nums[i], head)

• for i in range 0 to n – 1, ans := max of ans and find (nums[i], head)

• return ans

## Example (C++)

Let us see the following implementation to get better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
struct Node{
Node* child[2];
Node(){
child[1] = child[0] = NULL;
}
};
class Solution {
public:
for(int i = 31; i>= 0; i--){
int bit = (val >> i) & 1;
if(!curr->child[bit]){
curr->child[bit] = new Node();
}
curr = curr->child[bit];
}
}
int ans = 0;
for(int i = 31; i>= 0; i--){
int bit = (val >> i) & 1;
if(curr->child[!bit]){
ans |= (1 << i);
curr = curr->child[!bit];
} else {
curr = curr->child[bit];
}
}
return ans;
}
int findMaximumXOR(vector<int>& nums) {
int ans = 0;
int n = nums.size();
for(int i = 0; i < n; i++){
}
for(int i = 0; i < n; i++){
}
return ans;
}
};
main(){
vector<int> v = {3,10,5,25,2,8};
Solution ob;
cout << (ob.findMaximumXOR(v));
}

## Input

[3,10,5,25,2,8]

## Output

28

Updated on: 02-May-2020

119 Views