⊕ The universal key to ALL impartial combinatorial games
Welcome to the crown jewel of combinatorial game theory! The Sprague–Grundy theorem says that EVERY impartial combinatorial game is equivalent to a Nim heap. That heap size is called the Grundy number. Learn this, and you can solve any impartial game — from splitting heaps to XOR elimination and stone division. This article covers the mex computation, Grundy's Game (splitting heaps), the Chalkboard XOR Game, and Stone Division I & II. Four interactive problems await you at the end.
You already know that Standard Nim uses XOR of pile sizes to determine the winner — that's Bouton's theorem (1901). But what if the game rules are different? What if you can only remove 1, 2, or 3 stones? What if you split a pile into two? What if you erase numbers from a chalkboard?
Sprague (1935) and Grundy (1939) independently discovered the answer: EVERY impartial game — no matter how complex — is equivalent to a single Nim heap. The size of that heap is called the Grundy number (or nim-value). Once you compute it, you XOR the Grundy numbers of all sub-games, exactly like Nim-sum.
Tip
💡 The Core Insight: Grundy(n) = mex({ Grundy(m) | m reachable from n }). The mex (minimum excludant) is the smallest non-negative integer notin the reachable set. This maps any impartial game to a Nim heap of size Grundy(n).
Why does this matter for interviews? Because LeetCode, Codeforces, and CSES all have problems that require Grundy thinking. The "I've seen this before" factor is REAL — once you understand mex, you can solve any impartial game variant.
1. Grundy Numbers — Theory & mex Calculation
Let's start with the formal definition, then build intuition through examples.
Definition: Grundy Number
example.js
Grundy(state) = mex({ Grundy(s') | s' is a valid move from state })
Where mex(S) = Minimum EXcluded non-negative integer in set S
Examples:
mex({}) = 0 (empty set — smallest missing is 0)
mex({0}) = 1 (0 is present, 1 is missing)
mex({[0, 1]}) = 2 (0 and 1 present, 2 is missing)
mex({[0, 1, 2]}) = 3 (0, 1, 2 present, 3 is missing)
mex({[0, 2]}) = 1 (1 is missing even though 2 is present)
mex({[1, 2, 3]}) = 0 (0 is missing!)
Why mex? The Nim Connection
mex ensures that from a state with Grundy = g, you can move to any state with Grundy less than g, but cannot stay at g. This exactly mirrors a Nim pile of size g: from a pile of g stones, you can reduce it to any size 0 through g-1, but you cannot keep it at g.
The Sprague–Grundy Theorem
example.js
THEOREM: Any impartial game G composed of independent sub-games
G1, G2, ..., Gk can be analyzed as follows:
1. Compute Grundy(Gi) for each sub-game independently
2. Nim-sum = Grundy(G1) ⊕ Grundy(G2) ⊕ ... ⊕ Grundy(Gk)
3. If Nim-sum ≠ 0 → N-position (winning for current player)
4. If Nim-sum = 0 → P-position (losing for current player)
In other words: G ≅ Nim heap of size Grundy(G)
The XOR rule from standard Nim GENERALIZES to any impartial game!
This is the MOST IMPORTANT theorem in combinatorial game theory.
Subtraction Game — Worked Example
Let's compute Grundy numbers for a simple subtraction game where you can remove 1 or 2 stones from a pile. This is the classic "take-away" game.
Grundy Values — Remove One or Two. For a pile of n stones, legal moves remove exactly 1 or 2. Pattern: G(n) = n modulo 3 for moves {1, 2}.
Step-by-Step Grundy Computation
example.js
// Subtraction game: remove 1 or 2 stones (standard take-away)
Grundy(0) = mex({}) = 0 // Terminal state — no moves
Grundy(1) = mex({G(0)}) // Can move to 0
= mex({0}) = 1
Grundy(2) = mex({G(1), G(0)}) // Can move to 1 or 0
= mex({[1, 0]}) = 2
Grundy(3) = mex({G(2), G(1)}) // Can move to 2 or 1
= mex({[2, 1]}) = 0 // 0 is missing!
Grundy(4) = mex({G(3), G(2)}) // Can move to 3 or 2
= mex({[0, 2]}) = 1
Grundy(5) = mex({G(4), G(3)})
= mex({[1, 0]}) = 2
Pattern: Grundy(n) = n % 3 for {[1, 2]} subtraction game
Key Insight
🔑 Pattern Recognition: For a subtraction game with allowed moves {1, 2, ..., k}, Grundy(n) = n mod (k+1). This is because the reachable Grundy set is always{G(n-1), G(n-2), ..., G(n-k)} = {(n-1) mod (k+1), ..., (n-k) mod (k+1)}, which covers all values 0 through k except n mod (k+1). The mex is always n mod (k+1).
The Grand Unification: Grundy Table
Game Type
Grundy Formula
Example
Standard Nim
Grundy(n) = n
G(5) = 5
Subtraction {1, 2, ..., k}
Grundy(n) = n mod (k+1)
G(5) = 5 mod 3 = 2
Subtraction {1, 3, 4}
DP + mex (periodic sometimes)
G(5) = ? (compute)
Grundy's Game (split unequal)
DP + mex over split states
G(8) = 2
Stone Division I
DP over divisors
See below
Stone Division II
DP over divisors with k≥2
See below
Warning
⚠️ Critical Rule: Do NOT XOR pile sizes directly for non-standard Nim games! Always compute Grundy numbers first. Only when Grundy(n) = n (standard Nim) does XOR of raw pile sizes work. The Grundy number is the bridge between any impartial game and Nim.
2. Grundy's Game — Splitting Heaps
Problem (Grundy's Game): You are given a single heap of n stones. On each move, you must split the heap into two unequal non-empty heaps. The player who cannot make a move loses. Determine if the first player can force a win.
Note
🍬 Real-World Analogy: Imagine you have a pile of candy. On each turn, you must split any pile into two piles of DIFFERENT sizes. If all piles are size 1 or 2 (which can't be split unequally), the player whose turn it is loses. This is Grundy's Game! The name is fitting — Grundy himself studied this exact game to develop his theory.
🤔 Think About It — "At each heap, I split or pass"
"OK, so I have heaps. On each turn, I pick ONE heap and split it into two unequal parts. This creates TWO new heaps. The original heap disappears. So the game has multiple independent sub-games (heaps), and a move on one heap replaces it with two heaps. I need to compute Grundy for a single heap, then XOR across all heaps."
Grundy's Game — Unequal Split. Split a heap into two nonempty, UNEQUAL heaps; both remain in play. Correct recurrence: mex of each allowed split's XOR.
Grundy Computation for Splitting Games
The key insight: when a move replaces one heap with two heaps of sizes a and b, the resulting game state is the XOR of Grundy(a) and Grundy(b). So:
example.js
// Grundy's Game — Computing Grundy numbers
function computeGrundy(maxN) {
const grundy = new Array(maxN + 1).fill(0);
for (let n = 1; n <= maxN; n++) {
const reachable = new Set();
// Try all possible unequal splits
for (let a = 1; a < n; a++) {
const b = n - a;
if (a !== b) {
// Splitting n into (a, b) gives XOR of Grundy(a) and Grundy(b)
reachable.add(grundy[a] ^ grundy[b]);
}
}
// mex: find smallest non-negative not in reachable
let g = 0;
while (reachable.has(g)) g++;
grundy[n] = g;
}
return grundy;
}
// Grundy(0) = 0, G(1) = 0, G(2) = 0 (no valid splits)
// G(3) = mex({G(1)⊕G(2)}) = mex({0⊕0}) = mex({0}) = 1
// G(4) = mex({G(1)⊕G(3)}) = mex({0⊕1}) = mex({1}) = 0
// (G(2)⊕G(2) is invalid — equal split not allowed)
// G(5) = mex({G(1)⊕G(4), G(2)⊕G(3)})
// = mex({0⊕0, 0⊕1}) = mex({[0, 1]}) = 2
// Pattern: Grundy(n) = ? (depends on n, see diagram above)
📋 Edge Cases to Consider
n = 0: Empty heap — no moves possible. Grundy(0) = 0. Terminal state.
n = 1 or 2: Cannot split into two unequal non-empty parts. Grundy(1) = Grundy(2) = 0. These are terminal.
n = 3: Only split (1, 2) — unequal and both non-empty. G(3) = mex({0⊕0}) = 1.
Equal split rejection: (n/2, n/2) is invalid for even n. Do NOT include it in reachable set.
Multiple heaps: After several moves, you'll have many heaps. XOR their Grundy numbers. Non-zero → first wins.
The Winning Condition
Grundy's Game starts with a single heap of n stones. So the game is simply:
example.js
function grundysGame(n) {
// Precompute Grundy numbers
const grundy = computeGrundy(n);
// Initial state: one heap of size n
// Grundy of the whole game = Grundy(n)
return grundy[n] !== 0 ? "First" : "Second";
}
// Since the game starts with ONE heap, Grundy(n) = 0 means
// the first player LOSES. Grundy(n) ≠ 0 means first player WINS.
// From the table above: G(8) = 2 → First player wins!
Key Insight
🔑 Key Insight: Splitting games are the REASON Grundy numbers use XOR instead of sum. When one heap splits into two, the game state goes from Grundy(n) to Grundy(a) ⊕ Grundy(b). This is NOT additive — it's XOR. The mex of these XOR values gives the Grundy number. This is why XOR (not sum) is the universal connector for impartial games.
Problem rules: Alice and Bob take turns erasing exactly one number from the chalkboard. If the XOR of all remaining numbers becomes zero immediately after a move, the player who erased that number loses. A player facing a zero XOR at the start of their turn can win immediately.
Note
This is the Chalkboard XOR Game in our platform. It is nota game of removing equal pairs or finding pairs with XOR k. Those are different rules and would require a different strategy.
Chalkboard XOR: if the current XOR is zero the player wins immediately; otherwise parity of remaining elements determines who can force a win.
Reasoning from the XOR invariant
When the current XOR is zero, the current player wins by the problem's immediate-win condition. Otherwise, if the number of remaining elements is even, the current player can force a win: at least one removal preserves a nonzero XOR, and the opponent then faces an odd-length board. For an odd-length board with nonzero XOR, every legal safe move leaves an even-length board and gives the opponent that winning position.
example.js
function chalkboardXorGame(nums) {
let xor = 0;
for (const value of nums) xor ^= value;
return xor === 0 || nums.length % 2 === 0;
}
// [1,2,3] → true: starting XOR is zero
// [2,2,3] → false: XOR=3 and count=3 (odd)
// [4,5,6] → false: XOR=7 and count=3 (odd)
// [7,7,7,7] → true: starting XOR is zero
// Time O(n); extra space O(1).
Tip
Check the two sufficient conditions separately: XOR is already 0, or the number of elements is even. Do not rely on finding duplicate values; duplicates are not required for the winning condition.
These similarly named problems have different state transitions. Read the linked problem's rules before choosing an algorithm: only one active pile remains in our Stone Division I exercise, whereas Stone Division II retains every newly created pile and combines their Grundy values.
Stone Division I — Continue with one pile
With an active pile of n and permitted split counts S, choose x from S where x > 1 and x divides n. Split into x equal piles and continue play with one resulting pile of size n/x. The other piles leave the game. The player with no legal move loses.
example.js
function stoneDivisionOnePile(n, allowedSplits) {
const memo = new Map();
function win(m) {
if (memo.has(m)) return memo.get(m);
for (const x of allowedSplits) {
if (x > 1 && m % x === 0 && !win(m / x)) {
memo.set(m, true);
return true;
}
}
memo.set(m, false);
return false;
}
return win(n);
}
// n=6, allowed=[2,3] => false:
// both resulting positions (3 and 2) are winning for Bob.
// O(U * |S|) time, O(U) memo entries for U reachable sizes.
Note
In this one-active-pile variant, there is no XOR across the discarded piles: only the chosen resulting pile can be played. The winner follows the normal win/lose recurrence.
On a turn, select one pile of size m and a divisor d > 1 of m. Replace it with d piles each of size m/d. All of these new piles remain available in later turns. Their combined nim-value is 0 when d is even, otherwise it is Grundy(m/d). The rule allows d=m, which produces m terminal piles of size 1 and makes every m > 1 movable.
Stone Division II — Equal Splits and XOR. A move replaces one heap with d equal heaps; all descendants remain. Grundy(m) = mex of the XOR values for all allowed splits.
example.js
function stoneDivisionTwoPiles(pileSizes) {
const memo = new Map([[1, 0]]);
function grundy(m) {
if (memo.has(m)) return memo.get(m);
// Choosing d=m always creates m heaps of size 1, nim-value 0.
const seen = new Set([0]);
for (let d = 2; d * d <= m; d++) {
if (m % d !== 0) continue;
const other = m / d;
seen.add(d % 2 === 0 ? 0 : grundy(other));
if (other !== d)
seen.add(other % 2 === 0 ? 0 : grundy(d));
}
let g = 0;
while (seen.has(g)) g++;
memo.set(m, g);
return g;
}
let xor = 0;
for (const size of pileSizes) xor ^= grundy(size);
return xor !== 0;
}
// [2,2]: Grundy(2)=1, so 1 XOR 1=0 => second wins.
// [4]: Grundy(4)=1, so first wins.
Warning
The two problems are not interchangeable. Stone Division I uses a boolean winning-state recurrence on one active pile; Stone Division II uses a mex recurrence and XOR across all active piles. Do not apply the unrestricted-divisor recurrence to a problem that supplies a restricted set of legal splits.
Q1: When do I use Grundy numbers vs. simple XOR? Simple XOR (pile sizes) → only for standard Nim (remove any number from one pile). Grundy numbers → any other impartial game (splitting, restricted moves, non-standard rules).
Key Insight
Q2: How do I compute mex efficiently? Use a boolean array or Set. For small state spaces (< 10⁵), precompute via DP. For each state, mark reachable Grundy values, then find the first unmarked value.O(n × moves) total.
Key Insight
Q3: What's the Sprague–Grundy theorem in one sentence? "Every impartial game is equivalent to a Nim heap whose size equals the Grundy number of the game state, and XOR of sub-game Grundy numbers determines the winner."
Key Insight
Q4: How do I handle splitting moves in Grundy computation? When a heap splits into k heaps (e.g., (a₁, a₂, ..., aₖ)), the new game state has Grundy = Grundy(a₁) ⊕ Grundy(a₂) ⊕ ... ⊕ Grundy(aₖ). Add this XOR to the reachable set. Then compute mex.
Key Insight
Q5: What if the game has NO splitting — just restricted removal? That's a subtraction game. Grundy(n) often follows a periodic pattern. For allowed move set {1, ..., k}, Grundy(n) = n mod (k+1). For non-consecutive move sets, compute via DP and look for periodicity.
Key Insight
Q6: Can Grundy numbers be large? Yes! Grundy numbers can be larger than the pile size. For example, in a game where a heap can split into many sub-heaps, the Grundy number might grow beyond n. However, for most LeetCode problems, Grundy values stay small (0, 1, 2, ...).
📝 Key Takeaways
Sprague–Grundy theorem: Every impartial game = Nim heap of size Grundy(state). XOR sub-game Grundy numbers to determine win/lose.
Grundy(n) = mex({ Grundy(m) | m reachable }) — the universal formula. mex(S) = smallest non-negative integer NOT in S.
Standard Nim is a special case: Grundy(n) = n because from pile n you can reach Grundy 0, 1, ..., n-1.
Subtraction games: For moves {1, ..., k}, Grundy(n) = n mod (k+1). Always check for periodic patterns!
Grundy's Game (splitting): Split into two unequal heaps. Grundy(n) = mex({ G(a)⊕G(b) | a+b=n, a≠b }).
Chalkboard XOR Game: erase one number per turn. The current player wins if the XOR is already zero, or if the remaining count is even.
Stone Division: Split into k equal heaps. XOR = Grundy(d) if k odd, 0 if k even. Prime heaps are always terminal.
Even divisor trick: If n has an even divisor, 0 is in the reachable set → Grundy(n) ≥ 1.
Time: Grundy precomputation is O(n × divisors) or O(n × moves). Once computed, query is O(1).
The hierarchy: Learn Grundy → Learn ALL impartial games. It's the ultimate game theory weapon 🏆