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 subsets, yet at most different results, and a table of at most 60 numbers, built in one pass, describes every one of them: the largest, the -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 -bit integers under XOR as the vector space , and prove that the subset XORs of numbers form a subspace of size in which every value is reached by exactly subsets.
- Build an XOR basis by Gaussian elimination with word operations per number, and test whether a value is representable.
- Find the maximum subset XOR greedily and the -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)
The list has rank 3. How many of its subsets have XOR equal to , counting the empty subset?
Show the answer
2
Every value is reached by subsets, and is no exception: the empty subset and , since . The 16 subsets therefore produce exactly 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 , its pivot. To insert , scan its bits from the top. At a set bit with an empty slot, becomes the new pivot vector. At a set bit with an occupied slot, cancel the bit, , and continue downward. If reaches , it was already in the span.
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 word operations, so numbers cost , and the basis never holds more than vectors. The same loop, without storing anything, tests whether a value is representable: it is exactly when it reduces to .
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.
Each step stays in the same coset. Replacing by changes it by a vector of the span, so belongs to the span exactly when the reduced value does:
Two outcomes. If reduces to , the original was in the span and the rank stays the same. Otherwise the reduced value has a new pivot, it is independent of , and storing it in place of the original spans the same space as :
On : takes pivot 3; reduces to and takes pivot 2; reduces to , dependent; reduces to and takes pivot 1. The basis is .
Maximum XOR and the k-th smallest
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 appears only in the vector with pivot . Sort the vectors by pivot, from lowest to highest. Then the XOR of a selection has a 1 at pivot exactly when is selected, and two selections compare like the binary numbers they spell: the highest pivot where they differ decides. So the -th smallest span element () is .
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 the reduced basis is . Mind the empty subset: is listed first, but if the problem requires a non-empty subset, is attainable only when .
Why must the basis be reduced, not just in echelon form, before reading the -th smallest XOR off the bits of ?
- Echelon form may contain dependent vectors
- 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
- Reduction sorts the vectors, which the formula needs
- 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 of the XOR is 1 exactly when is chosen". With in echelon form, choosing alone gives , while choosing and gives : 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 -bit weights, find the largest XOR of edge weights along a walk from to , where edges may be reused. Root a spanning tree at and let be the XOR along the tree path to . Each non-tree edge closes a fundamental cycle with XOR .
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 restime. The greedy argument works from any starting value, here . 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 (Bouton, 1901): XOR is the arithmetic of impartial games (see Combinatorial Games & Sprague–Grundy).
Linear systems. A system of XOR constraints such as is a linear system over , 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 then takes , using the basis for restricted to vectors inserted at positions .
Key takeaways
- Under XOR, -bit integers are vectors in : subset XORs form a span of size , and every value is reached by exactly subsets.
- Insertion by elimination keeps at most pivot vectors with distinct top bits, per number; a value is representable exactly when it reduces to .
- The maximum subset XOR is greedy from the top pivot down; after reduction, the -th smallest XOR is read off the binary digits of .
- Walk XORs between two vertices form a coset of the cycle space, so the maximum-XOR walk is a basis of fundamental-cycle values plus the greedy step, .
- 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.
Ten 20-bit numbers have rank 4. How many distinct values do their subset XORs take, and how many subsets give each value?
- values, one subset each
- values, subsets each
- values, but the counts vary from value to value
- values
Show the answer
B. values, subsets each
The span has elements, and each is reached by a coset of the kernel, of size . Indeed subsets in total.
Why does the maximum-XOR greedy loop scan pivots from the highest bit down?
- Because lower vectors have smaller values
- Because once higher bits are fixed, only the vector with pivot can still change bit , and a 1 there outweighs all lower bits combined
- Because Gaussian elimination stored the vectors in that order
- Any order gives the same result
Show the answer
B. Because once higher bits are fixed, only the vector with pivot can still change bit , and a 1 there outweighs all lower bits combined
Each pivot decision is independent of the later (lower) ones as far as bit is concerned, and exceeds , the most all lower bits can add. Scanning upward instead can set a low bit early and lose a higher one.
In the maximum-XOR walk algorithm, why may the value of any fundamental cycle be XOR-ed into , even a cycle far from the tree path to ?
- Because the graph is undirected, so every edge lies on a cycle
- Because a walk can go from the path to the cycle, around it, and back along the same edges, and those edges cancel
- Because XOR is commutative
- 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 . So the detour to the cycle and back is free, and only the cycle's own XOR remains.
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?
- Gaussian elimination over , in polynomial time
- A SAT solver, since the problem is NP-complete
- Enumerating all assignments
- Bitmask DP over subsets of constraints
Show the answer
A. Gaussian elimination over , in polynomial time
XOR constraints are linear equations over : elimination decides solvability and finds a solution in 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).