Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Find the winner of the Game of removing odd or replacing even array elements
Next article icon

Game of replacing array elements

Last Updated : 03 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 : 

C++




// CPP program for Game of Replacement
#include <bits/stdc++.h>
using namespace std;
 
// Function return which player win the game
int playGame(int arr[], int n)
{
    // Create hash that will stores
    // all distinct element
    unordered_set<int> hash;
 
    // Traverse an array element
    for (int i = 0; i < n; i++)
        hash.insert(arr[i]);
 
    return (hash.size() % 2 == 0 ? 1 : 2);
}
 
// Driver Function
int main()
{
    int arr[] = { 1, 1, 2, 2, 2, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << "Player " << playGame(arr, n) << " Wins" << endl;
    return 0;
}
 
 

Java




// Java program for Game of Replacement
import java.util.HashSet;
public class GameOfReplacingArrayElements
{
    // Function return which player win the game
    public static int playGame(int arr[])
    {
        // Create hash that will stores
        // all distinct element
        HashSet<Integer> set=new HashSet<>();
 
        // Traverse an array element
        for(int i:arr)
            set.add(i);
        return (set.size()%2==0)?1:2;
    }
 
    public static void main(String args[]) {
        int arr[] = { 1, 1, 2, 2, 2, 2 };
        System.out.print("Player "+playGame(arr)+" wins");
    }
}
//This code is contributed by Gaurav Tiwari
 
 

Python3




# Python program for Game of Replacement
 
# Function return which player win the game
def playGame(arr, n):
 
    # Create hash that will stores
    # all distinct element
    s = set()
 
    # Traverse an array element
    for i in range(n):
        s.add(arr[i])
    return 1 if len(s) % 2 == 0 else 2
 
# Driver code
arr = [1, 1, 2, 2, 2, 2]
n = len(arr)
print("Player",playGame(arr, n),"Wins")
 
# This code is contributed by Shrikant13
 
 

C#




// C# program for Game of Replacement
using System;
using System.Collections.Generic;
 
public class GameOfReplacingArrayElements
{
    // Function return which player win the game
    public static int playGame(int []arr)
    {
        // Create hash that will stores
        // all distinct element
        HashSet<int> set = new HashSet<int>();
 
        // Traverse an array element
        foreach(int i in arr)
            set.Add(i);
        return (set.Count % 2 == 0) ? 1 : 2;
    }
 
    // Driver code
    public static void Main(String []args)
    {
        int []arr = { 1, 1, 2, 2, 2, 2 };
        Console.Write("Player " + playGame(arr) + " wins");
    }
}
 
// This code has been contributed by 29AjayKumar
 
 

Javascript




<script>
 
// Javascript program for Game of Replacement
 
// Function return which player win the game
function playGame(arr, n)
{
 
    // Create hash that will stores
    // all distinct element
    var hash = new Set();
 
    // Traverse an array element
    for (var i = 0; i < n; i++)
        hash.add(arr[i]);
 
    return (hash.size % 2 == 0 ? 1 : 2);
}
 
// Driver Function
var arr = [1, 1, 2, 2, 2, 2];
var n = arr.length;
document.write( "Player " + playGame(arr, n) + " Wins" );
 
// This code is contributed by importantly.
</script>
 
 
Output
Player 1 Wins

Time Complexity: O(n)

Auxiliary Space: O(n)



Next Article
Find the winner of the Game of removing odd or replacing even array elements

N

Nishant_Singh
Improve
Article Tags :
  • Arrays
  • DSA
  • Game Theory
  • Hash
Practice Tags :
  • Arrays
  • Game Theory
  • Hash

Similar Reads

  • Replacing an element makes array elements consecutive
    Given an array of positive distinct integers. We need to find the only element whose replacement with any other value makes array elements distinct consecutive. If it is not possible to make array elements consecutive, return -1. Examples : Input : arr[] = {45, 42, 46, 48, 47} Output : 42 Explanatio
    8 min read
  • Find the winner of the Game of removing odd or replacing even array elements
    Given an array arr[] consisting of N integers. Two players, Player 1 and Player 2, play turn-by-turn in which one player can may either of the following two moves: Convert even array element to any other integer.Remove odd array element. The player who is not able to make any move loses the game. Th
    7 min read
  • Implement Arrays in different Programming Languages
    Arrays are one of the basic data structures that should be learnt by every programmer. Arrays stores a collection of elements, each identified by an index or a key. They provide a way to organize and access a fixed-size sequential collection of elements of the same type. In this article, we will lea
    5 min read
  • Minimize the sum of MEX by removing all elements of array
    Given an array of integers arr[] of size N. You can perform the following operation N times: Pick any index i, and remove arr[i] from the array and add MEX(arr[]) i.e., Minimum Excluded of the array arr[] to your total score. Your task is to minimize the total score. Examples: Input: N = 8, arr[] =
    7 min read
  • Modify Array by modifying adjacent equal elements
    Given an array arr[] of size N of positive integers. The task is to rearrange the array after applying the conditions given below: If arr[i] and arr[i+1] are equal then multiply the ith (current) element with 2 and set the (i +1)th element to 0. After applying all the conditions move all zeros at th
    7 min read
  • Minimize the maximum frequency of Array elements by replacing them only once
    Given an array A[] of length N, the task is to minimize the maximum frequency of any array element by performing the following operation only once: Choose any random set (say S) of indices i (0 ? i ? N-1) of the array such that every element of S is the same and Replace every element of that index w
    7 min read
  • Minimum operations to make all Array elements 0 by MEX replacement
    Given an array of N integers. You can perform an operation that selects a contiguous subarray and replaces all its elements with the MEX (smallest non-negative integer that does not appear in that subarray), the task is to find the minimum number of operations required to make all the elements of th
    5 min read
  • Replace every array element by sum of previous and next
    Given an array of integers, update every element with sum of previous and next elements with following exceptions. First element is replaced by sum of first and second. Last element is replaced by sum of last and second last. Examples: Input : arr[] = { 2, 3, 4, 5, 6} Output : 5 6 8 10 11 Explanatio
    7 min read
  • Inserting Elements in an Array - Array Operations
    In this post, we will look into insertion operation in an Array, i.e., how to insert into an Array, such as: Insert Element at the Beginning of an ArrayInsert Element at a given position in an ArrayInsert Element at the End of an ArrayInsert Element at the Beginning of an ArrayInserting an element a
    2 min read
  • Find the winner in game of rotated Array
    Given a circular connected binary array X[] of length N. Considered two players A and B are playing the game on the following move: Choose a sub-array and left-rotate it once. The move is said to be valid if and only if the number of adjacent indices in X[] having different values (after rotation) i
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences