Replace all occurrences of X by Y for Q queries in given Array

10 Nov, 2021
Given an array arr[] and an 2D array query[][] consisting of queries. For each query q, replace all occurrences of query[i][0] in arr[], with query[i][1].
Examples:
Input: arr[] = {2, 2, 5, 1} query = {{2, 4}, {5, 2}}Output: {4, 4, 2, 1}Explanation: Following are the operations performed in the given array according to the queries given.For first query {2, 4}, replace all occurrences of 2 in arr[] with 4. arr[] will be updated as arr[] = {4, 4, 5, 1}. For second query {5, 2}, replace all occurrences of 5 with 2. arr[] will be updated as arr[] = {4, 4, 2, 1}.
Input: arr[] ={2, 2, 5}, query = {{4, 5}, {2, 5}, {1, 3}, {2, 4}}Output: {5, 5, 5}
Naive Approach: (Brute-Force solution) Naive approach would be to iterate through all the queries of query, and for each query[i][0], find all of its occurrences in arr[], and replace it with query[i][1]. 
Time Complexity: O(N*Q), where N is the size of arr[] and Q is size of query[][]. Auxiliary Space: O(1)
Efficient Approach: A better solution would be to use a Hashmap, that stores indexes of the element in the array. Follow the steps below to solve the given problem. 
Initialize a hashmap = {}, and fill it up with array element as key, and list indicating its position in the array.
Iterate through each query q of query[][].If q[0] is present in the hashmap,If q[1] is present in the hashmap, then extend the value of q[0] to the value of q[1] key.Else, add the value to q[1] key with the value of q[0] key.Delete the key-value pair for q[0] from the hashmap.
If q[0] is present in the hashmap,If q[1] is present in the hashmap, then extend the value of q[0] to the value of q[1] key.Else, add the value to q[1] key with the value of q[0] key.Delete the key-value pair for q[0] from the hashmap.
If q[1] is present in the hashmap, then extend the value of q[0] to the value of q[1] key.
Else, add the value to q[1] key with the value of q[0] key.
Delete the key-value pair for q[0] from the hashmap.
Now, create a new variable map = {}, from the values of the hashmap.
Interchange the key-value pairs, so that map will contain key-value pairs as index, and key value of hashmap.
Using this map, we can now update the original array arr, by updating values at each position of arr, with the value from map.
Below is the implementation of the above approach: 
C++
Python3
Javascript
// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function to replace all the// occurrences of a number with// another given number for Q queriesvoid update(vector<int>& A, int N, vector<vector<int> >& Q){       // Creating a hashmap    map<int, vector<int> > hashmap;    for (int i = 0; i < N; ++i) {        hashmap[A[i]].push_back(i);    }     // Iterating with q in given queries    for (auto q : Q) {        if (hashmap.count(q[0])) {            if (hashmap.count(q[1]))                hashmap[q[1]].insert(hashmap[q[1]].end(),                                     hashmap[q[0]].begin(),                                     hashmap[q[0]].end());            else                hashmap[q[1]] = hashmap[q[0]];            hashmap.erase(q[0]);        }    }     // Creating map to store key value pairs    map<int, int> new_map;    for (auto it = hashmap.begin(); it != hashmap.end();         ++it) {        for (auto index : it->second)            new_map[index] = it->first;    }     // Updating the main array with final values    for (auto it = new_map.begin(); it != new_map.end();         ++it)        A[it->first] = it->second;} // Driver Codeint main(){    vector<int> arr = { 2, 2, 5, 1 };    int N = arr.size();    vector<vector<int> > query = { { 2, 4 }, { 5, 2 } };    update(arr, N, query);    for (int i = 0; i < N; ++i) {        cout << arr[i] << " ";    }    return 0;}     // This code is contributed by rakeshsahni
# Python program for above approach # Function to replace all the# occurrences of a number with# another given number for Q queriesdef update(A, N, Q):      # Creating a hashmap    hashmap = {a:[] for a in A}    for i in range(N):        hashmap[A[i]].append(i)         # Iterating with q in given queries    for q in Q:        if q[0] in hashmap:            if q[1] in hashmap:                hashmap[q[1]].extend(hashmap[q[0]])            else:                hashmap[q[1]] = hashmap[q[0]]            del hashmap[q[0]]     # Creating map to store key value pairs    new_map = {}    for key, value in hashmap.items():        for index in value:            new_map[index] = key                 # Updating the main array with final values    for key in new_map.keys():        A[key] = new_map[key]     # Driver Codeif __name__ == '__main__':  arr = [2, 2, 5, 1]  N = len(arr)  query = [[2, 4], [5, 2]]  update(arr, N, query)  print(arr)
<script>// Javascript program for above approach // Function to replace all the// occurrences of a number with// another given number for Q queriesfunction update(A, N, Q){       // Creating a hashmap    let hashmap = new Map();    for(let i = 0; i < N; i++){        if(hashmap.has(A[i])){          let temp = hashmap.get(A[i])          temp.push(i)          hashmap.set(A[i], temp)        }else{          hashmap.set(A[i], [i])        }     }         // Iterating with q in given queries    for(q of Q){        if(hashmap.has(q[0])){            if (hashmap.has(q[1])){                let temp = hashmap.get(q[1]);                                 temp = [...temp, ...hashmap.get(q[0])]                hashmap.set(q[1], temp);            }            else{                hashmap.set(q[1], hashmap.get(q[0]))            }            hashmap.delete(q[0])        }    }     // Creating map to store key value pairs    let new_map = new Map()    for(x of hashmap)        for(index of x[1])            new_map.set(index, x[0])                 // Updating the main array with final values    for(key of new_map.keys())        A[key] = new_map.get(key)    document.write(`[ ${A}] `)}     // Driver Codelet arr = [2, 2, 5, 1]let N = arr.lengthlet query = [[2, 4], [5, 2]]update(arr, N, query) // This code is contributed by gfgking.</script>
[4, 4, 2, 1]
 
Time Complexity: O(max(N, Q)), where N is size of arr[] and Q is size of query[][]. Auxiliary Space: O(N)
rakeshsahni
gfgking
simmytarika5
array-range-queries
Arrays
Mathematical
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.