import java.util.*; public class Main { public static int[] anagramMappings(int[] arr1, int[] arr2) { //make hashmap of indexes of arr2 , can use LL queue as getting is O(1) operation in this HashMap<Integer,LinkedList<Integer>> map = new HashMap<>(); for(int i =0 ; i< arr2.length ; i++){ int val = arr2[i]; LinkedList<Integer> temp = map.getOrDefault(val , new LinkedList<Integer>()); temp.addLast(i); map.put(val , temp); } int ans[] = new int[arr2.length]; for(int i =0 ;i < arr1.length ; i++){ int val = arr1[i]; LinkedList<Integer> temp = map.get(val); //same elements indexes will be in order so we will have to remove ans[i] = temp.removeFirst(); } return ans; } public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int[] a = new int[n]; int[] b = new int[n]; for (int i = 0; i < a.length; i++) { a[i] = s.nextInt(); } for (int j = 0; j < b.length; j++) { b[j] = s.nextInt(); } int[] res = anagramMappings(a, b); for (int j = 0; j < res.length; j++) { System.out.print(res[j] + " "); } } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter