Find Common Elements in given sorted arrays

Given three sorted arrays

array1[] = {10, 50, 100, 200, 400, 800};
array2[] = {60, 70, 200, 800, 1000};
array3[] = {30, 40, 150, 200, 300, 700, 800, 1200};

Logic : 

1) Take a single Loop and iterate over the elements by checking the size of all the arrays,iterator variable i,j,k
2) if the element at the given index are same increment 1++,j++,k++
3) if ar1[i] < ar2[j] then i++ 
4) if ar2[j] < ar3[k] then j++
5) else k++

Implementation :

public class FindCommonElements 
{

  public static void main(String args[])
  {
	int ar1[] = {10, 50, 100, 200, 400, 800};
	int ar2[] = {60, 70, 200, 800, 1000};
	int ar3[] = {30, 40, 150, 200, 300, 700, 800, 1200};

	int i = 0, j = 0, k = 0;

	// Iterate through three arrays while all arrays have elements
	while (i < ar1.length && j < ar2.length && k < ar3.length)
	{
	  if (ar1[i] == ar2[j] && ar2[j] == ar3[k]){ 
		System.out.print(ar1[i]+" "); 
		i++; j++; k++; 
	  }else if (ar1[i] < ar2[j]){
		i++;
	  }else if (ar2[j] < ar3[k]){
		j++;
	  }else
		k++;
    }
  }
}


Output :

200 800 

 

core java 12

FOLLOW US ON LinkedIn



Explore Tutu'rself