VOOZH about

URL: https://www.geeksforgeeks.org/dsa/a-binary-string-game/

⇱ A Binary String Game - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

A Binary String Game

Last Updated : 15 Jul, 2025

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.

Output: 

Player 2

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

Comment
Article Tags:
Article Tags: