In this example, we’ll find intersection of two sorted arrays:
Input:
int[] arr1 = {10, 11, 12, 13, 14};
int[] arr2 = {8, 10, 12, 14};
Output:
[10 12 14]
1. Java
#Approach 1
To find the intersection of 2 sorted arrays, follow the below approach :
- Use two variables with nested loop, i and j
- Compare elements to each other arr1[i] == arr2[j]
- If matches, print the element (or append).
public class FindIntersectionOfTwoSortedArrays {
public static void main(String[] args) {
int[] arr1 = {10, 11, 12, 13, 14};
int[] arr2 = {8, 10, 12, 14};
StringBuilder intersect = new StringBuilder();
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
intersect.append(arr1[i] + " ");
}
}
}
System.out.println("[" + intersect + "]");
}
}
Output:
[10 12 14 ]
#Approach 2
To find the intersection of 2 sorted arrays, follow the below approach :
- Use two variables i = 0, j = 0
- If arr1[i] == arr2[j] then print any of them and increment both i and j.
- If arr1[i] < arr2[j] then increment i.
- Else increment j.
public class FindIntersectionOfTwoSortedArrays {
public static void main(String[] args) {
int[] arr1 = {10, 11, 12, 13, 14};
int[] arr2 = {8, 10, 12, 14};
StringBuilder intersect = new StringBuilder();
int i = 0, j = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] == arr2[j]) {
intersect.append(arr1[i] + " ");
i++; j++;
}
else if(arr1[i] < arr2[j]){
i++;
}
else{
j++;
}
}
System.out.println("[" + intersect + "]");
}
}
Output:
[10 12 14 ]
Complete Java Solutions can be found here: Github Link