text: Queries to print the character that occurs the maximum number of times in a given range | Function that answers all the queries ; Length of the string ; Number of queries ; Prefix array ; Iterate for all the characters ; Increase the count of the character ; Presum array for all 26 characters ; Update the prefix array ; Answer every query ; Range ; Iterate for all characters ; Times the lowercase character j occurs till r - th index ; Subtract the times it occurred till ( l - 1 ) th index ; Max times it occurs ; Print the answer ; Driver Code
code: function solveQueries ( str , query ) { let len = str . length ; let Q = query . length ; let pre = new Array ( len ) ; for ( let i = 0 ; i < len ; i ++ ) { pre [ i ] = new Array ( 26 ) ; for ( let j = 0 ; j < 26 ; j ++ ) { pre [ i ] [ j ] = 0 ; } } for ( let i = 0 ; i < len ; i ++ ) { pre [ i ] [ str [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ++ ; if ( i > 0 ) { for ( let j = 0 ; j < 26 ; j ++ ) pre [ i ] [ j ] += pre [ i - 1 ] [ j ] ; } } for ( let i = 0 ; i < Q ; i ++ ) { let l = query [ i ] [ 0 ] ; let r = query [ i ] [ 1 ] ; let maxi = 0 ; let c = ' ' ; for ( let j = 0 ; j < 26 ; j ++ ) { let times = pre [ r ] [ j ] ; if ( l > 0 ) times -= pre [ l - 1 ] [ j ] ; if ( times > maxi ) { maxi = times ; c = String . fromCharCode ( ' ' . charCodeAt ( 0 ) + j ) ; } } document . write ( " " + ( i + 1 ) + " " + c + " " ) ; } } let str = " " ; let query = [ [ 0 , 1 ] , [ 1 , 6 ] , [ 5 , 6 ] ] ; solveQueries ( str , query ) ;