Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

XOR Bases: Linear Algebra over GF(2)

Maximum-XOR subsets and Gaussian elimination on bits.

XOR any subset of a million 60-bit numbers together. There are 21,000,0002^{1{,}000{,}000} subsets, yet at most 2602^{60} different results, and a table of at most 60 numbers, built in one pass, describes every one of them: the largest, the kk-th smallest, and whether a given value can be reached at all. The reason is linear algebra: under XOR, integers are vectors over the two-element field.

What you’ll learn

  • Model ww-bit integers under XOR as the vector space GF(2)w\mathrm{GF}(2)^w, and prove that the subset XORs of nn numbers form a subspace of size 2r2^r in which every value is reached by exactly 2n−r2^{n-r} subsets.
  • Build an XOR basis by Gaussian elimination with O(w)O(w) word operations per number, and test whether a value is representable.
  • Find the maximum subset XOR greedily and the kk-th smallest from a reduced basis, with proofs.
  • Apply XOR bases to maximum-XOR walks in graphs through the cycle space, and connect them to Nim, XOR-SAT and learning parities.

Integers as vectors over GF(2)

Predict before you look

The list [12,10,6,5][12,10,6,5] has rank 3. How many of its 24=162^4=16 subsets have XOR equal to 00, counting the empty subset?

Show the answer

2

Every value is reached by 2n−r=24−3=22^{n-r}=2^{4-3}=2 subsets, and 00 is no exception: the empty subset and {12,10,6}\{12,10,6\}, since 12⊕10=612\oplus10=6. The 16 subsets therefore produce exactly 23=82^3=8 distinct values, each twice.

Gaussian elimination, one number at a time

Keep the basis in echelon form: basis[b] is either empty or a vector whose highest set bit is bb, its pivot. To insert xx, scan its bits from the top. At a set bit bb with an empty slot, xx becomes the new pivot vector. At a set bit bb with an occupied slot, cancel the bit, x←x⊕basis[b]x\leftarrow x\oplus\text{basis}[b], and continue downward. If xx reaches 00, it was already in the span.

python
W = 60                                  # bit width of the values

def insert(basis, x):
    """basis[b] is 0 or a vector whose highest set bit is b. Returns True if x was independent."""
    for b in range(W - 1, -1, -1):
        if not (x >> b) & 1:
            continue
        if basis[b] == 0:
            basis[b] = x                # a new pivot: x is independent
            return True
        x ^= basis[b]                   # cancel bit b and keep reducing
    return False                        # x reduced to 0: it was in the span already

basis = [0] * W
print([insert(basis, x) for x in [12, 10, 6, 5]])   # [True, True, False, True]

Each insertion costs O(w)O(w) word operations, so nn numbers cost O(nw)O(nw), and the basis never holds more than ww vectors. The same loop, without storing anything, tests whether a value is representable: it is exactly when it reduces to 00.

DerivationWhy elimination preserves the span
  1. pivots distinct ⟹ ⨁b∈Tbasis[b]≠0(T≠∅)\text{pivots distinct}\ \Longrightarrow\ \bigoplus_{b\in T}\text{basis}[b]\ne0\quad(T\ne\emptyset)

    Invariant. The stored vectors have distinct pivots, so they are independent: in any non-empty XOR of them, the highest pivot involved survives, since no other chosen vector has that bit set above its own pivot.

  2. x∈span⁡(B)  ⟺  x⊕v∈span⁡(B)(v∈B)x\in\operatorname{span}(B)\iff x\oplus v\in\operatorname{span}(B)\qquad(v\in B)

    Each step stays in the same coset. Replacing xx by x⊕basis[b]x\oplus\text{basis}[b] changes it by a vector of the span, so xx belongs to the span exactly when the reduced value does:

  3. span⁡(B∪{x⊕v})=span⁡(B∪{x})\operatorname{span}\big(B\cup\{x\oplus v\}\big)=\operatorname{span}\big(B\cup\{x\}\big)

    Two outcomes. If xx reduces to 00, the original xx was in the span and the rank stays the same. Otherwise the reduced value has a new pivot, it is independent of BB, and storing it in place of the original xx spans the same space as B∪{x}B\cup\{x\}:

On [12,10,6,5][12,10,6,5]: 12=1100212=1100_2 takes pivot 3; 10=1010210=1010_2 reduces to 1010⊕1100=011021010\oplus1100=0110_2 and takes pivot 2; 6=011026=0110_2 reduces to 00, dependent; 5=010125=0101_2 reduces to 0101⊕0110=001120101\oplus0110=0011_2 and takes pivot 1. The basis is {11002,01102,00112}\{1100_2,0110_2,0011_2\}.

Maximum XOR and the k-th smallest

