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
Intersection of Two Arrays INPUT nums1 1 2 2 1 nums2 2 2 Input Values: nums1 = [1,2,2,1] nums2 = [2,2] Find common unique elements ALGORITHM STEPS 1 Create Set from nums1 set1 = {1, 2} 2 Create Result Set result = {} (empty) 3 Iterate nums2 Check if elem in set1 4 Add to Result If found, add to result Hash Set Lookup set1: 1 2 Check 2: 2 in set1? OK result: 2 FINAL RESULT Intersection Found 2 Output: [2] Status: OK Only element 2 appears in both arrays Key Insight: Using a HashSet converts nums1 to unique elements in O(n) time. Then iterating through nums2 and checking set membership is O(1) per element. Total time complexity: O(n + m), space: O(n). TutorialsPoint - Intersection of Two Arrays | Hash Set - Single Pass
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