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
using System ; using System . Collections . Generic ; class GFG { static void minimumOperations ( string s , int n ) { Dictionary < char , List < int > > mp = new Dictionary < char , List < int > > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp . ContainsKey ( s [ i ] ) ) { mp [ s [ i ] ] . Add ( i ) ; } else { mp [ s [ i ] ] = new List < int > ( ) ; mp [ s [ i ] ] . Add ( i ) ; } } int ans = Int32 . MaxValue ; foreach ( KeyValuePair < char , List < int > > x in mp ) { int curr = 0 ; int prev = 0 ; bool first = true ; foreach ( int index in ( x . 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 ) ; } Console . Write ( ans ) ; } static void Main ( ) { string s = " YYXYZYXYZXY " ; int N = s . Length ; minimumOperations ( s , N ) ; } }