Solution Review: Minimum XOR
See the solution to the minimum XOR problem challenge.
We'll cover the following...
Solution
Intuition
Since bitwise tries are used to store binary prefixes efficiently, we can use bitwise tries to solve this problem. We'll convert all the array numbers into their binary forms and insert them into the trie, where each node will represent a bit of the number.
Algorithm
The summary of the algorithm is given below.
Step 1: Insertion in a trie
Convert all the integers from decimal to binary form and insert the bits into the trie. This implies that every trie node can have only two possible children, 0 and 1. Finally, add an integer parameter value to the definition of the trie node to store the final integer value in the leaf node.
Step 2: Finding the minimum XOR
The minimum value for the XOR of any two bits is 1. This is only achievable if the two bits involved are the opposite value of each other—that is, XORing 0 with 0 or 1 with 1 would result in a minimum value of 0.
Once we have a bitwise trie of numbers, we can calculate the minimum XOR with another number by traversing the trie downward, with the current number in binary form, and at each step, choosing the child node that will yield the minimum XOR value.
To minimize XOR, the strategy is to choose the same bit at each step whenever possible. If the current bit value of a number is 1, we'll try to choose the 1 children of the current node in the trie and vice versa. This will give us the minimum value of XOR.
Add the binary numbers into the trie one by one, creating a bitwise trie, and compute the minimum XOR of a number with all the previously inserted binaries. Try choosing the same bit at every step to minimize the XOR value. Update minimum XOR at each step. Return the value of minXOR as the answer.
Visualization
The following picture explains the construction of a bitwise trie and the steps to find the minimum XOR for an integer with other integers in the trie.
Complexity analysis
Variables
Number of integers in list =
. The average length of the binary representation of the integers =
...