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
def answerQueries ( arr , n , queries ) : NEW_LINE INDENT for i in range ( len ( queries ) ) : NEW_LINE INDENT ans = 0 NEW_LINE l = queries [ i ] [ 0 ] - 1 NEW_LINE r = queries [ i ] [ 1 ] - 1 NEW_LINE freq = dict ( ) NEW_LINE for j in range ( l , r + 1 ) : NEW_LINE INDENT freq [ arr [ j ] ] = freq . get ( arr [ j ] , 0 ) + 1 NEW_LINE DEDENT for i in freq : NEW_LINE INDENT ans += ( i * freq [ i ] ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE queries = [ [ 1 , 2 ] , [ 1 , 3 ] ] NEW_LINE answerQueries ( arr , n , queries ) NEW_LINE DEDENT