How to do the intersection of two sorted arrays?
How to do the intersection of two sorted arrays?
Logic:
print the element if the element is present or available in both the arrays.
 Use two index variables i and j, after that initial the values i = 0, j = 0
 If arr01 [i] is smaller than arr02 [j] then increment i.
 If arr01 [i] is greater than arr02 [j] then increment j.
 If both are same then print any of them and increment both i and j.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

public static void getIntersection(int arr01[], int arr02[], int m, int n){
int i = 0, j = 0;
while (i < m && j < n){
if (arr01[i] < arr02[j])
i++;
else if (arr02[j] < arr01[i])
j++;
else{
System.out.print(arr02[j++]+” “);
i++;
}
}
}
public static void main(String args[]){
int arr01[] = {1, 2, 4, 5, 6};
int arr02[] = {2, 3, 5, 7};
int m = arr01.length;
int n = arr02.length;
getIntersection(arr01, arr02, m, n);
}

Clues –
Solution must be O(M + N) in time and O(min(M, N)) space.
Can you apply merge sort’s merging logic here?
Solution – This is simple, we can do this in O(M + N) time, where M and N are the array lengths. What we will do here is similar to the “merging” step in merge sort. We will traverse the two sorted arrays simultaneously. Let’s say the first array, A, is indexed by i, and the second array, B, is indexed by j, then,
A[i] == B[j] – then add it to the intersection.
A[i] > B[j] – then increment j.
A[i] B[j]) {
// Increment index to second array
++j;
} else {
// A[i] < B[j]
// Increment index to first array
++i;
}
}
return intersection;
}
public class IntersecionPoint2Arrays {  
int intersectionPoint = –1;  
int x;  
int y;  
public int intersection(int[] arrA, int[] arrB) {  
while (x < arrA.length && y < arrB.length) {  
if (arrA[x] > arrB[y])  
y++;  
else if (arrA[x] < arrB[y])  
x++;  
else {  
intersectionPoint = arrA[x];  
return intersectionPoint;  
}  
}  
return intersectionPoint;  
}  
public static void main(String[] args) throws java.lang.Exception {  
int[] a = { 1, 2, 3, 6, 8, 10 };  
int[] b = { 4, 5, 6, 11, 15, 20 };  
IntersecionPoint2Arrays i = new IntersecionPoint2Arrays();  
System.out.println(“Intersection point is : “ + i.intersection(a, b));  
}  
} 
Output:
Intersection point is : 6
Given two unsorted arrays that represent two sets (elements in every array are distinct), find union and intersection of two arrays.
For example, if the input arrays are:
arr1[] = {7, 1, 5, 2, 3, 6}
arr2[] = {3, 8, 6, 20, 7}
Then your program should print Union as {1, 2, 3, 5, 6, 7, 8, 20} and Intersection as {3, 6}. Note that the elements of union and intersection can be printed in any order.