python
def max_xor(basis):
    res = 0
    for b in range(W - 1, -1, -1):
        res = max(res, res ^ basis[b])  # take basis[b] exactly when it sets bit b
    return res

print(max_xor(basis))                   # 15 for [12, 10, 6, 5]

For order statistics, first make the basis reduced: clear each pivot bit from every other basis vector, so that pivot bit pp appears only in the vector with pivot pp. Sort the rr vectors by pivot, v0,…,vr−1v_0,\dots,v_{r-1} from lowest to highest. Then the XOR of a selection has a 1 at pivot pip_i exactly when viv_i is selected, and two selections compare like the binary numbers they spell: the highest pivot where they differ decides. So the kk-th smallest span element (k=0,1,…,2r−1k=0,1,\dots,2^r-1) is ⨁{vi:bit i of k is 1}\bigoplus\{v_i:\text{bit }i\text{ of }k\text{ is }1\}.

python
def reduce_basis(basis):
    for b in range(W):
        if basis[b]:
            for c in range(b + 1, W):   # clear pivot bit b from every higher vector
                if (basis[c] >> b) & 1:
                    basis[c] ^= basis[b]
    return [v for v in basis if v]      # sorted by pivot, lowest first

def kth_smallest(red, k):               # k = 0 .. 2^r - 1; k = 0 gives 0
    res = 0
    for i, v in enumerate(red):
        if (k >> i) & 1:
            res ^= v
    return res

red = reduce_basis(basis[:])
print([kth_smallest(red, k) for k in range(8)])   # [0, 3, 5, 6, 9, 10, 12, 15]

For [12,10,6,5][12,10,6,5] the reduced basis is {00112,01012,10012}\{0011_2,0101_2,1001_2\}. Mind the empty subset: 00 is listed first, but if the problem requires a non-empty subset, 00 is attainable only when r<nr<n.

Check your understanding

Why must the basis be reduced, not just in echelon form, before reading the kk-th smallest XOR off the bits of kk?

  1. Echelon form may contain dependent vectors
  2. In echelon form a higher vector can also have a lower pivot bit set, so a value's pivot bits no longer spell out which vectors were chosen
  3. Reduction sorts the vectors, which the formula needs
  4. It need not; echelon form works as well
Show the answer

B. In echelon form a higher vector can also have a lower pivot bit set, so a value's pivot bits no longer spell out which vectors were chosen

The ordering argument needs "bit pip_i of the XOR is 1 exactly when viv_i is chosen". With {11002,01102,00112}\{1100_2,0110_2,0011_2\} in echelon form, choosing 110021100_2 alone gives 1212, while choosing 110021100_2 and 011020110_2 gives 10<1210<12: the order of values no longer matches the binary order of selections.

Walks, games and linear systems

Maximum-XOR walks. In an undirected graph whose edges carry ww-bit weights, find the largest XOR of edge weights along a walk from ss to tt, where edges may be reused. Root a spanning tree at ss and let d[v]d[v] be the XOR along the tree path to vv. Each non-tree edge (u,v,w)(u,v,w) closes a fundamental cycle with XOR d[u]⊕w⊕d[v]d[u]\oplus w\oplus d[v].

python
def max_xor_walk(n, edges, s, t):          # undirected (u, v, w); edges may be reused
    adj = [[] for _ in range(n)]
    for u, v, w in edges:
        adj[u].append((v, w))
        adj[v].append((u, w))
    d = [None] * n                         # d[v]: XOR along the tree path s -> v
    d[s] = 0
    basis = [0] * W
    stack = [s]
    while stack:
        u = stack.pop()
        for v, w in adj[u]:
            if d[v] is None:
                d[v] = d[u] ^ w
                stack.append(v)
            else:
                insert(basis, d[u] ^ w ^ d[v])   # a cycle's XOR (0 for tree edges)
    if d[t] is None:
        return None                        # t is unreachable
    res = d[t]
    for b in range(W - 1, -1, -1):
        res = max(res, res ^ basis[b])     # greedy, starting from d[t]
    return res

O((n+m) w)O((n+m)\,w) time. The greedy argument works from any starting value, here d[t]d[t]. For simple paths the problem is different and much harder.

Nim. In Nim, a position is lost for the player to move exactly when the XOR of the pile sizes is 00 (Bouton, 1901): XOR is the arithmetic of impartial games (see Combinatorial Games & Sprague–Grundy).

Linear systems. A system of XOR constraints such as x1⊕x4⊕x7=1x_1\oplus x_4\oplus x_7=1 is a linear system over GF(2)\mathrm{GF}(2), solved by Gaussian elimination. So XOR-SAT is in P, one of the tractable classes in Schaefer's (1978) dichotomy theorem, while general SAT is NP-complete; solvers such as CryptoMiniSat add Gaussian elimination for XOR clauses (Soos, Nohl & Castelluccia, 2009). "Lights Out" puzzles are such systems.

