Count minimum substring removals required to reduce string to a single distinct character | Java 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
import java . util . * ; class GFG { static void minimumOperations ( String s , int n ) { HashMap < Character , List < Integer > > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp . containsKey ( s . charAt ( i ) ) ) { mp . get ( s . charAt ( i ) ) . add ( i ) ; } else { mp . put ( s . charAt ( i ) , new ArrayList < Integer > ( Arrays . asList ( i ) ) ) ; } } int ans = Integer . MAX_VALUE ; for ( Map . Entry < Character , List < Integer > > x : mp . entrySet ( ) ) { int curr = 0 ; int prev = 0 ; boolean first = true ; for ( Integer index : ( x . getValue ( ) ) ) { 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 ) ; } System . out . print ( ans ) ; } public static void main ( String [ ] args ) { String s = " YYXYZYXYZXY " ; int N = s . length ( ) ; minimumOperations ( s , N ) ; } }