Learn / Tries

Maximum XOR

To find the number that gives the largest XOR with x, store numbers as bit strings in a binary trie, highest bit first. Walking down, take the branch with the opposite bit whenever it exists: a 1 in a higher bit outweighs every lower bit together.

How to recognise it

  • Maximise a XOR b over pairs or against a query value.
  • Numbers up to 2³¹ and too many pairs to try.
  • Queries with a limit on which numbers may be used (sort them and insert as the limit grows).
01101011
2 = 010, 5 = 101, 7 = 111, highest bit first. For x = 2, choosing the opposite bit at each level reaches 101: 2 XOR 5 = 7.

Opposite bits first

insert(x):  for b from 30 down to 0: go to child (x >> b) & 1, creating it
best(x):    for b from 30 down to 0:
                want = 1 - ((x >> b) & 1)
                if child want exists: result |= 1 << b; go there
                else: go to the other child

For the best pair, insert each number and query it against the numbers already inserted.

Offline queries

Sort the numbers and sort the queries by their limit. Before each query, insert every number up to its limit. If the trie is still empty, the answer is -1.

Common mistakes

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

Problems

0 of 2 solved

Check yourself

Why is choosing the opposite bit greedily correct?

How deep is the trie for 31-bit numbers?

With a limit m on each query, how is the trie kept right?