Ranges. Storing, for each pivot, the most recently inserted vector gives a "prefix basis": the maximum XOR of any subarray a[l..r]a[l..r] then takes O(w)O(w), using the basis for a[0..r]a[0..r] restricted to vectors inserted at positions ≥l\ge l.

Key takeaways

  • Under XOR, ww-bit integers are vectors in GF(2)w\mathrm{GF}(2)^w: subset XORs form a span of size 2r2^r, and every value is reached by exactly 2n−r2^{n-r} subsets.
  • Insertion by elimination keeps at most ww pivot vectors with distinct top bits, O(w)O(w) per number; a value is representable exactly when it reduces to 00.
  • The maximum subset XOR is greedy from the top pivot down; after reduction, the kk-th smallest XOR is read off the binary digits of kk.
  • Walk XORs between two vertices form a coset d[t]⊕Cd[t]\oplus C of the cycle space, so the maximum-XOR walk is a basis of fundamental-cycle values plus the greedy step, O((n+m)w)O((n+m)w).
  • XOR constraints are linear equations: XOR-SAT and Lights Out are solved by elimination, Nim is decided by a XOR, and adding noise turns parity learning into a conjectured-hard problem.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Ten 20-bit numbers have rank 4. How many distinct values do their subset XORs take, and how many subsets give each value?

  1. 2102^{10} values, one subset each
  2. 1616 values, 6464 subsets each
  3. 1616 values, but the counts vary from value to value
  4. 2202^{20} values
Show the answer

B. 1616 values, 6464 subsets each

The span has 2r=162^r=16 elements, and each is reached by a coset of the kernel, of size 2n−r=26=642^{n-r}=2^6=64. Indeed 16⋅64=1024=21016\cdot64=1024=2^{10} subsets in total.

Question 2

Why does the maximum-XOR greedy loop scan pivots from the highest bit down?

  1. Because lower vectors have smaller values
  2. Because once higher bits are fixed, only the vector with pivot bb can still change bit bb, and a 1 there outweighs all lower bits combined
  3. Because Gaussian elimination stored the vectors in that order
  4. Any order gives the same result
Show the answer

B. Because once higher bits are fixed, only the vector with pivot bb can still change bit bb, and a 1 there outweighs all lower bits combined

Each pivot decision is independent of the later (lower) ones as far as bit bb is concerned, and 2b2^b exceeds 2b−12^b-1, the most all lower bits can add. Scanning upward instead can set a low bit early and lose a higher one.

Question 3

In the maximum-XOR walk algorithm, why may the value of any fundamental cycle be XOR-ed into d[t]d[t], even a cycle far from the tree path to tt?

  1. Because the graph is undirected, so every edge lies on a cycle
  2. Because a walk can go from the path to the cycle, around it, and back along the same edges, and those edges cancel
  3. Because XOR is commutative
  4. It may not: only cycles that touch the tree path can be used
Show the answer

B. Because a walk can go from the path to the cycle, around it, and back along the same edges, and those edges cancel

Walks may reuse edges, and an edge used twice contributes w⊕w=0w\oplus w=0. So the detour to the cycle and back is free, and only the cycle's own XOR remains.

Question 4

A puzzle gives 500 Boolean variables and 600 constraints, each saying that the XOR of some variables equals 0 or 1. What is the right tool?

  1. Gaussian elimination over GF(2)\mathrm{GF}(2), in polynomial time
  2. A SAT solver, since the problem is NP-complete
  3. Enumerating all 25002^{500} assignments
  4. Bitmask DP over subsets of constraints
Show the answer

A. Gaussian elimination over GF(2)\mathrm{GF}(2), in polynomial time

XOR constraints are linear equations over GF(2)\mathrm{GF}(2): elimination decides solvability and finds a solution in O(nmmin⁡(n,m)/w)O(nm\min(n,m)/w) word operations or better. XOR-SAT is one of Schaefer's tractable cases.

Further reading

  • C. L. Bouton, "Nim, a game with a complete mathematical theory," Annals of Mathematics 3(1/4) (1901), 35–39.
  • T. J. Schaefer, "The complexity of satisfiability problems," Proceedings of STOC (1978), 216–226.
  • J. R. Bunch & J. E. Hopcroft, "Triangular factorization and inversion by fast matrix multiplication," Mathematics of Computation 28 (1974), 231–236.
  • D. H. Wiedemann, "Solving sparse linear equations over finite fields," IEEE Transactions on Information Theory 32(1) (1986), 54–62.
  • M. Soos, K. Nohl & C. Castelluccia, "Extending SAT solvers to cryptographic problems," Proceedings of SAT (2009).