Find the winner of game of repeatedly removing the first character to empty given string

• Difficulty Level : Medium
• Last Updated : 09 Jun, 2021

Given a positive integer N, representing the count of players playing the game and an array of strings arr[], consisting of the numeric strings made up of digits from the range [‘1’, ‘N’]. Considering ith player is assigned with the string arr[i], the task is to find the winner of the game when all N players play the game optimally as per the following rules:

• Player 1 starts the game, removes the first character of the string arr( 1-based indexing ), say X, and in the next turn Xth player will play the game and remove the first character of arr[X] and so on.
• The player who is not able to remove any character from the assigned string will win the game.

Examples:

Input: N = 3, arr[] = { “323”, “2”, “2” }
Output: Player 2
Explanation:
Turn 1: Removing arr by Player 1 modifies arr to “23”.
Turn 2: Removing arr by Player 3 modifies arr to “”.
Turn 3: Removing arr by Player 2 modifies arr to “”.
Turn 4: Player 2 is not able to remove any characters from arr.
Therefore, player 2 wins the game.

Input: N = 3, arr[] = { “121”, “21”, “23123” }
Output: Player 1

Approach: The problem can be solved using Queue to remove the first character of each string efficiently. Follow the steps below to solve the problem:

• Initialize an array of Queues, say Q[], such that Q[i] stores the characters of the string arr[i].
• Traverse the array Q[] using variable i as per the rules of the game and check if the count of characters in Q[i] is 0 or not. If found to be true, then print the “Player i”.

Below is the implementation of the above approach:

C++

 // C++ program to implement// the above approach #include using namespace std; // Function to find the winner of a game of// repeatedly removing the first character// to empty a stringvoid find_Winner(vector& arr, int N){     // Store characters of each    // string of the array arr[]    vector > Q(N);     // Stores count of strings in arr[]    int M = arr.size();     // Traverse the array arr[]    for (int i = 0; i < M; i++) {         // Stores length of current string        int len = arr[i].length();         // Traverse the string        for (int j = 0; j < len; j++) {             // Insert arr[i][j]            Q[i].push(arr[i][j] - 1);        }    }     // 1st Player starts the game    int player = 0;     while (Q[player].size() > 0) {         // Stores the player number        // for the next turn        int nextPlayer            = Q[player].front() - '0';         // Remove 1st character of        // current string        Q[player].pop();         // Update player number for        // the next turn        player = nextPlayer;    }     cout << "Player " << (player + 1);} // Driver Codeint main(){     int N = 3;    vector arr        = { "323", "2", "2" };     find_Winner(arr, N);    return 0;}

Java

 // Java program to implement// the above approachimport java.util.*; class GFG{ // Function to find the winner of a game of// repeatedly removing the first character// to empty a Stringstatic void find_Winner(String[] arr, int N){     // Store characters of each    // String of the array arr[]    @SuppressWarnings("unchecked")    Vector [] Q = new Vector[N];    for (int i = 0; i < Q.length; i++)        Q[i] = new Vector();       // Stores count of Strings in arr[]    int M = arr.length;     // Traverse the array arr[]    for (int i = 0; i < M; i++)    {         // Stores length of current String        int len = arr[i].length();         // Traverse the String        for (int j = 0; j < len; j++)        {             // Insert arr[i][j]            Q[i].add(arr[i].charAt(j));        }         }     // 1st Player starts the game    int player = 0;     while (Q[player].size() > 0 )    {         // Stores the player number        // for the next turn        int nextPlayer            = Q[player].get(0) - '0'-1;         // Remove 1st character of        // current String        Q[player].remove(0);         // Update player number for        // the next turn        player = nextPlayer;    }    System.out.print("Player " +  (player + 1));} // Driver Codepublic static void main(String[] args){    int N = 3;    String[] arr        = { "323", "2", "2" };    find_Winner(arr, N);}} // This code is contributed by gauravrajput1

Python3

 # Python3 program to implement# the above approach # Function to find the winner of a game of# repeatedly removing the first character# to empty a stringdef find_Winner(arr, N) :      # Store characters of each    # string of the array arr[]    Q = *N      for i in range(N) :               Q[i] = []      # Stores count of strings in arr[]    M = len(arr)      # Traverse the array arr[]    for i in range(M) :          # Stores length of current string        Len = len(arr[i])          # Traverse the string        for j in range(Len) :              # Insert arr[i][j]            Q[i].append(ord(arr[i][j]) - 1)      # 1st Player starts the game    player = 0      while (len(Q[player]) > 0) :          # Stores the player number        # for the next turn        nextPlayer = Q[player] - ord('0')          # Remove 1st character of        # current string        del Q[player]          # Update player number for        # the next turn        player = nextPlayer      print("Player", (player + 1))     N = 3arr = [ "323", "2", "2" ] find_Winner(arr, N) # This code is contributed by divyeshrabadiya07.

C#

 // C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find the winner of a game of// repeatedly removing the first character// to empty a Stringstatic void find_Winner(String[] arr, int N){         // Store characters of each    // String of the array []arr    List [] Q = new List[N];    for(int i = 0; i < Q.Length; i++)        Q[i] = new List();             // Stores count of Strings in []arr    int M = arr.Length;     // Traverse the array []arr    for(int i = 0; i < M; i++)    {                 // Stores length of current String        int len = arr[i].Length;         // Traverse the String        for(int j = 0; j < len; j++)        {                         // Insert arr[i,j]            Q[i].Add(arr[i][j]);        }    }     // 1st Player starts the game    int player = 0;     while (Q[player].Count > 0 )    {                 // Stores the player number        // for the next turn        int nextPlayer = Q[player] - '0'- 1;                 // Remove 1st character of        // current String        Q[player].RemoveAt(0);         // Update player number for        // the next turn        player = nextPlayer;    }    Console.Write("Player " + (player + 1));} // Driver Codepublic static void Main(String[] args){    int N = 3;    String[] arr = { "323", "2", "2" };         find_Winner(arr, N);}} // This code is contributed by Rajput-Ji

Javascript


Output:
Player 2

Time Complexity: O(N * M), where M is the length of the longest string present in the array.
Auxiliary Space: O(N * M)

My Personal Notes arrow_drop_up