LeetCode 15 - Intersection of Two Arrays

Intersection of Two Arrays

Given two arrays, write a function to compute their intersection.

1
2
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].

Note:

Each element in the result must be unique.
The result can be in any order.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
class Solution(object):
def intersection(self, nums1, nums2):
unique_nums1 = set()
unique_nums2 = set()
for number in nums1:
unique_nums1.add(number)
for number in nums2:
unique_nums2.add(number)
return list(unique_nums1 & unique_nums2)

A set only allows unique values. The key here is to create a set for both nums1 and nums2 and then return the intersection of the two sets. unique_nums1 & unique_nums2 returns another set so it is important to convert that to a list.

Time complexity O(n) because you need to run through both nums1 and nums2.

Space complexity O(n) because you need to allocate a set for each of the two arrays.

Apparently according to the fastest solutions on LeetCode, you can trim this down to a oneliner return list(set(nums1) & set(nums2)).