Find Binary string by converting all 01 or 10 to 11 after M iterations
Given a binary string str of size N and an integer M. This binary string can be modified by flipping all the 0’s to 1 which have exactly one 1 as a neighbour. The task is to find the final state of the binary string after M such iterations.
Note: 2≤N≤103, 1≤M≤109
Input: str=”01100″, M=1
Explanation: After First Iteration: 11110
Input: str = “0110100”, M=3
Explanation: After First Iteration: 1110110, After Second Iteration: 1110111, After Third Iteration: Remains the same.
Approach: The solution is based on the observation that the modification can go on for no more than N iterations, because even if in each iteration, atleast one 0 is flipped, then it would go on for maximum N times and, if no zero is flipped in an iteration, then this would mean that the binary string remain in the same state as on the previous step and the simulation is over. Hence, the total number of iterations will be a minimum of N and M. Follow the steps below to solve the problem:
- Initialize the variable N and set its value to the length of the binary string str.
- Set the value of M to the minimum of N or M.
- Iterate in the outer while loop until M is greater than 0.
- Initialize the string s1=”” to store the modified version after the current iteration.
- Iterate in the inner for loop from i=0 to i<N.
- Check the character at the ith index of the given binary string str.
- If str[i]==’1′, then add this character to the binary string s1.
- Else, check for it’s adjacent characters in the i-1 and i+1 indexes.
- If exactly one 1 is there, then add 1 to the binary string s1.
- Else, add 0 to the binary string s1.
- After the inner loop, check if the binary strings str and s1 are the same or not.
- If yes, then break the outer loop.
- Else, set binary string s1 as the new value of the binary string str and decrease the value of M by 1.
- Finally, print the binary string s1.
Below is the implementation of the above approach.
Time Complexity: O(min(M, N)*N)
Auxiliary Space: O(1)