Given an integer array, we need to find two numbers whose bitwise XOR (A ^ B) is maximized.
The brute force approach tests all pairs in O(N^2), which is way too slow when N = 100,000. People recommend building a Binary Trie (prefix tree of bits 0 and 1) to solve this in O(32 * N) = O(N) time. How does walking down a binary tree yield the maximum possible XOR?
The Maximum XOR problem is the ultimate showcase of how bit manipulation and trees blend together. Once you see the greedy nature of binary numbers, the Binary Trie solution becomes second nature.
1. The Greedy Bit Principle
In binary numbers, the Most Significant Bit (MSB) has more numerical value than all lower bits combined! For example, bit 30 ($2^{30} pprox 1.07 imes 10^9$) is strictly greater than the sum of all bits from 0 to 29 combined ($2^{30} – 1$).
Therefore, to maximize an XOR sum, you must be greedy from left to right (MSB down to LSB):
numis1, you desperately want to pair it with a number whose corresponding bit is0(because1 ^ 0 = 1).numis0, you want to pair it with a number whose corresponding bit is1(because0 ^ 1 = 1).2. Why a Binary Trie?
A Binary Trie is just a tree where every node has at most two children:
0(left) and1(right).x, you walk down the Trie. At each bitb, you ask: ‘Does the opposite branch (1 - b) exist?’1.b), so that bit in your XOR result becomes0.Because you made the best possible choice at every single bit position starting from the highest power of 2, the final accumulated number is mathematically guaranteed to be the global maximum XOR!
Clean Python 3.12 Implementation
Complexity Breakdown
O(31 * N) = O(N). InsertingNnumbers takes31 * Noperations. QueryingNnumbers takes31 * Noperations. Total time is strictly linear in the number of elements.O(31 * N)worst-case node allocations. In practice, prefix branches overlap heavily, keeping memory around a few megabytes.Here is the C++20 Binary Trie implementation. To avoid dynamic heap allocations during tree insertion, we use a flat contiguous node pool.
Complexity: Strictly
O(31 * N) = O(N)time with flat memory pooling.