import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr1[] = new int[n];
int arr2[] = new int[n];
for(int i = 0;i<n;i++){
arr1[i] = sc.nextInt();
}
for(int i = 0;i<n;i++){
arr2[i] = sc.nextInt();
}
ArrayList list = getIntersection(arr1,arr2);
System.out.print(list);
}
public static ArrayList getIntersection(int arr1[],int arr2[]){
HashMap<Integer,Boolean> map = new HashMap<>();
for(int i = 0;i<arr1.length;i++){
map.put(arr1[i],false);
}
for(int j = 0;j<arr2.length;j++){
if(map.containsKey(arr2[j])){
map.put(arr2[j],true);
}
}
ArrayList list = new ArrayList<>();
Set<Map.Entry<Integer,Boolean>> entrySet = map.entrySet();
for(Map.Entry<Integer,Boolean> entry : entrySet){
if(entry.getValue()){
list.add(entry.getKey());
}
}
return list;
}
}
One of my test case is not running, what is the correction i needed to get a required result(how array list will store repeated number)
HI @8006366388
there is more efficient way to solve this problem but you can improve your code by taking two
hashmap< Integer, Integer > type and storing the occurrence of each element.
then compare both the hashmap and add min occurrence of elements into your answer ArrayList.
.
i donot get what r u trying to say can u help me out to understand it more
@8006366388
i will explain you with an example
input
7
1 2 3 1 2 4 1
2 1 3 1 5 2 2
so we have two hashmap hm1 and hm2 for each array to store the occurrence of the integer values.
hm1 will be
1->3
2->2
3->1
4->1
hm2 will be
2->3
1->2
3->1
5->1
now traverse keyset of hm1 and check whether the key is present in hm2 as well if yes then compare values and take the min of it and add to your arraylist.
ans->[];
for key equal 1
1->min(2,3);
ans->[1,1]
now for key equal 2
2->min(2,3);
ans->[1,1,2,2]
now for key equal 3
3->min(1,1)
ans->[1,1,2,2,3];
i hope you will understand it now if you still face any issue you can ask.
can u provide me the code for this problem
@8006366388
try to code it on your own it will be better for your coding skills.
if you face any difficulty while coding you can ask me.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.