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:
K distant string
Next article icon

A Binary String Game

Last Updated : 24 Feb, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Binary String S. The task is to determine the winner of the game when two players play a game optimally with the string as per the given conditions:

  • Player 1 always starts first.
  • Two players take turns choosing a whole block of consecutive equal characters and deleting them from a given binary String S.
  • Player 1 can choose only an odd number of consecutive equal characters and Player 2 can choose only an even number of consecutive equal characters. The player may choose nothing and count it as their turn only if it is impossible to choose anything.
  • After all the characters are removed, the player with maximum scores wins the game and if scores are equal then print “-1”

Input: S = “1110011001010”
Output: Player 1
Explanation: 
The selected characters will be in bold and Player 1’s score is Score_1 and Player 2’s score is Score_2 :
Turn 1 : (Player 1) “1110011001010” → “0011001010” Score_1 = 3
Turn 2 : (Player 2) “0011001010” → “00001010” Score_2 = 2
Turn 3 : (Player 1) “00001010”→ “0000010” Score_1 = 4
Turn 4: (Player 2) “0000010” 
He cannot do anything as only one ‘1’ is present which is an odd number. 
Also, he can’t choose the ‘0’s as they are odd (5 and 1), Therefore, Score_2 =2
Turn 5:(Player 1) “0000010”→ “000000” Score_1=5
Turn 6:(Player 2) “000000” → “” Score_2 = 2 (No ‘1’ was deleted in this turn)

Final scores: Score_1 = 5 and Score_2 = 2
Therefore, Player 1 wins.

Input : S = “11111101”
Output: Player 2
Explanation: 
Turn 1 : (Player 1) “11111101” → “1111110” Score_1 = 3
Turn 2 : (Player 2) “1111110” → “0” Score_2 = 6
Turn 3 : (Player 1) “0” → “” Score_1 = 3

Final scores: Score_1 = 3 and Score_2 = 6
Therefore, Player 2 wins.

 

Approach: 

  1. If we observe this game carefully, we understand that the only consecutive 1s are contributing to the scores of these players.
  2. Create a list to store the lengths of the consecutive 1s in the string.
  3. Sort the list in descending order.
  4. Now iterate over the list and if the list element is odd it will be added to the score of the Player 1 and if it is even it will be added to the score of the Player 2.
  5. Now if the score of the Player 1 is greater than the score of the Player 2 then print “Player 1” and if the score of the Player 2 is greater than the score of the Player 1 then print “Player 2”.
  6. Print “-1” if there is a tie i.e., scores are the same.

Below is the implementation of the above approach.

C++




// C++ program for the above approach
#include<bits/stdc++.h>
using namespace std;
 
// Function to return the result of
// the game
string gameMax(string S)
{
     
    // length of the string
    int N = S.length();
  
    // List to maintain the lengths of
    // consecutive '1's in the string
    vector<int> list;
  
    // Variable that keeps a track of
    // the current length of the block
    // of consecutive '1's
    int one = 0;
  
    for(int i = 0; i < N; i++)
    {
        if (S[i] == '1')
        {
            one++;
        }
        else
        {
             
            // Adds non-zero lengths
            if (one != 0)
            {
                list.push_back(one);
            }
            one = 0;
        }
    }
  
    // This takes care of the case
    // when the last character is '1'
    if (one != 0)
    {
        list.push_back(one);
    }
  
    // Sorts the lengths in
    // descending order
    sort(list.begin(), list.end(),
         greater<int>());
  
    // Scores of the 2 players
    int score_1 = 0, score_2 = 0;
  
    for(int i = 0; i < list.size(); i++)
    {
         
        // For player 1
        if (list[i] % 2 == 1)
        {
            score_1 += list[i];
        }
  
        // For player 2
        else
        {
            score_2 += list[i];
        }
    }
  
    // In case of a tie
    if (score_1 == score_2)
        return "-1";
  
    // Print the result
    return (score_1 > score_2) ? "Player 1" :
                                 "Player 2";
}
 
// Driver Code
int main()
{
     
    // Given string S
    string S = "11111101";
  
    // Function call
    cout << gameMax(S);
}
 
// This code is contributed by rutvik_56
 
 

Java




// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to return the result of
    // the game
    public static String gameMax(String S)
    {
        // length of the string
        int N = S.length();
 
        // List to maintain the lengths of
        // consecutive '1's in the string
        List<Integer> list = new ArrayList<>();
 
        // Variable that keeps a track of
        // the current length of the block
        // of consecutive '1's
        int one = 0;
 
        for (int i = 0; i < N; i++) {
 
            if (S.charAt(i) == '1') {
                one++;
            }
            else {
 
                // Adds non-zero lengths
                if (one != 0) {
                    list.add(one);
                }
                one = 0;
            }
        }
 
        // This takes care of the case
        // when the last character is '1'
        if (one != 0) {
            list.add(one);
        }
 
        // Sorts the lengths in
        // descending order
        Collections.sort(list,
                         Collections.reverseOrder());
 
        // Scores of the 2 players
        int score_1 = 0, score_2 = 0;
 
        for (int i = 0; i < list.size(); i++) {
 
            // For player 1
            if (list.get(i) % 2 == 1) {
                score_1 += list.get(i);
            }
 
            // For player 2
            else {
                score_2 += list.get(i);
            }
        }
 
        // In case of a tie
        if (score_1 == score_2)
            return "-1";
 
        // Print the result
        return (score_1 > score_2) ? "Player 1"
                                   : "Player 2";
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given string S
        String S = "11111101";
 
        // Function Call
        System.out.println(gameMax(S));
    }
}
 
 

Python3




# Python3 program for
# the above approach
 
# Function to return the
# result of the game
def gameMax(S):
 
    # Length of the string
    N = len(S)
 
    # List to maintain the lengths of
    # consecutive '1's in the string
    list = []
 
    # Variable that keeps a track of
    # the current length of the block
    # of consecutive '1's
    one = 0
     
    for i in range(N):
        if(S[i] == '1'):
            one += 1
        else:
 
            # Adds non-zero lengths
            if(one != 0):
                list.append(one)
            one = 0
 
    # This takes care of the case
    # when the last character is '1'
    if(one != 0):
        list.append(one)
 
    # Sorts the lengths in
    # descending order
    list.sort(reverse = True)
 
    # Scores of the 2 players
    score_1 = 0
    score_2 = 0
 
    for i in range(len(list)):
 
        # For player 1
        if(list[i] % 2 == 1):
            score_1 += list[i]
 
        # For player 2
        else:
            score_2 += list[i]
 
    # In case of a tie
    if(score_1 == score_2):
        return '-1'
 
    # Print the result
    if(score_1 > score_2):
        return "Player 1"
    else:
        return "Player 2"
 
# Driver Code
 
# Given string S
S = "11111101"
 
# Function call
print(gameMax(S))
 
# This code is contributed by avanitrachhadiya2155
 
 

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to return the result of
// the game
public static String gameMax(String S)
{
     
    // length of the string
    int N = S.Length;
 
    // List to maintain the lengths of
    // consecutive '1's in the string
    List<int> list = new List<int>();
 
    // Variable that keeps a track of
    // the current length of the block
    // of consecutive '1's
    int one = 0;
 
    for(int i = 0; i < N; i++)
    {
        if (S[i] == '1')
        {
            one++;
        }
        else
        {
 
            // Adds non-zero lengths
            if (one != 0)
            {
                list.Add(one);
            }
            one = 0;
        }
    }
 
    // This takes care of the case
    // when the last character is '1'
    if (one != 0)
    {
        list.Add(one);
    }
 
    // Sorts the lengths in
    // descending order
    list.Sort();
    list.Reverse();
     
    // Scores of the 2 players
    int score_1 = 0, score_2 = 0;
 
    for(int i = 0; i < list.Count; i++)
    {
         
        // For player 1
        if (list[i] % 2 == 1)
        {
            score_1 += list[i];
        }
 
        // For player 2
        else
        {
            score_2 += list[i];
        }
    }
 
    // In case of a tie
    if (score_1 == score_2)
        return "-1";
 
    // Print the result
    return (score_1 > score_2) ?
         "Player 1" : "Player 2";
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given string S
    String S = "11111101";
 
    // Function Call
    Console.WriteLine(gameMax(S));
}
}
 
// This code is contributed by Amit Katiyar
 
 

Javascript




<script>
// javascript program for the
// above approach
 
