Determine the winner of a game of deleting Characters from a String

Given numeric string str, 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.
  • In one turn one player can remove the contiguous elements from the string and the number of elements removed will add up to his score. Player 1 will remove odd contiguous elements and Player 1 will remove even contiguous elements.
  • Any player who is not able to make a move loses the game.
  • After all the strings are removed, the player with maximum scores wins the game and if scores are equal then print “-1”.

Examples:

Input: str = “7788” 
Output: -1 
Explanation: 
First move for player 1 is to remove 77 and for player 2 is 88. Score for both is 2. Hence -1.

Input: str = “8822” 
Output: Player 2 
Explanation: 
There are no odd elements so player 1 cant make amove so player 2 wins.

Approach: Follow the steps below in order to solve the problem:



  1. Create an array A[] of size 10 to store the frequency of all the digits in the given string.
  2. Iterate the given string and update the frequency of each digit in the above array.
  3. Traverse the array A[] and take two variables as sum1 = 0 and sum2 = 0 to store the sum of scores.
  4. Increment sum1 if the index is odd i.e., Player 1 turn else increment sum2 if the index is even i.e., Player 2 turn.
  5. After the above steps check if sum1 is equal to sum2 then print -1 otherwise print the player number who wins the game on the basis of the score.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the winner of the
// game when both players play optimally
void determineWinner(string str)
{
    // Stores the frequency of all digit
    vector<int> A(10);
  
    // Stores the scores of player1
    // and player2 respectively
    int sum1 = 0, sum2 = 0;
  
    // Iterate to store frequencies
    for (int i = 0; i < str.length(); i++) {
        A[int(str[i]) - 48]++;
    }
  
    for (int i = 0; i <= 9; i++) {
  
        // Turn for the player1
        if (i % 2 != 0) {
  
            // Add score of player1
            sum1 = sum1 + A[i];
        }
        else {
  
            // Add score of player2
            sum2 = sum2 + A[i];
        }
    }
  
    // Check if its a draw
    if (sum1 == sum2) {
        cout << "-1";
    }
  
    // If score of player 1 is greater
    else if (sum1 > sum2) {
        cout << "Player 1";
    }
  
    // Otherwise
    else {
        cout << "Player 2";
    }
}
  
// Driver Code
int main()
{
    string str = "78787";
    determineWinner(str);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach 
import java.util.*;
  
class GFG{
  
// Function to find the winner of the
// game when both players play optimally
static void determineWinner(String str)
{
      
    // Stores the frequency of all digit
    int[] A = new int[10];
  
    // Stores the scores of player1
    // and player2 respectively
    int sum1 = 0, sum2 = 0;
  
    // Iterate to store frequencies
    for(int i = 0; i < str.length(); i++)
    {
        A[(int)str.charAt(i) - 48]++;
    }
  
    for(int i = 0; i <= 9; i++)
    {
          
        // Turn for the player1
        if (i % 2 != 0
        {
  
            // Add score of player1
            sum1 = sum1 + A[i];
        }
        else
        {
  
            // Add score of player2
            sum2 = sum2 + A[i];
        }
    }
  
    // Check if its a draw
    if (sum1 == sum2) 
    {
        System.out.print("-1");
    }
  
    // If score of player 1 is greater
    else if (sum1 > sum2)
    {
        System.out.print("Player 1");
    }
  
    // Otherwise
    else 
    {
        System.out.print("Player 2");
    }
}
  
// Driver code
public static void main (String[] args)
{
    String str = "78787";
      
    determineWinner(str);
}
}
  
// This code is contributed by offbeat

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach 
  
# Function to find the winner of the
# game when both players play optimally
def determineWinner(str):
  
    # Stores the frequency of all digit
    A = [0 for i in range(9)];
  
    # Stores the scores of player1
    # and player2 respectively
    sum1 = 0; sum2 = 0;
  
    # Iterate to store frequencies
    for i in range(0, len(str)):
        A[int(str[i])] += 1;
      
    for i in range(0, 9):
  
        # Turn for the player1
        if (i % 2 != 0):
  
            # Add score of player1
            sum1 = sum1 + A[i];
        else:
  
            # Add score of player2
            sum2 = sum2 + A[i];
          
    # Check if its a draw
    if (sum1 == sum2):
        print("-1");
      
    # If score of player 1 is greater
    elif(sum1 > sum2):
        print("Player 1");
      
    # Otherwise
    else:
        print("Player 2");
      
# Driver code
if __name__ == '__main__':
      
    str = "78787";
  
    determineWinner(str);
      
# This code is contributed by Amit Katiyar 

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach 
using System;
class GFG{
  
// Function to find the winner of the
// game when both players play optimally
static void determineWinner(String str)
{
      
    // Stores the frequency of all digit
    int[] A = new int[10];
  
    // Stores the scores of player1
    // and player2 respectively
    int sum1 = 0, sum2 = 0;
  
    // Iterate to store frequencies
    for(int i = 0; i < str.Length; i++)
    {
        A[(int)str[i] - 48]++;
    }
  
    for(int i = 0; i <= 9; i++)
    {
          
        // Turn for the player1
        if (i % 2 != 0) 
        {
  
            // Add score of player1
            sum1 = sum1 + A[i];
        }
        else
        {
  
            // Add score of player2
            sum2 = sum2 + A[i];
        }
    }
  
    // Check if its a draw
    if (sum1 == sum2) 
    {
        Console.Write("-1");
    }
  
    // If score of player 1 is greater
    else if (sum1 > sum2)
    {
        Console.Write("Player 1");
    }
  
    // Otherwise
    else 
    {
        Console.Write("Player 2");
    }
}
  
// Driver code
public static void Main(String[] args)
{
    String str = "78787";
      
    determineWinner(str);
}
}
  
// This code is contributed by Rohit_ranjan

chevron_right


Output: 

Player 1

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

I am Priyanshu Mishra pursuing a Technical Content Writer internship at GFG I write articles on Data Structures and AlgorithmsI am also exploring the areas of Web Development and competitive Programming

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.