Pre - calculate the frequency array
freq = new Array ( MAX ) ; for ( let i = 0 ; i < MAX ; i ++ ) { freq [ i ] = new Array ( n ) ; for ( let j = 0 ; j < n ; j ++ ) { freq [ i ] [ j ] = 0 ; } } preCalculate ( str , n ) ; for ( let i = 0 ; i < q ; i ++ ) { document . write ( firstNonRepeating ( str , n , queries [ i ] [ 0 ] , queries [ i ] [ 1 ] ) + " " ) ; }