Count minimum substring removals required to reduce string to a single distinct character | Function to find minimum removals required to convert given string to single distinct characters only ; Unordered map to store positions of characters X , Y and Z ; Update indices of X , Y , Z ; ; Stores the count of minimum removals ; Traverse the Map ; Count the number of removals required for current character ; Update the answer ; Print the answer ; Given string ; Size of string ; Function call
function minimumOperations ( s , n ) { var mp = { } ; for ( var i = 0 ; i < n ; i ++ ) { if ( mp . hasOwnProperty ( s [ i ] ) ) { mp [ s [ i ] ] . push ( i ) ; } else { mp [ s [ i ] ] = [ ] ; mp [ s [ i ] ] . push ( i ) ; } } var ans = 2147483647 ; for ( const [ key , value ] of Object . entries ( mp ) ) { var curr = 0 ; var prev = 0 ; var first = true ; for ( const index of value ) { if ( first ) { if ( index > 0 ) { curr ++ ; } prev = index ; first = false ; } else { if ( index !== prev + 1 ) { curr ++ ; } prev = index ; } } if ( prev !== n - 1 ) { curr ++ ; } ans = Math . min ( ans , curr ) ; } document . write ( ans ) ; } var s = " " ; var N = s . length ; minimumOperations ( s , N ) ;