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.
- 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++
#include <bits/stdc++.h>
using namespace std;
void update(vector< int >& A, int N, vector<vector< int > >& Q)
{
map< int , vector< int > > hashmap;
for ( int i = 0; i < N; ++i) {
hashmap[A[i]].push_back(i);
}
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]);
}
}
map< int , int > new_map;
for ( auto it = hashmap.begin(); it != hashmap.end();
++it) {
for ( auto index : it->second)
new_map[index] = it->first;
}
for ( auto it = new_map.begin(); it != new_map.end();
++it)
A[it->first] = it->second;
}
int 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;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static void update(List<Integer> A, int N,
List<List<Integer> > Q)
{
Map<Integer, List<Integer> > hashmap
= new HashMap<>();
for ( int i = 0 ; i < N; ++i) {
List<Integer> indices = hashmap.getOrDefault(
A.get(i), new ArrayList<>());
indices.add(i);
hashmap.put(A.get(i), indices);
}
for (List<Integer> q : Q) {
if (hashmap.containsKey(q.get( 0 ))) {
if (hashmap.containsKey(q.get( 1 ))) {
hashmap.get(q.get( 1 )).addAll(
hashmap.get(q.get( 0 )));
}
else {
hashmap.put(q.get( 1 ),
hashmap.get(q.get( 0 )));
}
hashmap.remove(q.get( 0 ));
}
}
Map<Integer, Integer> newMap = new HashMap<>();
for (Map.Entry<Integer, List<Integer> > entry :
hashmap.entrySet()) {
for ( int index : entry.getValue()) {
newMap.put(index, entry.getKey());
}
}
for (Map.Entry<Integer, Integer> entry :
newMap.entrySet()) {
A.set(entry.getKey(), entry.getValue());
}
}
public static void main(String[] args)
{
List<Integer> arr = Arrays.asList( 2 , 2 , 5 , 1 );
int N = arr.size();
List<List<Integer> > query = Arrays.asList(
Arrays.asList( 2 , 4 ), Arrays.asList( 5 , 2 ));
update(arr, N, query);
System.out.print(arr.toString());
}
}
|
Python3
def update(A, N, Q):
hashmap = {a:[] for a in A}
for i in range (N):
hashmap[A[i]].append(i)
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 ]]
new_map = {}
for key, value in hashmap.items():
for index in value:
new_map[index] = key
for key in new_map.keys():
A[key] = new_map[key]
if __name__ = = '__main__' :
arr = [ 2 , 2 , 5 , 1 ]
N = len (arr)
query = [[ 2 , 4 ], [ 5 , 2 ]]
update(arr, N, query)
print (arr)
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class GFG {
static void update(List< int > A, int N, List<List< int >> Q)
{
var hashmap = new Dictionary< int , List< int >>();
for ( int i = 0; i < N; ++i)
{
if (!hashmap.ContainsKey(A[i]))
hashmap[A[i]] = new List< int >();
hashmap[A[i]].Add(i);
}
for ( int i = 0; i < Q.Count; i++)
{
if (hashmap.ContainsKey(Q[i][0]))
{
if (hashmap.ContainsKey(Q[i][1]))
{
hashmap[Q[i][1]].AddRange(hashmap[Q[i][0]]);
}
else
{
hashmap[Q[i][1]] = hashmap[Q[i][0]];
}
hashmap.Remove(Q[i][0]);
}
}
var newMap = new Dictionary< int , int >();
foreach ( var entry in hashmap)
{
for ( int j = 0; j < entry.Value.Count; j++)
{
newMap[entry.Value[j]] = entry.Key;
}
}
for ( int i = 0; i < A.Count; i++)
{
if (newMap.ContainsKey(i))
{
A[i] = newMap[i];
}
}
}
public static void Main( string [] args)
{
List< int > arr = new List< int > { 2, 2, 5, 1 };
int N = arr.Count;
List<List< int >> query = new List<List< int >> {
new List< int > { 2, 4 },
new List< int > { 5, 2 }
};
update(arr, N, query);
Console.WriteLine( string .Join( " " , arr));
}
}
|
Javascript
<script>
function update(A, N, Q)
{
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])
}
}
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])
}
}
let new_map = new Map()
for (x of hashmap)
for (index of x[1])
new_map.set(index, x[0])
for (key of new_map.keys())
A[key] = new_map.get(key)
document.write(`[ ${A}] `)
}
let arr = [2, 2, 5, 1]
let N = arr.length
let query = [[2, 4], [5, 2]]
update(arr, N, query)
</script>
|
Time Complexity: O(N+Q), where N is size of arr[] and Q is size of query[][].
Auxiliary Space: O(N)