Minimum number of flips with rotation to make binary string alternating | Java program for the above approach ; Function that finds the minimum number of flips to make the binary string alternating if left circular rotation is allowed ; Initialize prefix arrays to store number of changes required to put 1 s at either even or odd position ; If i is odd ; Update the oddone and evenone count ; Else i is even ; Update the oddone and evenone count ; Initialize minimum flips ; Check if substring [ 0 , i ] is appended at end how many changes will be required ; Return minimum flips ; Driver Code ; Given String ; Length of given string ; Function call
import java . util . * ; class GFG { static int MinimumFlips ( String s , int n ) { int [ ] a = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { a [ i ] = ( s . charAt ( i ) == '1' ? 1 : 0 ) ; } int [ ] oddone = new int [ n + 1 ] ; int [ ] evenone = new int [ n + 1 ] ; oddone [ 0 ] = 0 ; evenone [ 0 ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 != 0 ) { oddone [ i + 1 ] = oddone [ i ] + ( a [ i ] == 1 ? 1 : 0 ) ; evenone [ i + 1 ] = evenone [ i ] + ( a [ i ] == 0 ? 1 : 0 ) ; } else { oddone [ i + 1 ] = oddone [ i ] + ( a [ i ] == 0 ? 1 : 0 ) ; evenone [ i + 1 ] = evenone [ i ] + ( a [ i ] == 1 ? 1 : 0 ) ; } } int minimum = Math . min ( oddone [ n ] , evenone [ n ] ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( n % 2 != 0 ) { minimum = Math . min ( minimum , oddone [ n ] - oddone [ i + 1 ] + evenone [ i + 1 ] ) ; minimum = Math . min ( minimum , evenone [ n ] - evenone [ i + 1 ] + oddone [ i + 1 ] ) ; } } return minimum ; } public static void main ( String [ ] args ) { String S = "000001100" ; int n = S . length ( ) ; System . out . print ( MinimumFlips ( S , n ) ) ; } }