LeetCode 350. Intersection of Two Arrays II

Post by ailswan Dec. 13, 2023

350. Intersection of Two Arrays II

Problem Statement

link: LeetCode.cn LeetCode

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.

Example:

Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2, 2]

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4, 9]

Solution Approach

The solution utilizes a dictionary to count occurrences of elements in one array, then iterates through the other array to find and append elements with their proper counts in the intersection list.

Algorithm

  1. Create a dictionary count1 to count the occurrences of each element in nums1.
  2. Initialize an empty list res to store the intersection of arrays.
  3. Iterate through each element n in nums2, if n is found in count1 and its count is greater than 0, append n to res and decrement its count in count1.
  4. Return the res list containing the intersection elements with their proper counts.

Implement

    class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
      count1 = collections.Counter(nums1)
      res = []
      for n in nums2:
          if n in count1 and count1[n] > 0:
              res.append(n)
              count1[n] -= 1
      return res