AlgoTales · Roadmap

Maximum XOR

Advanced · 12 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Maximum XOR finds the pair of numbers in a list whose XOR value is biggest, meaning their bits differ the most from the top down. A bitwise trie lets each number pick its best partner by always trying to go the opposite way at each bit.

Practical use cases

  • Web app: Most different pair of readings. A monitoring dashboard receives 100,000 sensor codes and wants the two that are most unlike each other bit by bit, for anomaly highlighting. Comparing all pairs means five billion comparisons. A two-door tree finds each code best opposite in about 32 steps, so the report is ready in seconds. The anomaly report that once ran overnight is ready before the manager finishes a cup of tea.
  • Web app: Choosing the most distinct user fingerprints. A fraud-checking tool turns device fingerprints into numbers and wants the pair that differ most. Walking the trie and preferring the opposite bit each time gives that pair without testing every combination. Each fingerprint is compared in a fixed number of steps, so the tool keeps working as the number of devices grows to millions.
  • System: Contests and network comparisons. Maximum XOR is a classic interview and contest question, and the same idea compares bit patterns in networking or cryptography analysis when brute force is far too slow. Choosing the opposite bit at every step is greedy, yet it is guaranteed right because higher bits outweigh all lower ones together.

The story: The Most Different Pair

The school quiz had a strange final round. Each team member got a number on a card, and the host said, "Pick two cards whose numbers are the most different, in the XOR sense: write them in binary, and count the result as big when many of their bits disagree, especially the big bits." Mira's team had a hundred cards.

Kabir said, "Easy: try every pair!" With a hundred cards that was almost five thousand pairs, and the quiz had a ten-minute clock. Mira shook her head. "Think about one card first. Its best partner has the opposite bit wherever possible, starting with the biggest bit, because a big bit is worth more than all the small bits together."

She put all numbers into her two-door locker corridor (the bitwise trie). For her own card 5 = 0101 she walked: "I want a 1 first... there is one! Next I want a 0... yes!" At each door she took the opposite door if it existed, otherwise she had to take the same one. Four steps and she had her partner: card 10.

Do this for every card, remember the best, and the whole quiz takes n × bits steps. This is Maximum XOR of two numbers: build a bitwise trie, then for each number greedily chase the opposite bits from the top.

How to spot this problem, and where you need it

You need the two numbers in a large list that are most different in their binary form, and checking every pair would take far too long.

Signs you need it

  • The problem says "maximum XOR of two numbers" or "most different pair" with a long list.
  • A nested loop over all pairs works for 1,000 items but never finishes at 100,000.
  • The numbers have a fixed number of bits, so you can think of them as strings of 0s and 1s.
  • The best match for a number is the one whose top bits are opposite to its own.

Where to use it in a project

  • Anomaly or similarity analysis on numeric fingerprints, hashes or codes.
  • Interview-style tasks or contest features that ask for the greatest XOR with some array element.

The solution

Insert the numbers into a 0/1 trie. For each number, walk the trie from the top bit; at each bit, if a child with the opposite bit exists, go there because that makes this bit of the XOR a 1, otherwise take the same bit. The number you end on is its best partner. Keep the largest XOR seen over all numbers.

Payoff: Before: about five billion pair comparisons for 100,000 numbers. After: roughly 3 million steps (32 per number).

Explain it like I am 8

Two numbers are "most different" when their 0s and 1s disagree in as many places as possible, and the first (biggest) places matter most. For each card, walk the two-door corridor and always choose the door that is the opposite of your own bit, if it exists.

How it works, step by step

  1. Build a bitwise trie of all numbers using the same number of bits (B).
  2. For each number x, start at the root with best = 0.
  3. For each bit from the top: let b be the bit of x. Prefer the opposite lane (1 - b).
  4. If the opposite lane exists, move to it and set that bit in best (they differ here). Otherwise go through the same lane and leave the bit 0.
  5. Take the largest best over all numbers. It is the maximum XOR of any two stored numbers.

The code in four languages

PHP

<?php
class BNode {
    public array $kid = [null, null];
}

function maxXor(array $nums, int $bits): int {
    $root = new BNode();
    foreach ($nums as $x) {                         // 1) bitwise trie of all numbers
        $n = $root;
        for ($i = $bits - 1; $i >= 0; $i--) {
            $b = ($x >> $i) & 1;
            $n->kid[$b] ??= new BNode();
            $n = $n->kid[$b];
        }
    }
    $best = 0;
    foreach ($nums as $x) {                         // 2) best partner for each number
        $n = $root;
        $cur = 0;
        for ($i = $bits - 1; $i >= 0; $i--) {
            $b = ($x >> $i) & 1;
            $want = 1 - $b;                         // opposite bit gives a 1 in the XOR
            if ($n->kid[$want] !== null) {
                $cur |= (1 << $i);                  // this bit of the answer is 1
                $n = $n->kid[$want];
            } else {
                $n = $n->kid[$b];                   // forced to match: bit stays 0
            }
        }
        $best = max($best, $cur);
    }
    return $best;
}

