Find Anagram Mappings

To create the index mapping array that maps elements from nums1 to nums2, you can follow these steps:

  1. Create a Mapping of Elements in nums2 to Their Indices: Use a dictionary to record the indices of the elements in nums2. If there are duplicate elements, store the index of their last occurrence.

  2. Create the Result Array: Iterate through nums1, and for each element, find its corresponding index in nums2 using the dictionary created in step 1.

  3. Return the Result Array: The resulting array will contain the mapping from nums1 to nums2.

Code

1
2
3
4
5
class Solution:
    def anagramMappings(self, nums1: List[int], nums2: List[int]) -> List[int]:
        index_mapping = {num: idx for idx, num in enumerate(nums2)}
        result = [index_mapping[num] for num in nums1]
        return result

Example

  • nums1 = [12,28,46,32,50], nums2 = [50,12,32,46,28]
  • index_mapping = {50: 0, 12: 1, 32: 2, 46: 3, 28: 4}
  • result = [1,4,3,2,0]

Insights

  • Efficiency: By using a dictionary to map elements to indices, you can achieve an (O(n)) time complexity, where (n) is the length of the arrays.
  • Duplicates: This approach works with duplicate elements by mapping to the last occurrence of each element in nums2.
  • Constraints: This approach adheres to the constraints, specifically that nums2 is an anagram of nums1, so the elements in nums1 will always be found in nums2.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# @param {Integer[]} a
# @param {Integer[]} b
# @return {Integer[]}
def anagram_mappings(a, b)
    output = []
    hash = {}
    for i in (0..b.size-1)
       hash[b[i]] = i 
    end
    for i in (0..a.size-1)
        output << hash[a[i]]
    end
    output
end