350. Intersection of Two Arrays II

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        c1 = Counter(nums1)
        c2 = Counter(nums2)

        ans = []
        for e in nums1:
            if c1[e] and c2[e]:
                minCount = min(c1[e], c2[e])
                ans += [e] * minCount
                c1[e] = 0
                c2[e] = 0

        return ans
class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        count = defaultdict(int)
        for e in nums1:
            count[e] += 1

        ans = []
        for e in nums2:
            if count[e]:
                ans.append(e)                    
                count[e] -= 1

        return ans