Find Intersection of Two Arrays – Java Code

Given two sorted arrays, Write a java code to find intersection of two arrays.

For example, if the input arrays are:

arr1[] = {2, 3, 6, 7, 9, 11}
arr2[] = {4, 6, 8, 9, 12}

Then your program should print intersection as {6, 9}. Before writing actual code, let’s first discuss different approaches to solve this problem.

Find first non-repeated character in a string – Java Code

How to Find Intersection of Two Arrays

 

Method 1 (Simplest or Naive Approach) :

In this approach, we take each element of a first array and compare with each element of a second array.
The time complexity of this approach is O(mn), Where m and n are the number of elements in arr1[] and arr2[].

 

Method 2 :

i) Use two index variables i and j, initialize them with 0.
ii) If arr1[i] is smaller than arr2[j] then increment i.
iii) If arr1[i] is greater than arr2[j] then increment j.
iv) If both are same then print any of the array value and increment both i and j.

The time complexity of this approach is O(m+n).

Subscribe Our Tutorials

Get Latest Updates on Facebook

Java Program to Find Intersection of Two Arrays

Java Program to Find Intersection of Two Arrays

Java Program to Find Intersection of Two Arrays

 

Method 3: Using HashSet

In this approach, we first initialize an empty set.Then, we traverse the first array and put each element of the first array in a set. Now, For every element x of the second array, we search x in the set. If x is present, then print it. The time complexity of this approach is O(m+n).

Conclusion

I have explained multiple approaches to find intersection of two arrays in Java and their time complexity. If you want to discuss any other approach then let us know through your comments.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.
Tagged , , . Bookmark the permalink.