Simple Algorithm
Algorithms & Data Structures · Optimal · 24 min

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 5×10115 \times 10^{11} XORs. A binary trie needs about 3×1073 \times 10^7 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 max⁡yx⊕y\max_y x \oplus y, and find the maximum XOR pair in O(nw)O(nw) time.
  • Reduce maximum-XOR subarrays to pairs of prefix XORs, and count pairs or subarrays whose XOR is below a bound in O(nw)O(nw).
  • 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

DerivationProof
  1. u>v  ⟺  uc=1 and vc=0,c=max⁡{ i:ui≠vi }u > v \iff u_c = 1 \text{ and } v_c = 0, \quad c = \max\{\, i : u_i \ne v_i \,\}

    Numbers of the same width compare like their bit strings: the highest bit where they differ decides, because 2c2^c exceeds the sum 2c−12^c - 1 of all lower bits.

  2. (x⊕y)i=ri  (i>c)  ⟹  yi=yi⋆  (i>c)(x \oplus y)_i = r_i \ \ (i > c) \;\Longrightarrow\; y_i = y^\star_i \ \ (i > c)

    Let r=x⊕y⋆r = x \oplus y^\star, and suppose some y∈Sy \in S has x⊕y>rx \oplus y > r. At the highest bit cc where they differ, (x⊕y)c=1(x \oplus y)_c = 1 and rc=0r_c = 0. Above cc the two XORs agree, so yy agrees with y⋆y^\star there: yy lies in the subtree where the greedy stood when it chose bit cc.

  3. yc=1−xc  ⟹  rc=1(contradiction)y_c = 1 - x_c \;\Longrightarrow\; r_c = 1 \quad \text{(contradiction)}

    But (x⊕y)c=1(x \oplus y)_c = 1 means yc=1−xcy_c = 1 - x_c, so the preferred child existed in that subtree, and the greedy would have taken it, making rc=1r_c = 1. Contradiction: no stored yy beats y⋆y^\star.

  4. Tmax⁡ pair=O(nw),space O(nw)T_{\max \text{ pair}} = O(nw), \qquad \text{space } O(nw)

    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:

Check your understanding

A binary trie stores 6, 9 and 12 (4 bits). Which partner does the greedy descent choose for x=5x = 5, and what XOR does it return?

  1. 12, giving 9
  2. 9, giving 12
  3. 6, giving 3
  4. 12, giving 12
Show the answer

B. 9, giving 12

x=01012x = 0101_2. Bit 3: want 1, and 9 and 12 have it. Bit 2: want 0, and only 9=100129 = 1001_2 has it. Then bits 1 and 0 are forced along 9's path. The result is 11002=12=5⊕91100_2 = 12 = 5 \oplus 9, larger than 5⊕12=95 \oplus 12 = 9 and 5⊕6=35 \oplus 6 = 3.

cpp
#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 n=2×105n = 2 \times 10^5 and W=30W = 30 the trie has at most 6×106+16 \times 10^6 + 1 nodes, 48 MB at 8 bytes each; reserve the vector up front to avoid reallocation spikes.

Subarrays, and counting below a bound

Let X[0]=0X[0] = 0 and X[i+1]=X[i]⊕a[i]X[i+1] = X[i] \oplus a[i]. Because v⊕v=0v \oplus v = 0, the shared part of two prefixes cancels, exactly as with prefix sums:

a[l]⊕a[l+1]⊕⋯⊕a[r]  =  X[r+1]⊕X[l](0≤l≤r<n, inclusive).a[l] \oplus a[l+1] \oplus \cdots \oplus a[r] \;=\; X[r+1] \oplus X[l] \qquad (0 \le l \le r < n,\ \text{inclusive}).

So the maximum XOR of a subarray is the maximum XOR of a pair among the n+1n + 1 prefix values, O(nw)O(nw) with the trie. For a=[3,11,1,8,4]a = [3, 11, 1, 8, 4] the prefix XORs are X=[0,3,8,9,1,5]X = [0, 3, 8, 9, 1, 5], the best pair is X[5]⊕X[2]=5⊕8=13X[5] \oplus X[2] = 5 \oplus 8 = 13, and the subarray is a[2..4]a[2..4]: 1⊕8⊕4=131 \oplus 8 \oplus 4 = 13, more than any single element.

DerivationCounting the stored y with x ⊕ y < K
  1. (x⊕y)b=0  ⟺  yb=xb(x \oplus y)_b = 0 \iff y_b = x_b

    x⊕y<Kx \oplus y < K holds exactly when, at the highest bit bb where x⊕yx \oplus y and KK differ, KK has a 1 and x⊕yx \oplus y a 0. Walk down along the path of the numbers yy for which x⊕yx \oplus y agrees with KK so far. At bit bb:

  2. Kb=1:total+=cnt(childxb),v←child1−xbK_b = 1:\quad \text{total} \mathrel{+}= \mathrm{cnt}(\mathrm{child}_{x_b}), \quad v \gets \mathrm{child}_{1 - x_b}

    If Kb=1K_b = 1: every stored yy in the child with bit xbx_b makes this XOR bit 0 while KK's is 1, so all of them count, whatever their lower bits. Add that child's counter, then continue into the child with bit 1−xb1 - x_b, which keeps agreeing with KK.

  3. Kb=0:v←childxb,each query costs O(w)K_b = 0:\quad v \gets \mathrm{child}_{x_b}, \qquad \text{each query costs } O(w)

    If Kb=0K_b = 0: an XOR bit of 1 would exceed KK, so only the child with bit xbx_b can still count. If the walk survives all ww bits, it ends at the numbers with x⊕y=Kx \oplus y = K, which are not counted for a strict bound:

