760. Find Anagram Mappings¶ Time: $O(n)$ Space: $O(n)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15class Solution { public: vector<int> anagramMappings(vector<int>& nums1, vector<int>& nums2) { vector<int> ans; unordered_map<int, stack<int>> numToIndices; for (int i = 0; i < nums2.size(); ++i) numToIndices[nums2[i]].push(i); for (const int num : nums1) ans.push_back(numToIndices[num].top()), numToIndices[num].pop(); return ans; } }; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16class Solution { public int[] anagramMappings(int[] nums1, int[] nums2) { int[] ans = new int[nums1.length]; Map<Integer, Deque<Integer>> numToIndices = new HashMap<>(); for (int i = 0; i < nums2.length; ++i) { numToIndices.putIfAbsent(nums2[i], new ArrayDeque<>()); numToIndices.get(nums2[i]).push(i); } for (int i = 0; i < nums1.length; ++i) ans[i] = numToIndices.get(nums1[i]).pop(); return ans; } } 1 2 3 4 5 6 7 8class Solution: def anagramMappings(self, nums1: list[int], nums2: list[int]) -> list[int]: numToIndices = collections.defaultdict(list) for i, num in enumerate(nums2): numToIndices[num].append(i) return [numToIndices[num].pop() for num in nums1]