LeetCode 0760. Find Anagram Mappings Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0760. Find Anagram Mappings

Description

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 ith 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 0th element of nums1 appears at nums2[1], and mapping[1] = 4 because the 1st 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 <= 100
  • nums2.length == nums1.length
  • 0 <= nums1[i], nums2[i] <= 105
  • nums2 is an anagram of nums1.

Solutions

Solution 1: Hash Table

We use a hash table d to store each element of the array nums2 and its corresponding index. Then we iterate through the array nums1, and for each element nums1[i], we retrieve its corresponding index from the hash table d and store it in the result array.

The time complexity is O(n) and the space complexity is O(n), where n is the length of the array.

PythonJavaC++GoTypeScript
class Solution: def anagramMappings(self, nums1: List[int], nums2: List[int]) -> List[int]: d = {x: i for i, x in enumerate(nums2)} return [d[x] for x in nums1](code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !