Minimum characters required to be removed to make frequency of each character unique | Java program to implement the above approach ; Function to find the minimum count of characters required to be deleted to make frequencies of all characters unique ; Stores frequency of each distinct character of str ; Store frequency of each distinct character such that the largest frequency is present at the top ; Stores minimum count of characters required to be deleted to make frequency of each character unique ; Traverse the String ; Update frequency of str [ i ] ; Traverse the map ; Insert current frequency into pq ; Traverse the priority_queue ; Stores topmost element of pq ; Pop the topmost element ; If pq is empty ; Return cntChar ; If frequent and topmost element of pq are equal ; If frequency of the topmost element is greater than 1 ; Insert the decremented value of frequent ; Update cntChar ; Driver Code ; Stores length of str
import java . util . * ; class GFG { static int minCntCharDeletionsfrequency ( char [ ] str , int N ) { HashMap < Character , Integer > mp = new HashMap < > ( ) ; PriorityQueue < Integer > pq = new PriorityQueue < > ( ( x , y ) -> Integer . compare ( y , x ) ) ; int cntChar = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( mp . containsKey ( str [ i ] ) ) { mp . put ( str [ i ] , mp . get ( str [ i ] ) + 1 ) ; } else { mp . put ( str [ i ] , 1 ) ; } } for ( Map . Entry < Character , Integer > it : mp . entrySet ( ) ) { pq . add ( it . getValue ( ) ) ; } while ( ! pq . isEmpty ( ) ) { int frequent = pq . peek ( ) ; pq . remove ( ) ; if ( pq . isEmpty ( ) ) { return cntChar ; } if ( frequent == pq . peek ( ) ) { if ( frequent > 1 ) { pq . add ( frequent - 1 ) ; } cntChar ++ ; } } return cntChar ; } public static void main ( String [ ] args ) { String str = " abbbcccd " ; int N = str . length ( ) ; System . out . print ( minCntCharDeletionsfrequency ( str . toCharArray ( ) , N ) ) ; } }