Largest index for each distinct character in given string with frequency K | C # 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 ; 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
using System ; using System . Collections . Generic ; class GFG { class pair { public char first ; public 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 ; } List < pair > answer = new List < 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 . Count ; ++ i ) { if ( answer [ i ] . second > - 1 ) { flag = 1 ; Console . Write ( answer [ i ] . first + " ▁ " + answer [ i ] . second + " STRNEWLINE " ) ; } } if ( flag == 0 ) Console . Write ( " - 1" + " STRNEWLINE " ) ; } public static void Main ( String [ ] args ) { String S = " cbaabaacbcd " ; int K = 2 ; int N = S . Length ; maxSubString ( S . ToCharArray ( ) , K , N ) ; } }