Algorithms · Visualized
Game: Sprague–Grundy (Nim)
Game Theory & Minimax
Two-player games — who wins with perfect play, and by how much.
The Sprague–Grundy theorem reduces any impartial combinatorial game to an equivalent single Nim pile: every position gets a Grundy number — the mex (minimum excludant) of the Grundy numbers of all positions reachable in one move. Time: O(n·b) average, O(n·b) worst; space: O(n) — stored Grundy numbers.
Big-O: Winning positions, DP over states, and minimax evaluation.
Sprague-Grundy Theorem (Nim Generalization)
Game TheoryThe Sprague–Grundy theorem reduces any impartial combinatorial game to an equivalent single Nim pile: every position gets a Grundy number — the mex (minimum excludant) of the Grundy numbers of all positions reachable in one move. Combined games are then analyzed by XOR-ing the Grundy numbers of the independent sub-games, exactly like standard Nim.
How Sprague–Grundy (Nim) Works
- A terminal position (no moves available) gets Grundy number 0.
- For any other position, compute the Grundy numbers of every position reachable in one move.
- Take the mex — the smallest non-negative integer NOT in that set — as this position's Grundy number.
- For several independent games played simultaneously, XOR the Grundy numbers of the sub-games.
- The position is a loss for the player to move if and only if the combined XOR is 0.
Sprague–Grundy (Nim) Worked Example
Input: Three independent Nim piles of sizes 3, 4, 5 — is the first player winning?
In standard Nim a pile of size n has Grundy number n. Combined Grundy = 3 ⊕ 4 ⊕ 5: 3 (011) ⊕ 4 (100) = 7 (111), and 7 ⊕ 5 (101) = 2 (010). Since 2 ≠ 0, the position is a win for the player about to move — mirror the winning move to keep the XOR at 0.
def mex(values):
g = 0
while g in values:
g += 1
return g
def grundy(piles):
max_n = max(piles)
g = [0]
for n in range(1, max_n + 1):
reachable = [g[k] for k in range(n)]
g.append(mex(reachable))
xor_all = 0
for p in piles:
xor_all ^= g[p]
return xor_all # 0 → losing, non-zero → winningBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Sprague–Grundy (Nim) Time & Space Complexity
When to Use Sprague–Grundy (Nim)
- Analyzing combined/composite impartial games (Nim variants, Kayles, and friends).
- AI for turn-based impartial games.
- Competitive programming game-theory problems.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.