Intersection is the common elements which present in both the arrays
Solution Steps:-
Step 1: We sort both the arrays
Step 2: We use two pointers i and j initialize both with zero.
Step3:Now we run loop while i<m and j<n and compare each element present in arr1 and arr2
Step4:
- if(arr1[i]==arr2[j]) we add arr1[i] element to arr3 and increment both ptr i,j.
- if(arr1[i]>arr2[j] we increment j
- if(arr[i]<arr2[j] we increment i
Finally we print arr3
PROGRAM :
let arr1=[1,3,2,5,66,55];
let arr2=[1,2,4,0,22,55,88,66];
let m=arr1.length;
let n=arr2.length;
// array to store common elements
let arr3=[];
// sort arrays
arr1.sort();
arr2.sort();
let i=0,j=0;
let cnt=0;
while(i<m && j<n){
if(arr1[i]==arr2[j]){
arr3[cnt]=arr1[i];
cnt++;
i=i+1;
j=j+1;
}
else if(arr1[i]>arr2[j]){
j=j+1;
}
else if(arr1[i]<arr2[j]){
i=i+1
}
}
console.log(arr3)