Minimum operations required to make the string satisfy the given condition | Python implementation of the approach ; Function to return the minimum operations required ; To store the first and the last occurrence of all the characters ; Set the first and the last occurrence of all the characters to - 1 ; 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
MAX = 26 ; NEW_LINE def minOperation ( str , len ) : NEW_LINE INDENT first , last = [ 0 ] * MAX , [ 0 ] * MAX ; NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT first [ i ] = - 1 ; NEW_LINE last [ i ] = - 1 ; NEW_LINE DEDENT for i in range ( len ) : NEW_LINE INDENT index = ( ord ( str [ i ] ) - ord ( ' a ' ) ) ; NEW_LINE if ( first [ index ] == - 1 ) : NEW_LINE INDENT first [ index ] = i ; NEW_LINE DEDENT last [ index ] = i ; NEW_LINE DEDENT minOp = - 1 ; NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT if ( first [ i ] == - 1 or first [ i ] == last [ i ] ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT cnt = len - ( last [ i ] - first [ i ] + 1 ) ; NEW_LINE if ( minOp == - 1 or cnt < minOp ) : NEW_LINE INDENT minOp = cnt ; NEW_LINE DEDENT DEDENT return minOp ; NEW_LINE DEDENT str = " abcda " ; NEW_LINE len = len ( str ) ; NEW_LINE print ( minOperation ( str , len ) ) ; NEW_LINE