Learn-dsa..in 30 days!



























CC-9 : Find common elements in 3 sorted arrays.

Description:

Given 3 input integer arrays arr1, arr2, arr3, that are sorted in ascending order. Find the common elements that occur in all 3 arrays.

Test cases and expected outputs:

Input Parameters Expected outputs
arr1={-3,-2,-1,0,1,2,3}
arr2={-2,-1,0}
arr3={-2,-1,0,4,5}
Common Element in the 3 arrays : -2.
Common Element in the 3 arrays : -1.
Common Element in the 3 arrays : 0.
arr1={4,5}
arr2={1,2,4,5}
arr3={1,2,4,5,6,7}
Common Element in the 3 arrays : 4.
Common Element in the 3 arrays : 5.
arr1={1,2,3}
arr2={2,4}
arr3={3,5}
*No* common element in the 3 arrays !

Pseudocode:

The java method should accept following input parameters: arr1 (int array), arr2 (int array), arr3 (int array).
Initialize a boolean variable noCmnElmt to true.
Iterate through arr1 using while loop:
For each element of arr1, search the same in arr2 and arr3 using while loops. Since the arrays are sorted, while searching arr2 and arr3, if you find an element greater than the current element of arr1, you may stop the current search as there is no further probability of finding the element.
If current element of arr1 is found in arr2 and arr3, print the same and set noCmnElmt to false.
• If at the end of the loop noCmnElmt is still true, it means no common element exists in the 3 arrays.

Code:

public void arrayFindCommon(int[] arr1,int[] arr2,int[] arr3) throws Exception{
	int arr1Idx=0;int arr2Idx=0;int arr3Idx=0;
	boolean foundArr2; boolean foundArr3; boolean noCmnElmt=true;
	while (arr1Idx < arr1.length) {
		arr2Idx=0; 	arr3Idx=0;
		foundArr2=false; foundArr3=false;
		while ((arr2Idx < arr2.length)&&(arr1[arr1Idx]>=arr2[arr2Idx])) {
			if (arr1[arr1Idx]==arr2[arr2Idx]) {
				foundArr2=true;
				arr2Idx++;
				break;
			}
			arr2Idx++;
		}
		while ((arr3Idx < arr3.length)&&(arr1[arr1Idx]>=arr3[arr3Idx])) {
			if (arr1[arr1Idx]==arr3[arr3Idx]) {
				foundArr3=true;
				arr3Idx++;
				break;
			}
			arr3Idx++;
		}	
		if (foundArr2==true && foundArr3==true) {
			System.out.println("\nCommon Element in the 3 arrays : "+arr1[arr1Idx] +"\n");	
			noCmnElmt=false;
		}
		arr1Idx++;
	}				
	if (noCmnElmt==true) {
		System.out.println("\n*No* common element in the 3 arrays !\n");	
	}
}

Click here to download and run code and test cases !