#292
Nim Game
EasyMathBrainteaserGame TheoryGame TheoryMathematical Patterns
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(1) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(1)Space O(1)
The optimal solution leverages the observation that if the number of stones is a multiple of 4, the first player cannot win if both play optimally. This is because any move will leave a non-multiple of 4 for the opponent, allowing them to eventually force a win.
⚙️
Algorithm
3 steps- 1Step 1: Check if n % 4 == 0.
- 2Step 2: If true, return false (the first player cannot win).
- 3Step 3: If false, return true (the first player can win).
solution.py2 lines
1def canWin(n):
2 return n % 4 != 0ℹ
Complexity note: The time complexity is O(1) because we are only performing a single modulus operation, and space complexity is also O(1) as we are using constant space.
- 1If the number of stones is a multiple of 4, the first player cannot win.
- 2The game can be reduced to a simple mathematical check rather than simulating all moves.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.