Count minimum substring removals required to reduce string to a single distinct character | C ++ program for the above approach ; 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 ; Driver Code ; Given string ; Size of string ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumOperations ( string s , int n ) { unordered_map < char , vector < int > > mp ; for ( int i = 0 ; i < n ; i ++ ) { mp [ s [ i ] ] . push_back ( i ) ; } int ans = INT_MAX ; for ( auto x : mp ) { int curr = 0 ; int prev = 0 ; bool first = true ; for ( int index : ( x . second ) ) { if ( first ) { if ( index > 0 ) { curr ++ ; } prev = index ; first = false ; } else { if ( index != prev + 1 ) { curr ++ ; } prev = index ; } } if ( prev != n - 1 ) { curr ++ ; } ans = min ( ans , curr ) ; } cout << ans ; } int main ( ) { string s = " YYXYZYXYZXY " ; int N = s . length ( ) ; minimumOperations ( s , N ) ; return 0 ; }