The problem asks to find an index mapping between two integer arrays nums1
and nums2
, where nums2
is an anagram of nums1
. This means the elements in nums2
are a permutation of the elements in nums1
. The mapping should indicate the index in nums2
where each element from nums1
appears.
The most efficient approach uses a hash map (dictionary in Python) to store the indices of each element in nums2
. We iterate through nums1
, and for each element, we look up its indices in the hash map. We then assign the index to the mapping array.
Time Complexity: O(N), where N is the length of the input arrays. We iterate through nums2
once to build the hash map, and then iterate through nums1
once to build the mapping array. Each operation within the loops (hash map insertion and lookup, list appending) takes constant time.
Space Complexity: O(N) in the worst case. The hash map could potentially store all the elements of nums2
if all elements are unique. The space used by the mapping array is also O(N).
from collections import defaultdict
class Solution:
def anagramMappings(self, nums1: list[int], nums2: list[int]) -> list[int]:
mapper = defaultdict(list) #Use list to handle duplicates
for i, num in enumerate(nums2):
mapper[num].append(i) #Append index to list for the number
result = []
for num in nums1:
result.append(mapper[num].pop(0)) #Pop the first index to handle multiple occurences
return result
Example Usage:
nums1 = [12, 28, 46, 32, 50]
nums2 = [50, 12, 32, 46, 28]
solution = Solution()
mapping = solution.anagramMappings(nums1, nums2)
print(mapping) # Output: [1, 4, 3, 2, 0]
nums1 = [84, 46]
nums2 = [84, 46]
mapping = solution.anagramMappings(nums1, nums2)
print(mapping) # Output: [0, 1]
import java.util.*;
class Solution {
public int[] anagramMappings(int[] nums1, int[] nums2) {
Map<Integer, Queue<Integer>> map = new HashMap<>(); //Use queue to handle duplicates and maintain order
for (int i = 0; i < nums2.length; i++) {
map.computeIfAbsent(nums2[i], k -> new LinkedList<>()).offer(i); //offer() to add to the queue
}
int[] result = new int[nums1.length];
for (int i = 0; i < nums1.length; i++) {
result[i] = map.get(nums1[i]).poll(); //poll() to remove from the queue
}
return result;
}
}
Example Usage (Java): You would need to create a Solution
object and call the anagramMappings
method with the input arrays, similar to the Python example. The output would be the same.
The Java code uses a Queue
(specifically LinkedList
) within the HashMap to handle potential duplicate numbers in nums2
. The offer()
method adds indices to the queue while poll()
removes the next available index, maintaining the order of occurrences. This addresses the case where a number appears multiple times in nums2
. The Python code uses list.pop(0)
to achieve the same effect.