Q22 PepCoding | Find Anagram Mappings

PHOTO EMBED

Thu Jan 26 2023 09:06:09 GMT+0000 (Coordinated Universal Time)

Saved by @Ayush_dabas07

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] + " ");
		}
	}

}
content_copyCOPY

https://www.pepcoding.com/resources/data-structures-and-algorithms-in-java-levelup/hashmap-and-heaps/find-anagram-mappings-official/ojquestion