*LeetCode 350 – Python 3 (Week 06 – 11)

I am not sure if the time complexity is right.

Solution 1

 class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        if len(nums1) > len(nums2):
            return self.intersect(nums2, nums1)
        
        lookup = collections.defaultdict(int)
        
        for num in nums1:
            lookup[num] += 1
            
        ans = []
        
        for num in nums2:
            if lookup[num] > 0:
                ans.append(num)
                lookup[num] -= 1
                
        return ans

Time complexity is O(n^2). Space complexity is O(m+n).

Leave a comment

Design a site like this with WordPress.com
Get started