Advanced Nim & Grundy Numbers — The Sprague–Grundy Theorem
⊕ From Nim to ALL impartial combinatorial games
Welcome to advanced Nim theory! 🚀 You already know Nim basics — now it's time to unlock the Sprague–Grundy theorem, the crown jewel of combinatorial game theory. This theorem says: EVERY impartial game is equivalent to Nim. Learn this, and you can solve ANY impartial game.
Standard Nim gives you XOR of pile sizes. But what about games where the rules differ per pile? Games where you can remove 1, 2, or 3 stones only? Games where you split a pile into two? These are ALL Nim in disguise.
Sprague–Grundy theorem (1935-1939): Every impartial combinatorial game is equivalent to a Nim heap of a certain size. That size is called the Grundy number (or nim-value). The XOR of Grundy numbers of sub-games determines the winner — exactly like Nim-sum!
Tip
💡 The Core Insight: If you can compute Grundy(n) for a game state "n", you reduce ANY impartial game to Nim. Grundy(n) = mex{ Grundy(m) | m reachable from n }. Then XOR all sub-game Grundy numbers. ≠ 0 → win, 0 → lose.
This is NOT just theory — advanced Nim variants appear in Codeforces, CSES, HackerRank, and AtCoder. The problems in this article cover 6 distinct variants that build on the Grundy framework.
1. Grundy Numbers & Nim Game II
Grundy numbers (also called nim-values) assign a non-negative integer to every game state. The Grundy number of a terminal state (no moves) is 0.
Definition
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
Example: S = {[0, 1, 3]} → mex(S) = 2
S = {[0, 1, 2, 4]} → mex(S) = 3
S = {} → mex(S) = 0 (terminal state)
Why mex? The Intuition
mex ensures that from a state with Grundy = g, you can move to any state with Grundy less than g (like reducing a Nim pile), but cannot move to a state with the same Grundy g. This exactly mirrors Nim: from a pile of size g, you can reduce it to any size 0 through g-1, but cannot keep it at g.
Sprague–Grundy Theorem — The Master 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
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!
Nim Game II (CSES) — Multiple Sets of Moves
Problem: n piles, each pile i has si stones. On each turn, you choose a pile and remove exactly k stones, where k must be in a given set of allowed moves (e.g., {1, 2, 3}). The player who takes the last stone wins.
This is NOT standard Nim — you can't remove any number, only specific counts. But Grundy numbers solve it cleanly:
example.js
// Nim Game II — CSES (moves allowed = {[1, 2, 3]})
function nimGameII(piles, moves = [1, 2, 3]) {
// Precompute Grundy numbers up to max pile size
const maxPile = Math.max(...piles);
const grundy = new Array(maxPile + 1).fill(0);
for (let i = 1; i <= maxPile; i++) {
const reachable = new Set();
for (const m of moves) {
if (i - m >= 0) reachable.add(grundy[i - m]);
}
// mex: find smallest non-negative not in reachable
let g = 0;
while (reachable.has(g)) g++;
grundy[i] = g;
}
// XOR all Grundy numbers
const xorSum = piles.reduce((acc, p) => acc ^ grundy[p], 0);
return xorSum !== 0 ? "First" : "Second";
}
// Pattern: Grundy[n] = n mod (moves.length + 1) for consecutive moves {"{1..k}"}
// But for arbitrary move sets, compute DP mex as above
Key Insight
🔑 Pattern Recognition: When the allowed moves are consecutive{1, 2, ..., k}, Grundy[n] = n mod (k+1). This is the subtraction game pattern. When moves are non-consecutive (e.g., {1, 3, 4}), compute Grundy array via DP+mex.
Let's connect the dots between standard Nim XOR and the general Grundy framework.
Standard Nim as a Special Case
In standard Nim, a pile of size n has Grundy number = n. Why? Because from a pile of size n, you can move to any size 0, 1, ..., n-1. So reachable Grundy set ={Grundy(0), Grundy(1), ..., Grundy(n-1)} = {0, 1, ..., n-1}. mex({0, 1, ..., n-1}) = n. Therefore Grundy(n) = n for standard Nim.
example.js
// Standard Nim pile of size n:
// Reachable states: {0, 1, 2, ..., n-1}
// Grundy(0) = 0, Grundy(1) = 1, ..., Grundy(n-1) = n-1
// mex{0, 1, 2, ..., n-1} = n
// ∴ Grundy(n) = n for standard Nim
// Nim-sum = Grundy(p1) ⊕ Grundy(p2) ⊕ ... ⊕ Grundy(pk)
// = p1 ⊕ p2 ⊕ ... ⊕ pk (same as before!)
The Full Hierarchy
Game Type
Grundy Number
Complexity
Standard Nim
Grundy(n) = n
O(1) per pile
Subtraction Game (moves {1..k})
Grundy(n) = n mod (k+1)
O(1) per pile
Arbitrary Move Set
DP + mex computation
O(n × moves) precompute
Staircase Nim
Grundy(odd stair) = stones, Grundy(even) = 0
O(n)
Nimble (coins on squares)
Grundy(square i with coins) = i if odd coins
O(n)
Poker Nim
Standard Nim + pass token = extra 0/1 toggle
O(n)
Industrial Nim
XOR of ranges using prefix XOR patterns
O(n) or O(1) with formula
Warning
⚠️ Common Pitfall: Don't blindly XOR pile sizes for non-standard Nim games. Always compute Grundy numbers first! Only when Grundy(n) = n (true only for standard Nim) does XOR of pile sizes directly work.
3. Staircase Nim — Grundy Perspective
Rule variation: n stairs (indexed 0 to n-1). Each stair i has sistones. A move moves stones from stair i to stair i-1 (down one step). Stair 0 is ground — stones reaching it are removed.
From the basics article, you know: XOR only odd-indexed stairs. Let's prove why with Grundy numbers.
Grundy Analysis of Staircase Nim
example.js
// Staircase Nim — Grundy Proof
//
// Each stair i is a sub-game. What's Grundy(i)?
// From stair i, you move stones to stair i-1.
// This is equivalent to: Grundy(i) = i XOR Grundy(i-1)? No...
//
// Key insight: Moving stones from i → i-1 changes the parity of
// stones on BOTH stairs. The "real" game is on odd stairs.
//
// For stair i:
// - If i is ODD: moving stones here is like reducing a Nim pile
// of size equal to the stone count (they will reach ground)
// - If i is EVEN: opponent can "mirror" any move you make here
//
// ∴ Grundy(i) = stones[i] if i is odd, 0 if i is even
// Final XOR = XOR of stones on odd-indexed stairs
Staircase Nim
Tech DOSE — Staircase Edge Cases
All stones on even stairs: XOR = 0 → losing for player to move (opponent mirrors every move)
Single odd stair with stones: XOR = that count. Non-zero → first player wins by moving all to ground.
Zero-indexed vs 1-indexed: Most problems use 0-indexed arrays where "odd" = index 1, 3, 5... In 1-indexed it's index 2, 4, 6... Always check indexing!
Large stone counts: Still O(n), XOR works for any integer size.
Misère play: The player who takes the LAST stone LOSES. This small rule change has a surprisingly simple fix for Nim.
The Misère Rule
For most impartial games, misère and normal play have vastly different solutions. Nim is special — the switch is almost trivial:
example.js
function misereNim(piles) {
const maxPile = Math.max(...piles);
const allOnes = maxPile <= 1; // All piles are 0 or 1
if (allOnes) {
// FLIP: Normal XOR logic is inverted
// Normal: odd count of 1s → First wins
// Misère: odd count of 1s → First LOSES
const xorAll = piles.reduce((a, b) => a ^ b, 0);
return xorAll === 0 ? "First" : "Second";
} else {
// Any pile > 1 → Same as normal Nim!
const nimSum = piles.reduce((a, b) => a ^ b, 0);
return nimSum !== 0 ? "First" : "Second";
}
}
// Why? The winning player can force a state where:
// 1. They leave exactly one pile with > 1 stone
// 2. All other piles are 0 or 1
// 3. The opponent is forced to take from the >1 pile
// 4. The opponent ends up taking the LAST stone = LOSS
Misere Nim
Misère Nim — Complete Decision Table
Game State
Normal Play
Misère Play
[1, 1] (even 1s)
P2 wins (nim-sum = 0)
P1 wins (flipped!)
[1, 1, 1] (odd 1s)
P1 wins (nim-sum ≠ 0)
P2 wins (flipped!)
[2, 1] (has >1)
P1 wins (nim-sum = 3 ≠ 0)
P1 wins (same)
[2, 2] (has >1)
P2 wins (nim-sum = 0)
P2 wins (same)
[3, 4, 5] (has >1)
P1 wins (nim-sum ≠ 0)
P1 wins (same)
Key Insight
🔑 Misère Memory Aid: "All ones? Flip the fun. One big pile? Game's the same." — When all piles ≤ 1, invert normal logic. Otherwise, play normal Nim.
5. Advanced Nim Variants — Poker, Nimble & Industrial
Poker Nim — Add or Remove Stones
Actual platform rules: On each move a player may remove any positive number of stones from one pile, or add between 1 andk stones to a pile. This is not a turn-skipping token game; no player may simply pass.
The winning condition remains the ordinary Nim-sum. When XOR is nonzero, the current player makes the standard reduction to XOR zero. When XOR is zero, an addition changes it to nonzero, and the opponent can remove those added stones to restore XOR zero. Therefore, the extra add operation does not let a losing zero-XOR position force a win.
Poker Nim — Adding Is Reversible. Platform variant: add up to k stones or remove any positive number. First player wins iff the XOR of all starting piles is nonzero.
example.js
function pokerNim(piles, k) {
// k is part of the allowed add-move rules, but not the winner test.
let nimSum = 0;
for (const pile of piles) nimSum ^= pile;
return nimSum === 0 ? "Second" : "First";
}
// [1,2,3], k=3 -> XOR=0 -> Second
// [3,5], k=2 -> XOR=6 -> First
// O(number of piles) time, O(1) extra space.
Warning
Do not treat adding stones as passing a turn.A pass-token variant is a different game and cannot be solved with this platform's Poker Nim rule without a separate proof.
Nimble is played on a line of numbered squares (0, 1, 2, ..., n). Coins are placed on some squares. A move consists of picking one coin and moving it to any LOWER-numbered square. Coins on square 0 are removed from play.
🤔 Think About It
A coin on square i can move to any square j where 0 ≤ j < i. This is EXACTLY like a Nim pile of size i — you can "reduce" a coin from position i to any smaller position. Multiple coins on the same square? Pairs cancel (like Nim piles of equal size cancel in XOR).
Nimble Game
example.js
// Nimble Game — Solution
function nimbleGame(squares) {
// squares[i] = number of coins on square i
// Each coin on square i contributes Grundy = i
// Pairs of coins on same square cancel (i ⊕ i = 0)
let xorSum = 0;
for (let i = 0; i < squares.length; i++) {
if (squares[i] % 2 === 1) {
xorSum ^= i; // Odd coins on square i → include i in XOR
}
// Even coins → cancel out (i ⊕ i = 0)
}
return xorSum !== 0 ? "First" : "Second";
}
// Intuition:
// - Each coin is a Nim pile of size = square index
// - Two coins on same square = two equal piles → cancel
// - Only need to track parity of coins per square
Key Insight
🔑 Nimble → Nim Reduction: A coin on square i is a Nim heap of size i. Count of coins on a square is how many copies of heap i exist. Pairs cancel (XOR). Only odd counts matter. This is a beautiful example of the Sprague–Grundy isomorphism.
Industrial Nim combines multiple machine "groups" where each group creates multiple piles following a pattern. The challenge: compute XOR efficiently without iterating over every pile.
Problem Structure
You have N groups. Each group i has start pile size si and count ci. The group creates piles of sizes si, si+1, ..., si+ci-1. Find XOR of ALL piles across ALL groups.
example.js
// Industrial Nim — Solution
// Key: XOR of range [L, R] efficiently using prefix XOR pattern
// Helper: XOR of all numbers from 0 to n
function xor0toN(n) {
const mod = n % 4;
if (mod === 0) return n;
if (mod === 1) return 1;
if (mod === 2) return n + 1;
return 0;
}
// XOR of range [L, R] = xor0toN(R) ⊕ xor0toN(L-1)
function xorRange(L, R) {
if (L === 0) return xor0toN(R);
return xor0toN(R) ^ xor0toN(L - 1);
}
function industrialNim(groups) {
// groups: [{start, count}, ...]
let xorSum = 0;
for (const {start, count} of groups) {
xorSum ^= xorRange(start, start + count - 1);
}
return xorSum !== 0 ? "First" : "Second";
}
// XOR 0..n pattern:
// n % 4 == 0 → n
// n % 4 == 1 → 1
// n % 4 == 2 → n + 1
// n % 4 == 3 → 0
Single pile group: count = 1 → XOR of that single size
Large ranges: The xor0toN function is O(1) — works for ANY range size up to 10^18
Overlapping ranges: XOR is commutative, overlapping piles just cancel. No special handling needed.
Integer overflow: In JavaScript, use BigInt for ranges beyond 2^31-1.
Tip
⚡ Pro Tip: Memorize the XOR-0-to-N pattern (n%4). It's one of the most useful bitwise tricks for range XOR problems. It reduces O(N) to O(1) and appears in many competitive programming problems beyond Nim.
Q1: When do I use Grundy numbers vs. simple XOR? Simple XOR (pile sizes) → only when the game is standard Nim (remove any number from one pile). Grundy numbers → any other impartial game (restricted moves, splitting, non-standard rules).
Key Insight
Q2: How do I compute Grundy numbers efficiently? For small state spaces (< 10^5), precompute via DP with mex. For large states, look for patterns: Grundy often follows periodic sequences (e.g., mod (k+1) for subtraction games). The mex definition is the general case, but many games have closed-form solutions.
Key Insight
Q3: What's the difference between normal and misère Nim again? Normal: last move WINS. Misère: last move LOSES. Strategy is IDENTICAL except when ALL piles ≤ 1. In that case, flip the win/lose: even count of 1s → misère wins, odd count → misère loses.
Key Insight
Q4: What if a game allows PASSING the turn? The linked Poker Nim variant allows adding up to k stones. Adding can be reversed by removing the added stones, so the ordinary XOR winner test remains valid. A game with actual pass tokens has different rules (pass from P-position → opponent in P-position).
Key Insight
Q5: How do I handle range XOR efficiently? Use the xor0toN pattern (n%4). XOR of range [L, R] = xor0toN(R) ⊕ xor0toN(L-1). This is O(1) and works for any integer range. This is essential for Industrial Nim and many other competitive programming problems.
Key Insight
Q6: Can I use Grundy numbers for PARTISAN games (Chess, Go)? No! Sprague–Grundy only applies to IMPARTIAL games (same moves for both players). Partisan games need different theory (Conway's surreal numbers, thermography). For interviews, if the game is partisan, look for symmetry/strategy-stealing arguments.
📝 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. Compute via DP for arbitrary move sets.
Standard Nim is a special case: Grundy(n) = n for full-pile removal. XOR of pile sizes is the simplified form.
Staircase Nim = XOR odd-indexed stairs — even stairs are mirrorable. Grundy(even) = 0, Grundy(odd) = stone count.
Misère Nim: Flip normal logic when all piles ≤ 1. Otherwise identical to normal play.
Poker Nim: Adding (up to k) can be reversed by the opponent. Initial pile XOR still determines the winner, unlike a separate pass-token game.
Nimble = Nim on squares: Coin on square i = Nim heap of size i. Pairs cancel (parity matters).
Industrial Nim: XOR ranges efficiently using xor0toN(n) = n if n%4=0, 1 if n%4=1, n+1 if n%4=2, 0 if n%4=3.
Time: O(n) or better — most advanced Nim solutions are linear or sub-linear with Grundy precomputation.
The hierarchy: Learn Grundy → Learn ALL impartial games. It's the ultimate game theory weapon 🏆
Note
🔮 What's Next? Now that you've mastered advanced Nim, continue to Grundy Numbers & Applications for deeper coverage of the Sprague–Grundy theorem and misère analysis for non-Nim games!