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 nums, return the largest value of nums[i] ^ nums[j] over all positions i and j, where ^ is Java's XOR operator. The two positions i and j may be the same, so an array with a single number gives 0.

Example 1
Input: nums = [3, 10, 5, 25, 2, 8]
Output: 28
Explanation: 5 ^ 25 = 00101 ^ 11001 = 11100 = 28.
Example 2
Input: nums = [14, 70, 53, 83, 49, 91, 36, 80, 92, 51, 66, 70]
Output: 127
Solution

The Idea

Write two numbers in binary, one above the other, and compare them column by column. XOR, written ^ in Java, puts a 1 in every column where the two bits differ and a 0 where they match. The columns are counted from the right: the rightmost bit is position 0, the one to its left is position 1, and so on.

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 00101 and 25 is 11001. They differ at positions 4, 3 and 2 and match at positions 1 and 0. So the row labelled 5 XOR 25 reads 11100, which is 16 + 8 + 4 = 28.

The six numbers of Example 1 in binary, bit positions 4 to 0. 5 is 00101 and 25 is 11001, and 5 XOR 25 is 11100, which is 28. On the right, the answer is decided from bit 4 down: bits 4, 3 and 2 can be 1, bits 1 and 0 cannot.

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 in the top two bits, and 25 with 3, 5 or 2 gives that.

The box labelled bit 2 asks for 111, and only 25 with 5 still gives it. No pair gives 1111 or 11101, so bits 1 and 0 stay 0, and the answer is 11100, which is 28.

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 11100, without trying the pairs? XOR can be undone: if a ^ b = c, then a ^ c = b. For example, 5 ^ 25 = 28, and 5 ^ 28 = 25.

So instead of asking whether some pair gives 28, we ask, for each number a, whether a ^ 28 is also in the array. With the numbers in a HashSet<Integer>, each such question is a single lookup.

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 num, the code gets its prefix with num & mask. The & operator keeps a bit of num only where mask also has a 1, and mask has 1s at every position from the top bit down to the current one. For 25 at bit 3, the prefix is 11000, which is 24.

At each position, the answer so far with the current bit turned on is the pattern to test, kept in a variable named candidate. Here is the test on Example 1. All six numbers are below 32, so every bit above position 4 is 0 in every number, and those answer bits stay 0. From bit 4 down:

BitPrefixes in the setPattern tested (candidate)Pair of prefixes found?Answer so far
40, 1610000yes, 0 ^ 1610000
30, 8, 2411000yes, 0 ^ 2411000
20, 4, 8, 2411100yes, 4 ^ 2411100
12, 4, 8, 10, 2411110no11100
02, 3, 5, 8, 10, 2511101no11100

Look at the row for bit 2. The prefixes 4 and 24 come from 5 (00101) and 25 (11001), the two highlighted rows in the picture. In the row for bit 1, the pattern is 11110, which is 30, and no prefix p has p ^ 30 in the set, so that bit stays 0.

Which bit positions to go through

Where does the search start? Java gives every int 32 bits, positions 0 to 31, and stores negative values in two's complement, where position 31 is 1 for every negative number. The numbers in nums are never negative, so their position 31 is always 0. So the search can start at position 30 and go down to 0.

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 works in these steps:

  1. First, set max, the answer built so far, to 0, and mask, the positions to keep from each number, to 0.
  2. A loop moves bit from 30 down to 0. Each round adds the current position to the mask with mask |= 1 << bit.
  3. Inside, a second loop puts the prefix num & mask of every number into a new HashSet named prefixes.
  4. Then candidate is set to max with the current bit turned on. A third loop goes over each prefix p and checks whether p ^ candidate is in prefixes. On a hit, max becomes candidate and that loop stops early.
  5. After position 0, max holds the largest XOR, and the method returns it.

The main method runs both examples, an array of one number, an array of three 8s, and the pair 0 and Integer.MAX_VALUE, the largest int.

Java
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:

Output
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 in binary, so its best pair differs in all seven lowest positions.

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 differs from 0, so all 31 answer bits are kept.

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.