Chalkboard XOR Game

hard math xor game-theory

Problem

Players take turns erasing one number from the chalkboard. If erasing a number makes the XOR of remaining numbers 0, the erasing player loses. Initial XOR 0 means Alice wins. Determine if Alice (first) wins assuming optimal play.

Inputnums = [1,1,2]
Outputfalse
Any move Alice makes leaves a losing position.

from functools import reduce
from operator import xor

def xorGame(nums):
    return reduce(xor, nums) == 0 or len(nums) % 2 == 0
var xorGame = function(nums) {
    let x = 0;
    for (const v of nums) x ^= v;
    return x === 0 || nums.length % 2 === 0;
};
class Solution {
    public boolean xorGame(int[] nums) {
        int x = 0;
        for (int v : nums) x ^= v;
        return x == 0 || nums.length % 2 == 0;
    }
}
class Solution {
public:
    bool xorGame(vector<int>& nums) {
        int x = 0;
        for (int v : nums) x ^= v;
        return x == 0 || nums.size() % 2 == 0;
    }
};
Time: O(n) Space: O(1)