Maximum XOR of Two Numbers in an Array
Maximum XOR of Two Numbers in an Array is LeetCode 421 (Medium). Given an integer array nums, return the largest value of nums[i] XOR nums[j] over all i and j; the two indices may be equal.
- Up to 2 × 10⁵ numbers, so checking every pair, O(n²), is far too slow.
- Every value is between 0 and 2³¹ − 1, so 31 bits describe it.
- 1 <= nums.length <= 2 * 10⁵
- 0 <= nums[i] <= 2³¹ - 1
Intuition
A bit of a XOR b is 1 only where a and b differ, and one high bit is worth more than all the bits below it together: 2^k is bigger than 2^k − 1. So a number's best partner is the one that differs from it at the highest possible bit, then at the next, and so on.
A binary trie answers that in one walk:
- Store: insert every number as a 31-bit path, highest bit first.
- Query: walk down from the root. At each bit take the branch with the opposite bit if it exists, because that sets this bit of the XOR to 1. If it doesn't, the same-bit branch is the only way on.
Finding the largest XOR between two values, or of one value against a set, is the classic job for a binary trie: the greedy top-down walk replaces comparing against every member. The same trie handles a stream of insertions, or queries against a set that grows over time.
Approach
Before reading on, ask which bit of the answer matters most, and what you would need to know about the other numbers to set that bit. Then think about how to store the numbers so that question takes one step. Aim for about 31 steps per number.
Two ways to solve it
Store the numbers as bit paths and walk the trie once per number.
- Direct: each walk names the best partner bit by bit.
- Reusable: the same trie answers queries against a growing set.
- Cost: up to 31 nodes per number.
The standard interview answer.
Decide the answer one bit at a time, from the top, using a set of prefixes.
- Small: one set of at most n prefixes at a time.
- Fast in Python: set lookups are built-in C code.
- Less direct: it finds the value, not the pair.
Pick it when memory or Python speed matters.
Both run in O(31n). The trie is the usual interview answer and finds each number's partner directly. The prefix set stores far less and ran about three times faster in Python on 2 × 10⁵ random numbers. The steps, code and demo follow the trie; the prefix-set code comes after the demo.
Insert every number into the trie
For each number, start at the root and go through bits 30 down to 0, creating the child for each bit when it is missing. Numbers that share leading bits share the start of their path, so each prefix is stored once.
Walk the trie for each number
Start at the root with xor = 0. At bit i, read the number's bit b and look for the child 1 − b: any number down that branch differs from this one at bit i.
Take the opposite branch when it exists
If child 1 − b exists, set bit i of xor and move there. Nothing below bit i can make up for losing it, so taking this branch is never a mistake.
Otherwise follow the same bit
If only child b exists, move there and leave bit i at 0. Some child always exists, because the number being queried is itself stored in the trie along this path.
Keep the largest XOR
After bit 0, xor is the best this number can make with any stored number. Take the maximum over all numbers. The winning pair is found as soon as either of its two numbers is queried.
Code in Python, C++ and Java
Prefix set
Build the answer from the top bit down. best holds the bits already decided, and want guesses that the next bit is 1. The guess works only if two numbers' top bits XOR to want. Since a ^ b == want means a ^ want == b, one set lookup per prefix checks it.
Common pitfalls
Walking the bits from low to high
for i in range(31):
bit = (num >> i) & 1for i in range(30, -1, -1):
bit = (num >> i) & 1Greedy is only right from the top, where each bit outweighs everything after it. Built low bit first, the trie on [1, 2, 4] lets 4 grab 1 for its lowest bit and settle for 4 XOR 1 = 5, missing 2 XOR 4 = 6.
Using too few bits
for i in range(15, -1, -1):
for i in range(30, -1, -1):
Values reach 2³¹ − 1, so the walk must start at bit 30. With 16 bits, [0, 65536] looks like two zeros and returns 0 instead of 65536.
Edge cases
For [7] or [7, 7] every stored path is the same as the query, so no opposite branch ever exists and each walk returns 0. That matches the problem: i may equal j, and 7 XOR 7 is 0.
Complexity
Maximum XOR of Two Numbers in an Array FAQ
How is this different from Maximum XOR With an Element From Array?
LeetCode 1707 gives queries [x, m] and only lets x pair with array values up to m. The same trie works, but the queries are sorted by m and numbers are inserted only as they become allowed, so each walk sees the right set.
Why is the answer never negative?
All values are between 0 and 2³¹ − 1, so bit 31, the sign bit of a 32-bit int, is 0 in every number and in every XOR. That is also why the walk can start at bit 30 and int is wide enough in C++ and Java.