Find sum of product of every number and its frequency in given range | Function to solve queries ; Calculating answer for every query ; The end points of the ith query ; map for storing frequency ; Incrementing the frequency ; Iterating over map to find answer ; Adding the contribution of ith number ; Print answer ; Driver code
function answerQueries ( arr , n , queries ) { for ( var i = 0 ; i < queries . length ; i ++ ) { var ans = 0 ; var l = queries [ i ] [ 0 ] - 1 ; var r = queries [ i ] [ 1 ] - 1 ; var freq = new Map ( ) ; for ( var j = l ; j <= r ; j ++ ) { if ( freq . has ( arr [ j ] ) ) freq . set ( arr [ j ] , freq . get ( arr [ j ] ) + 1 ) else freq . set ( arr [ j ] , 1 ) } freq . forEach ( ( value , key ) => { ans += ( key * value ) ; } ) ; document . write ( ans + " " ) ; } } var arr = [ 1 , 2 , 1 ] ; var n = arr . length ; var queries = [ [ 1 , 2 ] , [ 1 , 3 ] ] ; answerQueries ( arr , n , queries ) ;