Similar Problems

Similar Problems not available

Find Anagram Mappings - Leetcode Solution

Companies:

LeetCode:  Find Anagram Mappings Leetcode Solution

Difficulty: Easy

Topics: hash-table array  

Problem Statement:

Given two lists A and B, and B is an anagram of A. B is an anagram of A means B is made by randomizing the order of the elements in A.

We want to find an index mapping P, from A to B. A mapping P[i] = j means the ith element in A appears in B at index j.

These lists A and B may contain duplicates. If there are multiple answers, output any of them.

For example, given

A = [12, 28, 46, 32, 50] B = [50, 12, 32, 46, 28]

We should return

[1, 4, 3, 2, 0]

As P[0] = 1 because the 0th element of A appears at B[1], and P[1] = 4 because the 1st element of A appears at B[4], and so on.

Note:

  1. A, B have equal lengths in range [1, 100].
  2. A[i], B[i] are integers in range [0, 10^5].

Solution:

In the given example, A and B have the following values:

A = [12, 28, 46, 32, 50] B = [50, 12, 32, 46, 28]

We need to find an index mapping P, which means the ith element in A appears in B at index j. In other words, we need to find the index of each element in A in B.

To solve this problem, we can create a dictionary where the keys are the elements of B and the values are their indices. Then, we can iterate through A, and for each element in A, we can look up its index in B using the dictionary. We can then append the index to a result list, which will be our index mapping P.

Here is the code to implement this solution:

def anagramMappings(A, B): # create a dictionary to store the indices of the elements in B b_dict = {} for i in range(len(B)): b_dict[B[i]] = i

# iterate through A and look up the index of each element in B
p = []
for a in A:
    p.append(b_dict[a])

return p

example usage

A = [12, 28, 46, 32, 50] B = [50, 12, 32, 46, 28] print(anagramMappings(A, B))

Output:

[1, 4, 3, 2, 0]

The code first creates a dictionary where the keys are the elements of B and the values are their indices. Then, it iterates through A and looks up the index of each element in B using the dictionary. Finally, it appends the index to a result list, which is returned as the answer.

Overall, the time complexity of this solution is O(n), where n is the length of A/B. The space complexity is also O(n), as we are creating a dictionary to store the indices of the elements in B.

Find Anagram Mappings Solution Code

1