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 ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxSubstring ( string & S , int K , int N ) { int freq [ 26 ] ; memset ( freq , 0 , sizeof freq ) ; for ( int i = 0 ; i < N ; ++ i ) { freq [ S [ i ] - ' a ' ] = 1 ; } vector < pair < char , int > > answer ; for ( int i = 0 ; i < 26 ; ++ i ) { if ( freq [ i ] == 0 ) continue ; char ch = 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 . push_back ( { ch , index } ) ; } int flag = 0 ; for ( int i = 0 ; i < ( int ) answer . size ( ) ; ++ i ) { if ( answer [ i ] . second > -1 ) { flag = 1 ; cout << answer [ i ] . first << " ▁ " << answer [ i ] . second << endl ; } } if ( flag == 0 ) cout << " - 1" << endl ; } int main ( ) { string S = " cbaabaacbcd " ; int K = 2 ; int N = S . length ( ) ; maxSubstring ( S , K , N ) ; return 0 ; }