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
  • Practice Game Theory
  • Game Theory in DSA
  • Nash Equilibrium
  • Normal form games
  • Minimax Algorithm
  • Impartial games
  • Combinatorial Game Theory
  • Nim Game
  • Grundy Numbers
  • Sprague Grundy Theorem
  • Minimax Algo
  • Alpha Beta Pruning
  • Zorbist Hashing
  • Coin Game
  • DP in Game Theory
  • Problems on Game Theory for CP
Open In App
Next Article:
Find the last remaining Character in the Binary String according to the given conditions
Next article icon

Find the player who is the last to remove any character from the beginning of a Binary String

Last Updated : 18 May, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] consisting of binary strings, the task is to find the winner of the game when two players play the game optimally as per the following rules: 

  • Player 1 starts the game.
  • In each turn, a player must choose a non-empty string and remove a positive number of characters from the beginning of the string.
  • Player 1 can only choose a string starting with the character ‘0’ whereas Player 2 can only choose a string starting with the character ‘1’.
  • A player who cannot make a move loses the game.

Examples: 

Input: arr[] = {“010”, “101”} 
Output: Player 2 
Explanation: 
First move for player 1 = {0, 101} 
First move for player 2 = {0, 1} 
Second move for player 1 = {1} 
Second move for player 2 = {} 
No moves left for player 1. 
Therefore player2 wins. 

Input: arr[] = {“010”, “001”} 
Output: Player 1 

Approach: The idea is to compare the total number of moves each player can make if both the players play the game optimally. Follow the steps below: 

  1. If there are consecutive occurrences of the same character in any string, then simply replace them with a single occurrence of that character, since it is optimal to remove all occurrences of the character present at the start.
  2. Now, if the string has a starting element same as its last element, then the scenario of the game remains the same even without this string because if one player makes a move on this string, the other player makes the next move by removing the character from the same string, resulting in the exact same position for the first player.
  3. If a string has a starting element different from its last element, it requires the player to make one extra move.
  4. So, just count the number of extra moves each player has to make.
  5. The player who runs out of extra moves will lose the game.

Below is the implementation of the above approach:

C++14




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the player who
// loses the game
void findPlayer(string str[], int n)
{
  
    // Moves for the first player
    int move_first = 0;
  
    // Moves for the second player
    int move_sec = 0;
  
    // Iterate over array of strings
    for (int i = 0; i < n; i++) {
  
        // Check if the first and last
        // character are the same
        if (str[i][0]
            == str[i][str[i].length() - 1]) {
  
            // Check if string start and
            // end with character '0'
            if (str[i][0] == 48)
                move_first++;
            else
                move_sec++;
        }
    }
  
    // If first player have less moves
    if (move_first <= move_sec) {
        cout << "Player 2 wins";
    }
    else {
        cout << "Player 1 wins";
    }
}
  
// Driver Code
int main()
{
    // Given array of strings
    string str[] = { "010", "101" };
  
    int N = sizeof(str)
            / sizeof(str[0]);
  
    // Function Call
    findPlayer(str, N);
  
    return 0;
}
 
 

Java




// Java program for
// the above approach
import java.util.*;
class GFG{
  
// Function to find the player who
// loses the game
static void findPlayer(String str[],
                       int n)
{
  // Moves for the
  // first player
  int move_first = 0;
 
  // Moves for the
  // second player
  int move_sec = 0;
 
  // Iterate over array
  // of Strings
  for (int i = 0; i < n - 1; i++)
  {
    // Check if the first and last
    // character are the same
    if (str[i].charAt(0) ==
        str[i].charAt(str[i].length() - 1))
    {
      // Check if String start and
      // end with character '0'
      if (str[i].charAt(0) == 48)
        move_first++;
      else
        move_sec++;
    }
  }
 
  // If first player have less moves
  if (move_first <= move_sec)
  {
    System.out.print("Player 2 wins");
  }
  else
  {
    System.out.print("Player 1 wins");
  }
}
  
// Driver Code
public static void main(String[] args)
{
  // Given array of Strings
  String str[] = {"010", "101"};
 
  int N = str[0].length();
   
  // Function Call
  findPlayer(str, N);
}
}
 
// This code is contributed by Rajput-Ji
 
 

Python3




# Python3 program for the above approach
  
# Function to find the player who
# loses the game
def findPlayer(str, n):
  
    # Moves for the first player
    move_first = 0
  
    # Moves for the second player
    move_sec = 0
  
    # Iterate over array of strings
    for i in range(n):
  
        # Check if the first and last
        # character are the same
        if (str[i][0] ==
            str[i][len(str[i]) - 1]):
  
            # Check if string start and
            # end with character '0'
            if (str[i][0] == 48):
                move_first += 1
            else:
                move_sec += 1
         
    # If first player have less moves
    if (move_first <= move_sec):
        print("Player 2 wins")
    else:
        print("Player 1 wins")
     
# Driver Code
 
# Given array of strings
str = [ "010", "101" ]
  
N = len(str)
  
# Function call
findPlayer(str, N)
 
# This code is contributed by sanjoy_62
 
 

C#




// C# program for the above approach 
using System;
 
