Array sum after replacing all occurrences of X by Y for Q queries - GeeksforGeeks

27 May, 2021
Given an integer array arr[] and Q queries, the task is to find the sum of the array for each query of the following type: 
Each query contains 2 integers X and Y, where all the occurrences of X in arr[] are to be replaced by Y.
After each query, they print the sum of the array.
Examples:
Input: arr[] = { 1, 2, 1, 3, 2}, X[] = { 2, 3, 5 }, Y[] = { 3, 1, 2 } Output: 11 5 5 Explanation: After the 1st query, replace 2 with 3, arr[] = { 1, 3, 1, 3, 3 }, Sum = 11. After the 2nd query, replace 3 with 1, arr[] = { 1, 1, 1, 1, 1 }, Sum = 5. After the 3rd query, replace 5 with 2, arr[] = { 1, 1, 1, 1, 1 }, Sum = 5. 
Input: arr[] = { 12, 22, 11, 11, 2}, X[] = {2, 11, 22}, Y[] = {12, 222, 2} Output: 68 490 470 
Naive Approach: The simplest approach to solve the problem mentioned above is to traverse through the array and replace all the instances of X with Y for each query and calculate the sum. 
Time Complexity: O(N * Q)
Efficient Approach: To optimize the above method, follow the steps given below: 
Precompute and store the sum of the array in a variable S and store the frequencies of array elements in a Map count.
Then, do the following for each query: Find the frequency of X stored on the map.Subtract X * count[X] from S.Set count[Y] = count[X] and then count[X] = 0.Add Y * count[Y] to S.Print the updated value of S.
Find the frequency of X stored on the map.
Subtract X * count[X] from S.
Set count[Y] = count[X] and then count[X] = 0.
Add Y * count[Y] to S.
Print the updated value of S.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find the sum// of the array for the given Q queries #include <bits/stdc++.h>using namespace std; // Function that print the sum of// the array for Q queriesvoid sumOfTheArrayForQuery(int* A, int N,                           int* X, int* Y,                           int Q){    int sum = 0;     // Stores the frequencies    // of array elements    unordered_map<int, int> count;     // Calculate the sum of    // the initial array and    // store the frequency of    // each element in map     for (int i = 0; i < N; i++) {        sum += A[i];        count[A[i]]++;    }     // Iterate for all the queries     for (int i = 0; i < Q; i++) {        // Store query values        int x = X[i], y = Y[i];         // Decrement the sum accordingly        sum -= count[X[i]] * X[i];         // Increment the sum accordingly        sum += count[X[i]] * Y[i];         // Set count of Y[i]        count[Y[i]] += count[X[i]];         // Reset count of X[i]        count[X[i]] = 0;         // Print the sum        cout << sum << " ";    }} // Driver Codeint main(){    int arr[] = { 1, 2, 1, 3, 2 };    int X[] = { 2, 3, 5 };    int Y[] = { 3, 1, 2 };     int N = sizeof(arr) / sizeof(arr[0]);     int Q = sizeof(X) / sizeof(X[0]);     // Function call    sumOfTheArrayForQuery(arr, N, X, Y, Q);     return 0;}
// Java implementation to// find the sum of the array// for the given Q queriesimport java.util.*;class GFG{   // Function that print the sum of// the array for Q queriespublic static void sumOfTheArrayForQuery(int[] A, int N,                                         int[] X, int[] Y,                                         int Q){  int sum = 0;   // Stores the frequencies  // of array elements  // Create an empty hash map  HashMap<Integer,          Integer> count = new HashMap<>();   // Calculate the sum of  // the initial array and  // store the frequency of  // each element in map  for (int i = 0; i < N; i++)  {    sum += A[i];    if (count.containsKey(A[i]))    {      count.replace(A[i],      count.get(A[i]) + 1);    }    else    {      count.put(A[i], 1);    }  }   // Iterate for all the queries  for (int i = 0; i < Q; i++)  {    // Store query values    int x = X[i], y = Y[i];     if(count.containsKey(X[i]))    {      // Decrement the sum accordingly      sum -= count.get(X[i]) * X[i];      // Increment the sum accordingly      sum += count.get(X[i]) * Y[i];    }     // Set count of Y[i]    if(count.containsKey(Y[i]) &&       count.containsKey(X[i]))    {      count.replace(Y[i],      count.get(Y[i]) +      count.get(X[i]));    }     // Reset count of X[i]    if(count.containsKey(X[i]))    {      count.replace(X[i], 0);    }     // Print the sum    System.out.print(sum + " ");  }} // Driver codepublic static void main(String[] args){  int arr[] = {1, 2, 1, 3, 2};  int X[] = {2, 3, 5};  int Y[] = {3, 1, 2};   int N = arr.length;  int Q = X.length;   // Function call  sumOfTheArrayForQuery(arr, N,                        X, Y, Q);}} // This code is contributed by divyeshrabadiya07
# Python3 implementation to find the sum# of the array for the given Q queries # Function that print the sum of# the array for Q queriesdef sumOfTheArrayForQuery(A, N, X, Y, Q):         sum = 0     # Stores the frequencies    # of array elements    count = {}     # Calculate the sum of    # the initial array and    # store the frequency of    # each element in map    for i in range(N):        sum += A[i]                 if A[i] in count:            count[A[i]] += 1        else:            count[A[i]] = 1     # Iterate for all the queries    for i in range(Q):         # Store query values        x = X[i]        y = Y[i]                 if X[i] not in count:            count[X[i]] = 0        if Y[i] not in count:            count[Y[i]] = 0         # Decrement the sum accordingly        sum -= (count[X[i]] * X[i])         # Increment the sum accordingly        sum += count[X[i]] * Y[i]         # Set count of Y[i]        count[Y[i]] += count[X[i]]         # Reset count of X[i]        count[X[i]] = 0         # Print the sum        print(sum, end = " ") # Driver Codearr = [ 1, 2, 1, 3, 2, ]X = [ 2, 3, 5 ]Y = [ 3, 1, 2 ]N = len(arr)Q = len(X) # Function callsumOfTheArrayForQuery(arr, N, X, Y, Q) # This code is contributed by avanitrachhadiya2155
// C# implementation to// find the sum of the array// for the given Q queriesusing System;using System.Collections.Generic;class GFG{   // Function that print the sum of// the array for Q queriespublic static void sumOfTheArrayForQuery(int[] A, int N,                                         int[] X, int[] Y,                                         int Q){  int sum = 0;   // Stores the frequencies  // of array elements  // Create an empty hash map  Dictionary<int,             int> count = new Dictionary<int,                                         int>();   // Calculate the sum of  // the initial array and  // store the frequency of  // each element in map  for (int i = 0; i < N; i++)  {    sum += A[i];    if (count.ContainsKey(A[i]))    {      count[A[i]]= count[A[i]] + 1;    }    else    {      count.Add(A[i], 1);    }  }   // Iterate for all the queries  for (int i = 0; i < Q; i++)  {    // Store query values    int x = X[i], y = Y[i];     if(count.ContainsKey(X[i]))    {      // Decrement the sum accordingly      sum -= count[X[i]] * X[i];      // Increment the sum accordingly      sum += count[X[i]] * Y[i];    }     // Set count of Y[i]    if(count.ContainsKey(Y[i]) &&       count.ContainsKey(X[i]))    {      count[Y[i]] = count[Y[i]] +                    count[X[i]];    }     // Reset count of X[i]    if(count.ContainsKey(X[i]))    {      count[X[i]] = 0;    }     // Print the sum    Console.Write(sum + " ");  }} // Driver codepublic static void Main(String[] args){  int []arr = {1, 2, 1, 3, 2};  int []X = {2, 3, 5};  int []Y = {3, 1, 2};   int N = arr.Length;  int Q = X.Length;   // Function call  sumOfTheArrayForQuery(arr, N,                        X, Y, Q);}} // This code is contributed by Amit Katiyar
<script>  // Javascript implementation to find the sum// of the array for the given Q queries // Function that print the sum of// the array for Q queriesfunction sumOfTheArrayForQuery(A, N, X, Y, Q){    var sum = 0;     // Stores the frequencies    // of array elements    var count = new Map();     // Calculate the sum of    // the initial array and    // store the frequency of    // each element in map     for (var i = 0; i < N; i++) {        sum += A[i];        if(count.has(A[i]))            count.set(A[i], count.get(A[i])+1)        else            count.set(A[i], 1)    }     // Iterate for all the queries     for (var i = 0; i < Q; i++) {        // Store query values        var x = X[i], y = Y[i];         if(count.has(X[i]))        {            // Decrement the sum accordingly            sum -= count.get(X[i]) * X[i];                 // Increment the sum accordingly            sum += count.get(X[i]) * Y[i];        }         if(count.has(Y[i]))        {            // Set count of Y[i]            count.set(Y[i], count.get(Y[i]) + count.get(X[i]));        }         // Reset count of X[i]        count.set(X[i] , 0);         // Print the sum        document.write( sum + " ");    }} // Driver Codevar arr = [1, 2, 1, 3, 2];var X = [2, 3, 5 ];var Y = [3, 1, 2 ];var N = arr.length;var Q = X.length;// Function callsumOfTheArrayForQuery(arr, N, X, Y, Q);  </script>
11 5 5
 
Time Complexity: O(N), as each query has a computational complexity of O(1). Auxiliary Space: O(N)
avanitrachhadiya2155
divyeshrabadiya07
amit143katiyar
itsok
array-range-queries
cpp-map
frequency-counting
Arrays
Competitive Programming
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Prefix Sum Array - Implementation and Applications in Competitive Programming
Top 10 Algorithms and Data Structures for Competitive Programming