### Intersection of Two Arrays Solution - The Coding Shala

Home >> Interview Questions >> Intersection of two arrays

## Intersection of Two Arrays Solution

In this post, you will learn how to find the intersection of two arrays and its solution in Java.

Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]

Note: Each element in the result must be unique. The result can be in any order.

## Java Program to find the Intersection of Two Arrays

Approach 1:
We can find the intersection of two arrays using two HashSets.
Java Program:

```class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<Integer>();
Set<Integer> result = new HashSet<Integer>();
for(int num : nums2){
if(set.contains(num)){
}
}
int[] ans = new int[result.size()];
int i = 0;
for(Integer val : result) ans[i++] = val;
return ans;
}
}
```

Other Posts You May Like