## Similar Problems

Similar Problems not available

# Chalkboard Xor Game - Leetcode Solution

## Companies:

LeetCode: Chalkboard Xor Game Leetcode Solution

Difficulty: Hard

Topics: math bit-manipulation array

Introduction

In this problem, we have a game that is played on a chalkboard. Initially, the board contains an integer N. On each player's turn, they choose a number x from [1, N-1] and replace N with N xor x. The game continues until player 1 cannot make a move, i.e. there is no x in [1, N-1] that satisfies N xor x < N. The player who cannot make a move loses the game. We need to determine whether the first player to play can win the game or not.

Approach

We can solve this problem by observing some properties of the game. Firstly, we observe that if N is even, player 1 can always win the game. This is because if N is even, it can always be written as 2k for some integer k. In this case, player 1 can choose x as k, and N will be replaced by k xor (2k) = k^2 which is even.

Secondly, we observe that if N is odd, player 1 can only win the game if there are an odd number of odd integers in the range [1, N-1]. This is because if there are an odd number of odd integers, player 1 can always choose an odd integer x, and N will be replaced by N xor x, which is even. Then player 2 will have an even number, say e, to work with. In this case, player 2 can only choose an odd number, since e is even. This will give player 1 an odd number to work with, and the process continues until there are no odd integers left to choose.

However, if there are an even number of odd integers, player 2 can always respond with an even number, and player 1 will be stuck with an odd number. Therefore, in this case, player 2 wins.

Solution

We can implement the above approach in the following way:

- If N is even, return true, since player 1 can always win.
- Otherwise, count the number of odd integers in the range [1, N-1]. If this count is odd, return true, since player 1 can win, otherwise, return false, since player 2 can win.

We can count the number of odd integers in the range [1, N-1] by dividing N-1 by 2, since there are N-1 integers in the range [1, N-1], and every other one is odd. We can use the modulo operator to determine if N-1 is odd or even.

Here is the Python code for the above solution:

class Solution: def xorGame(self, nums: List[int]) -> bool: n = len(nums) xor_sum = 0 for i in nums: xor_sum ^= i return xor_sum == 0 or n % 2 == 0

## Chalkboard Xor Game Solution Code

`1`