Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

Combinatorial Games & Sprague–Grundy

Winning positions, nim-sums and Grundy numbers.

Three heaps hold 7, 10 and 12 stones. A move takes any number of stones from one heap, and whoever takes the last stone wins. Should you move first, and how? Write the heap sizes in binary and XOR them: 7⊕10⊕12=17 \oplus 10 \oplus 12 = 1, which is not 0, so the first player wins, and the one winning move takes a single stone from the 7. This lesson proves why, and shows that every game of this kind is secretly a single Nim heap.

What you’ll learn

  • Define impartial games under normal play and their P- and N-positions, and explain why one bit per position does not suffice to analyze sums of games.
  • Prove Bouton's theorem for Nim, and compute a winning move from the nim-sum.
  • Define Grundy numbers by the mex rule, prove the Sprague–Grundy theorem for sums of games, and compute Grundy values by DP.
  • Prove that every finite subtraction game is eventually periodic, and state what is known and open about octal games, misère and partizan play, and the complexity of games.

Impartial games and P-positions

As the Optimized lesson proved by induction on the DAG, the positions split uniquely into the two kinds:

  • a position is P iff every option (position reachable in one move) is N, which holds vacuously for a terminal position;
  • a position is N iff some option is P.

Games often fall apart into independent pieces: several heaps, several rows of pins, several regions of a board. In the sum G+HG + H, a move is a move in exactly one component, and the player who cannot move in any component loses. The positions of a sum are tuples of component positions, so kk heaps of up to nn stones give (n+1)k(n+1)^k positions: a DP over the sum itself explodes.

Think first Can you decide a sum from the P/N labels of its components alone? Try two Nim heaps: heaps of 1 and 1, and heaps of 1 and 2.

No. Every nonempty Nim heap is an N-position, yet 1+11 + 1 is P (whatever you take, your opponent takes the other heap), while 1+21 + 2 is N (reduce the 2 to a 1 and you have handed over 1+11 + 1). Two N-components can make either kind of sum, so each component needs more than one bit of information. Equal heaps are always P: the second player copies every move on the other heap.

Nim and Bouton’s theorem

DerivationProof
  1. 0⊕0⊕⋯⊕0=00 \oplus 0 \oplus \cdots \oplus 0 = 0

    The terminal position has nim-sum 0. All heaps are empty.

  2. 0⊕xi⊕xi′≠00 \oplus x_i \oplus x_i' \ne 0

    From nim-sum 0, every move leads to a nonzero nim-sum. A move changes exactly one heap, from xix_i to some xi′≠xix_i' \ne x_i, and the new nim-sum is

  3. xi⊕s<xi,s⊕xi⊕(xi⊕s)=0x_i \oplus s < x_i, \qquad s \oplus x_i \oplus (x_i \oplus s) = 0

    From nim-sum s≠0s \ne 0, some move reaches nim-sum 0. Let jj be the highest set bit of ss. An odd number of heaps have bit jj set, so some xix_i does; then xi⊕sx_i \oplus s clears bit jj of xix_i and leaves the higher bits alone, so it is smaller than xix_i and is a legal move:

  4. P-positions={(x1,…,xk):x1⊕⋯⊕xk=0}\text{P-positions} = \{(x_1, \dots, x_k) : x_1 \oplus \cdots \oplus x_k = 0\}

    So the positions with nim-sum 0 satisfy the P-rule (every option is outside the set) and the others satisfy the N-rule (some option is inside it). The labeling is unique, by induction on the DAG, so these are exactly the P-positions.

Check your understanding

Nim with heaps 3, 5 and 6, and it is your move. What happens with best play?

  1. You win by taking 1 stone from the heap of 6
  2. You win by emptying the heap of 3
  3. You lose: every move you make leaves a nonzero nim-sum for your opponent
  4. You win, because the heaps have different sizes
Show the answer

C. You lose: every move you make leaves a nonzero nim-sum for your opponent

3⊕5=63 \oplus 5 = 6 and 6⊕6=06 \oplus 6 = 0: a P-position, a loss for the player to move. Whatever you do, your opponent restores nim-sum 0, and eventually you face three empty heaps.

Misère Nim, where taking the last stone loses, needs only one change: play the normal strategy until your move would leave no heap larger than 1, and then leave an odd number of heaps of size 1 instead of an even one. Misère play of general games is far harder, as the last step shows.

Grundy numbers and the Sprague–Grundy theorem

