Maximum XOR of Two Numbers in an Array — LeetCode 421 Python Solution

MediumBit ManipulationTrieArrayHash Table
Problem
#421
Pattern
Trie
Reading time
6 min

The problem

Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n.

Example

Input
nums = [3,10,5,25,2,8]
Output
28
Explanation
The maximum result is 5 XOR 25 = 28.

Python solution

Python
class Trie:
    __slots__ = ("children",)

    def __init__(self):
        self.children: List[Trie | None] = [None, None]

    def insert(self, x: int):
        node = self
        for i in range(30, -1, -1):
            v = x >> i & 1
            if node.children[v] is None:
                node.children[v] = Trie()
            node = node.children[v]

    def search(self, x: int) -> int:
        node = self
        ans = 0
        for i in range(30, -1, -1):
            v = x >> i & 1
            if node.children[v ^ 1]:
                ans |= 1 << i
                node = node.children[v ^ 1]
            else:
                node = node.children[v]
        return ans


class Solution:
    def findMaximumXOR(self, nums: List[int]) -> int:
        trie = Trie()
        for x in nums:
            trie.insert(x)
        return max(trie.search(x) for x in nums)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Trie

Store a set of words by their shared prefixes so lookups cost the length of the word. LeetCode 421. Maximum XOR of Two Numbers in an Array is filed here because LeetCode tags it Trie, which is the vocabulary this hub collects.

The trie guide has the Python template for the pattern and the 49 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 421. Maximum XOR of Two Numbers in an Array?
LeetCode 421. Maximum XOR of Two Numbers in an Array is rated Medium on LeetCode.
What is the time complexity of LeetCode 421. Maximum XOR of Two Numbers in an Array?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 421. Maximum XOR of Two Numbers in an Array?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 421. Maximum XOR of Two Numbers in an Array cover?
LeetCode 421. Maximum XOR of Two Numbers in an Array is tagged Bit Manipulation, Trie, Array and Hash Table on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview