Minimum flips to make all 1 s in right and 0 s in left | Function to find the minimum count of flips required to make all 1 s on the right and all 0 s on the left of the given string ; Stores length of str ; Store count of 0 s in the string ; Traverse the string ; If current character is 0 ; Update zeros ; If count of 0 s in the string is 0 or n ; Store minimum count of flips required to make all 0 s on the left and all 1 s on the right ; Stores count of 1 s on the left of each index ; Stores count of flips required to make all 0 s on the left and all 1 s on the right ; Traverse the string ; If current character is 1 ; Update currOnes ; Update flips ; Update the minimum count of flips ; Driver Code
def minimumCntOfFlipsRequired ( str ) : NEW_LINE INDENT n = len ( str ) ; NEW_LINE zeros = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == '0' ) : NEW_LINE INDENT zeros += 1 ; NEW_LINE DEDENT DEDENT if ( zeros == 0 or zeros == n ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT minFlips = 10000001 ; NEW_LINE currOnes = 0 ; NEW_LINE flips = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == '1' ) : NEW_LINE INDENT currOnes += 1 ; NEW_LINE DEDENT flips = currOnes + ( zeros - ( i + 1 - currOnes ) ) ; NEW_LINE minFlips = min ( minFlips , flips ) ; NEW_LINE DEDENT return minFlips ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = "100101" ; NEW_LINE print ( minimumCntOfFlipsRequired ( str ) ) ; NEW_LINE DEDENT