810. Chalkboard XOR Game LeetCode Solution
In this guide, you will get 810. Chalkboard XOR Game LeetCode Solution with the best time and space complexity. The solution to Chalkboard XOR Game problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Chalkboard XOR Game solution in C++
- Chalkboard XOR Game solution in Java
- Chalkboard XOR Game solution in Python
- Additional Resources
Problem Statement of Chalkboard XOR Game
You are given an array of integers nums 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.
Example 1:
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 become [1, 1]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose.
Example 2:
Input: nums = [0,1]
Output: true
Example 3:
Input: nums = [1,2,3]
Output: true
Constraints:
1 <= nums.length <= 1000
0 <= nums[i] < 216
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
810. Chalkboard XOR Game LeetCode Solution in C++
class Solution {
public:
bool xorGame(vector<int>& nums) {
const int xors = accumulate(nums.begin(), nums.end(), 0, bit_xor<int>());
return xors == 0 || nums.size() % 2 == 0;
}
};
/* code provided by PROGIEZ */
810. Chalkboard XOR Game LeetCode Solution in Java
class Solution {
public boolean xorGame(int[] nums) {
final int xors = Arrays.stream(nums).reduce((a, b) -> a ^ b).getAsInt();
return xors == 0 || nums.length % 2 == 0;
}
}
// code provided by PROGIEZ
810. Chalkboard XOR Game LeetCode Solution in Python
class Solution:
def xorGame(self, nums: list[int]) -> bool:
return functools.reduce(operator.xor, nums) == 0 or len(nums) % 2 == 0
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.