Find Anagram Mappings
Problem
Given arrays A and B where B is an anagram of A, return an array mapping where mapping[i] is the index in B of A[i].
A=[12,28,46,32,50], B=[50,12,32,46,28][1,4,3,2,0]def anagramMappings(A, B):
idx = {v: i for i, v in enumerate(B)}
return [idx[v] for v in A]
function anagramMappings(A, B) {
const idx = new Map();
B.forEach((v, i) => idx.set(v, i));
return A.map(v => idx.get(v));
}
int[] anagramMappings(int[] A, int[] B) {
Map<Integer,Integer> idx = new HashMap<>();
for (int i = 0; i < B.length; i++) idx.put(B[i], i);
int[] res = new int[A.length];
for (int i = 0; i < A.length; i++) res[i] = idx.get(A[i]);
return res;
}
vector<int> anagramMappings(vector<int>& A, vector<int>& B) {
unordered_map<int,int> idx;
for (int i = 0; i < (int)B.size(); i++) idx[B[i]] = i;
vector<int> res;
for (int v : A) res.push_back(idx[v]);
return res;
}
Explanation
For each value in A we need to know where it lives in B. Instead of searching B from scratch every time, we build a single value-to-index lookup from B first, then read off answers instantly.
We walk B once and record idx[value] = i for each position i. Now idx answers "at what index does this value sit in B?" in constant time.
Then we map over A: for every element v, the answer is just idx[v]. Collecting those gives the full mapping array. Since B is an anagram of A, every value is guaranteed to be found.
Example: A=[12,28,46,32,50], B=[50,12,32,46,28]. The map says 12→1, 28→4, 46→3, 32→2, 50→0. Reading those for each A[i] gives [1,4,3,2,0].
Building the map is one pass and each lookup is instant, so the whole thing is linear instead of quadratic.