diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection deleted file mode 100644 index ffec70f26..000000000 --- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection +++ /dev/null @@ -1,64 +0,0 @@ -package com.thealgorithms.datastructures.hashmap.hashing; -/* -* this is algo which implies common mathematical set theory concept -* called intersection in which result is common values of both the sets -* here metaphor of sets is HashMap - - -Test Case: - Scanner scn=new Scanner(System.in); - int len =scn.nextInt(); - int arr[]=new int[len]; - int arr2[]=new int[len]; - - for(int i=0;i<2*len;i++) { - - if(i=len) { - arr2[i-len]=scn.nextInt(); - } - } - System.out.println(Main(arr,arr2)); - - - -*/ - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.Scanner; -import java.util.Set; - -public class Intersection { - - public static ArrayList Main(int arr[],int arr2[]) { - HashMap hmap=new HashMap<>(); - HashMap hmap2=new HashMap<>(); - for(int i=0;i res=new ArrayList<>(); - for(int i=0;i0) { - int val=hmap.get(arr2[i]); - hmap.put(arr2[i],val-1); - res.add(arr2[i]); - } - - } - return res; - } - public Intersection() { - - } - - - -} diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java new file mode 100644 index 000000000..b10c3c874 --- /dev/null +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java @@ -0,0 +1,38 @@ +package com.thealgorithms.datastructures.hashmap.hashing; + +/* + * this is algo which implies common mathematical set theory concept + * called intersection in which result is common values of both the sets + * here metaphor of sets is HashMap + */ + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Intersection { + + public static List intersection(int[] arr1, int[] arr2) { + if (arr1 == null || arr2 == null || arr1.length == 0 || arr2.length == 0) { + return Collections.emptyList(); + } + Map cnt = new HashMap<>(16); + for (int v : arr1) { + cnt.put(v, cnt.getOrDefault(v, 0) + 1); + } + List res = new ArrayList<>(); + for (int v : arr2) { + if (cnt.containsKey(v) && cnt.get(v) > 0) { + res.add(v); + cnt.put(v, cnt.get(v) - 1); + } + } + return res; + } + + private Intersection() { + + } +}