Java Program to Find Common Element Between Two Arrays

In this post we’ll see a Java program to find common elements between two arrays. For writing this program you may be asked not to use any inbuilt Java method, in that case you can iterate the arrays using for loop and list the common elements.
If it is permitted to use any inbuilt method then you can use retainAll() method of the Set in Java to get the common elements between two arrays.

Finding common elements between two arrays – Iterative

In this solution you can iterate one of the array in an outer loop and compare each element with all the elements of another array using an inner loop.

Output

Finding common elements between two sorted arrays

Above solution is O(N2), if you can sort the arrays then you can reduce the time to O(2NLogN + N).
After sorting the arrays you compare elements of the arrays in a while loop and increment only one of the array index if the elements are not equal otherwise increment index in both the arrays.

Output

Finding common elements between two arrays using HashSet

You can also use the retainAll() method of the HashSet to find the common elements between two arrays.
retainAll() method retains only those elements of the Set that are contained in the passed Collection.

Output

That’s all for the topic Java Program to Find Common Element Between Two Arrays. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.