Intersection of Two Arrays 1 - Unique Elements
EasyUpdated: Aug 2, 2025
Practice on:
Problem
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.
Examples
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]
Explanation: [4, 9] is also accepted.
Solution
Method 1 - Using 2 HashSets
Here are the steps to follow:
- Store all unique elements of
nums1inset1. - For each element in
nums2, if it exists inset1, add it toset2. - Convert
set2to an integer arrayans. - Return the array
anscontaining the intersection ofnums1andnums2.
Video Explanation
Here is the detailed video explanation: <div class="youtube-embed"><iframe src="https://www.youtube.com/embed/Xi43hFyOR-s" frameborder="0" allowfullscreen></iframe></div>
Code
Java
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer> set1 = new HashSet<Integer>();
for (int num: nums1) {
set1.add(num);
}
HashSet<Integer> set2 = new HashSet<Integer>();
for (int num: nums2) {
if (set1.contains(num)) {
set2.add(num);
}
}
int[] ans = new int[set2.size()];
int i = 0;
for (int num: set2) {
ans[i++] = num;
}
return ans;
}
}
Complexity
- ⏰ Time complexity:
O(m + n)wheremandnis size of ofnums1andnums2. - 🧺 Space complexity:
O(m + n)
Method 2 - Using 1 HashSet
Code
Java
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer> set1 = new HashSet<Integer>();
for (int num: nums1) {
set1.add(num);
}
List <Integer> intersection = new ArrayList<Integer>();
for (int num: nums2) {
if (set1.contains(num)) {
intersection.add(num);
set1.remove(num);
}
}
int[] ans = new int[intersection.size()];
int i = 0;
for (int num: intersection) {
ans[i++] = num;
}
return ans;
}
}
Method 3 - Binary Search
Here are the steps we can follow:
- Sort the arrays.
- Create a list to store the intersection results.
- Find unique elements in nums1 and check for their presence in nums2 using binary search.
- Convert the intersection list to an
ansarray. - Return the
ansarray containing the intersection ofnums1andnums2.
Code
Java
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
ArrayList<Integer> ansList = new ArrayList<Integer>();
for (int i = 0; i < nums1.length; i++) {
if (i == 0 || (i > 0 && nums1[i] != nums1[i - 1])) {
if (Arrays.binarySearch(nums2, nums1[i]) > -1) {
ansList.add(nums1[i]);
}
}
}
int[] ans = new int[ansList.size()];
// Convert ArrayList to int array (and can't be used as a variable name)
int k = 0;
for (int num: ansList) {
ans[k++] = num;
}
return ans;
}
}
Complexity
- ⏰ Time complexity:
O(m log m + n log n)wheremandnis size of ofnums1andnums2. Mainly, for sorting two arrays andO(n log m)for searching elements elements innums1innums2. - 🧺 Space complexity:
O(n)for usingansList