Count minimum character replacements required such that given string satisfies the given conditions | Java program for the above approach ; Function that finds the minimum count of steps required to make the string special ; Stores the frequency of the left & right half of string ; Find frequency of left half ; Find frequency of left half ; Make all characters equal to character c ; Case 1 : For s [ i ] < s [ j ] ; Subtract all the characters on left side that are <= d ; Adding all characters on the right side that same as d ; Find minimum value of count ; Similarly for Case 2 : s [ i ] > s [ j ] ; Return the minimum changes ; Driver Code ; Given string S ; Function Call
import java . io . * ; import java . util . * ; class Main { public static int minChange ( String s , int n ) { int L [ ] = new int [ 26 ] ; int R [ ] = new int [ 26 ] ; for ( int i = 0 ; i < n / 2 ; i ++ ) { char ch = s . charAt ( i ) ; L [ ch - ' a ' ] ++ ; } for ( int i = n / 2 ; i < n ; i ++ ) { char ch = s . charAt ( i ) ; R [ ch - ' a ' ] ++ ; } int count = n ; for ( char ch = ' a ' ; ch <= ' z ' ; ch ++ ) { count = Math . min ( count , n - L [ ch - ' a ' ] - R [ ch - ' a ' ] ) ; } int change = n / 2 ; for ( int d = 0 ; d + 1 < 26 ; d ++ ) { change -= L [ d ] ; change += R [ d ] ; count = Math . min ( count , change ) ; } change = n / 2 ; for ( int d = 0 ; d + 1 < 26 ; d ++ ) { change -= R [ d ] ; change += L [ d ] ; count = Math . min ( change , count ) ; } return count ; } public static void main ( String [ ] args ) { String S = " aababc " ; int N = S . length ( ) ; System . out . println ( minChange ( S , N ) ) ; } }