Friedrich Ewald My Personal Website

Leetcode: Intersection of two arrays II

Given two arrays, nums1 and nums2, return the intersection of those arrays in any order. The easiest way I was able to come up with was to sort the arrays first and then look at the beginning of the arrays. If both are equal, add the element to the output and pop the first element from each array. Otherwise, pop the smaller element of both arrays. Repeat this until one of the arrays is empty at which point there can be no more intersecting elements.

class Solution:
  def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
    nums1.sort()
    nums2.sort()
    out = []
    while len(nums1) > 0 and len(nums2) > 0:
      if nums1[0] == nums2[0]:
        out.append(nums1[0])
        nums1 = nums1[1:]
        nums2 = nums2[1:]
      elif nums1[0] < nums2[0]:
        nums1 = nums1[1:]
      else:
        nums2 = nums2[1:]
    return out
Runtime: 62 ms, faster than 80.36% of Python3 online submissions for Intersection of Two Arrays II. Memory Usage: 14.2 MB, less than 14.77% of Python3 online submissions for Intersection of Two Arrays II.


About the author

is an experienced Software Engineer with a Master's degree in Computer Science. He started this website in late 2015, mostly as a digital business card. He is interested in Go, Python, Ruby, SQL- and NoSQL-databases, machine learning and AI and is experienced in building scalable, distributed systems and micro-services at multiple larger and smaller companies.