Leetcode icon indicating copy to clipboard operation
Leetcode copied to clipboard

Add solution to Leetcode #349 - intersection of two arrays

Open konaraddi opened this issue 4 years ago • 0 comments

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

class Solution:
  def intersection(self, arrA: List[int], arrB: List[int]) -> List[int]:

    arrA.sort()
    arrB.sort()

    intersection = []

    aIndex = 0
    bIndex = 0
    recentOverlap = None

    while aIndex < len(arrA) and bIndex < len(arrB):
      if arrA[aIndex] > arrB[bIndex]:
        bIndex += 1
      elif arrA[aIndex] == arrB[bIndex]:
        if arrB[bIndex] != recentOverlap: # skip duplicate overlapping elements
          recentOverlap = arrB[bIndex]
          intersection.append(recentOverlap)
        bIndex += 1 # you could increment aIndex instead
      else:
        # arrA[aIndex] < arrB[bIndex]
        aIndex += 1

    return intersection

konaraddi avatar Oct 12 '19 18:10 konaraddi