- binary-string, Bit Magic, Pattern Searching, Searching, Strings

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≤109Examples:Input: str=”01100″, M=1Output: 11110Explanation: After First Iteration: 11110Input: str = “0110100”, M=3Output: 1110111Explanation: 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:Below is the implementation of the above approach.C++#include using namespace std;  void findString(string str, int M){    int N = str.length();              M = min(M, N);          string s1 = “”;          while (M != 0) {                          s1 = “”;          for (int i = 0; i < N; i++) {              if (str[i] == '0') {                                                  if ((str[i - 1] == '1'                     && str[i + 1] != '1')                    || (str[i - 1] != '1'                        && str[i + 1] == '1'))                                          s1 += '1';                  else                    s1 += '0';            }            else                s1 += '1';        }                                  if (str == s1)            break;                          str = s1;        M--;    }      cout