1+ import java .util .*;
2+
3+ public class intersectionOfTwoArrays {
4+
5+ public static void main (String [] args ){
6+ Scanner sc = new Scanner (System .in );
7+ int n1 = sc .nextInt ();
8+ int [] arr1 = new int [n1 ];
9+ int n2 = sc .nextInt ();
10+ int [] arr2 = new int [n2 ];
11+ for (int i = 0 ; i < n1 ; i ++){
12+ arr1 [i ] = sc .nextInt ();
13+ }
14+ for (int i = 0 ; i < n1 ; i ++){
15+ arr2 [i ] = sc .nextInt ();
16+ }
17+ intersection (arr1 , arr2 , n1 , n2 );
18+ sc .close ();
19+ }
20+
21+ public static void intersection (int [] a ,int [] b , int n , int m ){
22+ HashMap <Integer ,Integer > map = new HashMap <>(); // created a hashmap which will store distinct elements with their frequencies
23+ for (int i = 0 ; i < n ; i ++){
24+ map .put (a [i ],map .getOrDefault (a [i ],0 )+1 ); // updating frequencies of each element
25+ }
26+ int [] arr = new int [100001 ]; // created an array which will store the elements which are present in both the arrays
27+ Arrays .fill (arr ,0 );
28+ for (int i = 0 ; i < m ; i ++){
29+ if (map .containsKey (b [i ])){ // updating array which contains elements that are present in both the arrays
30+ arr [b [i ]] = 1 ;
31+ }
32+ }
33+ ArrayList <Integer > al = new ArrayList <>(); // creating a list
34+ for (int i = 0 ; i < m ; i ++){
35+ if (arr [b [i ]]==1 ){ // checking if the element is present in both the arrays or not
36+ al .add (b [i ]); // adding the elements to the list
37+ }
38+ }
39+ System .out .println (al );
40+ }
41+
42+ }
0 commit comments