mediumTrieBit ManipulationTrie

Maximum XOR of Two Numbers in an Array

mediumTime: O(n * 32)Space: O(n * 32)

Recognize the pattern

maximize XOR of any two numbersbit-by-bit greedy choiceopposite bits preferred

Brute force idea

A straightforward first read of Maximum XOR of Two Numbers in an Array is this: XOR every pair. Checks all pairs without exploiting bit structure. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

Better approach

The deeper shift in Maximum XOR of Two Numbers in an Array is this: Build a binary trie (each path is a number's bit representation from MSB to LSB). For each number, greedily traverse the trie choosing the opposite bit at each level to maximize XOR. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

Key invariant

At the center of Maximum XOR of Two Numbers in an Array is one steady idea: To maximize XOR, you want opposite bits at every position (1 XOR 0 = 1). The trie lets you greedily choose the opposite bit at each level — if it exists, take it; otherwise, take what's available. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Watch out for

The trap in Maximum XOR of Two Numbers in an Array usually looks like this: Building a decimal trie instead of a binary trie — each node has exactly 2 children (0 and 1), representing each bit position from most significant to least. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Trie Pattern