Find the player with least 0s after emptying a Binary String by removing non-empty substrings
Given a binary string S, the task is to determine the winner of the game when two players play a game optimally in alternate turns with the given string, as per the following conditions:
- Player 1 always starts first.
- In each turn, a player removes a non-empty substring from the given string.
- After the given string is emptied, the player having the minimum count of 0s will win the game. If both players have an equal count of 0s, then print “Tie”.
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: S = “00011”
Output: Player 1
Explanation: Substrings can be chosen as follows:
Turn 1: Player 1 removes the substring S[4…5]. Therefore, Player 1 contains “11”.
Turn 2: Player 2 removes the substring S[0…0]. Therefore, Player 2 contains “0”.
Turn 3: Player 1 removes the substring S[0…0]. Therefore, Player 1 contains “110”.
Turn 4: Player 2 removes the substring S[0…0]. Therefore, Player 2 contains “00”.
Therefore, Player 1 wins the game.
Input: S = “0110011”
Output: Player 2
Approach: The problem can be solved based on the following observations:
- If the count of 0s in the string is an even number then player 1 and player 2 choose the substring “0” in each turn and no player will win this game.
- Otherwise, store the count of consecutive 1s in an array and apply the game of nim rule on the array.
- Nim-Sum: The cumulative XOR value of the number of coins/stones in each pile/heaps(here consecutive 1s) at any point of the game is called Nim-Sum at that point.
Follow the steps below to solve the problem:
- Initialize a variable, say cntZero, to store the count of 0s in the string.
- Initialize a variable, say cntConOne, to store the count of consecutive 1s in the string.
- Initialize a variable, say nimSum, to store the Nim-Sum of consecutive 1s of the given string.
- Traverse the array and calculate the count of 0s and nimSum.
- Finally, check if the value of cntZero is an even number or not. If found to be true, then print Tie.
- Otherwise, check if the value of nimSum is greater than 0 or not. If found to be true, then print Player 1.
- Otherwise, print player 2.
Below is the implementation of the above approach:
Time Complexity: O(N), where N is the length of the string
Auxiliary Space: O(1)