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
Game of Nim: Input → XOR → WinnerInput Piles135XOR Operation1 ⊕ 3 ⊕ 5= 7Winner7 ≠ 0Alice Wins!Nim TheoremFirst player wins iffXOR of all piles ≠ 0Time: O(n), Space: O(1)Output: true
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
Asked in
Google 12 Microsoft 8 Amazon 6
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen