Nim Game (LeetCode 292): Solution and Explanation

Easy
Math
Brainteaser
Game Theory

Two players take 1 to 3 stones from one heap, and whoever takes the last stone wins. You move first; decide whether you win with perfect play. The answer depends only on n mod 4.

Intuition

Game problems like this start with tiny cases. With 1, 2 or 3 stones you take them all and win. With 4 stones every move leaves 1, 2 or 3, and your friend takes the rest, so 4 is a loss for whoever has to move.

In general a heap is a win when some move leaves the opponent on a loss, and a loss when every move leaves the opponent on a win. Filling that table in for 0 to 12 gives lose, win, win, win, lose, win, win, win, lose, and so on: the losses are exactly the multiples of 4.

The reason is a pairing strategy. If the heap is a multiple of 4 and the opponent takes x stones, you take 4 - x, which puts the heap back on a multiple of 4. Eventually that multiple is 0 on their turn. If the heap is not a multiple of 4, you take n % 4 first and become the player using that strategy.

Approach: Remainder mod 4

  1. Note that the player facing a multiple of 4 always loses, since the other player can answer every take of x with 4 - x.
  2. Any other heap is a win, because taking n % 4 stones hands the opponent a multiple of 4.
  3. Return n % 4 != 0.

Step-by-step example

n = 4
  1. 0 stones on your turn means the opponent took the last one: loss.
  2. 1, 2 and 3 are wins, since you can take every stone.
  3. From 4 you can only reach 3, 2 or 1, all wins for your friend, so 4 is a loss.
  4. 4 % 4 = 0. Return false.

Code: Python, Java, C++

1class Solution:
2    def canWinNim(self, n: int) -> bool:
3        return n % 4 != 0
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Remainder mod 4 O(1)
Bottom-up win/lose table O(n)
Recursion with memoization O(n)
Time

O(1)

One modulo and one comparison.

Space

O(1)

No extra storage.

Other approaches

Bottom-up win/lose table (time O(n), space O(1) with a rolling window of three)

Set win[0] = false and win[k] = not win[k-1] or not win[k-2] or not win[k-3]. It is correct and is how you discover the pattern, but n can be about 2.1 billion, which is far too much time and memory.

Recursion with memoization (time O(n), space O(n))

Ask whether any move leads to a losing state for the opponent, caching results. Same table as above, with recursion depth n on top, so it overflows the stack for large inputs.

Common mistakes

  • Simulating the game or building the table for n up to 2^31 - 1. It times out or runs out of memory.
  • Writing n % 4 == 0 and returning it directly. That is the losing condition, so the answer is its negation.
  • Assuming the first player always wins because they move first. With 4, 8, 12 stones the second player wins.

Frequently asked questions

Why does taking 4 - x keep a multiple of 4?

If the heap is 4m and your opponent takes x, you take 4 - x, so the two moves remove exactly 4 together and the heap becomes 4(m - 1). Since x is 1 to 3, 4 - x is also a legal move.

What if players could take 1 to k stones?

The same argument works with k + 1 in place of 4. The first player loses exactly when n is a multiple of k + 1.

Is this the same as general Nim?

It is the single-heap subtraction game. Classic Nim with several heaps and any number of stones per move is solved with the XOR of heap sizes instead.