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).
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
- Maximum XOR of Two Numbers in an Arraymediumguide ready
- Maximum XOR With an Element From Arrayhardguide ready