find common elements

Programs to Find Common Elements between Two Unsorted Arrays

Given set of two unsorted arrays as input, the goal is to find common elements between them in an efficient way. Let’s solve this problem using the following methods i.e., Method 1: Iterative approach, Method 2: Using HashSet and Method 3: Using HashSet retainAll() method.


Method 1: Iterative Approach


Time Complexity – O(n2– Since nested for loops. So this is not an effective solution.

Let’s try to solve the above problem in other two different ways.

Method 2: Using HashSet


Time Complexity: O(n+n) -> O(n). This approach is better than the above approach.

You can also use HashSet’s retainAll() method. This method helps to retain only the elements that are common between two collections. Please check the below example on how to use this method to solve the above problem.

Method 3: Using HashSet retainAll() method


Recommended Posts


Leave a Reply

Notify of