Find all common numbers in given three sorted arrays.

Objective: Given three sorted(ascending order) arrays of integers, find out all the common elements in them.

Input: Three sorted arrays.

Output: All the common elements.

Examples :

Array A = {1,2,3,4,5,6,7,8,9,10};
Array B = {1,3,5,6,7,8,12};
Array C = {2,3,4,5,8,9};
Common Elements are 3,5,8


Approach:

  • Very Simple Solution.
  • Navigate all three arrays(A,B,C) simultaneously using indexes say, i,j,k.
  • if(A[i]==B[j]==C[k]) then print A[i] and do i++, j++, k++.
  • if not then compare all A[i],B[j],C[k] and which ever is smaller, increase its index.
  • Stop when any of these array gets over

Complete Code:

public class FindCommonElement3Arrays {
public void findCommon(int [] A, int [] B, int [] C){
int i=0,j=0,k=0;
while(i<A.length && j<B.length && k<C.length){
if((A[i]==B[j])&& (B[j]==C[k])){
System.out.print(A[i] + " ");
i++;j++;k++;
}else if((A[i]<=B[j])&& (A[i]<=C[k])){
i++;
}else if((B[j]<=A[i])&& (B[j]<=C[k])){
j++;
}else{
k++;
}
}
}
public static void main(String args[]){
int [] A = {1,2,3,4,5,6,7,8,9,10};
int [] B = {1,3,5,6,7,8,12};
int [] C = {2,3,4,5,8,9};
FindCommonElement3Arrays f = new FindCommonElement3Arrays();
System.out.print("Common Elements are : ");
f.findCommon(A, B, C);
}
}

Output:

Common Elements are : 3 5 8