349. Intersection of Two Arrays - Explanation
Description
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.
Note: The intersection of two arrays is defined as the set of elements that are present in both arrays.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]Explanation: [4,9] is also accepted.
Constraints:
1 <= nums1.length, nums2.length <= 10000 <= nums1[i], nums2[i] <= 1000
Topics
Prerequisites
Before attempting this problem, you should be comfortable with:
- Hash Set - Using sets for O(1) lookups and storing unique elements
- Hash Map - Tracking element presence or counts with key-value pairs
- Two Pointers - Using two indices to traverse sorted arrays efficiently
- Sorting - Understanding how sorted order enables efficient comparison algorithms
1. Brute Force
Intuition
The simplest approach is to check every element in the first array against every element in the second array. When we find a match, we add it to our result set. Using a set ensures we only include each common element once, even if it appears multiple times in both arrays.
Algorithm
- Initialize an empty set
resto store unique intersection elements. - For each element
iinnums1:- For each element
jinnums2:- If
i == j, additoresand break the inner loop.
- If
- For each element
- Convert
resto a list and return it.
Time & Space Complexity
- Time complexity:
- Space complexity:
Where is the size of the array and is the size of the array .
2. Sorting + Two Pointers
Intuition
By sorting both arrays, we can use two pointers to efficiently find common elements. We advance the pointer pointing to the smaller element. When both pointers point to equal elements, we found an intersection. We skip duplicates to ensure each element appears only once in the result.
Algorithm
- Sort both
nums1andnums2. - Initialize two pointers
iandjat the start of each array. - While both pointers are in bounds:
- Advance
jwhilenums2[j] < nums1[i]. - If
nums1[i] == nums2[j], add to result. - Advance
i, skipping any duplicates.
- Advance
- Return the result list.
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
nums1.sort()
nums2.sort()
n, m = len(nums1), len(nums2)
res, i, j = [], 0, 0
while i < n and j < m:
while j < m and nums2[j] < nums1[i]:
j += 1
if j < m:
if nums1[i] == nums2[j]:
res.append(nums1[i])
i += 1
while i < n and nums1[i] == nums1[i - 1]:
i += 1
return resTime & Space Complexity
- Time complexity:
- Space complexity:
Where is the size of the array and is the size of the array .
3. Hash Set
Intuition
Converting both arrays to sets removes duplicates and enables O(1) lookup. We then iterate through one set and check membership in the other. Any element present in both sets belongs to the intersection.
Algorithm
- Convert
nums1to a setset1. - Convert
nums2to a setset2. - Iterate through
set1:- If the element exists in
set2, add it to the result.
- If the element exists in
- Return the result list.
Time & Space Complexity
- Time complexity:
- Space complexity:
Where is the size of the array and is the size of the array .
4. Hash Map
Intuition
We use a hash map to track which elements from nums1 we have seen. We mark each element with value 1. When iterating through nums2, if we find a marked element, we add it to the result and set its value to 0 to prevent duplicates.
Algorithm
- Create a hash map
seenand mark all elements innums1with value1. - Initialize an empty result list.
- For each element in
nums2:- If
seen[num] == 1, addnumto result and setseen[num] = 0.
- If
- Return the result list.
Time & Space Complexity
- Time complexity:
- Space complexity:
Where is the size of the array and is the size of the array .
5. Hash Set (Optimal)
Intuition
We can improve on the two-set approach by using only one set. Store all elements from nums1 in a set, then iterate through nums2. When we find a match, add it to the result and remove it from the set to avoid duplicates.
Algorithm
- Create a set
seenfrom all elements innums1. - Initialize an empty result list.
- For each element in
nums2:- If the element is in
seen, add it to the result and remove it fromseen.
- If the element is in
- Return the result list.
Time & Space Complexity
- Time complexity:
- Space complexity:
Where is the size of the array and is the size of the array .
6. Built-In Functions
Intuition
Most programming languages provide built-in set intersection operations. By converting both arrays to sets and using the intersection function, we get a clean one-liner solution. The implementation details are handled by the language's standard library.
Algorithm
- Convert
nums1to a set. - Convert
nums2to a set. - Compute the intersection of the two sets using the built-in function.
- Convert the result to an array and return it.
Time & Space Complexity
- Time complexity: in average case, in worst case.
- Space complexity:
Where is the size of the array and is the size of the array .
Common Pitfalls
Including Duplicates in the Result
The intersection should contain each common element only once, even if it appears multiple times in both arrays. For example, if nums1 = [1, 1, 2] and nums2 = [1, 1], the result should be [1], not [1, 1]. Using a set for the result or marking elements as "already added" prevents this issue.
Comparing Values Instead of Using Efficient Lookups
A brute force approach comparing every pair of elements is O(n * m), which is inefficient for large arrays. The optimal approach uses a hash set for O(1) lookups, reducing time complexity to O(n + m). Always consider converting one array to a set before checking membership.
Sign in to join the discussion