Intersection of Two Arrays

Easy

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and the result can be in any order.

Examples

InputOutput
nums1 = [1,2,2,1], nums2 = [2,2][2]
nums1 = [4,9,5], nums2 = [9,4,9,8,4][4,9] or [9,4]

Python Solution

def intersection(nums1: list[int], nums2: list[int]) -> list[int]:
    set1 = set(nums1)
    return list({x for x in nums2 if x in set1})

JavaScript Solution

function intersection(nums1, nums2) {
  const set1 = new Set(nums1);
  return [...new Set(nums2.filter(x => set1.has(x)))];
}

Step-by-Step Explanation

  1. Convert nums1 to a set for O(1) lookup.
  2. Filter nums2 for elements in set1, then deduplicate with a set.

Complexity Analysis

TimeO(m + n)
SpaceO(m)

Tags

ArrayHash Map

Related Problems

Related Tools

All Problems