Intersection of Two Arrays
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.
- 1 ≤ nums1.length, nums2.length ≤ 10⁴
- −10⁹ ≤ nums1[i], nums2[i] ≤ 10⁹
Example
nums1 = [1,2,2,1], nums2 = [2,2][2]A brute-force approach would check every element in nums1 against every element in nums2, resulting in O(n*m) time complexity. Instead, by converting nums1 to a set, we enable O(1) average-time membership checks. Iterating over the unique elements of nums2 and checking membership in nums1's set allows us to build the intersection efficiently. The critical moment is when the algorithm encounters '2' in nums2's unique set and confirms it exists in nums1's set, adding it to the result. This approach guarantees uniqueness and avoids duplicates naturally.
Approach
Straightforward Solution
A naive approach uses nested loops to check each element of nums1 against every element of nums2, resulting in O(n*m) time complexity, which is inefficient for large inputs.
Core Observation
The intersection requires identifying elements common to both arrays, but only once each. Sets provide O(1) average-time membership checks and inherently store unique elements, making them ideal for this problem.
Path to Optimal
Recognizing that uniqueness and membership checks are central, converting nums1 to a set allows constant-time lookups. Iterating over the unique elements of nums2 (also converted to a set) and checking for membership in nums1's set yields the intersection elements efficiently. This reduces time complexity to O(n + m) on average.
Optimal Approach
Convert nums1 to a set for O(1) membership checks. Iterate over the unique elements of nums2, and for each element, check if it exists in nums1's set. If yes, append it to the result list. Return the result list containing unique intersection elements.
Time
O(n + m)
Converting nums1 to a set takes O(n), iterating over the unique elements of nums2 takes O(m), and each membership check is O(1) on average, resulting in O(n + m) total time.
Space
O(n)
The set storing nums1's elements requires O(n) auxiliary space, proportional to the size of nums1. The output list uses space proportional to the intersection size, which is unavoidable.
Pattern Spotlight
Hash Maps (Set Membership for Intersection)
Use a hash set to store one array's elements for O(1) membership queries, then iterate over the unique elements of the other array to efficiently build the intersection without duplicates.
Solution
| 1 | class Solution: |
| 2 | def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: |
| 3 | nums1_set = set(nums1) |
| 4 | unique_intersection = [] |
| 5 | |
| 6 | for num in set(nums2): |
| 7 | if num in nums1_set: |
| 8 | unique_intersection.append(num) |
| 9 | |
| 10 | return unique_intersection |
Step-by-Step Solution
Build a Set from the First Array to Enable Fast Membership Checks
| 3 | nums1_set = set(nums1) |
| 4 | unique_intersection = [] |
Objective
To create a hash set from nums1 that allows constant-time membership queries.
Key Insight
Converting nums1 into a set removes duplicates and enables O(1) average-time membership checks. This transforms the problem from a costly nested search into a simple lookup operation, which is the foundation for an efficient intersection algorithm.
Interview Quick-Check
Core Logic
Using a set for nums1 allows the algorithm to check if an element from nums2 exists in nums1 in constant time.
Common Pitfalls & Bugs
Failing to convert nums1 to a set results in O(n*m) time complexity due to repeated linear searches.
Iterate Over Unique Elements of the Second Array to Collect Intersection
| 6 | for num in set(nums2): |
| 7 | if num in nums1_set: |
| 8 | unique_intersection.append(num) |
Objective
To iterate through the unique elements of nums2 and collect those present in nums1's set.
Key Insight
Iterating over the unique elements of nums2 (by converting it to a set) ensures that duplicates in nums2 do not cause repeated entries in the result. Checking membership in nums1's set filters only common elements. Appending these elements to the result list builds the intersection efficiently and correctly.
Interview Quick-Check
Core Logic
Iterating over set(nums2) guarantees uniqueness in the iteration, preventing duplicate intersection entries.
State & Boundaries
The membership check `if num in nums1_set` ensures only common elements are added.
Common Pitfalls & Bugs
Iterating over nums2 without converting to a set can cause duplicates in the output.
Return the List of Unique Intersection Elements
| 10 | return unique_intersection |
Objective
To return the collected list of unique intersection elements as the final result.
Key Insight
After building the list of unique intersection elements, returning it completes the solution. The list contains no duplicates due to the iteration over set(nums2) and membership checks against nums1's set.
Interview Quick-Check
Core Logic
Returning the result list provides the final answer containing all unique elements common to both arrays.
Line Analysis
This solution has 2 Critical lines interviewers watch for.
if num in nums1_set:
Check if the current element from nums2 exists in nums1's set.
This membership check filters only elements common to both arrays, which is the fundamental operation for computing the intersection.
nums1_set = set(nums1)
Convert nums1 into a set to enable O(1) membership checks.
This conversion is the key optimization that transforms membership queries from O(n) linear scans to O(1) average-time lookups, drastically improving efficiency.
for num in set(nums2):
Iterate over the unique elements of nums2 by converting it to a set.
Converting nums2 to a set ensures that duplicates in nums2 do not cause repeated intersection entries, maintaining uniqueness in the output.
unique_intersection.append(num)
Append the common element to the result list.
Adding the element to the result list builds the final intersection output, ensuring each element appears only once due to prior uniqueness guarantees.
unique_intersection = []
Initialize the result list that will hold the unique intersection elements.
This list stores the elements that are confirmed to appear in both arrays. It starts empty because no common elements have been found yet.
return unique_intersection
Return the list of unique intersection elements.
Returning the result completes the function, providing the caller with the correctly computed intersection.
Test Your Understanding
Why does converting nums1 to a set improve the efficiency of finding the intersection?
Because a set provides O(1) average-time membership checks, allowing the algorithm to quickly determine if an element from nums2 exists in nums1 without scanning the entire array, reducing the time complexity from O(n*m) to O(n + m).
Related Problems
Hash Maps pattern
Don't just read it. Drill it.
Reconstruct Intersection of Two Arrays from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.
Unlock the Intersection of Two Arrays drill