Largest index for each distinct character in given string with frequency K | Java implementation of the approach ; Function to find largest index for each distinct character occuring exactly K times . ; finding all characters present in S ; Finding all distinct characters in S ; vector to store result for each character ; loop through each lower case English character ; if current character is absent in s ; getting current character ; finding count of character ch in S ; to store max Index encountred so far ; printing required result ; If no such character exists , print - 1 ; Driver code
import java . util . * ; class GFG { static class pair { char first ; int second ; public pair ( char first , int second ) { this . first = first ; this . second = second ; } } static void maxSubString ( char [ ] S , int K , int N ) { int [ ] freq = new int [ 26 ] ; for ( int i = 0 ; i < N ; ++ i ) { freq [ S [ i ] - ' a ' ] = 1 ; } Vector < pair > answer = new Vector < pair > ( ) ; for ( int i = 0 ; i < 26 ; ++ i ) { if ( freq [ i ] == 0 ) continue ; char ch = ( char ) ( i + 97 ) ; int count = 0 ; int index = - 1 ; for ( int j = 0 ; j < N ; ++ j ) { if ( S [ j ] == ch ) count ++ ; if ( count == K ) index = j ; } answer . add ( new pair ( ch , index ) ) ; } int flag = 0 ; for ( int i = 0 ; i < ( int ) answer . size ( ) ; ++ i ) { if ( answer . get ( i ) . second > - 1 ) { flag = 1 ; System . out . print ( answer . get ( i ) . first + " ▁ " + answer . get ( i ) . second + "NEW_LINE"); } } if ( flag == 0 ) System . out . print ( " - 1" + "NEW_LINE"); } public static void main ( String [ ] args ) { String S = " cbaabaacbcd " ; int K = 2 ; int N = S . length ( ) ; maxSubString ( S . toCharArray ( ) , K , N ) ; } }