Weekly Contest 78-------->810. Chalkboard XOR Game
We are given non-negative integers nums[i] which are 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. (Also, we'll say 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.
Example: Input: nums = [1, 1, 2] Output: false Explanation: Alice has two choices: erase 1 or erase 2. If she erases 1, the nums array becomes [1, 2]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose. If Alice erases 2 first, now nums becomes [1, 1]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose.
Notes:
1 <= N <= 1000
.0 <= nums[i] <= 2^16
.
Approach #1: C++.
class Solution { public: bool xorGame(vector<int>& nums) { int num = 0; for (int i : nums) num ^= i; return num == 0 || nums.size() % 2 == 0; } };
Approach #2: Java.
class Solution { public boolean xorGame(int[] nums) { int xo = 0; for (int i : nums) xo ^= i; return xo == 0 || nums.length % 2 == 0; } }
Approach #3: Python.
class Solution(object): def xorGame(self, nums): """ :type nums: List[int] :rtype: bool """ xo = 0 for i in nums: xo ^= i return xo == 0 or len(nums) % 2 == 0
Analysis:
Math:
Corner Case: If the XOR of all nums is 0, then A wins.
Now we discuss the more general case where the input doesn't from the corner case.
Proposition: Suppose the current chalkboard is S and the len(S) = N, now it's player P's turn. P can
always make a move if XOR(S) != 0 and N is even.
Proof:
- Let X = XOR(S), when X != 0, at least one bit of X must be 1. Let bit 'b' of X be the bit ie., X[b] = 1.
- Then we can divide the numbers in S into two groups: U and V, where numbers in U have 0 at bit b, and numbers in V have 1 at bit b.
- Initially, len(U) could be even or odd, But len(V) must be odd, otherwise we wouldn't have X[b] = 1, So len(U) must be odd too because of the following:
- len(V) + len(U) = N
- len(V) is odd
- N is even
- The fact len(U) is odd implies that there must be at least one number (say Y) in S which has Y[b] = 0.
- If player P removes the number Y from S, the result chalkboard S' will have X' = XOR(S') = X xor Y, where X'[b] = 1. So S' != 0.
The explanation come from https://leetcode.com/problems/chalkboard-xor-game/discuss/165396/Detailed-math-explanation-Easy-to-understand