760. Find Anagram Mappings

Given two listsAandB, andBis an anagram ofA.Bis an anagram ofAmeansBis made by randomizing the order of the elements inA.

We want to find anindex mappingP, fromAtoB. A mappingP[i] = jmeans theith element inAappears inBat indexj.

These listsAandBmay 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] = 1because the0th element ofAappears atB[1], andP[1] = 4because the1st element ofAappears atB[4], and so on.

Note:

  1. A, Bhave equal lengths in range[1, 100].

  2. A[i], B[i]are integers in range[0, 10^5].

Thoughts:1

  1. (K,V) : (value, list of (index of B))

  2. get the value of A[i], retrieve the last element from the mapped list

Code

class Solution {
    public int[] anagramMappings(int[] A, int[] B) {
        int [] result = new int [A.length];
        Map<Integer, List<Integer>> map = new HashMap<>();
        for( int i = 0; i < B.length; i++){
            map.computeIfAbsent(B[i], k->new ArrayList<>()).add(i);
        }

        for( int i = 0; i < A.length; i++){
            result[i] = map.get(A[i]).remove(map.get(A[i]).size() - 1);
        }

        return result;
    }
}

from diddit's post

Use Sorting:

from tyuan73's post

from PuckDuck's post

fastest C++:

fastest Java

fastest Python

Last updated

Was this helpful?