Find Anagram Mappings Problem
Description
LeetCode Problem 760.
You are given two integer arrays nums1 and nums2 where nums2 is an anagram of nums1. Both arrays may contain duplicates.
Return an index mapping array mapping from nums1 to nums2 where mapping[i] = j means the i^th element in nums1 appears in nums2 at index j. If there are multiple answers, return any of them.
An array a is an anagram of an array b means b is made by randomizing the order of the elements in a.
Example 1:
Input: nums1 = [12,28,46,32,50], nums2 = [50,12,32,46,28]
Output: [1,4,3,2,0]
Explanation: As mapping[0] = 1 because the 0^th element of nums1 appears at nums2[1], and mapping[1] = 4 because the 1^st element of nums1 appears at nums2[4], and so on.
Example 2:
Input: nums1 = [84,46], nums2 = [84,46]
Output: [0,1]
Constraints:
1 <= nums1.length <= 100nums2.length == nums1.length0 <= nums1[i], nums2[i] <= 10^5nums2is an anagram ofnums1.
Solution
Approach: Hash Map from Value to Index
For each nums1[i] we need any index j with nums2[j] == nums1[i]. Scanning nums2 for every element would take O(n2) time. Instead, go through nums2 once and store, for every value, an index where it appears. Then mapping[i] is simply the stored index of nums1[i].
Since nums2 is an anagram of nums1, every value of nums1 is in the map, so the lookup never fails.
With duplicates, later indices overwrite earlier ones in the map, so equal values in nums1 all map to the same index. That is still a valid answer: the problem only asks that nums1[i] appears in nums2 at index mapping[i], and any valid mapping is accepted. (If you want every index used exactly once, store a list of indices per value and take a different one each time.)
Complexity: O(n) time and O(n) extra space for the map.
class Solution:
def anagramMappings(self, nums1: List[int], nums2: List[int]) -> List[int]:
index_of = {x: j for j, x in enumerate(nums2)} # value -> an index where it appears in nums2
return [index_of[x] for x in nums1]