VOOZH about

URL: https://www.geeksforgeeks.org/dsa/game-replacing-array-elements/

⇱ Game of replacing array elements - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Game of replacing array elements

Last Updated : 3 Oct, 2022

There are two players A and B who are interested in playing a game of numbers. In each move a player pick two distinct number, let's say a1 and a2 and then replace all a2 by a1 or a1 by a2. They stop playing game if any one of them is unable to pick two number and the player who is unable to pick two distinct number in an array, loses the game. First player always move first and then second. Task is to find which player wins. 

Examples: 

Input:  arr[] = { 1, 3, 3, 2, 2, 1 }
Output: Player 2 wins
Explanation:
First plays always loses irrespective of the numbers chosen by him. For example,
say first player picks ( 1 & 3) replace all 3 by 1  
Now array Become { 1, 1, 1, 2, 2, 1 }
Then second player picks ( 1 & 2 )
either he replace 1 by 2 or 2 by 1 
Array Become { 1, 1, 1, 1, 1, 1 }
Now first player is not able to choose.

Input: arr[] = { 1, 2, 1, 2 }
Output: Player 1 wins

From above examples, we can observe that if number of count of distinct element is even, first player always wins. Else second player wins.

Lets take an another example : 

 int arr[] = 1, 2, 3, 4, 5, 6 

Here number of distinct element is even(n). If player 1 pick any two number lets say (4, 1), then we left with n-1 distinct element. So player second left with n-1 distinct element. This process go on until distinct element become 1. Here n = 6  

Player : P1 p2 P1 p2 P1 P2 
distinct : [n, n-1, n-2, n-3, n-4, n-5 ] 
 
"At this point no distinct element left, 
so p2 is unable to pick two Dis element."

Below implementation of the above idea : 


Output
Player 1 Wins

Time Complexity: O(n)

Auxiliary Space: O(n)

Comment
Article Tags: