Problem Description
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.
Key Insights
- Use a hash set for efficient O(1) membership tests.
- Converting one array into a set eliminates duplicates and facilitates quick lookups.
- Iterate through the other array and add common elements to a result set ensuring uniqueness.
- Alternative approaches include sorting and using two pointers or binary search, but a hash set approach offers a clear O(m+n) solution.
Space and Time Complexity
Time Complexity: O(m + n), where m and n are the lengths of nums1 and nums2 respectively. Space Complexity: O(min(m, n)), due to storing elements in the sets.
Solution
Convert one of the arrays (e.g., nums1) into a set to allow constant time existence checks. Then iterate over the elements of nums2, checking if each element is part of the nums1 set. When an element is found in both arrays, add it to a result set to ensure uniqueness. Finally, convert this set back to an array or list to return the result. This approach guarantees that every element is processed only once and automatically handles duplicate values.