You are given two arrays A and B, where B is an anagram of A (B contains the same elements as A but possibly in a different order). Each element in A also appears in B exactly once (for distinct elements). For duplicate values, map each occurrence in A to the corresponding occurrence in B.
Return an array P where P[i] is the index of A[i] in B. For duplicate values, use the first unclaimed occurrence of that value in B to ensure a valid mapping.
Build a hash map from each value in B to a list of its indices. Iterate through A. For each element, look up its list of indices in B, take the first one (pop from the front), and record it in the result array. This handles duplicates correctly by consuming one index at a time.
Time complexity is O(n) and space complexity is O(n) where n is the array length. The hash map allows O(1) lookup per element, and the queue-like handling of duplicate indices ensures each occurrence is uniquely mapped.
Edge cases include empty arrays (return empty array), single-element arrays, and arrays with duplicate values where multiple occurrences of the same number exist in both arrays.
Example Input & Output
Empty arrays
A[0]=12 at B[1]; A[1]=28 at B[4]; A[2]=46 at B[3]; A[3]=32 at B[2]; A[4]=50 at B[0]
Single element
Each element maps to its position in B
Duplicate values: first occurrence mapping
Algorithm Flow

Solution Approach
Given two arrays A and B where B is an anagram of A, find the mapping from A's elements to their positions in B. Build a hash map from B: for each element, store its index. Then for each element in A, look up its index in the map.
Since B contains the same elements as A, each element in A maps to exactly one index in B. The hash map provides O(1) lookup for each element.
Time complexity is O(n), space complexity is O(n).
Best Answers
import java.util.*;
class Solution {
public int[] solution(int[] A, int[] B) {
Map<Integer, Queue<Integer>> map = new HashMap<>();
for (int i = 0; i < B.length; i++) {
map.computeIfAbsent(B[i], k -> new LinkedList<>()).add(i);
}
int[] res = new int[A.length];
for (int i = 0; i < A.length; i++) {
res[i] = map.get(A[i]).poll();
}
return res;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
