Minimum characters required to be removed to sort binary string in ascending order | Function to find the minimum count of characters to be removed to make the string sorted in ascending order ; Length of given string ; Stores the first occurrence of '1' ; Stores the last occurrence of '0' ; Traverse the string to find the first occurrence of '1' ; Traverse the string to find the last occurrence of '0' ; Return 0 if the str have only one type of character ; Initialize count1 and count0 to count '1' s before lastIdx0 and '0' s after firstIdx1 ; Traverse the string to count0 ; Traverse the string to count1 ; Return the minimum of count0 and count1 ; Given string str ; Function call
function minDeletion ( str ) { let n = str . length ; let firstIdx1 = - 1 ; let lastIdx0 = - 1 ; for ( let i = 0 ; i < n ; i ++ ) { if ( str [ i ] == ' ' ) { firstIdx1 = i ; break ; } } for ( let i = n - 1 ; i >= 0 ; i -- ) { if ( str [ i ] == ' ' ) { lastIdx0 = i ; break ; } } if ( firstIdx1 == - 1 lastIdx0 == - 1 ) return 0 ; let count1 = 0 , count0 = 0 ; for ( let i = 0 ; i < lastIdx0 ; i ++ ) { if ( str [ i ] == ' ' ) { count1 ++ ; } } for ( let i = firstIdx1 + 1 ; i < n ; i ++ ) { if ( str [ i ] == ' ' ) { count0 ++ ; } } return Math . min ( count0 , count1 ) ; } let str = " " ; document . write ( minDeletion ( str ) ) ;