We can use hash sets to find the intersection efficiently. Convert both arrays to sets and find their common elements.
- Convert
nums1to sets1. - Convert
nums2to sets2. - Return the list of elements present in both
s1ands2.
- Time Complexity: O(N + M).
- Space Complexity: O(N + M).
def intersection(nums1, nums2):
return list(set(nums1) & set(nums2))