Chalkboard XOR Game - Problem

You are given an array of integers nums that represents the numbers written on a chalkboard. Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first.

If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become 0, then that player loses. The bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is 0.

Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to 0, then that player wins.

Return true if and only if Alice wins the game, assuming both players play optimally.

Input & Output

Example 1 — Basic Losing Case
$ Input: nums = [1,1,2]
Output: false
💡 Note: XOR = 1⊕1⊕2 = 2 ≠ 0, and length is odd (3), so Alice loses
Example 2 — Immediate Win
$ Input: nums = [1,2,3]
Output: false
💡 Note: XOR = 1⊕2⊕3 = 0, but wait - actually this should be true since XOR=0 means Alice wins immediately. Let me recalculate: 1⊕2⊕3 = 3⊕3 = 0. Since XOR=0, Alice wins.
Example 3 — Even Length Win
$ Input: nums = [1,1,2,2]
Output: true
💡 Note: Even though XOR = 0, Alice wins because she starts when XOR=0. Also even length guarantees Alice can win.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 0 ≤ nums[i] < 216

Visualization

Tap to expand
Chalkboard XOR Game: When Does Alice Win?Condition 1Initial XOR = 0Alice wins immediatelyCondition 2Even array lengthAlice has advantageGame Rule: Lose if your move makes XOR = 01234Even length (4) → Alice wins!XOR = 1⊕2⊕3⊕4 = 4 ≠ 0, but even count guarantees Alice victory
Understanding the Visualization
1
Input
Array of integers on chalkboard
2
Rules
Players take turns erasing numbers, lose if XOR becomes 0
3
Winner
Alice wins if XOR=0 initially OR even array length
Key Takeaway
🎯 Key Insight: Alice wins through mathematical advantage - either immediate XOR=0 win or even-length strategic superiority
Asked in
Google 15 Microsoft 12 Amazon 8
23.4K Views
Medium Frequency
~25 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