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