Find Anagram Mappings - Problem

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.

Input & Output

Example 1 — Basic Mapping
$ Input: nums1 = [12,28,46,32,50], nums2 = [50,12,32,46,28]
Output: [1,4,3,2,0]
💡 Note: 12 maps to index 1, 28 maps to index 4, 46 maps to index 3, 32 maps to index 2, 50 maps to index 0
Example 2 — With Duplicates
$ Input: nums1 = [84,46], nums2 = [84,46]
Output: [0,1]
💡 Note: nums1[0]=84 maps to nums2[0]=84, nums1[1]=46 maps to nums2[1]=46
Example 3 — Multiple Same Values
$ Input: nums1 = [40,40,40], nums2 = [40,40,40]
Output: [0,1,2]
💡 Note: First 40 maps to index 0, second 40 maps to index 1, third 40 maps to index 2

Constraints

  • 1 ≤ nums1.length ≤ 100
  • nums2.length == nums1.length
  • -105 ≤ nums1[i], nums2[i] ≤ 105
  • nums2 is an anagram of nums1

Visualization

Tap to expand
Find Anagram Mappings INPUT nums1 (source) 12 i=0 28 i=1 46 i=2 32 i=3 50 i=4 nums2 (target) 50 j=0 12 j=1 32 j=2 46 j=3 28 j=4 nums2 is anagram of nums1 Same elements, different order ALGORITHM (Hash Map) 1 Build Hash Map Map nums2 values to indices hashMap = { 50: 0, 12: 1, 32: 2, 46: 3, 28: 4 } value --> index in nums2 2 Iterate nums1 For each element in nums1 3 Lookup in Hash Find index from hashMap 4 Build Result Append index to mapping[] Time: O(n) | Space: O(n) FINAL RESULT Index Mapping Process nums1[0]=12 --> hash[12]=1 nums1[1]=28 --> hash[28]=4 nums1[2]=46 --> hash[46]=3 nums1[3]=32 --> hash[32]=2 nums1[4]=50 --> hash[50]=0 Output: mapping[] 1 4 3 2 0 [1, 4, 3, 2, 0] Verification: OK nums1[i] == nums2[mapping[i]] for all i in [0..4] Key Insight: Using a hash map allows O(1) lookup for each element's position in nums2. Instead of searching through nums2 for each element (O(n^2)), we precompute all indices in O(n), making the total time complexity O(n). This is the optimal solution for anagram mapping. TutorialsPoint - Find Anagram Mappings | Hash Map Approach
Asked in
Google 25 Amazon 18 Facebook 12
32.5K Views
Medium Frequency
~15 min Avg. Time
684 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen