349. Intersection of Two Arrays

# Easy

Key: use set to improve efficiency.

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        result = set()
        set1 = set(nums1)
        set2 = set(nums2)
        
        if len(set1)  <  len(set2):
            return self.helper(set1, set2)
        else:
            return self.helper(set2, set1)
        
    def helper(self, set1, set2):
        return [x for x in set1 if x in set2]

Time complexity = O(m+n)O(m+n) . Space complexity = O(n+m)O(n+m) except the result.

Last updated