Skip to content

Commit 08ec3df

Browse files
421. Maximum XOR of Two Numbers in an Array
Difficulty: Medium 29 / 29 test cases passed. Runtime: 188 ms Memory Usage: 18 MB
1 parent de8b470 commit 08ec3df

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"""
2+
Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai < 231.
3+
Find the maximum result of ai XOR aj, where 0 ≤ i, j < n.
4+
Could you do this in O(n) runtime?
5+
6+
Example:
7+
Input: [3, 10, 5, 25, 2, 8]
8+
Output: 28
9+
Explanation: The maximum result is 5 ^ 25 = 28.
10+
"""
11+
#Difficulty: Medium
12+
#29 / 29 test cases passed.
13+
#Runtime: 188 ms
14+
#Memory Usage: 18 MB
15+
16+
#Runtime: 188 ms, faster than 72.25% of Python3 online submissions for Maximum XOR of Two Numbers in an Array.
17+
#Memory Usage: 18 MB, less than 89.19% of Python3 online submissions for Maximum XOR of Two Numbers in an Array.
18+
19+
class Solution:
20+
def findMaximumXOR(self, nums: List[int]) -> int:
21+
maximum = 0
22+
mask = 0
23+
result = set()
24+
length = len(nums)
25+
for i in range(30, -1, -1):
26+
mask |= 1 << i
27+
new = maximum | 1 << i
28+
for i in range(length):
29+
result.add(nums[i] & mask)
30+
for prefix in result:
31+
if new ^ prefix in result:
32+
maximum = new
33+
break
34+
result.clear()
35+
return maximum

0 commit comments

Comments
 (0)