Intersection of Two Arrays — LeetCode 349 Python Solution
EasyArrayHash TableTwo PointersBinary SearchSorting
- Problem
- #349
- 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 be unique and you may return the result in any order.
Example
- Input
- nums1 = [1,2,2,1], nums2 = [2,2]
- Output
- [2]
Python solution
Python
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return list(set(nums1) & set(nums2))Complexity
| Measure | Complexity |
|---|---|
| Time | O(n+m) |
| Space | O(n) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 349. Intersection of Two Arrays 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 349. Intersection of Two Arrays?
- LeetCode 349. Intersection of Two Arrays is rated Easy on LeetCode.
- What is the time complexity of LeetCode 349. Intersection of Two Arrays?
- The Python solution on this page runs in O(n+m).
- What is the space complexity of LeetCode 349. Intersection of Two Arrays?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 349. Intersection of Two Arrays cover?
- LeetCode 349. Intersection of Two Arrays is tagged Array, Hash Table, Two Pointers, Binary Search and Sorting on LeetCode.