Array sum after replacing all occurrences of X by Y for Q queries | Function that print the sum of the array for Q queries ; Stores the frequencies of array elements ; Calculate the sum of the initial array and store the frequency of each element in map ; Iterate for all the queries ; Store query values ; Decrement the sum accordingly ; Increment the sum accordingly ; Set count of Y [ i ] ; Reset count of X [ i ] ; Print the sum ; Driver Code ; Function call
def sumOfTheArrayForQuery ( A , N , X , Y , Q ) : NEW_LINE INDENT sum = 0 NEW_LINE count = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += A [ i ] NEW_LINE if A [ i ] in count : NEW_LINE INDENT count [ A [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count [ A [ i ] ] = 1 NEW_LINE DEDENT DEDENT for i in range ( Q ) : NEW_LINE INDENT x = X [ i ] NEW_LINE y = Y [ i ] NEW_LINE if X [ i ] not in count : NEW_LINE INDENT count [ X [ i ] ] = 0 NEW_LINE DEDENT if Y [ i ] not in count : NEW_LINE INDENT count [ Y [ i ] ] = 0 NEW_LINE DEDENT sum -= ( count [ X [ i ] ] * X [ i ] ) NEW_LINE sum += count [ X [ i ] ] * Y [ i ] NEW_LINE count [ Y [ i ] ] += count [ X [ i ] ] NEW_LINE count [ X [ i ] ] = 0 NEW_LINE print ( sum , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 1 , 3 , 2 , ] NEW_LINE X = [ 2 , 3 , 5 ] NEW_LINE Y = [ 3 , 1 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE Q = len ( X ) NEW_LINE sumOfTheArrayForQuery ( arr , N , X , Y , Q ) NEW_LINE