Minimum number of characters required to be removed such that every character occurs same number of times | Java program for the above approach ; Function to find minimum number of character removals required to make frequency of all distinct characters the same ; Stores the frequency of each character ; Traverse the string ; Stores the frequency of each charachter in sorted order ; Insert the frequency in multiset ; Stores the count of elements required to be removed ; Stores the size of multiset ; Traverse the multiset ; Update the ans ; Increment i by 1 ; Return ; Driver Code ; Input
import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static int minimumDeletion ( String s , int n ) { HashMap < Character , Integer > countMap = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { char ch = s . charAt ( i ) ; countMap . put ( ch , countMap . getOrDefault ( ch , 0 ) + 1 ) ; } ArrayList < Integer > countMultiset = new ArrayList < > ( countMap . values ( ) ) ; Collections . sort ( countMultiset ) ; int ans = Integer . MAX_VALUE ; int i = 0 ; int m = countMultiset . size ( ) ; for ( int j : countMultiset ) { ans = Math . min ( ans , n - ( m - i ) * j ) ; i ++ ; } return ans ; } public static void main ( String [ ] args ) { String S = " geeksforgeeks " ; int N = S . length ( ) ; System . out . println ( minimumDeletion ( S , N ) ) ; } }