Patterns/Part VI - Math & Discrete/Gaussian Elimination GF(2)

Pattern Reference

Gaussian Elimination GF(2)

"Solve linear systems over GF(2). XOR basis, linear basis of array, find if target reachable, maximum XOR subset."

Loading...

Deep Dive Tutorial

Gaussian elimination over GF(2): represent each equation as a bitmask. Process pivots from highest bit to lowest. For each pivot column, find a row with that bit set (if none, that variable is free). XOR the pivot row into all other rows with that bit set. After elimination, the reduced row echelon form gives the solution structure. Rank = number of pivot rows. If a "0 = 1" equation exists: no solution.

Gaussian elimination over GF(2)
// Gaussian elimination over GF(2)
// rows: array of bitmasks representing equations (augmented: last bit is RHS)
function gaussianGF2(rows, n) {
    // n = number of variables
    const basis = [];
    let rank = 0;
    for (let col = n - 1; col >= 0; col--) {
        // Find pivot row with this column bit set
        let pivot = -1;
        for (let r = rank; r < rows.length; r++) {
            if ((rows[r] >> col) & 1) { pivot = r; break; }
        }
        if (pivot === -1) continue; // free variable in this column
        [rows[rank], rows[pivot]] = [rows[pivot], rows[rank]];
        // XOR pivot into all other rows with this bit set
        for (let r = 0; r < rows.length; r++) {
            if (r !== rank && (rows[r] >> col) & 1) rows[r] ^= rows[rank];
        }
        basis[col] = rows[rank];
        rank++;
    }
    return { rank, rows: rows.slice(0, rank) };
}

// Check if target is XOR-reachable from basis vectors
function isReachable(vectors, target) {
    // Insert target into basis; if it reduces to 0, it was already in span
    let x = target;
    for (let i = 29; i >= 0; i--) {
        if (!((x >> i) & 1)) continue;
        const pivot = vectors.find(v => (v >> i) & 1);
        if (!pivot) { vectors.push(x); return false; } // x adds new dimension
        x ^= pivot;
    }
    return true; // x reduces to 0, was in span
}

Worked Problems

GF(2) Gaussian elimination vs XOR basis:
- XOR basis: greedy insertion, finds max XOR reachable — O(30n)
- GF(2) Gaussian: full row reduction, finds solution space, checks solvability — O(n² or n×30)

When to use full Gaussian:
- System of XOR equations with multiple unknowns
- "Can we XOR some subset to get target?" (same as XOR basis span check)
- Counting solutions (2^(num_free_variables) solutions if consistent)
- Linear independence over GF(2) (rank of matrix)

Key property: GF(2) arithmetic: addition = XOR, multiplication = AND. All standard Gaussian elimination rules work, just with bitwise ops.