Minimum shifts of substrings of 1 s required to group all 1 s together in a given Binary string | Function to count indices substrings of 1 s need to be shifted such that all 1 s in the string are grouped together ; Stores first occurrence of '1 ; Stores last occurrence of '1 ; Count of 0 s between firstOne and lastOne ; Traverse the string to find the first and last occurrences of '1 ; Count number of 0 s present between firstOne and lastOne ; Print minimum operations ; Given string
def countShifts ( str ) : NEW_LINE ' NEW_LINE INDENT firstOne = - 1 NEW_LINE DEDENT ' NEW_LINE INDENT lastOne = - 1 NEW_LINE count = 0 NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( len ( str ) ) : NEW_LINE INDENT if ( str [ i ] == '1' ) : NEW_LINE INDENT if ( firstOne == - 1 ) : NEW_LINE INDENT firstOne = i NEW_LINE DEDENT lastOne = i NEW_LINE DEDENT DEDENT if ( ( firstOne == - 1 ) or ( firstOne == lastOne ) ) : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT for i in range ( firstOne , lastOne + 1 , 1 ) : NEW_LINE INDENT if ( str [ i ] == '0' ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT str = "00110111011" NEW_LINE countShifts ( str ) NEW_LINE