π§© Problem Statement
Given 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 returned in any order.
π’ Examples
python
Input: nums1 = [1, 2, 2, 1], nums2 = [2, 2]
Output: [2]
Input: nums1 = [4, 9, 5], nums2 = [9, 4, 9, 8, 4]
Output: [9, 4] # or [4, 9]
β
Constraints
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000
π‘ Key Insight
This is a classic set theory problem:
You need to return the unique elements common to both arrays.
Pythonβs set
data structure makes this problem very easy and efficient.
β
Solution 1: Using Python Sets (One-liner)
π Python Code
python
class Solution:
def intersection(self, nums1, nums2):
return list(set(nums1) & set(nums2))
set(nums1)
and set(nums2)
remove duplicates.
&
computes the set intersection.
- Convert back to a list to return the result.
β±οΈ Time & Space Complexity
OperationComplexityTimeO(n + m)SpaceO(n + m)
Where n
and m
are lengths of nums1
and nums2
.
β
Solution 2: Manual Hash Set Check (Step-by-Step)
This approach is helpful for interviews where you want to show the logic clearly.
π Python Code
python
class Solution:
def intersection(self, nums1, nums2):
set1 = set(nums1)
result = set()
for num in nums2:
if num in set1:
result.add(num)
return list(result)
set1
: all unique elements from nums1
result
: store unique intersection elements from nums2
π Step-by-Step Walkthrough
Example:
python
nums1 = [1, 2, 2, 1]
nums2 = [2, 2]
set1 = {1, 2}
- Iterate over
nums2
:
- 2 β in
set1
β add to result
- 2 β already added β skip (sets prevent duplicates)
- Final
result = [2]
π§ Use Cases
- Database queries: find common user IDs
- Text processing: common words in documents
- API: determine shared resource access
β
Conclusion
LeetCode 349: Intersection of Two Arrays is a great introduction to set operations in Python.
Whether you use built-in operators or write the logic manually, understanding both is useful for coding interviews and real-world applications.
For follow-ups, check out:
- LeetCode 350 β Intersection II (includes duplicates)