Skip to content

Commit d9796a6

Browse files
committed
solve Maximum XOR of Two Numbers in an Array
1 parent 4cf98c4 commit d9796a6

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
# XOR between two numbers is high if there is difference in the most significant
6+
# bits.
7+
# For each number, during iteration, we need to find if there is another number
8+
# which has complementary bits starting with the most significant bit.
9+
# We can use a prefix tree (AKA trie) to store the binary bits.
10+
# A search in a trie is O(length of trie) = O(32) = O(1) in this case.
11+
#
12+
# During iteration, we search in the trie for the ideal number using the
13+
# complementary bit at each step, starting from the most significant bit.
14+
# So, time complexity is O(n).
15+
#
16+
# Space complexity is the space required to store the trie which is 32 level deep
17+
# perfect binary tree in worst case. So, 2^32 - 1 units of storage. But it's O(1).
18+
#
19+
# Further optimisations:
20+
# 1. Store bits instead of as strings in the keys of the trie.
21+
# 2. Instead of storing the number as in node["END"], we can also compute the number
22+
# from the path as we traverse.
23+
def findMaximumXOR(self, nums: List[int]) -> int:
24+
trie = {"ROOT": {}}
25+
26+
node = trie["ROOT"]
27+
for num in nums:
28+
node = trie["ROOT"]
29+
for ch in "{:032b}".format(num):
30+
if not ch in node:
31+
node[ch] = {}
32+
node = node[ch]
33+
node["END"] = num
34+
35+
ans = 0
36+
37+
for num in nums:
38+
node = trie["ROOT"]
39+
for ch in "{:032b}".format(num):
40+
complement = "1" if ch == "0" else "0"
41+
node = node[complement] if complement in node else node[ch]
42+
43+
# "END" must be in node
44+
ans = max(ans, num ^ node["END"])
45+
46+
return ans
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import unittest
2+
3+
from maximum_xor_of_two_numbers_in_an_array import Solution
4+
5+
6+
class TestMaximumXOROfTwoNumbersInAnArray(unittest.TestCase):
7+
def test_example_1(self):
8+
assert Solution().findMaximumXOR(nums=[3, 10, 5, 25, 2, 8]) == 28
9+
10+
def test_example_2(self):
11+
assert Solution().findMaximumXOR(nums=[3, 10, 5]) == 15

0 commit comments

Comments
 (0)