Binary Tries & Maximum XOR
Bitwise tries for maximum-XOR pairs, subarrays and queries.
Given a million 30-bit integers, which two have the largest XOR? Checking every pair means about XORs. A binary trie needs about steps, because it asks one question per bit: can this bit of the answer be 1?
What you’ll learn
- Prove that the greedy descent in a binary trie returns , and find the maximum XOR pair in time.
- Reduce maximum-XOR subarrays to pairs of prefix XORs, and count pairs or subarrays whose XOR is below a bound in .
- Answer maximum-XOR queries restricted by value (offline by sorting, or online with subtree minima) and by index range (persistent tries).
- Build the minimum XOR spanning tree from the trie's structure, and connect binary tries to XOR bases and to predecessor search.
The greedy descent, proved
Numbers of the same width compare like their bit strings: the highest bit where they differ decides, because exceeds the sum of all lower bits.
Let , and suppose some has . At the highest bit where they differ, and . Above the two XORs agree, so agrees with there: lies in the subtree where the greedy stood when it chose bit .
But means , so the preferred child existed in that subtree, and the greedy would have taken it, making . Contradiction: no stored beats .
A query costs one step per bit. Querying each number against the trie of the numbers before it, then inserting it, examines every pair once:
A binary trie stores 6, 9 and 12 (4 bits). Which partner does the greedy descent choose for , and what XOR does it return?
- 12, giving 9
- 9, giving 12
- 6, giving 3
- 12, giving 12
Show the answer
B. 9, giving 12
. Bit 3: want 1, and 9 and 12 have it. Bit 2: want 0, and only has it. Then bits 1 and 0 are forced along 9's path. The result is , larger than and .
#include <array>
#include <vector>
const int W = 30; // values are below 2^30
std::vector<std::array<int, 2>> kids(1, {0, 0}); // node 0 is the root; 0 also means "none"
void insert(int x) {
int v = 0;
for (int b = W - 1; b >= 0; b--) {
int bit = (x >> b) & 1;
if (!kids[v][bit]) { kids[v][bit] = kids.size(); kids.push_back({0, 0}); }
v = kids[v][bit];
}
}
int query(int x) { // max x ^ y over inserted y (at least one)
int v = 0, res = 0;
for (int b = W - 1; b >= 0; b--) {
int want = ((x >> b) & 1) ^ 1;
if (kids[v][want]) { res |= 1 << b; v = kids[v][want]; }
else v = kids[v][want ^ 1];
}
return res;
}The contest version. With and the trie has at most nodes, 48 MB at 8 bytes each; reserve the vector up front to avoid reallocation spikes.
Subarrays, and counting below a bound
Let and . Because , the shared part of two prefixes cancels, exactly as with prefix sums:
So the maximum XOR of a subarray is the maximum XOR of a pair among the prefix values, with the trie. For the prefix XORs are , the best pair is , and the subarray is : , more than any single element.
holds exactly when, at the highest bit where and differ, has a 1 and a 0. Walk down along the path of the numbers for which agrees with so far. At bit :
If : every stored in the child with bit makes this XOR bit 0 while 's is 1, so all of them count, whatever their lower bits. Add that child's counter, then continue into the child with bit , which keeps agreeing with .
If : an XOR bit of 1 would exceed , so only the child with bit can still count. If the walk survives all bits, it ends at the numbers with , which are not counted for a strict bound:
def count_pairs_below(nums, K, w=30): # pairs i < j with nums[i] ^ nums[j] < K
kids, cnt = [[0, 0]], [0]
total = 0
for x in nums:
v = 0 # 1. count earlier y with x ^ y < K
for b in range(w - 1, -1, -1):
xb, kb = (x >> b) & 1, (K >> b) & 1
if kb: # XOR bit 0 here already makes it smaller
total += cnt[kids[v][xb]] if kids[v][xb] else 0
v = kids[v][1 - xb]
else: # the XOR bit must stay 0
v = kids[v][xb]
if not v:
break
v = 0 # 2. insert x, counting passes
for b in range(w - 1, -1, -1):
bit = (x >> b) & 1
if not kids[v][bit]:
kids[v][bit] = len(kids); kids.append([0, 0]); cnt.append(0)
v = kids[v][bit]
cnt[v] += 1
return totalChoose so that . Run on the prefix XORs, it counts subarrays with XOR below ; "at least " is the complement, and "exactly " needs only a hash map of prefix values, as with subarray sums.
Think first How many subarrays of have an XOR below 4? Use the prefix XORs .
Four. Count the pairs with : , , and ; all other pairs give 4 or more. They are the subarrays , , and , with XORs 3, 1, 2 and 1.
Constraints: by value and by index range
By value, offline. Queries ask for over the stored . Sort the numbers, sort the queries by , insert numbers while they are at most , and answer with the plain greedy: time.
By value, online. Store in every node the minimum number in its subtree, and treat a child as missing when its minimum exceeds . The proof of the greedy goes through unchanged, because the nodes that survive are exactly the trie of .
By index range. Queries ask for over , inclusive, online. Keep every version of the trie, version holding with a counter in each node. Inserting copies only the nodes on its path and shares everything else with version , which is path copying, so all versions together take nodes. A child contains some with exactly when its counter in version exceeds its counter in version , and the greedy runs on that difference, in per query.
def build_versions(a, w): # roots[t]: the trie of a[0..t-1], with counts
L, R, C = [0], [0], [0] # node 0 is a shared empty node
roots = [0]
for x in a:
old = roots[-1]
cur = len(L); L.append(L[old]); R.append(R[old]); C.append(C[old] + 1)
roots.append(cur)
for b in range(w - 1, -1, -1): # copy x's path, share everything else
side = R if (x >> b) & 1 else L
old = side[old]
new = len(L); L.append(L[old]); R.append(R[old]); C.append(C[old] + 1)
side[cur] = new
cur = new
return roots, L, R, C
def range_max_xor(roots, L, R, C, w, l, r, x): # max of x ^ a[i] over l <= i <= r
u, v, res = roots[r + 1], roots[l], 0
for b in range(w - 1, -1, -1):
want, other = (L, R) if (x >> b) & 1 else (R, L) # prefer the opposite bit
if C[want[u]] - C[want[v]] > 0: # some a[i] with l <= i <= r lies there
res |= 1 << b
u, v = want[u], want[v]
else:
u, v = other[u], other[v]
return resL, R and C are the left child, right child and counter of every node. The shared empty node 0 has counter 0 and points to itself, so a missing child simply counts as empty.
Think first A persistent binary trie keeps all versions for numbers of bits. About how many nodes does it allocate, and how does that compare with copying the whole trie for every version?
Each insertion copies the nodes on one root-to-leaf path and shares the rest: nodes, the same order as a single trie. Copying the whole trie per version would take on the order of nodes.
XOR spanning trees, XOR bases and predecessor search
Numbers in share every bit above . Two numbers on the same side also share bit , so their XOR is below ; two numbers on different sides differ at bit , so their XOR is at least .
Run Kruskal's algorithm restricted to . All edges inside and inside come before any crossing edge, and they connect each side completely (each side is a complete graph); Kruskal's choices inside are those of Kruskal run on alone.
When the first crossing edge arrives, and are two components, so Kruskal adds exactly that one, the lightest, and every later crossing edge closes a cycle. The same separation holds at every level, since nodes higher up split on higher bits, so the recursion from the root yields an MST of .
To find each lightest crossing edge, query every number of the smaller side for its minimum XOR in the other side's subtree (the greedy descent, toward the same bit). A number is on the smaller side at most times, since the subtree containing it at least doubles each time, so the whole tree takes time with a single trie, against for Kruskal on all edges.
What is the weight of the minimum XOR spanning tree of ?
Show the answer
13
The root splits on bit 3: against , lightest crossing edge . Inside, bit 2 splits from , lightest edge ; then bit 0 splits 4 from 5, edge . Total , which Kruskal on all six edges confirms.
Subsets, not pairs. The maximum XOR of any subset of the numbers mixes many of them, and a trie cannot help. Viewed as vectors over GF(2), the numbers span a space with a basis of at most vectors with distinct leading bits; greedy over that XOR basis from the top bit gives the answer in . That is the subject of XOR Bases: Linear Algebra over GF(2).
Predecessor search. A binary trie over the universe , , also answers "the largest stored key ". The x-fast trie keeps a hash table of the prefixes present at each depth and binary-searches over the depths for the longest prefix that shares with the set: hash lookups, in space. The y-fast trie (Willard, 1983) buckets the keys into groups of about held in balanced trees and stores one representative per group, cutting the space to . Van Emde Boas trees (1975) reach the same time recursively, and fusion trees (Fredman & Willard, 1993) take ; Pătraşcu and Thorup (2006) proved that for universes polynomial in and near-linear space, is optimal.
Key takeaways
- In a binary trie, taking the opposite bit whenever possible maximizes , because a bit outweighs all lower bits; the maximum XOR pair costs .
- Prefix XORs, , turn subarray questions into pair questions; counters in the nodes count pairs below a bound in per query.
- Constraints compose with the trie: sort offline by a value bound or prune by subtree minima online; for index ranges, keep every version by path copying in nodes and compare counters of two versions.
- The minimum XOR spanning tree is the union of the children's trees plus the lightest crossing edge at every branching node, computable in .
- Subset XORs need an XOR basis over GF(2), not a trie; binary tries with a hash table per level give predecessor search, optimal in near-linear space.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A persistent binary trie answers over . At a node, how does the query decide that a child contains a usable ?
- Its counter in version is positive
- Its counter in version is positive
- Its counter in version minus its counter in version is positive
- The child stores the smallest index in its subtree, which must be at least
Show the answer
C. Its counter in version minus its counter in version is positive
Version contains and version contains ; the difference of their counters counts exactly the elements with index in inside that subtree.
Why does the minimum XOR spanning tree use exactly one edge between the two subtrees of a trie node that branches on bit ?
- Because the trie itself is a tree
- Because the lightest crossing edge is unique
- Because each subtree is a complete graph, and complete graphs need no extra edges
- Because every crossing edge weighs at least and every edge inside a side less, so Kruskal connects each side first and then needs one crossing edge
Show the answer
D. Because every crossing edge weighs at least and every edge inside a side less, so Kruskal connects each side first and then needs one crossing edge
Kruskal takes edges by weight. All inside edges come first and leave the two sides as two connected components; the first crossing edge joins them and every later one would close a cycle.
With and , which subarray has XOR equal to for ?
- , inclusive
- , inclusive
- , inclusive
- , inclusive
Show the answer
C. , inclusive
is the XOR of and the XOR of ; the common part cancels, leaving . It is the same off-by-one as with prefix sums, .
Counting stored with , the walk reaches a bit where . What does it do?
- Adds the counter of the child with bit , then continues into the child with bit
- Moves to the child with bit without adding anything
- Adds the counters of both children and stops
- Adds the counter of the child with bit , then continues into the child with bit
Show the answer
A. Adds the counter of the child with bit , then continues into the child with bit
Numbers in the child with bit make this XOR bit 0 while has 1, so they are smaller than whatever comes below: count them all. The other child keeps the XOR equal to so far, so the walk must continue there.
Further reading
- D. E. Knuth, The Art of Computer Programming, vol. 3, Sorting and Searching, 2nd ed. (Addison-Wesley, 1998), section 6.3 (digital searching).
- D. E. Willard, "Log-logarithmic worst-case range queries are possible in space Θ(N)," Information Processing Letters 17(2) (1983), 81–84.
- P. van Emde Boas, "Preserving order in a forest in less than logarithmic time," Proceedings of the 16th IEEE Symposium on Foundations of Computer Science (1975), 75–84.
- M. Pătraşcu & M. Thorup, "Time-space trade-offs for predecessor search," Proceedings of STOC (2006).
- J. R. Driscoll, N. Sarnak, D. D. Sleator & R. E. Tarjan, "Making data structures persistent," Journal of Computer and System Sciences 38(1) (1989), 86–124.