Nim Game

Easy

Topics
MathGame Theory

You are playing Nim: a heap of n stones, players alternate removing 1 to 3 stones, and whoever removes the last stone wins. You move first and both play optimally. Return true if you can win.

Example 1

stones1234
you lose with this many stones
Cells are possible pile sizes. You can take 1 to 3 stones, so from any pile that is not a multiple of 4 you can always leave a multiple of 4 behind — and your opponent is then in the losing position. So the answer is just n % 4 != 0: false for 4.
Shaded pile sizes are the losing positions for the player to move.
Input:  n = 4
Output: false

Example 2

stones1
So the answer is just n % 4 != 0: true for 1.
Input:  n = 1
Output: true

Example 3

stones1234567
you lose with this many stones
Input:  n = 7
Output: true

Constraints

  • 1 <= n <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls

Intuition

Each player removes 1, 2 or 3 stones and whoever takes the last stone wins. Work out the small cases and the pattern appears immediately:

n = 1, 2, 3   take them all, win
n = 4         any move leaves 3, 2 or 1 for the opponent, who then wins   LOSE
n = 5, 6, 7   leave exactly 4 for the opponent, who is now in the lost position
n = 8         every move leaves 5, 6 or 7, all winning for the opponent   LOSE

So the losing positions are the multiples of 4, and the reason is a strategy rather than a coincidence. If n % 4 != 0 you can always remove n % 4 stones, handing the opponent a multiple of 4. From a multiple of 4 every available move (1, 2 or 3) leaves a non-multiple, so the opponent can do the same thing back to you. The multiple-of-4 property is preserved by your moves and destroyed by theirs, which is exactly what a winning invariant looks like.

💡 This is the standard argument for impartial games: find the set of positions from which every move leads to a winning position for the opponent.

Approach

  1. Return n % 4 != 0.

Dry Run

n = 4   ->  4 % 4 == 0  ->  false (you lose)
n = 7   ->  7 % 4 == 3  ->  true; take 3, leaving 4
n = 1   ->  true; take it
n = 2^31 - 1 = 2147483647, which is 3 mod 4  ->  true

Complexity

  • Time — O(1): one modulo. A DP over positions would be O(n), and at n up to 2^31-1 that is not merely slower but infeasible — which is the point of finding the pattern.
  • Space — O(1).

Common Pitfalls

  • Writing the O(n) DP. It is correct and will not finish at these constraints.
  • Stating the rule without the strategy. The follow-up is always "why?", and the answer is that n % 4 is the move that restores the invariant.
  • Getting the direction backwards: a multiple of 4 is a loss for the player about to move.
  • Assuming both players play optimally needs stating — the result only holds if the opponent also plays well.

Full Solution — all languages

class Solution:
    def canWinNim(self, n):
        return n % 4 != 0
Asked at Adobe
SensAI
Beta
Tap the mic to stop voice mode