RainX_69

Maximum XOR of two elements in an array

Dec 17th, 2022
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.12 KB | Source Code | 0 0
  1. /*
  2.  
  3. Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n.
  4.  
  5. Example 1:
  6. Input: nums = [3,10,5,25,2,8]
  7. Output: 28
  8. Explanation: The maximum result is 5 XOR 25 = 28.
  9.  
  10. Example 2:
  11. Input: nums = [14,70,53,83,49,91,36,80,92,51,66,70]
  12. Output: 127
  13.  
  14.  
  15. Constraints:
  16.  
  17. 1 <= nums.length <= 2 * 10^5
  18. 0 <= nums[i] <= 2^31 - 1
  19.  
  20. */
  21.  
  22.  
  23. struct BIT_TrieNode{
  24.     BIT_TrieNode* children[2];
  25.     BIT_TrieNode(){
  26.         this->children[0]=NULL;
  27.         this->children[1]=NULL;
  28.     }
  29. };
  30.  
  31. class Solution {
  32. private:
  33.     BIT_TrieNode* root;
  34. public:
  35.     void insert(int num){
  36.         BIT_TrieNode* pCrawl=root;
  37.         for(int i=31;i>=0;i--){
  38.             int bit_state=(num >> i) & 1;   // CHECK IF ith bit is 1 or 0
  39.             if(pCrawl->children[bit_state]==NULL){
  40.                 pCrawl->children[bit_state]=new BIT_TrieNode();
  41.             }
  42.             pCrawl=pCrawl->children[bit_state];
  43.         }
  44.     }
  45.    
  46.     int query(int num){
  47.         BIT_TrieNode* pCrawl=root;
  48.         int res=0;
  49.         for(int i=31;i>=0;i--){
  50.             int bit_state=(num >> i) & 1;
  51.             if(pCrawl->children[bit_state^1]!=NULL){ // check if opposite bit is available, if yes, go for it since different bit results in 1 in XOR
  52.                 pCrawl=pCrawl->children[bit_state^1];
  53.                 res=res | (1 << i);  // turning bit on
  54.             }
  55.             else{
  56.                 pCrawl=pCrawl->children[bit_state];
  57.             }
  58.         }
  59.         return res;
  60.     }
  61.    
  62.     int findMaximumXOR(vector<int>& nums) {
  63.         root=new BIT_TrieNode();
  64.         int res=0;
  65.         for(auto x: nums){
  66.             insert(x);
  67.         }
  68.         for(auto x: nums){
  69.             res=max(res,query(x)); // the thought process is that we already made the trie using bits, now for example 1 we know binary of 5 is 00000000000000000000000000000101 in 32 bit format. So, while iterating on this binary rep of 5, if we get a 1 we should take that as we see in query. We always try to take the opposite bit of the current bit as this will result in 1 and give max XOR
  70.         }
  71.         return res;
  72.     }
  73. };
  74.  
Tags: C++ dsa Xor
Advertisement
Add Comment
Please, Sign In to add comment