Intersection of Two Arrays
Given two integer arrays, return an array of their intersection. Each element in the result must be unique. The order of the result can be arbitrary.
Use a hash set to store elements from the first array. Then iterate through the second array: if an element exists in the set, add it to the result and remove it from the set (to prevent duplicates in the result). This runs in O(n+m) time and O(n) space.
For example, nums1 = [1,2,2,1], nums2 = [2,2] → result is [2]. Only unique intersecting elements are included.
If the arrays are sorted, an alternative two-pointer approach can solve this in O(n+m) time with O(1) space. However, the hash set approach works on unsorted arrays and is simpler.
The problem can also be solved by sorting both arrays and using two pointers, which uses O(1) space but requires sorting first. The hash set approach is preferred when space is not a concern because it is simpler and works on unsorted data.
Example Input & Output
Intersection is 2 (unique).
No common elements.
Order does not matter.
Algorithm Flow

Solution Approach
Add all nums1 elements to a set. Iterate nums2, if element in set, add to result and remove from set.
Time O(n+m), Space O(n).
Best Answers
import java.util.*;
class Solution {
public int[] solution(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<>();
for (int n : nums1) set.add(n);
List<Integer> list = new ArrayList<>();
for (int n : nums2) {
if (set.contains(n)) { list.add(n); set.remove(n); }
}
int[] result = new int[list.size()];
for (int i = 0; i < list.size(); i++) result[i] = list.get(i);
java.util.Arrays.sort(result);
return result;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
