Map elements of an array to elements of another array

• Difficulty Level : Easy
• Last Updated : 16 Nov, 2018

Given two arrays A and B of positive integers, elements of array B can be mapped to elements of array A only if both the elements have same value. The task is to compute the positions in array A to which elements of array B will be mapped. Print NA if mapping for a particular element cannot be done.
Note: For one position only one integer can be mapped.

Examples:

Input: A[] = {1, 5, 2, 4, 4, 3}, B[] = {1, 2, 5, 1}
Output: 0 2 1 NA
B, B and B can be mapped to A, A and A respectively but B cannot be mapped to any element of A because the only ‘1’ in A has already been mapped

Input: A[] = {2, 1, 2, 3, 3, 4, 2, 4, 1}, B[] = {1, 2, 5, 1, 2, 4, 2, 3, 2, 1}
Output: 1 0 NA 8 2 5 6 3 NA NA

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

The idea is to use a hash table where keys are elements of A[] and values are indexes of these elements. Since there can be more than one occurrences of an element, we use a list of items as values in the hash table.

Below is the implementation of the above problem:

 // C++ program to map elements of an array// to equal elements of another array#include using namespace std;  // Function to print the mapping of elementsvoid printMapping(int A[], int B[], int N, int M){     // Create a hash table where all indexes are    // stored for a given value   unordered_map> m;   for (int i=0; i 0)       {           cout << m[B[i]].front() << " ";           m[B[i]].pop_front();       }         else // No mapping found       {           cout << "NA ";       }   }}  // Driver codeint main(){    int A[] = {2, 1, 2, 3, 3, 4, 2, 4, 1};    int N = sizeof(A) / sizeof(A);    int B[] = {1, 2, 5, 1, 2, 4, 2, 3, 2, 1};    int M = sizeof(B) / sizeof(B);    printMapping(A, B, N, M);        return 0;}
Output:
1 0 NA 8 2 5 6 3 NA NA

My Personal Notes arrow_drop_up