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}

The common elements between these two arrays are {6, 9}.

Find Intersection of Two Arrays

We have discussed the problem statement. In this tutorial, I am going to discuss multiple approaches to solve the problem.

How to Find Array Intersection

Method 1 : Brute Force Approach

To find array intersection, the simplest approach is to use two loops. 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[].

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

Find Intersection of Two Arrays – Java Code

In our previous approach, we have used two for loops to solve this problem. Let’s improve our solution to solve this problem in single loop.

To solve this problem in single iteration, here are the steps –

i) Use two index variables i and j, initialize them with 0.
ii) If element present at 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).

Find intersection of two arrays video tutorial

Method 3: Using HashSet

We can also solve this problem using set data structure.

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 we print it.

Here, we are using additional space for this problem.

Why we are using HashSet?

Hashset does not allow duplicate elements and also the lookup time is O(1).

The time complexity of this approach is O(m+n) and it’s space complexity is O(m).

Programming questions on arrays

Conclusion

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

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.