Largest index for each distinct character in given string with frequency K | Python3 implementation of the approach Function to find largest index for each distinct character occuring exactly K times . ; 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
def maxSubstring ( S , K , N ) : NEW_LINE INDENT def maxSubstring ( S , K , N ) : NEW_LINE INDENT freq = [ 0 for i in range ( 26 ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT freq [ ord ( S [ i ] ) - 97 ] = 1 NEW_LINE DEDENT answer = [ ] NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( freq [ i ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT ch = chr ( i + 97 ) NEW_LINE count = 0 NEW_LINE index = - 1 NEW_LINE for j in range ( N ) : NEW_LINE INDENT if ( S [ j ] == ch ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT if ( count == K ) : NEW_LINE INDENT index = j NEW_LINE DEDENT DEDENT answer . append ( [ ch , index ] ) NEW_LINE DEDENT flag = 0 NEW_LINE for i in range ( len ( answer ) ) : NEW_LINE INDENT if ( answer [ i ] [ 1 ] > - 1 ) : NEW_LINE INDENT flag = 1 NEW_LINE print ( answer [ i ] [ 0 ] , answer [ i ] [ 1 ] ) NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " cbaabaacbcd " NEW_LINE K = 2 NEW_LINE N = len ( S ) NEW_LINE maxSubstring ( S , K , N ) NEW_LINE DEDENT