Minimize characters to be changed to make the left and right rotation of a string same | Java program of the above approach ; Function to find the minimum characters to be removed from the string ; Initialize answer by N ; If length is even ; Frequency array for odd and even indices ; Store the frequency of the characters at even and odd indices ; Stores the most occuring frequency for even and odd indices ; Update the answer ; If length is odd ; Stores the frequency of the characters of the string ; Stores the most occuring character in the string ; Update the answer ; Driver code
class GFG { public static int getMinimumRemoval ( String str ) { int n = str . length ( ) ; int ans = n ; if ( n % 2 == 0 ) { int [ ] freqEven = new int [ 128 ] ; int [ ] freqOdd = new int [ 128 ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) { freqEven [ str . charAt ( i ) ] ++ ; } else { freqOdd [ str . charAt ( i ) ] ++ ; } } int evenMax = 0 , oddMax = 0 ; for ( char chr = ' a ' ; chr <= ' z ' ; chr ++ ) { evenMax = Math . max ( evenMax , freqEven [ chr ] ) ; oddMax = Math . max ( oddMax , freqOdd [ chr ] ) ; } ans = ans - evenMax - oddMax ; } else { int [ ] freq = new int [ 128 ] ; for ( int i = 0 ; i < n ; i ++ ) { freq [ str . charAt ( i ) ] ++ ; } int strMax = 0 ; for ( char chr = ' a ' ; chr <= ' z ' ; chr ++ ) { strMax = Math . max ( strMax , freq [ chr ] ) ; } ans = ans - strMax ; } return ans ; } public static void main ( String [ ] args ) { String str = " geeksgeeks " ; System . out . print ( getMinimumRemoval ( str ) ) ; } }