easy Intersection of Two Arrays
Problem Statement
Given two arrays, nums1 and nums2 containing integers, return an array of the intersection of nums1 and nums2. In the resultant array, each integer should be unique, and elements can be in any order.
Examples
-
Example 1:
- Input:
nums1 = [3,1,2,6,7,8],nums2 = [2,3,4,5,7,9] - Expected Output:
[2,3,7] - Justification: The numbers 2, 3, and 7 are present in both
nums1andnums2.
- Input:
-
Example 2:
- Input:
nums1 = [1,2,3],nums2 = [4,5,6] - Expected Output:
[] - Justification: There are no common elements between
nums1andnums2, hence the output is an empty array.
- Input:
-
Example 3:
- Input:
nums1 = [7,8,9,10],nums2 = [10,9,8,7] - Expected Output:
[7,8,9,10] - Justification: All elements from
nums1are present innums2and vice versa.
- Input:
Try it yourself
Try solving this question here:
✅ Solution Intersection of Two Arrays
Problem Statement
Given two arrays, nums1 and nums2 containing integers, return an array of the intersection of nums1 and nums2. In the resultant array, each integer should be unique, and elements can be in any order.
Examples
-
Example 1:
- Input:
nums1 = [3,1,2,6,7,8],nums2 = [2,3,4,5,7,9] - Expected Output:
[2,3,7] - Justification: The numbers 2, 3, and 7 are present in both
nums1andnums2.
- Input:
-
Example 2:
- Input:
nums1 = [1,2,3],nums2 = [4,5,6] - Expected Output:
[] - Justification: There are no common elements between
nums1andnums2, hence the output is an empty array.
- Input:
-
Example 3:
- Input:
nums1 = [7,8,9,10],nums2 = [10,9,8,7] - Expected Output:
[7,8,9,10] - Justification: All elements from
nums1are present innums2and vice versa.
- Input:
Solution
To solve this problem, we will utilize a set-based approach. Sets are ideal for this task because they automatically remove duplicate elements and allow for efficient element lookup. First, we'll convert both input arrays into sets. This conversion eliminates any duplicates within each array, aligning with our requirement to return only unique common elements. Then, we'll find the intersection of these two sets, which gives us the set of elements present in both arrays. This method is effective because set operations are generally more efficient than iterating through arrays, especially when dealing with duplicates and the need for uniqueness. Our approach reduces the problem to simple set operations, making the solution more elegant and performant.
The rationale behind using sets over other data structures is twofold. Firstly, the automatic removal of duplicates simplifies our task. Secondly, the intersection operation directly corresponds to our goal of finding common elements, ensuring that the algorithm is both intuitive and efficient.
Step-by-step Algorithm
- Initialize Two Sets: Start by creating two empty sets,
set1andset2. These will store the unique elements fromnums1andnums2, respectively. - Populate the First Set (
set1): Loop through each element innums1. For every element, add it toset1. This step ensures thatset1contains all unique elements fromnums1. - Populate the Second Set (
set2): Repeat the process fornums2, adding each of its elements toset2. Now,set2contains all unique elements fromnums2. - Find Intersection: Identify the common elements between
set1andset2. This can be done by checking each element ofset1to see if it also exists inset2, or by utilizing set intersection operations available in many programming languages. - Prepare the Result: Convert the intersection set into an array. This step involves initializing an array and populating it with the elements from the intersection set.
- Return the Result: Finally, return the array created in the previous step. This array contains all unique elements that are present in both
nums1andnums2.
Algorithm Walkthrough with Input
Given nums1 = [3,1,2,6,7,8], nums2 = [2,3,4,5,7,9]:
-
Initialize Sets:
set1 = {}set2 = {}
-
Populate
set1:- Loop through
nums1: add 3, 1, 2, 6, 7, and 8 toset1. - After the loop,
set1 = {1, 2, 3, 6, 7, 8}.
- Loop through
-
Populate
set2:- Loop through
nums2: add 2, 3, 4, 5, 7, and 9 toset2. - After the loop,
set2 = {2, 3, 4, 5, 7, 9}.
- Loop through
-
Find Intersection:
- Identify common elements between
set1andset2. - Intersection:
{2, 3, 7}.
- Identify common elements between
-
Prepare the Result:
- Convert the intersection set to an array:
[2, 3, 7].
- Convert the intersection set to an array:
-
Return the Result:
- The final result is
[2, 3, 7], which is the array of unique elements present in bothnums1andnums2.
- The final result is
Code
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
// Add elements of nums1 to set1
for (int num : nums1) {
set1.add(num);
}
// Add elements of nums2 to set2
for (int num : nums2) {
set2.add(num);
}
// Manually find intersection
Set<Integer> intersection = new HashSet<>();
for (int num : set1) {
if (set2.contains(num)) {
intersection.add(num);
}
}
// Convert intersection set to an array
int[] result = new int[intersection.size()];
int i = 0;
for (int num : intersection) {
result[i++] = num;
}
return result;
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(
Arrays.toString(
solution.intersection(
new int[] { 3, 1, 2, 6, 7, 8 },
new int[] { 2, 3, 4, 5, 7, 9 }
)
)
);
System.out.println(
Arrays.toString(
solution.intersection(new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 })
)
);
System.out.println(
Arrays.toString(
solution.intersection(
new int[] { 7, 8, 9, 10 },
new int[] { 10, 9, 8, 7 }
)
)
);
}
}
Complexity Analysis
Time Complexity:
- Creating Sets:
for the first array and for the second, where nandmare the lengths of the two input arrays. - Finding Intersection: Iterating through the smaller set and checking for each element in the larger set, leading to
in the best case and in the worst case.
Thus, the overall time complexity combines these steps, resulting in
Space Complexity:
- Space is required for storing elements of both arrays in sets, leading to a space complexity of
in the worst case when all elements are unique.
🤖 Don't fully get this? Learn it with Claude
Stuck on Intersection of Two Arrays? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Intersection of Two Arrays** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Intersection of Two Arrays** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Intersection of Two Arrays**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Intersection of Two Arrays**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.