Problem Statement
(Source) Given a non-empty array of numbers, a0 , a1 , a2 , … , an−1 , where 0 ≤ ai < 231 .
Find the maximum result of ai XOR aj , where 0 ≤ i, j < n.
Could you do this in O(n) runtime?
Example:
Input: [3, 10, 5, 25, 2, 8] Output: 28 Explanation: The maximum result is 5 ^ 25 = 28.
Solution
Tags: Trie
, Bit Manipulation
.
Self-explained code is as follows. The time complexity is O(n) as expected.
class Solution(object):
def findMaximumXOR(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
arr = map(lambda x: bin(x)[2:].rjust(32, '0'), nums)
pt = {} # prefix tree
def add(pt, x):
for i in xrange(len(x)):
if x[i] not in pt:
pt[x[i]] = {}
pt = pt[x[i]]
def calculate(pt, x):
t = []
for i in xrange(len(x)):
keys = pt.keys()
if len(keys) == 1:
if x[i] in keys:
t.append('0')
else:
t.append('1')
pt = pt[keys.pop()]
else:
keys.remove(x[i])
t.append('1')
pt = pt[keys.pop()]
return int(''.join(t), base=2)
res = 0
add(pt, arr[0])
for i in xrange(1, len(arr)):
res = max(res, calculate(pt, arr[i]))
add(pt, arr[i])
return res