349. Intersection of Two Arrays
349. Intersection of Two Arrays
Summary
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.
Approach
Use a hash set for the smaller array.
Then check each number in the larger array against that set.
Function
Initialization:
ans: set
Main:
smaller = nums1 if len(nums1) < len(nums2) else nums2
larger = nums1 if len(nums1) >= len(nums2) else nums2
smallerset = set()
For s in smaller:
smallerset.add(s)
For l in larger:
If l in smallerset:
ans.add(l)
Return list(ans).
Complexity
Time Complexity: O(len(nums1) + len(nums2)). First, we build a set for the smaller array. Then we scan the larger array. Finally, converting the answer set to a list takes linear time in the size of the result.
Space Complexity: O(min(len(nums1), len(nums2))).