LeetCode #421 Medium

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.
Constraints
  • 1 <= nums.length <= 2 * 10⁵
  • 0 <= nums[i] <= 2³¹ - 1
triebit-manipulationgreedy
Open on LeetCode ↗
02

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.
How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

5

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def findMaximumXOR(self, nums):
▶3 root = {}
▶4 for num in nums:
▶5 node = root
▶6 for i in range(30, -1, -1):
▶7 node = node.setdefault((num >> i) & 1, {})
▶8 best = 0
▶9 for num in nums:
▶10 node, xor = root, 0
▶11 for i in range(30, -1, -1):
▶12 bit = (num >> i) & 1
▶13 if 1 - bit in node:
▶14 xor |= 1 << i
▶15 node = node[1 - bit]
▶16 else:
▶17 node = node[bit]
▶18 best = max(best, xor)
▶19 return best
nums910014010012110010019rootnumber1001partnerxorbest0insert 9 → 4 new nodes
num91001 in binary
new nodes4
Insert 9 as the path 1 → 0 → 0 → 1, highest bit first. It shares no leading bits with earlier numbers, so every node on its path is new. This example needs 4 bits; the code always uses 31.
nums91001401001211000100110094rootnumber0100partnerxorbest0insert 4 → 4 new nodes
num40100 in binary
new nodes4
Insert 4 as the path 0 → 1 → 0 → 0, highest bit first. It shares no leading bits with earlier numbers, so every node on its path is new. This example needs 4 bits; the code always uses 31.
nums9100140100121100010100101009124rootnumber1100partnerxorbest0insert 12 → 3 new nodes
num121100 in binary
new nodes3
Insert 12 as the path 1 → 1 → 0 → 0, highest bit first. Its first 1 bit matches an earlier number, so that part of the path is reused and only 3 new nodes are added. This example needs 4 bits; the code always uses 31.
nums9100140100121100010100101009124rootnumber1001partner0xor1best0bit 3: 9 has 1 → take 0 → xor bit 1
num91001
bit 31want 0
xor so far1
Bit 3 of 9 is 1. A stored number has 0 here, so going that way makes the numbers differ and sets this XOR bit to 1. That is worth more than every lower bit together, so take it without looking further.
nums9100140100121100010100101009124rootnumber1001partner01xor11best0bit 2: 9 has 0 → take 1 → xor bit 1
num91001
bit 20want 1
xor so far11
Bit 2 of 9 is 0. A stored number has 1 here, so going that way makes the numbers differ and sets this XOR bit to 1. That is worth more than every lower bit together, so take it without looking further.
nums9100140100121100010100101009124rootnumber1001partner010xor110best0bit 1: no 1 branch → take 0 → xor bit 0
num91001
bit 10want 1
xor so far110
Bit 1 of 9 is 0, but no stored number on this path has 1 here. The only way down is the same bit, so this XOR bit stays 0. A child always exists: 9 itself lies on this path.
nums9100140100121100010100101009124rootnumber1001partner0100xor1101best0bit 0: 9 has 1 → take 0 → xor bit 1
num91001
bit 01want 0
xor so far1101
Bit 0 of 9 is 1. A stored number has 0 here, so going that way makes the numbers differ and sets this XOR bit to 1. That is worth more than every lower bit together, so take it without looking further.
nums9100140100121100010100101009124rootnumber1001partner0100xor1101best139 XOR 4 = 13 → new best
xor139 with 4
best13
The walk ends at the leaf for 4, the best partner for 9: 9 XOR 4 = 13. That beats the best so far.
nums9100140100121100010100101009124rootnumber0100partner1xor1best13bit 3: 4 has 0 → take 1 → xor bit 1
num40100
bit 30want 1
xor so far1
Bit 3 of 4 is 0. A stored number has 1 here, so going that way makes the numbers differ and sets this XOR bit to 1. That is worth more than every lower bit together, so take it without looking further.
nums9100140100121100010100101009124rootnumber0100partner10xor11best13bit 2: 4 has 1 → take 0 → xor bit 1
num40100
bit 21want 0
xor so far11
Bit 2 of 4 is 1. A stored number has 0 here, so going that way makes the numbers differ and sets this XOR bit to 1. That is worth more than every lower bit together, so take it without looking further.
nums9100140100121100010100101009124rootnumber0100partner100xor110best13bit 1: no 1 branch → take 0 → xor bit 0
num40100
bit 10want 1
xor so far110
Bit 1 of 4 is 0, but no stored number on this path has 1 here. The only way down is the same bit, so this XOR bit stays 0. A child always exists: 4 itself lies on this path.
nums9100140100121100010100101009124rootnumber0100partner1001xor1101best13bit 0: 4 has 0 → take 1 → xor bit 1
num40100
bit 00want 1
xor so far1101
Bit 0 of 4 is 0. A stored number has 1 here, so going that way makes the numbers differ and sets this XOR bit to 1. That is worth more than every lower bit together, so take it without looking further.
nums9100140100121100010100101009124rootnumber0100partner1001xor1101best134 XOR 9 = 13 → best stays 13
xor134 with 9
best13
The walk ends at the leaf for 9, the best partner for 4: 4 XOR 9 = 13. That does not beat 13, so the best stays.
nums9100140100121100010100101009124rootnumber1100partner0xor1best13bit 3: 12 has 1 → take 0 → xor bit 1
num121100
bit 31want 0
xor so far1
Bit 3 of 12 is 1. A stored number has 0 here, so going that way makes the numbers differ and sets this XOR bit to 1. That is worth more than every lower bit together, so take it without looking further.
nums9100140100121100010100101009124rootnumber1100partner01xor10best13bit 2: no 0 branch → take 1 → xor bit 0
num121100
bit 21want 0
xor so far10
Bit 2 of 12 is 1, but no stored number on this path has 0 here. The only way down is the same bit, so this XOR bit stays 0. A child always exists: 12 itself lies on this path.
nums9100140100121100010100101009124rootnumber1100partner010xor100best13bit 1: no 1 branch → take 0 → xor bit 0
num121100
bit 10want 1
xor so far100
Bit 1 of 12 is 0, but no stored number on this path has 1 here. The only way down is the same bit, so this XOR bit stays 0. A child always exists: 12 itself lies on this path.
nums9100140100121100010100101009124rootnumber1100partner0100xor1000best13bit 0: no 1 branch → take 0 → xor bit 0
num121100
bit 00want 1
xor so far1000
Bit 0 of 12 is 0, but no stored number on this path has 1 here. The only way down is the same bit, so this XOR bit stays 0. A child always exists: 12 itself lies on this path.
nums9100140100121100010100101009124rootnumber1100partner0100xor1000best1312 XOR 4 = 8 → best stays 13
xor812 with 4
best13
The walk ends at the leaf for 4, the best partner for 12: 12 XOR 4 = 8. That does not beat 13, so the best stays.
nums9100140100121100010100101009124rootnumberpartnerxorbest13every number queried → return 13
result13
Each number found its best partner in 4 steps, so the largest XOR overall is 13. Checking every pair would have taken n² work.
05

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.

06

Common pitfalls

Walking the bits from low to high

✗ Wrong
for i in range(31):
    bit = (num >> i) & 1
✓ Right
for i in range(30, -1, -1):
    bit = (num >> i) & 1

Greedy 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

✗ Wrong
for i in range(15, -1, -1):
✓ Right
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.

07

Edge cases

One number, or all numbers equal

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.

08

Complexity

Time
O(31n)
Space
O(31n)
Each insert and each walk visits 31 levels. The trie gains at most 31 nodes per number, fewer when numbers share leading bits.
09

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.