Game of Nim - Problem
The Classic Game of Nim
Alice and Bob are playing the ancient mathematical game of Nim. The game starts with
On each turn, a player must:
โข Choose any non-empty pile
โข Remove any positive number of stones from that pile (from 1 stone up to all remaining stones)
The player who cannot make a move (because all piles are empty) loses the game. Both players play optimally, meaning they always make the best possible move.
Given an integer array
Alice and Bob are playing the ancient mathematical game of Nim. The game starts with
n piles of stones, where each pile contains a certain number of stones. Players take turns removing stones from the piles, with Alice going first.On each turn, a player must:
โข Choose any non-empty pile
โข Remove any positive number of stones from that pile (from 1 stone up to all remaining stones)
The player who cannot make a move (because all piles are empty) loses the game. Both players play optimally, meaning they always make the best possible move.
Given an integer array
piles where piles[i] represents the number of stones in the i-th pile, determine if Alice can guarantee a win. Return true if Alice has a winning strategy, false if Bob will win with optimal play. Input & Output
example_1.py โ Basic winning position
$
Input:
piles = [1, 3, 5, 4]
โบ
Output:
true
๐ก Note:
Alice can win. The nim-sum is 1โ3โ5โ4 = 7, which is non-zero. Alice can make a move to force Bob into a losing position (nim-sum = 0).
example_2.py โ Balanced losing position
$
Input:
piles = [2, 7, 5]
โบ
Output:
true
๐ก Note:
Alice wins because nim-sum = 2โ7โ5 = 0โ5 = 5 โ 0. Any non-zero nim-sum means the current player can force a win.
example_3.py โ Perfect losing position
$
Input:
piles = [3, 4, 7]
โบ
Output:
false
๐ก Note:
Alice loses because nim-sum = 3โ4โ7 = 7โ7 = 0. When nim-sum is 0, the current player is in a losing position with optimal play.
Visualization
Tap to expand
Understanding the Visualization
1
Binary Representation
Convert each pile size to binary and align them in columns
2
Column-wise XOR
XOR each binary column independently (even 1s become 0, odd 1s become 1)
3
Interpret Result
If result is all zeros, current player loses; otherwise they can win
4
Winning Strategy
From non-zero nim-sum, always exists a move to make nim-sum zero for opponent
Key Takeaway
๐ฏ Key Insight: XOR captures the 'balance' of the game - when balanced (XOR = 0), you lose; when unbalanced, you can always rebalance it in your favor!
Time & Space Complexity
Time Complexity
O(n)
Single pass through all piles to compute XOR
โ Linear Growth
Space Complexity
O(1)
Only using a single variable to store the nim-sum
โ Linear Space
Constraints
- 1 โค piles.length โค 7
- 1 โค piles[i] โค 7
- Both players play optimally
- Alice always goes first
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code