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

• Last Updated : 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] in arr[], with query[i].

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], find all of its occurrences in arr[], and replace it with query[i]

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 is present in the hashmap,
• If q is present in the hashmap, then extend the value of q to the value of q key.
• Else, add the value to q key with the value of q key.
• Delete the key-value pair for q 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++

 // C++ program for above approach#include using namespace std; // Function to replace all the// occurrences of a number with// another given number for Q queriesvoid update(vector& A, int N, vector >& Q){       // Creating a hashmap    map > 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)) {            if (hashmap.count(q))                hashmap[q].insert(hashmap[q].end(),                                     hashmap[q].begin(),                                     hashmap[q].end());            else                hashmap[q] = hashmap[q];            hashmap.erase(q);        }    }     // Creating map to store key value pairs    map 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 arr = { 2, 2, 5, 1 };    int N = arr.size();    vector > 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

Python3

 # 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 in hashmap:            if q in hashmap:                hashmap[q].extend(hashmap[q])            else:                hashmap[q] = hashmap[q]            del hashmap[q]     # 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)

Javascript


Output:
[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)

My Personal Notes arrow_drop_up