public class InterSection { public static void main(String[] args) { int arr1[]= {4,1,2,3}; int arr2[]= {5,4,2,8}; System.out.println("Intersection of the Two Arrays:: ");
Most of the time they'll say don't use any built in method to solve the problem. for (int i = 0; i < arr1.length; i++) { for (int j = 0; j < arr2.length; j++) { if(arr1[i] == arr2[j]) { return arr2[j]; } } }
Another approach 1. Add array1 to hashset1 2. Add array2 to hashset2 3. Hashset1.retainAll(hashset2) We can use the below also but it will add the second array element into hashset if(!hashset.add(arrElement))
That's the reason why we use a HashSet here as it stores only unique elements so when you add elements to the hash from the array you get only a set with unique elements and avoids the duplicates
all your solutions are containing the collections/ using some apis. generally interviewer asks for solutions without using any datastructures.
public class InterSection {
public static void main(String[] args) {
int arr1[]= {4,1,2,3};
int arr2[]= {5,4,2,8};
System.out.println("Intersection of the Two Arrays:: ");
for(int i=0; i
Most of the time they'll say don't use any built in method to solve the problem.
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if(arr1[i] == arr2[j]) {
return arr2[j];
}
}
}
Can we use hashmap also ?
Another approach
1. Add array1 to hashset1
2. Add array2 to hashset2
3. Hashset1.retainAll(hashset2)
We can use the below also but it will add the second array element into hashset
if(!hashset.add(arrElement))
Hi,
What is the purpose of using hashset here. Please let me know
hashset allows only non duplicate elements. so there will be no repeatation of same common element
if there are dublicate elements while we are adding elements to the hashset what should we do?
This code will fail.
That's the reason why we use a HashSet here as it stores only unique elements so when you add elements to the hash from the array you get only a set with unique elements and avoids the duplicates
code please