Number of coins to be removed for the first player to win the Game
Two friends, A, and B are playing a game. In this game, a group of N coins is placed. The players can pick any number of coins between 1 and 4 (both inclusive) in their chance. The player who takes the last coin wins the game. If A starts first, find out how many coins should he pick such that he is guaranteed to win the game or determine if it’s impossible for him to win?
Note: Consider both A and B to play the game optimally.
Input: N = 18
Explanation: Player A is guaranteed a win if he picks 3 coins first.
Input: N = 10
Explanation: Player A is guaranteed to lose no matter how many matches he picks at first.
Approach: This problem can be solved by observing the fact that the sum of two numbers can always be made 5.
Considering all cases possible:
- If one selects 1 coin then the second can take 4 to make the sum of 5.
- If one selects 2 coins then the second can take 3 to make the sum of 5.
- If one selects 3 coins then the second can take 2 to make the sum of 5.
- If one selects 4 coins then the second can take 1 to make the sum of 5.
So in all cases, the second player can make a sum of 5. Hence if Player “A” can make the total number of coins left a multiple of 5 after the first turn then in each even number of turns after that, player “A” can make that sum a multiple of (as whatever B picks the player A will be able to make the sum as 5 and hence can make any multiple of 5). And hence be available to win the game.
Follow the steps to solve the problem:
- In order to make the coins left a multiple of 5, player A has to select N % 5 coins.
- And if N%5 = 0 then he cannot make a sum of 5 as he can take from 1 to 4 coins only.
- So he will be guaranteed to lose the game.
- Hence if N % 5 = 0 then he will lose the game and if it is non 0 then player A will choose N % 5 and be guaranteed to win the game.
Below is the implementation of the above approach.
Player A should pick 3 coins Player A will lose Player A should pick 3 coins
Time Complexity: O(1)
Auxiliary Space: O(1)
Please Login to comment...