Intersection of Two Arrays II — LeetCode 350 Python Solution
- Problem
- #350
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(m + n) |
| Space | O(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.