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
function minimumReverse ( s , n ) { let k = 0 , l = 0 ; let sum1 = 0 , sum0 = 0 ; for ( let i = 1 ; i < n ; i ++ ) { if ( s [ i ] == ' ' ) sum1 ++ ; else sum0 ++ ; if ( s [ i ] == s [ i - 1 ] && s [ i ] == ' ' ) k ++ ; else if ( s [ i ] == s [ i - 1 ] && s [ i ] == ' ' ) l ++ ; } if ( s [ 0 ] == ' ' ) sum1 ++ ; sum0 ++ ; if ( Math . abs ( sum1 - sum0 ) > 1 ) return - 1 ; return Math . max ( k , l ) ; } let S = " " ; let N = S . length ; document . write ( minimumReverse ( S , N ) ) ;