Introduction
In this article, we will solve the problem to predict the winner of a game by converting 0 to 1 turn by turn following the given rules.
Let’s get started with the problem statement.
Problem Statement
Given binary string str consisting of only 0 and 1, where 0 represent an unoccupied position, and 1 represents an occupied position.
Two players, A and B, have to occupy an unoccupied position (convert 0 to 1) turn by turn following the given rules:
-
The player can only occupy the unoccupied position
-
The player can only move to its adjacent position in every turn
If a player cannot move on the turn, he loses. Predict the winner of the game if both play optimally, given that A makes the first move.
Please try to solve this problem on your own before moving on to further discussion here.
Let’s understand the problem statement by working on some examples.
Example - Suppose you are given a binary string str=”10101001”.
The winner of this game will be B.
Let's see how?
First turn - A has 4 options to occupy, position-2, position-4, position-6 and position-7. Now, if A occupies position-2 or position-4, it won't be able to make any more moves in its next turn as it will have 1’s on both sides. So, the only safe options are position-6 and position-7, and it can occupy any of them.
If A occupies the 6th position(1-based indexing), in this way - 10101A01
Second Turn - B has 3 options → 10101A01 (the 3 zeroes in red)
Let’s explore all the three options and see what happens in each of these cases -
-
If B occupies position-2, then A can move to the 7th position in the next move. Then, in the next move, B will have no options left to move as the state of the game will be like this - 1B101AA1, B has 1’s on both sides. So, B will lose.
-
If B occupies position-4, then B will eventually lose, similar to the above case.
-
If B occupies position-7, then in the next move, A will not be able to make any moves as the state of the game will be like this - 10101AB1, A will have 1 on its left and B on its right. So, A will lose, and B will be the winner.
Since we know that all the players will play optimally so if B chooses to occupy position-7, then the winner of the game will be B itself. Hence, the answer will be B.
As you can see, the problem is based on observation. In such problems, there is no such definite or fixed approach. You need to take some examples on your own and try to simulate the given situation. Accordingly, we can conclude the steps we need to follow to gain the desired results.
Let’s see the approach in the next section of this blog.





