Maximum XOR of Two Numbers in an Array
Find the largest XOR of any two numbers in an array by deciding the answer one bit at a time.
Given an array of non-negative integers numsnums[i] ^ nums[j]ij^ij
Example 1
Output: 28
Explanation: 5 ^ 25 = 00101 ^ 11001 = 11100 = 28.
Example 2
Output: 127
The Idea
Write two numbers in binary, one above the other, and compare them column by column. XOR, written ^
Look at the picture below. The six numbers of Example 1 are written with five bits each, positions 4 to 0. In the highlighted rows, 5 is 001011100111100
Six numbers make 15 pairs, and 5 with 25 gives the largest XOR of them. How can we be sure of that without working out all 15? Look at the bit positions again. A 1 at position 4 is worth 16, more than all the lower positions together, since 8 + 4 + 2 + 1 = 15. So any XOR with a 1 at position 4 beats every XOR with a 0 there.
That suggests deciding the answer one bit at a time, from the top. On the right of the picture, the box labelled bit 4 holds 1, because only 25 has a 1 there, and 25 with any other number gives a 1. The box labelled bit 3 asks for 11
The box labelled bit 2 asks for 11111111110111100
Setting each bit to 1 whenever some pair allows it, from the top bit down, and never undoing that choice is called a greedy choice. It is safe here because a 1 at a higher position always outweighs all the bits below it.
Solution Approach
Trying every pair works, but the number of pairs grows fast. Deciding the answer bit by bit instead means settling three things: how to test whether one bit of the answer can be 1, which part of each number to compare, and which positions to go through. A tree that stores the numbers bit by bit gives an optional second way to run the same test.
Trying every pair
Why not work out the XOR of every pair and keep the largest? With n numbers there are n(n - 1)/2 pairs. That is 15 for Example 1, but almost 20 billion for 200,000 numbers. Deciding the answer bit by bit needs only a pass or two over the numbers for each bit position.
Testing one bit with a set
How do we know whether some pair gives a wanted pattern, say 11100a ^ b = ca ^ c = b
So instead of asking whether some pair gives 28, we ask, for each number aa ^ 28HashSet<Integer>
Comparing only the top bits
Which part of each number goes into the set? While bit 3 is being tested, the answer's bits below position 3 are still open, so the numbers' bits below position 3 must not count yet. So each number is cut down to its bits from the top down to the current position, with the bits below set to 0. That cut-down number is called a prefix.
For a number numnum & mask&nummaskmask11000
At each position, the answer so far with the current bit turned on is the pattern to test, kept in a variable named candidate
| Bit | Prefixes in the set | Pattern tested (candidate) | Pair of prefixes found? | Answer so far |
|---|---|---|---|---|
| 4 | 0, 16 | 10000 | yes, 0 ^ 16 | 10000 |
| 3 | 0, 8, 24 | 11000 | yes, 0 ^ 24 | 11000 |
| 2 | 0, 4, 8, 24 | 11100 | yes, 4 ^ 24 | 11100 |
| 1 | 2, 4, 8, 10, 24 | 11110 | no | 11100 |
| 0 | 2, 3, 5, 8, 10, 25 | 11101 | no | 11100 |
Look at the row for bit 2. The prefixes 4 and 24 come from 5 (001011100111110pp ^ 30
Which bit positions to go through
Where does the search start? Java gives every intnums
Optional: a binary trie
The set of prefixes is built again for every bit. Another way stores all the numbers once, in a tree where each number is a path of 31 steps, one per bit from position 30 down. Each step goes to a child labelled 0 or 1. A tree like this, where the labels along a path spell out a stored value, is called a trie.
In Example 1, all six numbers share one path through positions 30 to 5, where every bit is 0. At position 4 the path splits: 25 goes to the child labelled 1, and the other five numbers to the child labelled 0. To find the best partner for a number, walk down and at each step take the child with the opposite bit when there is one, since differing bits give a 1. This also takes 31 steps per number, but the trie can need up to 31 · n nodes.
Java Solution
The method findMaximumXOR
- First, set
, the answer built so far, to 0, andmax , the positions to keep from each number, to 0.mask - A loop moves
from 30 down to 0. Each round adds the current position to the mask withbit .mask |= 1 << bit - Inside, a second loop puts the prefix
of every number into a newnum & mask namedHashSet .prefixes - Then
is set tocandidate with the current bit turned on. A third loop goes over each prefixmax and checks whetherp is inp ^ candidate . On a hit,prefixes becomesmax and that loop stops early.candidate - After position 0,
holds the largest XOR, and the method returns it.max
The mainInteger.MAX_VALUEint
import java.util.HashSet;
import java.util.Set;
public class MaximumXorOfTwoNumbers {
public static int findMaximumXOR(int[] nums) {
int max = 0;
int mask = 0;
for (int bit = 30; bit >= 0; bit--) { // values are non-negative, so bit 31 is 0
mask |= 1 << bit; // keep the top bits down to this one
Set<Integer> prefixes = new HashSet<>();
for (int num : nums) {
prefixes.add(num & mask);
}
int candidate = max | (1 << bit); // can this bit be 1 in the answer?
for (int p : prefixes) {
// a ^ b = candidate <=> a ^ candidate = b
if (prefixes.contains(p ^ candidate)) {
max = candidate;
break;
}
}
}
return max;
}
public static void main(String[] args) {
System.out.println(findMaximumXOR(new int[] {3, 10, 5, 25, 2, 8}));
int[] nums = {14, 70, 53, 83, 49, 91, 36, 80, 92, 51, 66, 70};
System.out.println(findMaximumXOR(nums));
System.out.println(findMaximumXOR(new int[] {7}));
System.out.println(findMaximumXOR(new int[] {8, 8, 8}));
System.out.println(findMaximumXOR(new int[] {0, Integer.MAX_VALUE}));
}
}
Running it prints:
28
127
0
0
2147483647
Look at the first line: 28, from 5 and 25 in the picture. Example 2 gives 127, which is 1111111
The third and fourth lines print 0. With the single number 7, the one pair is 7 with itself, and a number XOR itself is 0 because every bit matches. The three 8s give 0 for the same reason. The last line, 2147483647, has a 1 at every position from 30 down to 0. Every bit of Integer.MAX_VALUE
Complexity
The work is one round per bit position, and each round goes over the numbers about twice.
- Time: O(31 · n), which is O(n), because each of the 31 rounds puts the n prefixes into a new set and then makes at most one lookup per prefix.
- Space: O(n), because the set holds at most one prefix per number and is replaced in the next round.