python
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 total

Choose ww so that K<2wK < 2^w. Run on the prefix XORs, it counts subarrays with XOR below KK; "at least KK" is the complement, and "exactly KK" needs only a hash map of prefix values, as with subarray sums.

Think first How many subarrays of a=[3,11,1,8,4]a = [3, 11, 1, 8, 4] have an XOR below 4? Use the prefix XORs X=[0,3,8,9,1,5]X = [0, 3, 8, 9, 1, 5].

Four. Count the pairs i<ji < j with X[i]⊕X[j]<4X[i] \oplus X[j] < 4: 0⊕3=30 \oplus 3 = 3, 0⊕1=10 \oplus 1 = 1, 3⊕1=23 \oplus 1 = 2 and 8⊕9=18 \oplus 9 = 1; all other pairs give 4 or more. They are the subarrays [3][3], [3,11,1,8][3, 11, 1, 8], [11,1,8][11, 1, 8] and [1][1], with XORs 3, 1, 2 and 1.

Constraints: by value and by index range

By value, offline. Queries (xj,mj)(x_j, m_j) ask for max⁡xj⊕y\max x_j \oplus y over the stored y≤mjy \le m_j. Sort the numbers, sort the queries by mjm_j, insert numbers while they are at most mjm_j, and answer with the plain greedy: O((n+q)w+nlog⁡n+qlog⁡q)O((n + q)w + n \log n + q \log q) time.

By value, online. Store in every node the minimum number in its subtree, and treat a child as missing when its minimum exceeds mm. The proof of the greedy goes through unchanged, because the nodes that survive are exactly the trie of {y∈S:y≤m}\{y \in S : y \le m\}.

By index range. Queries (x,l,r)(x, l, r) ask for max⁡x⊕a[i]\max x \oplus a[i] over l≤i≤rl \le i \le r, inclusive, online. Keep every version of the trie, version tt holding a[0..t−1]a[0..t-1] with a counter in each node. Inserting a[t]a[t] copies only the w+1w + 1 nodes on its path and shares everything else with version tt, which is path copying, so all versions together take 1+n(w+1)1 + n(w + 1) nodes. A child contains some a[i]a[i] with l≤i≤rl \le i \le r exactly when its counter in version r+1r + 1 exceeds its counter in version ll, and the greedy runs on that difference, in O(w)O(w) per query.

python
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 res

L, 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 n=2×105n = 2 \times 10^5 numbers of w=30w = 30 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 w+1=31w + 1 = 31 nodes on one root-to-leaf path and shares the rest: 1+n(w+1)=6,200,0011 + n(w + 1) = 6{,}200{,}001 nodes, the same order as a single trie. Copying the whole trie per version would take on the order of n⋅nw≈1012n \cdot nw \approx 10^{12} nodes.

XOR spanning trees, XOR bases and predecessor search

DerivationProof with Kruskal
  1. x,y same side⇒x⊕y<2b  ≤  x′⊕y′⇐x′,y′ on different sidesx, y \text{ same side} \Rightarrow x \oplus y < 2^b \;\le\; x' \oplus y' \Leftarrow x', y' \text{ on different sides}

    Numbers in A∪BA \cup B share every bit above bb. Two numbers on the same side also share bit bb, so their XOR is below 2b2^b; two numbers on different sides differ at bit bb, so their XOR is at least 2b2^b.

  2. Kruskal(A∪B)=Kruskal(A)∪Kruskal(B)∪{ emin⁡(A,B) }\text{Kruskal}(A \cup B) = \text{Kruskal}(A) \cup \text{Kruskal}(B) \cup \{\, e_{\min}(A, B) \,\}

    Run Kruskal's algorithm restricted to A∪BA \cup B. All edges inside AA and inside BB come before any crossing edge, and they connect each side completely (each side is a complete graph); Kruskal's choices inside AA are those of Kruskal run on AA alone.

  3. w(MST(S))=∑branching nodesmin⁡a∈A, b∈Ba⊕bw(\mathrm{MST}(S)) = \sum_{\text{branching nodes}} \min_{a \in A,\, b \in B} a \oplus b

    When the first crossing edge arrives, AA and BB 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 SS.

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 log⁡2n\log_2 n times, since the subtree containing it at least doubles each time, so the whole tree takes O(nwlog⁡n)O(nw \log n) time with a single trie, against O(n2log⁡n)O(n^2 \log n) for Kruskal on all (n2)\binom{n}{2} edges.

Predict before you look

What is the weight of the minimum XOR spanning tree of {1,4,5,12}\{1, 4, 5, 12\}?

Show the answer

13

The root splits on bit 3: {1,4,5}\{1, 4, 5\} against {12}\{12\}, lightest crossing edge 4⊕12=84 \oplus 12 = 8. Inside, bit 2 splits {1}\{1\} from {4,5}\{4, 5\}, lightest edge 1⊕5=41 \oplus 5 = 4; then bit 0 splits 4 from 5, edge 4⊕5=14 \oplus 5 = 1. Total 8+4+1=138 + 4 + 1 = 13, 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 ww vectors with distinct leading bits; greedy over that XOR basis from the top bit gives the answer in O(nw)O(nw). That is the subject of XOR Bases: Linear Algebra over GF(2).

Predecessor search. A binary trie over the universe [0,U)[0, U), U=2wU = 2^w, also answers "the largest stored key ≤x\le x". The x-fast trie keeps a hash table of the prefixes present at each depth and binary-searches over the ww depths for the longest prefix that xx shares with the set: O(log⁡w)=O(log⁡log⁡U)O(\log w) = O(\log \log U) hash lookups, in O(nw)O(nw) space. The y-fast trie (Willard, 1983) buckets the keys into groups of about ww held in balanced trees and stores one representative per group, cutting the space to O(n)O(n). Van Emde Boas trees (1975) reach the same time recursively, and fusion trees (Fredman & Willard, 1993) take O(log⁡n/log⁡w)O(\log n / \log w); Pătraşcu and Thorup (2006) proved that for universes polynomial in nn and near-linear space, Θ(log⁡log⁡U)\Theta(\log \log U) is optimal.

Key takeaways

  • In a binary trie, taking the opposite bit whenever possible maximizes x⊕yx \oplus y, because a bit outweighs all lower bits; the maximum XOR pair costs O(nw)O(nw).
  • Prefix XORs, a[l]⊕⋯⊕a[r]=X[r+1]⊕X[l]a[l] \oplus \cdots \oplus a[r] = X[r+1] \oplus X[l], turn subarray questions into pair questions; counters in the nodes count pairs below a bound in O(w)O(w) 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 1+n(w+1)1 + n(w + 1) 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 O(nwlog⁡n)O(nw \log n).
  • Subset XORs need an XOR basis over GF(2), not a trie; binary tries with a hash table per level give O(log⁡log⁡U)O(\log \log U) 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.

Question 1

A persistent binary trie answers max⁡x⊕a[i]\max x \oplus a[i] over l≤i≤rl \le i \le r. At a node, how does the query decide that a child contains a usable a[i]a[i]?

  1. Its counter in version rr is positive
  2. Its counter in version r+1r + 1 is positive
  3. Its counter in version r+1r + 1 minus its counter in version ll is positive
  4. The child stores the smallest index in its subtree, which must be at least ll
Show the answer

C. Its counter in version r+1r + 1 minus its counter in version ll is positive

Version r+1r + 1 contains a[0..r]a[0..r] and version ll contains a[0..l−1]a[0..l-1]; the difference of their counters counts exactly the elements with index in [l,r][l, r] inside that subtree.

Question 2

Why does the minimum XOR spanning tree use exactly one edge between the two subtrees of a trie node that branches on bit bb?

  1. Because the trie itself is a tree
  2. Because the lightest crossing edge is unique
  3. Because each subtree is a complete graph, and complete graphs need no extra edges
  4. Because every crossing edge weighs at least 2b2^b 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 2b2^b 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.

Question 3

With X[0]=0X[0] = 0 and X[i+1]=X[i]⊕a[i]X[i+1] = X[i] \oplus a[i], which subarray has XOR equal to X[j]⊕X[i]X[j] \oplus X[i] for i<ji < j?

  1. a[i..j]a[i..j], inclusive
  2. a[i+1..j]a[i+1..j], inclusive
  3. a[i..j−1]a[i..j-1], inclusive
  4. a[i+1..j+1]a[i+1..j+1], inclusive
Show the answer

C. a[i..j−1]a[i..j-1], inclusive

X[j]X[j] is the XOR of a[0..j−1]a[0..j-1] and X[i]X[i] the XOR of a[0..i−1]a[0..i-1]; the common part a[0..i−1]a[0..i-1] cancels, leaving a[i..j−1]a[i..j-1]. It is the same off-by-one as with prefix sums, P[r+1]−P[l]P[r+1] - P[l].

Question 4

Counting stored yy with x⊕y<Kx \oplus y < K, the walk reaches a bit bb where Kb=1K_b = 1. What does it do?

  1. Adds the counter of the child with bit xbx_b, then continues into the child with bit 1−xb1 - x_b
  2. Moves to the child with bit 1−xb1 - x_b without adding anything
  3. Adds the counters of both children and stops
  4. Adds the counter of the child with bit 1−xb1 - x_b, then continues into the child with bit xbx_b
Show the answer

A. Adds the counter of the child with bit xbx_b, then continues into the child with bit 1−xb1 - x_b

Numbers in the child with bit xbx_b make this XOR bit 0 while KK has 1, so they are smaller than KK whatever comes below: count them all. The other child keeps the XOR equal to KK 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.