Maximum length prefix such that frequency of each character is atmost number of characters with minimum frequency | Java implementation to find the prefix of the s such that occurrence of each character is atmost the count of minimum frequency in the s ; Function to find the maximum possible prefix of the s ; Hash map to store the frequency of the characters in the s ; Iterate over the s to find the occurence of each Character ; Minimum frequency of the Characters ; Loop to find the count of minimum frequency in the hash - map ; Loop to find the maximum possible length of the prefix in the s ; Condition to check if the frequency is greater than minimum possible freq ; maxprefix s and its length . ; Driver code ; s is initialize . ; str is passed in MaxPrefix function .
import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static void MaxPrefix ( String s ) { Map < Character , Integer > Dict = new HashMap < > ( ) ; for ( char i : s . toCharArray ( ) ) { Dict . put ( i , Dict . getOrDefault ( i , 0 ) + 1 ) ; } int minfrequency = Integer . MAX_VALUE ; for ( Integer x : Dict . values ( ) ) { minfrequency = Math . min ( minfrequency , x ) ; } int countminFrequency = 0 ; for ( Map . Entry < Character , Integer > x : Dict . entrySet ( ) ) { if ( x . getValue ( ) == minfrequency ) countminFrequency += 1 ; } Map < Character , Integer > mapper = new HashMap < > ( ) ; int indi = 0 ; for ( char i : s . toCharArray ( ) ) { mapper . put ( i , mapper . getOrDefault ( i , 0 ) + 1 ) ; if ( mapper . get ( i ) > countminFrequency ) break ; indi += 1 ; } System . out . println ( s . substring ( 0 , indi ) ) ; } public static void main ( String [ ] args ) { String str = " aabcdaab " ; MaxPrefix ( str ) ; } }