Index of character depending on frequency count in string | JavaScript implementation of the approach ; Function to perform the queries ; L [ i ] [ j ] stores the largest i such that ith character appears exactly jth times in str [ 0. . . i ] ; F [ i ] [ j ] stores the smallest i such that ith character appears exactly jth times in str [ 0. . . i ] ; To store the frequency of each of the character of str ; Current character of str ; Update its frequency ; For every lowercase character of the English alphabet ; If it is equal to the character under consideration then update L [ ] [ ] and R [ ] [ ] as it is cnt [ j ] th occurrence of character k ; Only update L [ ] [ ] as k has not been occurred so only index has to be incremented ; Perform the queries ; Type 1 query ; Type 2 query ; Driver code ; Queries ; Perform the queries
let MAX = 26 ; function performQueries ( str , q , type , ch , freq ) { let n = str . length ; let L = new Array ( MAX ) ; let F = new Array ( MAX ) ; let cnt = new Array ( MAX ) ; for ( let i = 0 ; i < MAX ; i ++ ) { L [ i ] = new Array ( n ) ; F [ i ] = new Array ( n ) ; cnt [ i ] = 0 ; for ( let j = 0 ; j < n ; j ++ ) { L [ i ] [ j ] = 0 ; F [ i ] [ j ] = 0 ; } } for ( let i = 0 ; i < n ; i ++ ) { let k = str [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ; cnt [ k ] ++ ; for ( let j = 0 ; j < MAX ; j ++ ) { if ( k == j ) { L [ j ] [ cnt [ j ] ] = i ; F [ j ] [ cnt [ j ] ] = i ; } else L [ j ] [ cnt [ j ] ] = L [ j ] [ cnt [ j ] ] + 1 ; } } for ( let i = 0 ; i < q ; i ++ ) { if ( type [ i ] == 1 ) { document . write ( L [ ch [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ] [ freq [ i ] ] ) ; } else { document . write ( F [ ch [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ] [ freq [ i ] ] ) ; } document . write ( " " ) ; } } let str = " " ; let type = [ 1 , 2 ] ; let ch = [ ' ' , ' ' ] ; let freq = [ 2 , 2 ] ; let q = type . length ; performQueries ( str , q , type , ch , freq ) ;