Nim Game
Easy
Topics
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
n % 4 != 0: false for 4.Input: n = 4 Output: false
Example 2
n % 4 != 0: true for 1.Input: n = 1 Output: true
Example 3
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 LOSESo 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
- 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 -> trueComplexity
- Time — O(1): one modulo. A DP over positions would be O(n), and at
nup 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 % 4is 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 != 0import java.util.*;
class Solution {
public boolean canWinNim(int n) {
return n % 4 != 0;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool canWinNim(int n) {
return n % 4 != 0;
}
};/**
* @param {number} n
* @return {boolean}
*/ var canWinNim = function(n) {
return n % 4 !== 0;
};