Maximum XOR of Two Numbers in an Array

Pattern: Maximum XOR

medium

Store each number as 31 bits in a binary trie, highest bit first. For each number, walk the trie choosing the opposite bit whenever possible; that builds the largest XOR with any stored number.

The problem

Return the largest value of nums[i] XOR nums[j] over all pairs (i may equal j).

Think first

  • Which bit matters most?
  • Why is choosing the opposite bit greedily right?
  • How does a trie help?

Hints

    Brute force, and why it fails

    Try every pair: O(n²).

    The key insight

    Deciding bits from the top down, the trie answers 'is there a number continuing this prefix?' in O(1) per bit.

    Dry run

    [3, 10, 5, 25, 2, 8]. 5 = 00101 and 25 = 11001.

    Step 1 of 2

    The plan

    for x: insert x
      walk from the root: at bit b, prefer the child opposite to x's bit, adding 1 << b when taken
    return the best
    

    Complexity

    Time
    O(31 × n)
    Space
    O(31 × n)

    One walk per number.

    Edge cases

    • One number: 0.
    • Equal numbers: 0.
    • Large values up to 2³¹ - 1.
    I've built my logic, show the code

    Java

    class Solution {
        public int findMaximumXOR(int[] nums) {
            int[][] next = new int[nums.length * 31 + 1][2];   // a binary trie of the numbers, highest bit first
            int nodes = 1, best = 0;
            for (int x : nums) {
                int n = 0, m = 0;                   // insert x, and walk m along the most opposite path
                for (int b = 30; b >= 0; b--) {
                    int bit = x >> b & 1;
                    if (next[n][bit] == 0) next[n][bit] = nodes++;
                    n = next[n][bit];
                }
                int got = 0;
                for (int b = 30; b >= 0; b--) {     // greedily choose the opposite bit: a higher bit outweighs all lower ones
                    int want = (x >> b & 1) ^ 1;
                    if (next[m][want] != 0) { got |= 1 << b; m = next[m][want]; }
                    else m = next[m][want ^ 1];
                }
                best = Math.max(best, got);
            }
            return best;
        }
    }

    C++

    class Solution {
    public:
        int findMaximumXOR(vector<int>& nums) {
            vector<vector<int>> next(1, vector<int>(2, 0));   // a binary trie of the numbers, highest bit first
            int best = 0;
            for (int x : nums) {
                int n = 0;
                for (int b = 30; b >= 0; b--) {     // insert x
                    int bit = x >> b & 1;
                    if (next[n][bit] == 0) {
                        next[n][bit] = static_cast<int>(next.size());
                        next.push_back(vector<int>(2, 0));
                    }
                    n = next[n][bit];
                }
                int m = 0, got = 0;
                for (int b = 30; b >= 0; b--) {     // greedily choose the opposite bit: a higher bit outweighs all lower ones
                    int want = (x >> b & 1) ^ 1;
                    if (next[m][want] != 0) { got |= 1 << b; m = next[m][want]; }
                    else m = next[m][want ^ 1];
                }
                best = max(best, got);
            }
            return best;
        }
    };

    Python

    class Solution:
        def findMaximumXOR(self, nums: list[int]) -> int:
            root, best = {}, 0                      # a binary trie of the numbers, highest bit first
            for x in nums:
                node = root
                for b in range(30, -1, -1):         # insert x
                    node = node.setdefault(x >> b & 1, {})
                node, got = root, 0
                for b in range(30, -1, -1):         # greedily choose the opposite bit
                    want = (x >> b & 1) ^ 1
                    if want in node:
                        got |= 1 << b
                        node = node[want]
                    else:
                        node = node[want ^ 1]
                best = max(best, got)
            return best

    Common mistakes

    • Walking from the lowest bit.
    • Querying an empty trie.

    Similar problems