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 ; Prlet minimum operations ; Given string
function countShifts ( str ) { let firstOne = - 1 ; let lastOne = - 1 ; let count = 0 ; for ( let i = 0 ; i < str . length ; i ++ ) { if ( str [ i ] == ' ' ) { if ( firstOne == - 1 ) firstOne = i ; lastOne = i ; } } if ( ( firstOne == - 1 ) || ( firstOne == lastOne ) ) { Console . Write ( 0 ) ; return ; } for ( let i = firstOne ; i <= lastOne ; i ++ ) { if ( str [ i ] == ' ' ) { count ++ ; } } document . write ( count ) ; } let str = " " ; countShifts ( str ) ;