Home/Data Structures & Algorithms/Tries & Prefix Search Engines

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Prefix trees, Radix trees, Aho-Corasick automaton, Suffix Automata, and network IP routing tables.
How does a 32-bit Binary Trie find the Maximum XOR of Two Numbers in O(N) time?
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 valueRead more
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
- Time Complexity:
- Space Complexity:
See lessO(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.