The intersection of two arrays II solution ~ Leetcode

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]
  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.
  • Create two counters representing the number of times each element appeared in the array for both arrays.
  • Iterate through the keys of the first counter and check if the key exists in the second counter.
  • If the key exists, add the key to the output array. It has to be extended with the minimum number of times the key appeared in either of those arrays.
from collections import Counter
class Solution(object):
def intersect(self, nums1, nums2):
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
counter_1 = Counter(nums1) #creates a dictionary of key value pairs
counter_2 = Counter(nums2)
output = [] #output array to store the ouput
for key in counter_1.keys():
if key in counter_2.keys():
output.extend([key]*min(counter_1[key], counter_2[key]))
return output


Input: nums1 = [1,1], nums2 = [2,2,5,6,9,0,5,3,4]
Output: []



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store