Minimum operations required to make the string satisfy the given condition | Javascript implementation of the approach ; Function to return the minimum operations required ; To store the first and the last occurrence of all the characters ; Update the occurrences of the characters ; Only set the first occurrence if it hasn 't already been set ; To store the minimum operations ; If the frequency of the current character in the string is less than 2 ; Count of characters to be removed so that the string starts and ends at the current character ; Driver code
var MAX = 26 ; function minOperation ( str , len ) { var first = Array ( MAX ) . fill ( - 1 ) ; var last = Array ( MAX ) . fill ( - 1 ) ; for ( var i = 0 ; i < len ; i ++ ) { var index = ( str [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ) ; if ( first [ index ] == - 1 ) first [ index ] = i ; last [ index ] = i ; } var minOp = - 1 ; for ( var i = 0 ; i < MAX ; i ++ ) { if ( first [ i ] == - 1 first [ i ] == last [ i ] ) continue ; var cnt = len - ( last [ i ] - first [ i ] + 1 ) ; if ( minOp == - 1 cnt < minOp ) minOp = cnt ; } return minOp ; } var str = " " ; var len = str . length ; document . write ( minOperation ( str , len ) ) ;