Nim Game - Problem
The Ultimate Nim Game Challenge!
Imagine you're sitting across from your friend with a pile of stones between you, about to engage in one of the oldest strategic games known to humanity - Nim! ๐ชจ
Here's how it works: You have a heap containing
Your Mission: Given the number of stones
Input: An integer
Output:
Example: If there are 4 stones, no matter what you do (take 1, 2, or 3), your opponent can always take the remaining stones and win!
Imagine you're sitting across from your friend with a pile of stones between you, about to engage in one of the oldest strategic games known to humanity - Nim! ๐ชจ
Here's how it works: You have a heap containing
n stones on the table. You and your friend take turns removing stones, and you go first. On each turn, a player must remove between 1 to 3 stones from the heap. The player who takes the last stone wins the game! ๐Your Mission: Given the number of stones
n, determine if you can guarantee a win assuming both players play optimally (meaning everyone makes the best possible move at each turn).Input: An integer
n representing the initial number of stonesOutput:
true if you can guarantee a win, false otherwiseExample: If there are 4 stones, no matter what you do (take 1, 2, or 3), your opponent can always take the remaining stones and win!
Input & Output
example_1.py โ Small winning position
$
Input:
n = 1
โบ
Output:
true
๐ก Note:
You can take 1 stone and win immediately since you took the last stone.
example_2.py โ Classic losing position
$
Input:
n = 4
โบ
Output:
false
๐ก Note:
No matter how many stones you take (1, 2, or 3), your opponent can take all remaining stones in their turn. Take 1โ3 left (opponent takes all), Take 2โ2 left (opponent takes all), Take 3โ1 left (opponent takes it).
example_3.py โ Force opponent into losing position
$
Input:
n = 5
โบ
Output:
true
๐ก Note:
You can take 1 stone, leaving 4 stones. Now your opponent is in a losing position (multiple of 4), and no matter what they do, you can win.
Visualization
Tap to expand
Understanding the Visualization
1
Pattern Discovery
Test small values to discover the losing pattern
2
Strategic Analysis
Understand why multiples of 4 are trapped positions
3
Optimal Strategy
Always leave your opponent with a multiple of 4 stones
Key Takeaway
๐ฏ Key Insight: Positions where n % 4 = 0 are losing positions because any move you make can be countered to maintain the opponent's advantage. The game becomes a race to force your opponent into these 'trap' positions!
Time & Space Complexity
Time Complexity
O(1)
Single modulo operation
โ Linear Growth
Space Complexity
O(1)
Only uses a constant amount of extra space
โ Linear Space
Constraints
- 1 โค n โค 231 - 1
- Both players play optimally
- You always go first
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code