You are given two arrays ‘A’ and ‘B’, each containing ‘N’ distinct integers. You are also given that ‘B’ is an anagram of ‘A’
Find the index mapping from array ‘A’ to array ‘B’, ie: for each element in ‘A’ you need to find the index in ‘B’ corresponding to that element.
An array ‘B’ is an anagram of an array ‘A’ means ‘B’ is made by randomizing the order of the elements in ‘A’.
For Example :If ‘N’ = 5, ‘A’ = {10, 20, 30, 40, 50} and ‘B’ = {20, 10, 40, 50, 30}
Then we will print {1, 0, 4, 2, 3} because:
A[0] occurs at 1st index in array B, A[1] occurs at 0th index, A[2] occurs at 4th index, A[3] occurs at 2nd index, A[4] occurs at 3rd index.
The first line contains a single integer ‘T’ denoting the number of test cases, then each test case follows:
The first line of each test case contains a single integer ‘N’, denoting the number of elements in the array.
The second line of each test case contains N distinct integers ‘A’, denoting the array elements of the first array.
The third line of each test case contains N distinct integers ‘B’, denoting the array elements of the second array.
Output Format :
For each test case, print the index mapping for the two anagram arrays.
Output for each test case will be printed in a separate line.
Note :
You are not required to print anything; it has already been taken care of. Just implement the function.
1 ≤ T ≤ 10
1 ≤ N ≤ 10000
-10^9 ≤ A[i], B[i] ≤ 10^9
Time limit: 1 sec
2
5
10 20 30 40 50
20 10 40 50 30
5
10 20 30 40 50
10 20 30 40 50
1 0 4 2 3
0 1 2 3 4
For test case 1 :
We will print {1, 0, 4, 2, 3} because:
A[0] occurs at 1st index in array B, A[1] occurs at 0th index, A[2] occurs at 4th index, A[3] occurs at 2nd index, A[4] occurs at 3rd index.
For test case 2 :
We will print {0, 1, 2, 3, 4} because:
Array ‘A’ is the same as array ‘B’, as they both have the same ordering of elements.
2
3
1 2 3
3 2 1
3
1 2 3
3 1 2
2 1 0
1 2 0
Store the information for the elements of array ‘B’ in a hash-map.
This is quite an easy problem. All we need to do is to store the elements of array ‘B’ in a hash-map so that the index corresponds to each element is stored in it. Now we can simply iterate through each element in array ‘A’, and find the index corresponding to that element in the hash-map. Here we won’t have to make any additional checks, this is because we are given that both the input arrays are anagrams, so checking for the elements existing in the hash-map will not necessarily be required.
The steps are as follows :
O( N ), where N denotes the size of the array.
We iterate through each element in both ‘A’ and ‘B’ exactly once.
Hence the time complexity is O( N ).
O( N ), where N denotes the size of the array.
Extra space is used to store the information about the index corresponding to each element in array B.
Hence the space complexity is O( N ).