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.
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]
nums1 to a Set: Using a set will automatically handle the uniqueness requirement.nums2: Check if the current element exists in the set created from nums1.nums2 exists in the set from nums1, add it to a result set (this ensures uniqueness in results).nums1.nums2 and performing set operations for each element takes (O(m)) time where (m) is the length of nums2.def intersection(nums1, nums2):
# Convert nums1 to a set
set1 = set(nums1)
# Create an empty set for the result
result_set = set()
# Iterate through nums2 and check for intersections
for num in nums2:
if num in set1:
result_set.add(num)
# Convert the result set to a list and return
return list(result_set)
nums1 = [4,9,5]
nums2 = [9,4,9,8,4]
print(intersection(nums1, nums2)) # Output: [9, 4]
nums1 = [1,2,2,1]
nums2 = [2,2]
print(intersection(nums1, nums2)) # Output: [2]
This solution effectively and efficiently captures the intersection of two arrays while ensuring that the result contains unique elements.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?