Maximum XOR of Two Numbers in an Array
Pick two numbers from the array maximizing a XOR b — in better than O(n²).
Intuition
XOR is maximized bit by bit from the top: a high differing bit beats all lower bits combined. Store every number's 32-bit path in a binary trie (0/1 children). For each number, walk the trie greedily choosing the opposite bit whenever that branch exists — that partner maximizes the XOR with this number. Best over all numbers is the answer.
Approach
Why brute force wastes work
All pairs is O(n²). But the best partner for a number is determined greedily per bit — high bits dominate — so a per-bit index (the trie) finds it in 32 steps.
Build the bit trie
Insert each number as its 32-bit path, most significant bit first. Nodes are {0:…, 1:…} dicts.
Greedy opposite walk
For each num, from the top bit down: prefer the child with the flipped bit (sets this XOR bit to 1); fall back to the same bit. Accumulate the XOR value; track the global max.
Solution & live demo
Edge cases
Opposite branch never exists — XOR 0.
Pairs with itself → 0 (insert-then-query order makes this safe).
Zero's best partner is simply the max element.