Minimum substring reversals required to make given Binary String alternating | Function to count the minimum number of substrings required to be reversed to make the string S alternating ; Store count of consecutive pairs ; Stores the count of 1 s and 0 s ; Traverse through the string ; Increment 1 s count ; Increment 0 s count ; Increment K if consecutive same elements are found ; Increment 1 s count ; else : Increment 0 s count ; Check if it is possible or not ; Otherwise , print the number of required operations ; Driver code ; Function Call
def minimumReverse ( s , n ) : NEW_LINE INDENT k = 0 ; NEW_LINE l = 0 ; NEW_LINE sum1 = 0 ; NEW_LINE sum0 = 0 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT sum1 += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT sum0 += 1 ; NEW_LINE DEDENT if ( s [ i ] == s [ i - 1 ] and s [ i ] == '0' ) : NEW_LINE INDENT k += 1 ; NEW_LINE DEDENT elif ( s [ i ] == s [ i - 1 ] and s [ i ] == '1' ) : NEW_LINE INDENT l += 1 ; NEW_LINE DEDENT DEDENT if ( s [ 0 ] == '1' ) : NEW_LINE INDENT sum1 += 1 ; NEW_LINE sum0 += 1 ; NEW_LINE DEDENT if ( abs ( sum1 - sum0 ) > 1 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT return max ( k , l ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "10001" ; NEW_LINE N = len ( S ) ; NEW_LINE print ( minimumReverse ( S , N ) ) ; NEW_LINE DEDENT