Skip to content
Problem 292 · LeetCode 292(opens in a new tab)

Nim Game

EasyGame theory

Two players share one heap of n stones. They take turns, and you move first. On a turn a player must take 1, 2 or 3 stones from the heap. Whoever takes the final stone wins the game.

Both of you play as well as possible. Return true if you are sure to win, and false otherwise.

Example 1

Input:  n = 8
Output: false
Why:    after any move, your friend can bring the heap to 4, then to 0
2 more examples and the constraints

Example 2

Input:  n = 6
Output: true
Why:    take 2, leaving 4; whatever your friend takes, you take the rest

Example 3

Input:  n = 3
Output: true
Why:    take all 3 stones at once

Constraints

  • 1 ≤ n ≤ 2,147,483,647 (2^31 − 1)

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Solve every smaller heapO(n)
  2. Multiples of 4 loseO(1)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 2^31 − 1Verdict
Solve every smaller heapO(n)
Finds the pattern; too slow
Multiples of 4 loseO(1)
Best; one remainder

n = stones in the heap.

Edge cases to test

  • One to three stones. You take them all at once and win.
  • Exactly 4 stones. Every move leaves 1 to 3 for your friend, who then takes the rest: false.
  • The largest n. 2,147,483,647 leaves remainder 3, so true. A loop up to n is far too slow here.
  • Large multiple of 4. 1,000,000 is a multiple of 4, so false.

Common mistakes

  • Writing plain recursion over all moves, which repeats work and blows the stack for large n.
  • Allocating a boolean array of size n, which runs out of memory near 2^31.
  • Flipping the answer: a multiple of 4 is the losing case, not the winning one.

How to talk through it

  1. 1Clarify. Does taking the last stone win? Must each player take at least one stone? Both play perfectly?
  2. 2Solve small heaps. Heaps 1 to 3 win, 4 loses, 5 to 7 win by leaving 4, and 8 loses again.
  3. 3State the rule. A multiple of 4 loses for the player to move; anything else wins by taking n % 4.
  4. 4Prove it. If they take k stones, you take 4 − k, so each round removes 4 and the multiple of 4 comes back.
  5. 5Test out loud. Check 1, 4, 5 and 8 against the table.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?