MediumNo. 0421

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

Pattern
Trie
Topics
Bit Manipulation, Trie, Array, Hash Table
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

PythonSolution
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

Time
O(n)
Space · auxiliary
O(n)

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

Related problems
No.ProblemDifficulty
1178Number of Valid Words for Each PuzzleHard
2932Maximum Strong Pair XOR IEasy
2935Maximum Strong Pair XOR IIHard
0139Word BreakMedium
0140Word Break IIHard
0268Missing NumberEasy

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.

Free to download. Check it runs on your machine, then pick a plan.