Minimum operations required to make the string satisfy the given condition | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 26 ; int minOperation ( string str , int len ) { int first [ MAX ] , last [ MAX ] ; for ( int i = 0 ; i < MAX ; i ++ ) { first [ i ] = -1 ; last [ i ] = -1 ; } for ( int i = 0 ; i < len ; i ++ ) { int index = ( str [ i ] - ' a ' ) ; if ( first [ index ] == -1 ) first [ index ] = i ; last [ index ] = i ; } int minOp = -1 ; for ( int i = 0 ; i < MAX ; i ++ ) { if ( first [ i ] == -1 first [ i ] == last [ i ] ) continue ; int cnt = len - ( last [ i ] - first [ i ] + 1 ) ; if ( minOp == -1 cnt < minOp ) minOp = cnt ; } return minOp ; } int main ( ) { string str = " abcda " ; int len = str . length ( ) ; cout << minOperation ( str , len ) ; return 0 ; }