Intersection of Two Arrays
EasyGiven two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and the result can be in any order.
Examples
| Input | Output |
|---|---|
| nums1 = [1,2,2,1], nums2 = [2,2] | [2] |
| nums1 = [4,9,5], nums2 = [9,4,9,8,4] | [4,9] or [9,4] |
Python Solution
def intersection(nums1: list[int], nums2: list[int]) -> list[int]:
set1 = set(nums1)
return list({x for x in nums2 if x in set1})JavaScript Solution
function intersection(nums1, nums2) {
const set1 = new Set(nums1);
return [...new Set(nums2.filter(x => set1.has(x)))];
}Step-by-Step Explanation
- Convert nums1 to a set for O(1) lookup.
- Filter nums2 for elements in set1, then deduplicate with a set.
Complexity Analysis
| Time | O(m + n) |
| Space | O(m) |
Tags
ArrayHash Map
Related Problems
Related Tools
All Problems
Two SumReverse a StringPalindrome CheckFizzBuzzBinary SearchReverse Linked ListMerge Two Sorted ArraysValid ParenthesesMaximum Subarray (Kadane's Algorithm)Remove Duplicates from Sorted ArrayNth Fibonacci NumberValid AnagramFirst Unique CharacterClimbing StairsRoman to IntegerBest Time to Buy and Sell StockContains DuplicateMove ZeroesLongest Common Prefix