w3resource

Java Array Exercises: Find common elements from three sorted arrays

Java Array: Exercise-25 with Solution

Write a Java program to find common elements from three sorted (in non-decreasing order) arrays.

Pictorial Presentation:

Java Array Exercises: Find common elements from three sorted arrays

Sample Solution:

Java Code:

import java.util.*;
public class Exercise25 {
public static void main(String[] args) {
	ArrayList<Integer> common = new ArrayList<Integer>();
   int array1[] = {2, 4, 8};
   int array2[] = {2, 3, 4, 8, 10, 16};
   int array3[] = {4, 8, 14, 40};
	int x = 0, y = 0, z = 0;
	while (x < array1.length && y < array2.length && z < array3.length){
		if (array1[x] == array2[y] && array2[y] == array3[z]){
			common.add(array1[x]);
			x++;
			y++;
			z++;
		}
		else if (array1[x] < array2[y])
			x++;
		else if (array2[y] < array3[z])
			y++;
		else
			z++;
	}
	System.out.println("Common elements from three sorted (in non-decreasing order ) arrays: ");
System.out.println(common);
}
}

Sample Data: array1 = 2, 4, 8
array2 = 2, 3, 4, 8, 10, 16
array3 = 4, 8, 14, 40

Sample Output:

                                                                              
Common elements from three sorted (in non-decreasing order ) arrays:   
[4, 8]

Flowchart:

Flowchart: Java exercises: Find common elements from three sorted arrays

Visualize Java code execution (Python Tutor):


Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to find a missing number in an array.
Next: Write a Java program to move all 0's to the end of an array. Maintain the relative order of the other (non-zero) array elements.

What is the difficulty level of this exercise?



Java: Tips of the Day

Array vs ArrayLists:

The main difference between these two is that an Array is of fixed size so once you have created an Array you cannot change it but the ArrayList is not of fixed size. You can create instances of ArrayLists without specifying its size. So if you create such instances of an ArrayList without specifying its size Java will create an instance of an ArrayList of default size.

Once an ArrayList is full it re-sizes itself. In fact, an ArrayList is internally supported by an array. So when an ArrayList is resized it will slow down its performance a bit as the contents of the old Array must be copied to a new Array.

At the same time, it's compulsory to specify the size of an Array directly or indirectly while creating it. And also Arrays can store both primitives and objects while ArrayLists only can store objects.

Ref: https://bit.ly/3o8L2KH