class GFG{
  
// Function to find the player who
// loses the game
static void findPlayer(string[] str, int n)
{
     
    // Moves for the first player
    int move_first = 0;
  
    // Moves for the second player
    int move_sec = 0;
  
    // Iterate over array of strings
    for(int i = 0; i < n; i++)
    {
         
        // Check if the first and last
        // character are the same
        if (str[i][0] ==
            str[i][str[i].Length - 1])
        {
             
            // Check if string start and
            // end with character '0'
            if ((str[i][0]) == 48)
                move_first++;
            else
                move_sec++;
        }
    }
  
    // If first player have less moves
    if (move_first <= move_sec)
    {
        Console.Write("Player 2 wins");
    }
    else
    {
        Console.Write("Player 1 wins");
    }
}
  
// Driver Code
public static void Main ()
{
     
    // Given array of strings
    string[] str = { "010", "101" };
  
    int N = str.Length;
  
    // Function call
    findPlayer(str, N);
}
}
 
// This code is contributed by sanjoy_62
 
 

Javascript




<script>
// javascript program for the
// above approach
 
// Function to find the player who
// loses the game
function findPlayer(str, n)
{
  // Moves for the
  // first player
  let move_first = 0;
  
  // Moves for the
  // second player
  let move_sec = 0;
  
  // Iterate over array
  // of Strings
  for (let i = 0; i < n - 1; i++)
  {
    // Check if the first and last
    // character are the same
    if (str[i][0] ==
        str[i][str[i].length - 1])
    {
      // Check if String start and
      // end with character '0'
      if (str[i][0]== 48)
        move_first++;
      else
        move_sec++;
    }
  }
  
  // If first player have less moves
  if (move_first <= move_sec)
  {
    document.write("Player 2 wins");
  }
  else
  {
    document.write("Player 1 wins");
  }
}
 
  
// Driver Code
 
    // Given array of Strings
  let str = ["010", "101"];
  
  let N = str[0].length;
    
  // Function Call
  findPlayer(str, N);
           
</script>
 
 
Output: 
Player 2 wins

 

Time Complexity: O(N) 
Auxiliary Space: O(1)



Next Article
Find the last remaining Character in the Binary String according to the given conditions
author
patelnagendra1
Improve
Article Tags :
  • DSA
  • Game Theory
  • Greedy
  • Strings
  • binary-string
Practice Tags :
  • Game Theory
  • Greedy
  • Strings

Similar Reads

  • Find the last player to be able to flip a character in a Binary String
    Given a binary string S of length N, the task is to find the winner of the game if two players A and B plays optimally as per the following rules: Player A always starts the game.In a player's first turn, he can move to any index (1-based indexing) consisting of '0' and make it '1'.For the subsequen
    10 min read
  • Find the player who rearranges the characters to get a palindrome string first
    Given an even length string S consisting of lower-case English alphabets only, we have two players playing the game. The rules are as follows: the player wins the game, if, at any move, a player can re-arrange the characters of the string to get a palindrome string.if the player cannot win the game,
    10 min read
  • Find the last remaining Character in the Binary String according to the given conditions
    Given a binary string str consisting of only 0's and 1's. The following two operations can be performed on it: One digit can delete another digit i.e. a 0 can delete a 1 and vice versa.If at any moment, the entire string consists only 0's or 1's, then the respective digit is printed. The task is to
    7 min read
  • Remove the first and last character of each word in a string
    Given the string the task is to remove the first and last character of each word in a string.Examples: Input: Geeks for geeksOutput: eek o eek Input: Geeksforgeeks is bestOutput: eeksforgeek es Approach : Split the String based on the spaceRun a loop from the first letter to the last letter.Check if
    4 min read
  • Minimum characters required to be removed to sort binary string in ascending order
    Given a binary string str, the task is to remove the minimum number of characters from the given binary string such that the characters in the remaining string form a sorted order. Examples: Input: str = "1000101"Output: 2Explanation: Removal of the first two occurrences of '1' modifies the string t
    8 min read
  • Minimum characters required to be removed to sort binary string in ascending order - Set 2
    Given binary string str of size N, the task is to remove the minimum number of characters from the given binary string such that the characters in the remaining string are in sorted order. Examples: Input: str = “1000101”Output: 2Explanation: Removal of the first two occurrences of ‘1’ modifies the
    10 min read
  • Find winner when players remove multiples of A or B from Array in each turn
    Given an array arr of size N, and also given that Alice and Bob are playing a game and Alice has a number A and Bob has a number B. They both have alternate turns starting with Alice. In each turn, the current player must remove a non-zero number of elements from the array and each removed element s
    7 min read
  • Queries to find the last non-repeating character in the sub-string of a given string
    Given a string str, the task is to answer Q queries where every query consists of two integers L and R and we have to find the last non-repeating character in the sub-string str[L...R]. If there is no non-repeating character then print -1.Examples: Input: str = "GeeksForGeeks", q[] = {{2, 9}, {2, 3}
    11 min read
  • Minimum number of characters to be removed to make a binary string alternate
    Given a binary string, the task is to find minimum number of characters to be removed from it so that it becomes alternate. A binary string is alternate if there are no two consecutive 0s or 1s.Examples : Input : s = "000111" Output : 4 We need to delete two 0s and two 1s to make string alternate. I
    4 min read
  • Find the player to be able to replace the last element that can be replaced by its divisors
    Given an array arr[] consisting of N integers and two players A and B playing a game together by performing the following operations: Choose an integer from arr[] and replace that number with one of its divisors.A previously selected integer cannot be chosen again.As 1 does not have any divisor othe
    4 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