Advertisement
Iam_Sandeep

Maximum xor of any two elements in given array

Jul 20th, 2022
1,007
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.83 KB | None | 0 0
  1. class Solution:
  2.     def findMaximumXOR(self, nums: List[int]) -> int:
  3.         root={}
  4.         def add(word):
  5.             cur=root
  6.             for i in range(31,-1,-1):
  7.                 t=1 if (1<<i) & word else 0
  8.                 if t in cur:
  9.                     cur=cur[t]
  10.                 else:
  11.                     cur[t]={}
  12.                     cur=cur[t]
  13.                    
  14.         for word in nums:
  15.             add(word)
  16.         ans=0
  17.         for num in nums:
  18.             cur=root
  19.             curans=0
  20.             for i in range(31,-1,-1):
  21.                 dig=1 if num & (1<<i) else 0
  22.                 if 1-dig in cur:
  23.                     cur=cur[1-dig]
  24.                     curans=curans |(1<<i)
  25.                 else:
  26.                     cur=cur[dig]
  27.             ans=max(ans,curans)
  28.         return ans
  29.                    
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement