Back to Trie
Course Practice
Medium

Maximum XOR of Two Numbers in an Array

LAB

Return the maximum xor obtainable from any pair of numbers.

EXAMPLES

Example 1
Input
{
  "nums": [
    3,
    10,
    5,
    25,
    2,
    8
  ]
}

Output
28

FUNCTION SHAPE

nums: intArrayint
SOLUTION NOTE

For each number, we want to find another number that differs in as many significant bit positions as possible, maximizing XOR.

Reveal reference solution +
pythonREFERENCE
def findMaximumXOR(self, nums: List[int]) -> int:
    trie = XORTrie()
    for num in nums:
        trie.insert(num)

    max_xor = 0
    for num in nums:
        max_xor = max(max_xor, trie.findMaxXOR(num))
    return max_xor
TimeO(n)
SpaceO(n)
Open on LeetCode
00:00
2 local tests readyRun with ⌘/Ctrl + Enter. Your code stays in this browser.

Runs solve(...) locally in a browser worker. SWE Playbook does not submit your code. Only run code you trust; Python code may access the network.