Largest index for each distinct character in given string with frequency K | JavaScript 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
function maxSubString ( S , K , N ) { function maxSubString ( S , K , N ) { var freq = new Array ( 26 ) . fill ( 0 ) ; for ( var i = 0 ; i < N ; ++ i ) { freq [ S [ i ] . charCodeAt ( 0 ) - " " . charCodeAt ( 0 ) ] = 1 ; } var answer = [ ] ; for ( var i = 0 ; i < 26 ; ++ i ) { if ( freq [ i ] === 0 ) continue ; var ch = String . fromCharCode ( i + 97 ) ; var count = 0 ; var index = - 1 ; for ( var j = 0 ; j < N ; ++ j ) { if ( S [ j ] === ch ) count ++ ; if ( count === K ) index = j ; } answer . push ( [ ch , index ] ) ; } var flag = 0 ; for ( var i = 0 ; i < answer . length ; ++ i ) { if ( answer [ i ] [ 1 ] > - 1 ) { flag = 1 ; document . write ( answer [ i ] [ 0 ] + " " + answer [ i ] [ 1 ] + " " ) ; } } if ( flag === 0 ) document . write ( " " + " " ) ; } var S = " " ; var K = 2 ; var N = S . length ; maxSubString ( S . split ( " " ) , K , N ) ;