Skip to content
Related Articles

Related Articles

Merge two Maps of Array into one sorted Map of Array

View Discussion
Improve Article
Save Article
  • Last Updated : 25 Feb, 2022
View Discussion
Improve Article
Save Article

Given two maps map1 and map2 having a string as the key and arrays of integers as values, the task is to merge them in one map such that if a key is common in both the maps, the respective arrays should be merged.

Examples:

Input: map1 = { (“key1”, {0, 1}), (“key2”, {0, 1}) }, map2 = { (“key2”, {1, 2}) };
Output: { (key1, {0, 1}), (key2, {0, 1, 2}) }
Explanation: After merging key1 array will become {0, 1} and for key2 after merging array will become {0, 1, 2} 

Input: map1 = {(“key1”, {0, 1})}, map2 = {(“key2”, {1, 2})};
Output: {(key1, [0, 1]), (key2, [1, 2])}

 

Approach: The solution to the problem is based on the concept of merging two arrays. Follow the steps mentioned below:

  • Create a map to store the merged maps
  • Traverse map1 and store all the key-value pairs in map1.
  • Traverse map2 and:
    • If the key of map2 does not exists in map1, just insert this key value pair in map1
    • If the key of map2 exists in map1,
      • Take the array of map1 and array of map2
      • Sort both the arrays, and
      • Merge them using approach mentioned in merge two arrays.
  • Return the map3 at the end.

Below is the implementation of the above approach.

C++




// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to merge arrays
vector<int> mergeArrays(vector<int>& a, vector<int>& b,
                        int n, int m)
{
    vector<int> mergedArray;
 
    // Declaring a map.
    // Using map as a inbuilt tool
    // to store elements in sorted order.
    map<int, bool> mp;
 
    // Inserting values to a map.
    for (int i = 0; i < n; i++)
        mp[a[i]] = true;
 
    for (int i = 0; i < m; i++)
        mp[b[i]] = true;
 
    // Printing keys of the map.
    for (auto i : mp)
        mergedArray.push_back(i.first);
    return mergedArray;
}
 
// Function to merge maps
map<string, vector<int> >
mergeMap(map<string, vector<int> >& map1,
         map<string, vector<int> >& map2)
{
    map<string, vector<int> > map3;
    map3.insert(map1.begin(), map1.end());
 
    for (auto itr : map2) {
        if (map3.find(itr.first) == map3.end())
            map3.insert({ itr.first, itr.second });
        else {
            auto temp_itr = map3.find(itr.first);
            vector<int> arr = mergeArrays(
                itr.second, temp_itr->second,
                itr.second.size(),
                temp_itr->second.size());
            map3[itr.first] = arr;
        }
    }
    return map3;
}
 
// Driver code
int main()
{
    map<string, vector<int> > map1, map2, map3;
    map1.insert({ "key1", { 0, 1 } });
    map1.insert({ "key2", { 0, 1 } });
    map2.insert({ "key2", { 1, 2 } });
 
    // Function call
    map3 = mergeMap(map1, map2);
 
    for (auto itr : map3) {
        cout << "\"" << itr.first << "\", { ";
        for (auto x : itr.second)
            cout << x << " ";
        cout << "}\n";
    }
    return 0;
}


Javascript




<script>
    // JavaScript code to implement the approach
 
    // Function to merge arrays
    const mergeArrays = (a, b, n, m) => {
        let mergedArray = [];
 
        // Declaring a map.
        // Using map as a inbuilt tool
        // to store elements in sorted order.
        let mp = {};
 
        // Inserting values to a map.
        for (let i = 0; i < n; i++)
            mp[a[i]] = true;
 
        for (let i = 0; i < m; i++)
            mp[b[i]] = true;
 
        // Printing keys of the map.
        for (let i in mp)
            mergedArray.push(i);
        return mergedArray;
    }
 
    // Function to merge maps
    const mergeMap = (map1, map2) => {
        let map3 = {};
        for (let itm in map1) map3[itm] = map1[itm];
 
        for (let itr in map2) {
            if (!(itr in map3))
                map3[itr] = map2[itr];
            else {
                let arr = mergeArrays(map2[itr], map3[itr], map2[itr].length, map3[itr].length);
 
                map3[itr] = arr;
            }
        }
        return map3;
    }
 
    // Driver code
 
    let map1 = {}, map2 = {}, map3 = {};
 
    map1["key1"] = [0, 1];
    map1["key2"] = [0, 1];
    map2["key2"] = [1, 2];
 
    // Function call
    map3 = mergeMap(map1, map2);
 
    for (let itr in map3) {
        document.write(`"${itr}", { `);
        for (let x in map3[itr])
            document.write(`${map3[itr][x]} `);
        document.write("}<br/>");
    }
 
// This code is contributed by rakeshsahni
 
</script>


 
 

Output

"key1", { 0 1 }
"key2", { 0 1 2 }

 

Time Complexity: O(N * log N + M * log M)
Auxiliary Space: O(M + N)

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!