LC 349 & LC 350


Solution to LeetCode 349 Intersection of Two Arrays and LeetCode 350 Intersection of Two Arrays II.

LeetCode 349

Intersection of Two Arrays (Easy) [link]

Time complexity O(n). Space complexity O(n).

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        table1 = collections.defaultdict(int)
        table2 = collections.defaultdict(int)
        for i in range(len(nums1)):
            table1[nums1[i]] += 1
        for i in range(len(nums2)):
            table2[nums2[i]] += 1
        res=[]
        for i in table1.keys():
            if i in table2.keys():
                res.append(i)
        return res
class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        table1 = collections.Counter(nums1)
        table2 = collections.Counter(nums2)
        res=[]
        for i in table1.keys():
            if i in table2.keys():
                res.append(i)
        return res

LeetCode 350

Intersection of Two Arrays II (Easy) [link]

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        table1 = collections.Counter(nums1)
        table2 = collections.Counter(nums2)
        res=[]
        for i in table1.keys():
            if i in table2.keys():
                for j in range(min(table1[i], table2[i])):
                    res.append(i)
        return res

  TOC