Minimize characters to be changed to make the left and right rotation of a string same | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMinimumRemoval ( string str ) { int n = str . length ( ) ; int ans = n ; if ( n % 2 == 0 ) { vector < int > freqEven ( 128 ) ; vector < int > freqOdd ( 128 ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) { freqEven [ str [ i ] ] ++ ; } else { freqOdd [ str [ i ] ] ++ ; } } int evenMax = 0 , oddMax = 0 ; for ( char chr = ' a ' ; chr <= ' z ' ; chr ++ ) { evenMax = max ( evenMax , freqEven [ chr ] ) ; oddMax = max ( oddMax , freqOdd [ chr ] ) ; } ans = ans - evenMax - oddMax ; } else { vector < int > freq ( 128 ) ; for ( int i = 0 ; i < n ; i ++ ) { freq [ str [ i ] ] ++ ; } int strMax = 0 ; for ( char chr = ' a ' ; chr <= ' z ' ; chr ++ ) { strMax = max ( strMax , freq [ chr ] ) ; } ans = ans - strMax ; } return ans ; } int main ( ) { string str = " geeksgeeks " ; cout << getMinimumRemoval ( str ) ; }