Flip all 0 s in given Binary Strings K times with different neighbours | Function to modify the given string K number of times by flipping 0 s having different adjacent characters ; Size of the string ; Stores modified string after each iteration ; Iterate over the range [ 0 k ] ; Traverse the string S ; If '0' is present at 0 th index then replace it with 1 st index ; If '0' is present at the last index then replace it with last index - 1 character ; Otherwise , convert 0 s to 1 if the adjacent characters are different ; If during this iteration there is no change in the string then break this loop ; Update the string S ; Print the updated string ; Driver Code
def convertString ( S , k ) : NEW_LINE INDENT n = len ( S ) NEW_LINE temp = S NEW_LINE temp = list ( temp ) NEW_LINE for i in range ( k ) : NEW_LINE INDENT for j in range ( n - 1 ) : NEW_LINE INDENT if ( j == 0 and S [ j ] == '0' ) : NEW_LINE INDENT temp [ j ] = S [ j + 1 ] NEW_LINE DEDENT elif ( j == n - 1 and S [ j ] == '0' ) : NEW_LINE INDENT temp [ j ] = S [ j - 1 ] NEW_LINE DEDENT elif ( S [ j - 1 ] != S [ j + 1 ] and S [ j ] == '0' ) : NEW_LINE INDENT temp [ j ] = '1' NEW_LINE DEDENT DEDENT if ( S == temp ) : NEW_LINE INDENT break NEW_LINE DEDENT temp = ' ' . join ( temp ) NEW_LINE S = temp NEW_LINE DEDENT print ( S ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "10010001" NEW_LINE K = 1 NEW_LINE convertString ( S , K ) NEW_LINE DEDENT