Intersection of Two Arrays - 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.

The intersection contains elements that appear in both arrays, with no duplicates in the final result.

Input & Output

Example 1 — Basic Case
$ Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]
💡 Note: The number 2 appears in both arrays. Even though 2 appears multiple times, we only include it once in the result.
Example 2 — Multiple Intersections
$ Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
💡 Note: Both 4 and 9 appear in both arrays. The order in the result doesn't matter, so [9,4] would also be correct.
Example 3 — No Intersection
$ Input: nums1 = [1,2,3], nums2 = [4,5,6]
Output: []
💡 Note: No elements appear in both arrays, so the intersection is empty.

Constraints

  • 1 ≤ nums1.length, nums2.length ≤ 1000
  • 0 ≤ nums1[i], nums2[i] ≤ 1000

Visualization

Tap to expand
Array Intersection Problemnums1 = [1,2,2,1]1221nums2 = [2,2]2212nums1nums2intersectionResult: [2]
Understanding the Visualization
1
Input
Two integer arrays with possible duplicates
2
Process
Find elements that appear in both arrays
3
Output
Array of unique common elements
Key Takeaway
🎯 Key Insight: Hash sets turn O(n×m) nested loops into O(n+m) single pass by providing O(1) lookups
Asked in
Google 42 Amazon 38 Microsoft 25 Facebook 22
78.5K Views
High Frequency
~15 min Avg. Time
2.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