Technique
Binary (XOR) Trie
Insert numbers bit by bit (MSB first) into a trie and greedily walk the opposite bit to maximise (or minimise) XOR with a query.
Learn firstTrie (Prefix Tree)Bit Tricks & Bitmasking
0%
mastery
0/5 solved
0/5 solved
Recognise it
The signal
maximum XOR of a pair
1Brute force
Check all pairs O(n2).
2The observation
Pair enumeration: higher bits dominate, so choose per bit greedily.
3Why it works
Each root-to-leaf path is an inserted number; subtree counts allow counting queries.
Reach for it when
- +max XOR with an element <= limit (offline sorted)
- +count pairs with XOR < k
Not when
- ×queries need XOR over a subset (xor-basis)
Practice
0/5 solved
- Maximum Xor SubarrayCSESMedium
- Maximum XOR of Two Numbers in an ArrayCitadel, GoogleMedium
- Maximum XOR With an Element From ArrayHard
- Maximum Genetic Difference QueryHard
- Dr. Evil UnderscoresCodeforces1900
Pitfalls
Misconceptions
- !walking LSB first (must go MSB first)
Looks like it, isn't
- Maximum Genetic Difference Query needs Offline Query Processing
Why
A trie per query is too slow. Attach the queries to nodes, DFS while inserting/removing root-path values in one binary trie. source ↗
Go deeper3 combinations · resources
Combinations
Binary (XOR) Trie+Offline Query Processing
max XOR with an element <= m_i
- Binary (XOR) Trie:
- max XOR with inserted numbers
- Offline Query Processing:
- sorts queries by limit so only allowed numbers are inserted
maximum XOR of a subarray
- Binary (XOR) Trie:
- maximises XOR with an earlier prefix
- Prefix Sum:
- subarray XOR = prefix XOR pair
Binary (XOR) Trie+Tree DFS (Paths & Recursion)+Offline Query Processing
max XOR of a value with any ancestor of a node, many queries
- Binary (XOR) Trie:
- the max XOR against values on the root path (counts per trie node allow removal)
- Tree DFS (Paths & Recursion):
- on entry insert the node's value, on exit remove it
- Offline Query Processing:
- attach the queries to their nodes