Parottasalna Course Notes
Algorithm

POTD #9 - Intersection of Two arrays with Duplicate Elements | Geeks For Geeks

Problem Statement

Geeks For Geeks – https://www.geeksforgeeks.org/problems/intersection-of-two-arrays-with-duplicate-elements/1

Given two integer arrays a[] and b[], you have to find the intersection of the two arrays. Intersection of two arrays is said to be elements that are common in both arrays. The intersection should not have duplicate elements and the result should contain items in any order.

Note:The driver code will sort the resulting array in increasing order before printing

Input: a[] = [1, 2, 1, 3, 1], b[] = [3, 1, 3, 4, 1]
Output: [1, 3]
Explanation: 1 and 3 are the only common elements and we need to print only one occurrence of common elements.

Input: a[] = [1, 1, 1], b[] = [1, 1, 1, 1, 1]
Output: [1]
Explanation: 1 is the only common element present in both the arrays.

My Approach

  • Made an entry to a dict for all num present in a
  • While iterating b, if a num is present in the dict, then added it to the result set.
  • return the list of the result set.
class Solution:
    def intersectionWithDuplicates(self, a, b):
        # code here
        result = set()
        hash_set = {}
        for item in a:
            if hash_set.get(item) is None:
                hash_set[item] = True
        
        for item in b:
            if hash_set.get(item):
                result.add(item)
        
        return list(result)

Originally published on parottasalna.com.

Related posts