HardNo. 0810

Chalkboard XOR Game — LeetCode 810 Python Solution

Topics
Bit Manipulation, Brainteaser, Array, Math, Game Theory
Reading time
2 min

The problem

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.

Example

Input
nums = [1,1,2]
Output
false
Explanation
Alice has two choices: erase 1 or erase 2.

Python solution

PythonSolution
class Solution:
    def xorGame(self, nums: List[int]) -> bool:
        return len(nums) % 2 == 0 or reduce(xor, nums) == 0

Complexity

Time
O(n)where n is the length of the array nums
Space · auxiliary
O(1)

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 810. Chalkboard XOR Game is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Bit Manipulation.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 810. Chalkboard XOR Game?

LeetCode 810. Chalkboard XOR Game is rated Hard on LeetCode.

What is the time complexity of LeetCode 810. Chalkboard XOR Game?

The Python solution on this page runs in O(n), where n is the length of the array \textit{nums}.

What is the space complexity of LeetCode 810. Chalkboard XOR Game?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 810. Chalkboard XOR Game cover?

LeetCode 810. Chalkboard XOR Game is tagged Bit Manipulation, Brainteaser, Array, Math and Game Theory on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.