echo maxXor([5, 3, 10, 12], 4) . PHP_EOL;            // 15
echo maxXor([3, 10, 5, 25, 2, 8], 5) . PHP_EOL;      // 28 (5 xor 25)
echo maxXor([7], 4) . PHP_EOL;                       // 0 (only itself)

JavaScript

class BNode {
  constructor() { this.kid = [null, null]; }
}

function maxXor(nums, bits) {
  const root = new BNode();
  for (const x of nums) {                          // 1) bitwise trie of all numbers
    let n = root;
    for (let i = bits - 1; i >= 0; i--) {
      const b = (x >> i) & 1;
      if (n.kid[b] === null) n.kid[b] = new BNode();
      n = n.kid[b];
    }
  }
  let best = 0;
  for (const x of nums) {                          // 2) best partner for each number
    let n = root;
    let cur = 0;
    for (let i = bits - 1; i >= 0; i--) {
      const b = (x >> i) & 1;
      const want = 1 - b;                          // opposite bit gives a 1 in the XOR
      if (n.kid[want] !== null) {
        cur |= (1 << i);                           // this bit of the answer is 1
        n = n.kid[want];
      } else {
        n = n.kid[b];                              // forced to match: bit stays 0
      }
    }
    best = Math.max(best, cur);
  }
  return best;
}

console.log(maxXor([5, 3, 10, 12], 4));            // 15
console.log(maxXor([3, 10, 5, 25, 2, 8], 5));      // 28 (5 xor 25)
console.log(maxXor([7], 4));                       // 0 (only itself)

Java

public class Main {
    static class BNode {
        BNode[] kid = new BNode[2];
    }

    static int maxXor(int[] nums, int bits) {
        BNode root = new BNode();
        for (int x : nums) {                         // 1) bitwise trie of all numbers
            BNode n = root;
            for (int i = bits - 1; i >= 0; i--) {
                int b = (x >> i) & 1;
                if (n.kid[b] == null) n.kid[b] = new BNode();
                n = n.kid[b];
            }
        }
        int best = 0;
        for (int x : nums) {                         // 2) best partner for each number
            BNode n = root;
            int cur = 0;
            for (int i = bits - 1; i >= 0; i--) {
                int b = (x >> i) & 1;
                int want = 1 - b;                    // opposite bit gives a 1 in the XOR
                if (n.kid[want] != null) {
                    cur |= (1 << i);                 // this bit of the answer is 1
                    n = n.kid[want];
                } else {
                    n = n.kid[b];                    // forced to match: bit stays 0
                }
            }
            best = Math.max(best, cur);
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(maxXor(new int[]{5, 3, 10, 12}, 4));          // 15
        System.out.println(maxXor(new int[]{3, 10, 5, 25, 2, 8}, 5));    // 28 (5 xor 25)
        System.out.println(maxXor(new int[]{7}, 4));                     // 0 (only itself)
    }
}

Go

package main

import "fmt"

type bNode struct {
	kid [2]*bNode
}

func maxXor(nums []int, bits int) int {
	root := &bNode{}
	for _, x := range nums { // 1) bitwise trie of all numbers
		n := root
		for i := bits - 1; i >= 0; i-- {
			b := (x >> i) & 1
			if n.kid[b] == nil {
				n.kid[b] = &bNode{}
			}
			n = n.kid[b]
		}
	}
	best := 0
	for _, x := range nums { // 2) best partner for each number
		n := root
		cur := 0
		for i := bits - 1; i >= 0; i-- {
			b := (x >> i) & 1
			want := 1 - b // opposite bit gives a 1 in the XOR
			if n.kid[want] != nil {
				cur |= 1 << i // this bit of the answer is 1
				n = n.kid[want]
			} else {
				n = n.kid[b] // forced to match: bit stays 0
			}
		}
		best = max(best, cur)
	}
	return best
}

func main() {
	fmt.Println(maxXor([]int{5, 3, 10, 12}, 4))       // 15
	fmt.Println(maxXor([]int{3, 10, 5, 25, 2, 8}, 5)) // 28 (5 xor 25)
	fmt.Println(maxXor([]int{7}, 4))                  // 0 (only itself)
}

Time: O(n x B) · Extra space: O(n x B). B is the number of bits (around 32). Each number is inserted once and queried once, far better than trying all pairs in O(n squared).

Watch out for

  • Choosing the same-bit lane first: you want the OPPOSITE lane because it gives a 1 in the XOR.
  • Greedily choosing a smaller bit when a bigger bit is available: high bits are worth more than all lower ones together, so start from the top.
  • Using different bit lengths for insert and query, which breaks the path alignment.

Quick check

  1. At each bit, which lane do we prefer when chasing the biggest XOR?
    • The same bit as x
    • The opposite bit of x
    • Always lane 0
  2. Why start from the biggest bit?
    • It is easier to code
    • One high bit outweighs every lower bit combined
    • The trie is smaller
  3. Numbers fit in 32 bits. Roughly how many steps for n numbers?
    • n x 32
    • n x n
    • 32