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

C++Server Side ProgrammingProgramming

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

  • curr := 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

  • head := new node

  • 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:
   void insertNode(int val, Node* head){
      Node* curr = head;
      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 find(int val, Node* head){
      Node* curr = head;
      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();
      Node* head = new Node();
      for(int i = 0; i < n; i++){
         insertNode(nums[i], head);
      }
      for(int i = 0; i < n; i++){
         ans = max(ans, find(nums[i], head));
      }
      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
raja
Published on 02-May-2020 12:09:04
Advertisements