308. Intersection of Two Arrays
Easy
Set Intersection
Hashing
Problem
Given two integer arrays nums1 and nums2, return an array containing their distinct common elements. Each value must appear only once in the result, and the result may be returned in any order.
Examples
Example 1
Input: [1,2,2,1], [2,2]
Output: [2]
Example 2
Input: [4,9,5], [9,4,9,8,4]
Output: [4,9]
Example 3
Input: [1], [2]
Output: []
Constraints
� 1 <= nums1.length, nums2.length <= 1000
� -1000 <= nums1[i], nums2[i] <= 1000
Hints
?? Store the distinct values of one array in a set.
?? Check which values of the other array belong to that set.
?? Use another set or delete matched values to avoid duplicates.
Expected Complexity
Time: O(n + m)
Space: O(n)
Follow-up
How would you solve the problem if both arrays were already sorted?
Practice Notes
Attempts: 0
Time spent: 0min
Hints used: 0
JavaScript
00:00
Loading...
Case 1
Case 2
Case 3
Input
[1,2,2,1], [2,2]Expected
[2]