// Function to return the result of
// the game
function gameMax(S)
{
      
    // length of the string
    let N = S.length;
  
    // List to maintain the lengths of
    // consecutive '1's in the string
    let list = [];
  
    // Variable that keeps a track of
    // the current length of the block
    // of consecutive '1's
    let one = 0;
  
    for(let i = 0; i < N; i++)
    {
        if (S[i] == '1')
        {
            one++;
        }
        else
        {
  
            // Adds non-zero lengths
            if (one != 0)
            {
                list.push(one);
            }
            one = 0;
        }
    }
  
    // This takes care of the case
    // when the last character is '1'
    if (one != 0)
    {
        list.push(one);
    }
  
    // Sorts the lengths in
    // descending order
    list.sort();
    list.reverse();
      
    // Scores of the 2 players
    let score_1 = 0, score_2 = 0;
  
    for(let i = 0; i < list.length; i++)
    {
          
        // For player 1
        if (list[i] % 2 == 1)
        {
            score_1 += list[i];
        }
  
        // For player 2
        else
        {
            score_2 += list[i];
        }
    }
  
    // In case of a tie
    if (score_1 == score_2)
        return "-1";
  
    // Print the result
    return (score_1 > score_2) ?
         "Player 1" : "Player 2";
}
  
// Driver Code
 
    // Given string S
    let S = "11111101";
  
    // Function Call
    document.write(gameMax(S));
    
   // This code is contributed by target_2.
</script>
 
 

Output: 

Player 2

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



Next Article
K distant string

K

kunalsg18elec
Improve
Article Tags :
  • DSA
  • Game Theory
  • Greedy
  • Strings
  • binary-string
Practice Tags :
  • Game Theory
  • Greedy
  • Strings

Similar Reads

  • Find winner in the game of Binary Array
    Given a binary array X[] of size N. Two players A and B are playing games having the following rules, then the task is to determine the winner if B starts first and both players play optimally. The rules are: In the first turn, a player selects any index i (1 ≤ i ≤ N) such that A[i] = 0.After their
    7 min read
  • K distant string
    Given a string of length n and a non-negative integer k. Find k distant string of given string. Distance between two letters is the difference between their positions in the alphabet. for example: dist(c, e) = dist(e, c) = 2.dist(a, z) = dist(z, a) = 25. By using this concept, the distance between t
    7 min read
  • CSES Solutions - Another Game
    There are n heaps of coins and two players who move alternately. On each move, a player selects some of the nonempty heaps and removes one coin from each heap. The player who removes the last coin wins the game. Your task is to find out who wins if both players play optimally. Examples: Input: N = 3
    5 min read
  • Alternatively Merge two Strings
    Given 2 strings, merge them in an alternate way, i.e. the final string's first character is the first character of the first string, the second character of the final string is the first character of the second string and so on. And if once you reach end of one string while if another string is stil
    4 min read
  • Cost to make a string Panagram | Set 2
    Given an array cost[] containing the cost of adding each alphabet from (a – z) and a string str consisting of lowercase English alphabets which may or may not be a Panagram. The task is to make the given string a Panagram with the following operations: Adding a character in str costs twice the cost
    8 min read
  • Minimum cost to modify a string
    Given string str consisting of lower case alphabets only and an integer K. The task is to find the minimum cost to modify the string such that the ASCII value difference between any two characters of the given string is less than equal to K. The following operations can be performed on the string: I
    15+ min read
  • What are Pascal Strings ?
    This article intends to provide a basic understanding of traditionally used strings i.e. "Pascal Strings". As the name is self-explanatory, pascal strings are an essential constituent of the PASCAL programming language. Pascal is a computer programming language that Niklaus Wirth of Switzerland crea
    4 min read
  • strcspn() in C
    The C library function strcspn() calculates the length of the number of characters before the 1st occurrence of character present in both the string. Syntax : strcspn(const char *str1, const char *str2) Parameters: str1 : The Target string in which search has to be made. str2 : Argument string conta
    3 min read
  • String in Data Structure
    A string is a sequence of characters. The following facts make string an interesting data structure. Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immu
    3 min read
  • Combinatorial Game Theory | Set 1 (Introduction)
    Combinatorial games are two-person games with perfect information and no chance moves (no randomization like coin toss is involved that can effect the game). These games have a win-or-lose or tie outcome and determined by a set of positions, including an initial position, and the player whose turn i
    3 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