Intersection of Two Arrays - Problem
Given two integer arrays nums1 and nums2, find their intersection and return it as an array.
The intersection contains all elements that appear in both arrays, but each element should appear only once in the result (no duplicates). You may return the result in any order.
Example: If nums1 = [1,2,2,1] and nums2 = [2,2], the intersection is [2] because 2 appears in both arrays, but we only include it once in the result.
Input & Output
example_1.py โ Basic Intersection
$
Input:
nums1 = [1,2,2,1], nums2 = [2,2]
โบ
Output:
[2]
๐ก Note:
The only number that appears in both arrays is 2. Even though 2 appears multiple times in both arrays, we only include it once in the result.
example_2.py โ Multiple Intersections
$
Input:
nums1 = [4,9,5], nums2 = [9,4,9,8,4]
โบ
Output:
[9,4]
๐ก Note:
Both 4 and 9 appear in both arrays. The result can be in any order, so [4,9] would also be correct.
example_3.py โ No Intersection
$
Input:
nums1 = [1,2,3], nums2 = [4,5,6]
โบ
Output:
[]
๐ก Note:
There are no common elements between the two arrays, so the intersection is empty.
Constraints
- 1 โค nums1.length, nums2.length โค 1000
- 0 โค nums1[i], nums2[i] โค 1000
- Each result element must be unique
Visualization
Tap to expand
Understanding the Visualization
1
Build Hash Set
Create a hash set from nums1 for instant lookups
2
Check Membership
For each element in nums2, check if it exists in the hash set
3
Collect Matches
Add found elements to result set (automatically handles duplicates)
4
Return Result
Convert result set to array and return
Key Takeaway
๐ฏ Key Insight: Hash sets turn expensive search operations into instant lookups, making intersection finding much more efficient!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code