Chalkboard XOR Game - Problem
The Chalkboard XOR Game is a strategic two-player game where Alice and Bob take turns erasing numbers from a chalkboard.

Here's how it works:
• You're given an array nums representing numbers written on a chalkboard
Alice starts first, then players alternate turns
• Each turn, a player must erase exactly one number
• If erasing a number causes the XOR of all remaining numbers to become 0, that player loses
• If a player starts their turn with the XOR already equal to 0, they win immediately

Goal: Determine if Alice wins assuming both players play optimally.

XOR Rules:
• XOR of one element = that element itself
• XOR of no elements = 0
• XOR is associative and commutative

Input & Output

example_1.py — Basic Winning Case
$ Input: [1, 1, 2]
Output: false
💡 Note: Initial XOR = 1⊕1⊕2 = 2 (not 0). Array length = 3 (odd). Since XOR≠0 and length is odd, Bob wins. Alice cannot force a winning position.
example_2.py — Even Length Case
$ Input: [1, 1, 2, 2]
Output: true
💡 Note: Initial XOR = 1⊕1⊕2⊕2 = 0. Alice wins immediately because the XOR is already 0 at the start of her turn.
example_3.py — Strategic Even Case
$ Input: [1, 2, 3]
Output: false
💡 Note: Initial XOR = 1⊕2⊕3 = 0. Alice wins immediately! Even though length is odd, the initial XOR being 0 gives Alice an instant victory.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 0 ≤ nums[i] < 216
  • Both players play optimally

Visualization

Tap to expand
Chalkboard XOR Game StrategyAlice Wins If:XOR = 0 (Immediate Win)OR Array Length is EvenEven Length Example[2, 4, 6, 8] length = 4XOR = 2⊕4⊕6⊕8 = 12 ≠ 0Even length → Alice Wins!Alice controls game parityOdd Length Example[1, 3, 5] length = 3XOR = 1⊕3⊕5 = 7 ≠ 0Odd length → Bob Wins!Bob can force Alice into XOR=0Game Theory InsightPlayers alternate moves, Alice starts firstEven arrays: Alice has last non-losing moveMathematical Solutionreturn (XOR == 0) || (length % 2 == 0)
Understanding the Visualization
1
Initial Check
If XOR of all numbers equals 0, Alice wins immediately
2
Parity Analysis
Even length arrays favor Alice, odd length favor Bob
3
Strategic Moves
Alice can mirror Bob's strategy when she has the advantage
4
Optimal Play
Both players play to avoid making XOR=0 on their turn
Key Takeaway
🎯 Key Insight: This problem reduces to pure mathematics - no need to simulate the game! Alice's winning conditions are determined by initial XOR value and array length parity.
Asked in
Google 35 Microsoft 28 Apple 22 Amazon 18
24.7K Views
Medium Frequency
~15 min Avg. Time
892 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