Remove minimum number of elements such that no common element exist in both array in Python

In this tutorial, we will write a Python program to remove minimum elements from the array so that no common elements exist in both arrays.

Following is the approach we are going to follow:

We will count the occurrence of each element in both the array and store them in the python dictionary. Then we will check if there are any common elements in the arrays if yes then remove the element from the array which has fewer occurrences because we want to remove minimum elements while doing so we also count the number of elements removed and print them.

Consider the following example for a better understanding.

Consider two Array
A = [1 2 2 3 4 4 5 6]
B = [2 4 7 8 9]
Counting the occurrence of each elements of both the array
occA = { 1:1, 2:2, 3:1, 4:2, 5:1, 6:1 }
occB = { 2:1, 4:1, 7:1, 8:1, 9:1 }
The common elements of both the array are 2 and 4
The array B has minimum occurrences of 2 and 4 so we remove them.
Hence minimum number of elements removed is 2 and both array become
A = [1 2 2 3 4 4 5 6]
B = [7 8 9]

Python program to remove minimum elements from the array such that no common elements exist in both arrays

Following is the code snippet

#Program to Remove minimum number of elements such that no common element exist in both array in Python

#function to remove minimum elements
def removeMinEle(A, B):
    
    occA = {}
    occB = {}
    
    #counting the occurrrence of elements of A
    for element in A:
        if element not in occA: 
            occA[element]=1
        else:
            occA[element]+=1
            
    #counting the occurrrence of elements of B
    for element in B:
        if element not in occB: 
            occB[element]=1
        else:
            occB[element]+=1
    
    #removing minimum occurace of common elements
    removed=0
    for element in occA.keys():
        if element in occB.keys():
            removed = removed + min(occA[element],occB[element])
            
    return removed


# Driver Program

A = [1, 2, 2, 3, 4, 4, 5, 6]
B = [2, 4, 7, 8, 9]

removed = removeMinEle(A,B)

print("Number of Removed elements")
print(removed)

OUTPUT:

Number of  Removed elements
2

Leave a Reply

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