Find winner of the game when any set bit is removed in each move
Two players, Player 1 and Player 2, are given an integer N to play a game. The rules of the game are as follows :
- In one turn, a player can remove any set bit of N in its binary representation to make a new N.
- Player 1 always takes the first turn.
- If a player cannot make a move, he loses.
Input: N = 8
Explanation: N = 8
N = 1000 (binary)
Player 1 takes the bit.
The remaining bits are all zero.
Player 2 cannot make a move,
so Player 1 wins.
Input: N = 3
Approach: The given problem can be solved by following the below idea:
Calculate the number of set bits in N. If the number of set bits is odd then player 1 will always win [because he will take the following turns – 1st, 3rd, 5th, . . . and any odd turn]. Otherwise, player 2 will win the game.
Follow the steps mentioned below to implement the:
- Calculate the number of set bits in N.
- If the number of the set bits is odd then player 1 wins.
- Else, player 2 wins.
Below is the implementation of the above approach.
Time Complexity: O(log N)
Auxiliary Space: O(1)
Approach: Naive Recursion with memoization
- First, check if the solution for the given input N is already present in the memoization map.
- If it is present, then return the value of the solution from the map to avoid recalculation.
- If it is not present, use a loop to iterate through all the bits of N.
- Remove the set bit by using the XOR operation.
- Then recursively call the solve function for the new value of N.
- After the recursive call, we use the OR operation to set the bit back to the original value of N.
- Check if the returned solution from the recursive call is Player 2 losing or not. If it is Player 2 losing.
- update the memoization map with the solution and return Player 1 wins.
- If we have iterated through all the bits of N and Player 2 has not lost.
- update the memoization map with Player 2 winning and return Player 2 wins.
- Finally, print the result.
Below is the code implementation of the above approach:
Time Complexity: O(logN)
Auxiliary Space: O(N)
Please Login to comment...