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: true
💡 Note: XOR = 1⊕2⊕3 = 0. Since XOR equals 0 at the start of Alice's turn, Alice wins immediately.
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 INPUT nums array: 1 idx 0 1 idx 1 2 idx 2 Binary Values: 01 01 10 Total XOR: 1 XOR 1 XOR 2 = 0 XOR 2 = 2 XOR = 2 n = 3 (odd count) Alice starts first ALGORITHM STEPS 1 Check Initial XOR If XOR==0, Alice wins XOR=2 (not 0) 2 Count Elements n = 3 elements 3 is ODD 3 Apply Win Rule Alice wins if: XOR==0 OR n is EVEN 4 Evaluate XOR != 0 AND n is ODD Alice loses! Decision Logic: if XOR == 0: return true if n % 2 == 0: return true else: return false FINAL RESULT Game Analysis: Alice's Turn (First) Remove 1: XOR = 1^2 = 3 Remove 1: XOR = 1^2 = 3 Remove 2: XOR = 1^1 = 0 (Alice loses immediately!) Bob's Strategy With odd elements and XOR != 0, Bob can force win Output: false Bob wins optimally Key Insight: Alice wins if XOR of all elements is 0 (immediate win) OR if the count of elements is EVEN. With EVEN elements and non-zero XOR, Alice can always find a safe move. With ODD elements and non-zero XOR, Bob can mirror Alice's strategy and eventually force Alice into a losing position. TutorialsPoint - Chalkboard XOR Game | Optimal Solution
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