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 - Optimal Solution INPUT Stone Piles Visualization 1 Pile 0 3 Pile 1 5 Pile 2 piles = [1, 3, 5] n = 3 piles total ALGORITHM STEPS 1 Nim-Sum (XOR) XOR all pile values 2 Calculate XOR 1 XOR 3 XOR 5 3 Binary XOR 001 XOR 011 XOR 101 4 Check Result If XOR != 0, Alice wins XOR Calculation 1 = 001 (binary) 3 = 011 (binary) 5 = 101 (binary) XOR = 111 = 7 != 0 FINAL RESULT ALICE WINS! Nim-Sum = 7 Since 7 != 0 First player wins! Output: true Key Insight: In Nim, the first player wins if and only if the XOR (Nim-Sum) of all pile sizes is non-zero. This is because the player can always make a move to leave the opponent with XOR = 0 (losing position). Time Complexity: O(n) | Space Complexity: O(1) TutorialsPoint - Game of Nim | Optimal XOR Solution
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