Tries · Pattern 3 of 3

Bitwise trie: the largest XOR, bit by bit

Store each number as a path of bits from the highest to the lowest, so every node has at most two children. To get the largest XOR with x, walk down and take the opposite bit whenever it exists.

1 variation · 1 problem

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Maximum (or minimum) XOR of a pair
  • XOR of a query value with numbers from a list
  • Bits decided from the highest down, greedily

The template

Bitwise Trie
int findMaximumXOR(int[] nums) {
    int[][] child = new int[nums.length * 31 + 1][2];   // node 0 is the root; 0 also means "none"
    int nodes = 1, best = 0;
    for (int x : nums) {
        int cur = 0;
        for (int b = 30; b >= 0; b--) {                // insert x, highest bit first
            int bit = (x >> b) & 1;
            if (child[cur][bit] == 0) child[cur][bit] = nodes++;
            cur = child[cur][bit];
        }
        cur = 0;
        int xor = 0;
        for (int b = 30; b >= 0; b--) {                // best partner: the opposite bit when it exists
            int bit = (x >> b) & 1;
            if (child[cur][1 - bit] != 0) { xor |= 1 << b; cur = child[cur][1 - bit]; }
            else cur = child[cur][bit];
        }
        best = Math.max(best, xor);
    }
    return best;
}

The variations

  1. 1Maximum XOR of a pair

    Insert each number, then walk the trie with it, preferring the opposite bit at every level. Each preferred step sets that bit of the XOR to 1, and a higher bit always beats every lower bit combined, so the greedy choice is optimal.

Mistakes to avoid

  • Walking bits from the lowest up: the highest bit is worth more than all lower bits together, so it must be decided first.
  • Querying before inserting x and then reading a missing child: insert first (x XOR x = 0 is a safe fallback), or check for null.
  • Using too few bits: for values up to 2^31 − 1 start at bit 30.
Back to Tries →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.