LeetCode 349. Intersection of Two Arrays

Description

https://leetcode.com/problems/intersection-of-two-arrays/

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

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]

Note:

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

Explanation

Convert two lists to two sets and then find numbers which are in both sets.

Python Solution

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        results = []
        
        nums1 = set(nums1)
        nums2 = set(nums2)
        
        for num in nums2:
            if num in nums1:
                results.append(num)
                                
        return results
  • Time Complexity: O(N).
  • Space Complexity: O(N).

Leave a Reply

Your email address will not be published. Required fields are marked *