760. Find Anagram Mappings
Given two listsAandB, andBis an anagram ofA.Bis an anagram ofAmeansBis made by randomizing the order of the elements inA.
We want to find anindex mappingP, fromAtoB. A mappingP[i] = jmeans theith element inAappears inBat indexj.
These listsAandBmay contain duplicates. If there are multiple answers, output any of them.
For example, given
A = [12, 28, 46, 32, 50]
B = [50, 12, 32, 46, 28]We should return
[1, 4, 3, 2, 0]as P[0] = 1because the0th element ofAappears atB[1], andP[1] = 4because the1st element ofAappears atB[4], and so on.
Note:
A, Bhave equal lengths in range[1, 100].A[i], B[i]are integers in range[0, 10^5].
Thoughts:1
(K,V) : (value, list of (index of B))
get the value of A[i], retrieve the last element from the mapped list
Code
class Solution {
public int[] anagramMappings(int[] A, int[] B) {
int [] result = new int [A.length];
Map<Integer, List<Integer>> map = new HashMap<>();
for( int i = 0; i < B.length; i++){
map.computeIfAbsent(B[i], k->new ArrayList<>()).add(i);
}
for( int i = 0; i < A.length; i++){
result[i] = map.get(A[i]).remove(map.get(A[i]).size() - 1);
}
return result;
}
}Use Sorting:
fastest C++:
fastest Java
fastest Python
Last updated
Was this helpful?