Problem statement

https://leetcode.com/problems/find-anagram-mappings/

Solution 1

For each value keep list of indexes. Then iterate through indexes and create connections.

Complexity

Time and space complexity is O(n).

Code

class Solution:
    def anagramMappings(self, A, B):
        A_d, B_d = defaultdict(list), defaultdict(list)
        for i, a in enumerate(A): A_d[a].append(i)
        for i, b in enumerate(B): B_d[b].append(i)
        ans = [0] * len(A)
        for key in A_d.keys():
            for i, j in zip(A_d[key], B_d[key]): ans[i] = j
        
        return ans

Solution 2

Actually it is allowed to have equal indexes so we can do it in simpler way.

Complexity

Time and space complexity is O(n).

Code

class Solution:
    def anagramMappings(self, A, B):
        d = {x: i for i, x in enumerate(B)}
        return [d[x] for x in A]