algoadvance

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.

Example

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]

Clarifying Questions

  1. Can the arrays be empty?
    • Yes, the arrays can be empty. The intersection of two empty arrays is an empty array.
  2. Are there any constraints on the values within the arrays?
    • The arrays contain integers, and we generally need only to concern ourselves with typical integer values dealt with in standard computational tasks.
  3. Do we need to preserve the order of elements in the result?
    • No, the order of elements in the result does not matter according to the problem description.

Strategy

  1. Convert nums1 to a Set: Using a set will automatically handle the uniqueness requirement.
  2. Iterate Through nums2: Check if the current element exists in the set created from nums1.
  3. Add to Result Set: If the element from nums2 exists in the set from nums1, add it to a result set (this ensures uniqueness in results).
  4. Convert Result Set to List: Since the final result is required to be a list, convert the resultant set to a list.

Time Complexity

Python Code

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)

Example Execution

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.

Try our interview co-pilot at AlgoAdvance.com