Intersection of Two Arrays II — LeetCode 350 Python Solution

EasyArrayHash TableTwo PointersBinary SearchSorting
Problem
#350
Reading time
2 min

The problem

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]

Python solution

Python
class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        cnt = Counter(nums1)
        ans = []
        for x in nums2:
            if cnt[x]:
                ans.append(x)
                cnt[x] -= 1
        return ans

Complexity

MeasureComplexity
TimeO(m + n)
SpaceO(m) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 350. Intersection of Two Arrays II is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 350. Intersection of Two Arrays II?
LeetCode 350. Intersection of Two Arrays II is rated Easy on LeetCode.
What is the time complexity of LeetCode 350. Intersection of Two Arrays II?
The Python solution on this page runs in O(m + n).
What is the space complexity of LeetCode 350. Intersection of Two Arrays II?
The Python solution on this page uses O(m) auxiliary space.
What topics does LeetCode 350. Intersection of Two Arrays II cover?
LeetCode 350. Intersection of Two Arrays II is tagged Array, Hash Table, Two Pointers, Binary Search and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview