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
Step 1: Build Hash Set from nums11221โ†“12Hash Set {1, 2}Step 2: Check nums2 Elements22Check: is 2 in hash set?โœ“ Yes! Add to result2Final Result2Intersection: [2]
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!
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
73.4K Views
High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen