
Sponsored
Sponsored
This approach utilizes hash sets to efficiently track and identify unique intersections between the two arrays. By converting one of the arrays into a set, we can check for existence of elements in constant time, and we store intersections in another set to ensure uniqueness.
Time complexity is O(n + m) for inserting and checking elements, with n and m being the sizes of nums1 and nums2 respectively. Space complexity is O(n + m) for the two sets used.
1def intersection(nums1, nums2):
2 set1 = set(nums1)
3 resultSet = set()
4
5 for num in nums2:
6 if num in set1:
7 resultSet.add(num)
8
9 return list(resultSet)
10
11nums1 = [4, 9, 5]
12nums2 = [9, 4, 9, 8, 4]
13result = intersection(nums1, nums2)
14print(result)This Python solution leverages Python's native set data structure to perform the intersection. It stores nums1 in a set and then iterates through nums2, checking for presence in set1 and adding to resultSet for the results.
This approach sorts both arrays and uses two pointers to identify the intersection. The sorted order ensures that we can efficiently find common elements in a single pass through both arrays.
Time complexity is O(n log n + m log m) due to sorting, where n and m are the sizes of nums1 and nums2. Space complexity is O(n + m) for storing the sorted arrays.
1
This JavaScript solution sorts both arrays and uses two indices to find common elements. Only distinct elements are collected in the result array by checking the last item pushed.