I am practicing leetcode. Here is the question. https://leetcode.com/problems/intersection-of-two-arrays-ii/:
Given two integer arrays
nums1andnums2, 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.
Where I am doing the mistake?
def intersect(nums1: List[int], nums2: List[int]) -> List[int]:
ht = dict()
length1 = len(nums1)
length2 = len(nums2)
longer = []
smaller = []
intersection = []
if length1 > length2:
longer = nums1
smaller = nums2
else:
longer = nums2
smaller = nums1
for i in range(len(longer)):
ht[i] = longer[i]
for j in range(len(smaller)):
if smaller[j] in ht:
intersection.append(smaller[j])
else:
j += 1
return intersection
The answer is accepted for
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
However, it fails for
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
My output is [4].