Game of Nim - Problem
Alice and Bob take turns playing a game with Alice starting first. In this game, there are n piles of stones. On each player's turn, the player should remove any positive number of stones from a non-empty pile of his or her choice.
The first player who cannot make a move loses, and the other player wins. Given an integer array piles, where piles[i] is the number of stones in the ith pile, return true if Alice wins, or false if Bob wins.
Both Alice and Bob play optimally.
Input & Output
Example 1 — Basic Nim Game
$
Input:
piles = [1,3,5]
›
Output:
true
💡 Note:
XOR of all piles: 1 ⊕ 3 ⊕ 5 = 7 ≠ 0, so Alice (first player) wins
Example 2 — Balanced Position
$
Input:
piles = [1,1]
›
Output:
false
💡 Note:
XOR of all piles: 1 ⊕ 1 = 0, so Bob (second player) wins
Example 3 — Single Pile
$
Input:
piles = [5]
›
Output:
true
💡 Note:
XOR = 5 ≠ 0, Alice can take all stones and wins
Constraints
- 1 ≤ piles.length ≤ 7
- 1 ≤ piles[i] ≤ 7
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of pile sizes [1,3,5]
2
Process
XOR all values: 1⊕3⊕5 = 7
3
Output
7 ≠ 0 → Alice wins → true
Key Takeaway
🎯 Key Insight: The XOR of all pile sizes instantly reveals the winner without simulating the game
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code