Number of flips to make binary string alternate | Set 1 | Utility method to flip a character ; Utility method to get minimum flips when alternate string starts with expected char ; if current character is not expected , increase flip count ; flip expected character each time ; method return minimum flip to make binary string alternate ; return minimum of following two 1 ) flips when alternate string starts with 0 2 ) flips when alternate string starts with 1 ; Driver code to test above method
function flip ( ch ) { return ( ch == ' ' ) ? ' ' : ' ' ; } function getFlipWithStartingCharcter ( str , expected ) { let flipCount = 0 ; for ( let i = 0 ; i < str . length ; i ++ ) { if ( str . charAt ( i ) != expected ) flipCount ++ ; expected = flip ( expected ) ; } return flipCount ; } function minFlipToMakeStringAlternate ( str ) { return Math . min ( getFlipWithStartingCharcter ( str , ' ' ) , getFlipWithStartingCharcter ( str , ' ' ) ) ; } let str = " " ; document . write ( minFlipToMakeStringAlternate ( str ) ) ;