DerivationProof, by induction over the positions of the sum
  1. g(G′+H)=g(G′)⊕g(H),g(G+H′)=g(G)⊕g(H′)g(G' + H) = g(G') \oplus g(H), \qquad g(G + H') = g(G) \oplus g(H')

    The options of G+HG + H are the G′+HG' + H and the G+H′G + H'. By induction they satisfy the formula; let x=g(G)⊕g(H)x = g(G) \oplus g(H). It suffices to show that the options' values include every y<xy < x but not xx itself.

  2. g(G′)≠g(G)  ⟹  g(G′)⊕g(H)≠xg(G') \ne g(G) \;\Longrightarrow\; g(G') \oplus g(H) \ne x

    No option has value xx. By the mex rule no option G′G' has g(G′)=g(G)g(G') = g(G), so g(G′)⊕g(H)≠g(G)⊕g(H)g(G') \oplus g(H) \ne g(G) \oplus g(H); the same holds for the options H′H'.

  3. g(G′+H)=(g(G)⊕d)⊕g(H)=x⊕d=yg(G' + H) = \big(g(G) \oplus d\big) \oplus g(H) = x \oplus d = y

    Every y<xy < x is an option's value. Let d=x⊕yd = x \oplus y and let jj be its highest set bit. Since y<xy < x, bit jj of xx is 1, so it is 1 in g(G)g(G) or in g(H)g(H); say in g(G)g(G). Then g(G)⊕d<g(G)g(G) \oplus d < g(G), so by the mex rule some option G′G' has exactly that value:

  4. g(G+X)=g(G)⊕g(X)=g(∗g(G)+X)g(G + X) = g(G) \oplus g(X) = g\big(*g(G) + X\big)

    Hence g(G+H)=xg(G + H) = x. Since a Nim heap of size g(G)g(G) has Grundy number g(G)g(G) too, G+XG + X and ∗g(G)+X*g(G) + X have the same Grundy number for every XX, so they are P-positions together, which is the sense in which GG "is" a Nim heap.

python
def grundy_subtraction(S, n):          # Grundy values of one pile; a move removes s in S stones
    g = [0] * (n + 1)
    for k in range(1, n + 1):
        options = {g[k - s] for s in S if s <= k}
        m = 0
        while m in options:            # mex: the smallest value no option has
            m += 1
        g[k] = m
    return g

O(n ∣S∣)O(n\,\abs{S}) time. For S={1,3,4}S = \{1, 3, 4\} the values are 0,1,0,1,2,3,20, 1, 0, 1, 2, 3, 2, repeating with period 7, so the zeros are at n mod 7∈{0,2}n \bmod 7 \in \{0, 2\}: the losing positions of the Optimized lesson. A game of many piles is decided by XORing one table lookup per pile, instead of a DP over the product of the piles.

Check your understanding

Three piles hold 5, 9 and 12 stones, and a move removes 1, 3 or 4 stones from one pile. Who wins with best play?

  1. The player to move, by taking 4 from the pile of 12
  2. The player to move, because 5+9+125 + 9 + 12 is even
  3. The player to move, because every single pile is a winning position
  4. The other player: the position is a P-position
Show the answer

D. The other player: the position is a P-position

The Grundy values are g(5)=3g(5) = 3, g(9)=g(2)=0g(9) = g(2) = 0 and g(12)=g(5)=3g(12) = g(5) = 3, and 3⊕0⊕3=03 \oplus 0 \oplus 3 = 0. Every move changes one pile's value and makes the XOR nonzero, and the opponent can always restore 0.

Periodicity, octal games and the limits of the theory

Games in which a move may also split a heap are harder. In Kayles, a move knocks down one pin or two adjacent pins from a row, which may break the row in two; a row of nn pins is a heap, and a broken row is a sum. Its Grundy numbers come from the same DP, with an XOR inside the mex: g(n)=mex⁡{g(a)⊕g(b):a+b∈{n−1,n−2}}g(n) = \operatorname{mex}\{g(a) \oplus g(b) : a + b \in \{n-1, n-2\}\}. Guy and Smith (1956) introduced this family of octal games together with a periodicity test: if g(n+p)=g(n)g(n + p) = g(n) holds for every nn from n0n_0 up to about 2n0+p2n_0 + p (plus the largest number of pins a move removes), then it holds for every n≥n0n \ge n_0. A finite computation can therefore prove periodicity forever.

GameA moveGrundy values from n=0n = 0Behavior
Nim heapremove any number of stones0,1,2,3,…0, 1, 2, 3, \dotsg(n)=ng(n) = n
Subtraction {1,3,4}\{1, 3, 4\}remove 1, 3 or 4 stones0,1,0,1,2,3,2,…0, 1, 0, 1, 2, 3, 2, \dotsperiod 7 from the start
Kaylesremove 1 or 2 adjacent pins; the row may split0,1,2,3,1,4,3,2,1,4,2,6,…0, 1, 2, 3, 1, 4, 3, 2, 1, 4, 2, 6, \dotsperiod 12 from n=71n = 71 on
Dawson's Kaylesremove 2 adjacent pins; the row may split0,0,1,1,2,0,3,1,1,0,3,3,…0, 0, 1, 1, 2, 0, 3, 1, 1, 0, 3, 3, \dotsperiod 34 from n=53n = 53 on
Grundy's gamesplit a heap into two unequal heaps0,0,0,1,0,2,1,0,2,1,0,2,…0, 0, 0, 1, 0, 2, 1, 0, 2, 1, 0, 2, \dotsperiodicity unknown
Computed with the mex DP for heaps up to 2000; for Kayles and Dawson's Kayles the periodicity test turns the computation into a proof. Kayles's values never exceed 8 and Dawson's Kayles's never exceed 9.

Complexity. A Grundy DP is polynomial in the number of positions, which is usually exponential in the size of the game's description. For succinctly described games the question is genuinely hard: deciding who wins generalized geography, or Kayles played on an arbitrary graph, is PSPACE-complete (Schaefer, 1978), and generalized chess is EXPTIME-complete (Fraenkel & Lichtenstein, 1981). Still, backward induction at enormous scale has solved real games: checkers is a draw with perfect play (Schaeffer et al., 2007).

Partizan games. When the players have different moves, as in chess or in Hackenbush with colored edges, one Nim heap per component is no longer enough. Conway's theory (On Numbers and Games, 1976; Winning Ways, with Berlekamp and Guy, 1982) gives every short game a value in an ordered group in which sums of games add; the values include the surreal numbers, named by Knuth (1974), and impartial games are the special case whose values are the nimbers ∗n*n.

Misère play. If the last player to move loses, sums no longer reduce to XOR. Plambeck and Siegel (2008) introduced misère quotients, finite algebraic structures that capture a misère game's behavior in sums, and used them to solve many octal games under misère play.

Key takeaways

  • An impartial position is P iff every option is N; for sums of games one bit per component is not enough.
  • Bouton: a Nim position is P iff the XOR of the heap sizes is 0, and a winning move replaces a heap holding the top bit of the nim-sum ss by its XOR with ss.
  • The Grundy number g(G)=mex⁡{g(G′)}g(G) = \operatorname{mex}\{g(G')\} is computed by a DP over positions, and by the Sprague–Grundy theorem g(G+H)=g(G)⊕g(H)g(G + H) = g(G) \oplus g(H): every impartial game acts like a Nim heap of size g(G)g(G).
  • Finite subtraction games are eventually periodic by a pigeonhole argument; games that split heaps, such as Kayles, are often periodic too, but whether every octal game is remains open.
  • Succinct games can be PSPACE- or EXPTIME-complete, and misère and partizan play need richer theories than XOR.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Which Nim position is a loss for the player to move?

  1. Heaps 1, 2, 4
  2. Heaps 2, 2, 1
  3. Heaps 1, 2, 3
  4. Heaps 3, 3, 3
Show the answer

C. Heaps 1, 2, 3

1⊕2⊕3=01 \oplus 2 \oplus 3 = 0, so it is a P-position. The others have nim-sums 77, 11 and 33, all nonzero.

Question 2

A position's options have Grundy numbers 0,1,3,40, 1, 3, 4 and 44. What is its Grundy number?

  1. 5
  2. 0
  3. 2
  4. 4
Show the answer

C. 2

The mex of {0,1,3,4}\{0, 1, 3, 4\} is 2, the smallest value that no option has. So the position is an N-position (its value is nonzero), and in a sum it acts like a Nim heap of size 2.

Question 3

A position is the sum of three independent games whose Grundy numbers are 4, 6 and 2. Who wins with best play?

  1. The player to move, because every component has a nonzero value
  2. The other player: 4⊕6⊕2=04 \oplus 6 \oplus 2 = 0
  3. The player to move, because 4+6+2=12≠04 + 6 + 2 = 12 \ne 0
  4. It cannot be decided from the Grundy numbers alone
Show the answer

B. The other player: 4⊕6⊕2=04 \oplus 6 \oplus 2 = 0

By the Sprague–Grundy theorem the sum has Grundy number 4⊕6⊕2=04 \oplus 6 \oplus 2 = 0, so it is a P-position: the player to move loses, whatever the three games are.

Question 4

Why must the Grundy sequence of every subtraction game with a finite move set SS be eventually periodic?

  1. Because Grundy numbers are always 0 or 1
  2. Because g(n)=n mod (max⁡S+1)g(n) = n \bmod (\max S + 1) for every finite SS
  3. Because the values are bounded by ∣S∣\abs{S} and each depends only on the previous max⁡S\max S values, so a window must repeat
  4. It need not be: Grundy's game is a finite subtraction game with no known period
Show the answer

C. Because the values are bounded by ∣S∣\abs{S} and each depends only on the previous max⁡S\max S values, so a window must repeat

Finitely many possible windows of max⁡S\max S consecutive bounded values means some window repeats (pigeonhole), and since the next value is a function of the window, everything after the repetition repeats too.

Further reading

  • C. L. Bouton, "Nim, a game with a complete mathematical theory," Annals of Mathematics 3 (1901–1902), 35–39.
  • R. Sprague, "Über mathematische Kampfspiele," Tôhoku Mathematical Journal 41 (1935); P. M. Grundy, "Mathematics and games," Eureka 2 (1939).
  • R. K. Guy & C. A. B. Smith, "The G-values of various games," Proceedings of the Cambridge Philosophical Society 52 (1956).
  • E. R. Berlekamp, J. H. Conway & R. K. Guy, Winning Ways for your Mathematical Plays (Academic Press, 1982; 2nd ed., A K Peters, 2001–2004).
  • A. N. Siegel, Combinatorial Game Theory (American Mathematical Society, 2013).