# Intersection of Two Arrays II in Python

Suppose we have two arrays A and B, there are few elements in these array. We have to find the intersection of them. So if A = [1, 4, 5, 3, 6], and B = [2, 3, 5, 7, 9], then intersection will be [3, 5]

To solve this, we will follow these steps −

• Take two arrays A and B
• if length of A is smaller than length of B, then swap them
• calculate the frequency of elements in the array and store them into m
• for each element e in B, if e is present in m, and frequency is non-zero,
• decrease frequency m[e] by 1
• insert e into the resultant array
• return the resultant array

## Example

Let us see the following implementation to get better understanding −

class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
m = {}
if len(nums1)<len(nums2):
nums1,nums2 = nums2,nums1
for i in nums1:
if i not in m:
m[i] = 1
else:
m[i]+=1
result = []
for i in nums2:
if i in m and m[i]:
m[i]-=1
result.append(i)
return result

## Input

[1,4,5,3,6]
[2,3,5,7,9]

## Output

[3,5]
{"ft_lang_label":"__label__en","ft_lang_prob":0.70127577,"math_prob":0.99711126,"size":676,"snap":"2019-51-2020-05","text_gpt3_token_len":238,"char_repetition_ratio":0.12053572,"word_repetition_ratio":0.0,"special_character_ratio":0.39053255,"punctuation_ratio":0.23626374,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.99734056,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-01-18T22:31:12Z\",\"WARC-Record-ID\":\"<urn:uuid:5ffa3a13-16ce-4c78-9014-aa9dba843aca>\",\"Content-Length\":\"21891\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:8f323951-d213-4096-a2b7-f8dd7000393c>\",\"WARC-Concurrent-To\":\"<urn:uuid:8cd9bf66-f632-4e5c-ac67-783f78113462>\",\"WARC-IP-Address\":\"72.21.91.42\",\"WARC-Target-URI\":\"https://www.tutorialspoint.com/intersection-of-two-arrays-ii-in-python\",\"WARC-Payload-Digest\":\"sha1:I5DSUVBALSF6SCENYOKOHNDXQ742KSAP\",\"WARC-Block-Digest\":\"sha1:IWP4IZYQ4LO7FZ5KEZLENAAH2VRWTPGT\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-05/CC-MAIN-2020-05_segments_1579250593994.14_warc_CC-MAIN-20200118221909-20200119005909-00493.warc.gz\"}"}