Minimum delete operations to make all elements of array same in Python

Today we’ll be learning to determine the required number of minimum delete operations to make all elements of array same in Python.

Determine the number of minimum delete operations to get an array of the same elements

We’ll go ahead by creating a dictionary data type. It will store all the individual elements as it’s key and the count of their appearance as the value.

The strategy is to keep all the appearances of the element having the highest frequency and delete all the other elements.

To determine the number, we’ll need to find the difference between the total number of the elements of the array and the frequency of the element having maximum appearances.

To store the individual elements in a dictionary, we’ll be checking whether the element is already present in the dictionary by using the ‘get’ function.

The ‘get’ function takes two parameters. The first parameter is the ‘key’ which needs to be searched. The second parameter is the value that would be returned if the key is not present in the dictionary.

To find the element having the highest frequency, we’ll use the built-in ‘max’ function over the ‘dict_values’ type of class, similar to a list, which will be returned by ‘values’ function.

Algorithm:

  • Create a dictionary that stores all the elements that appear in the array, along with the frequency.
  • Find the frequency of the element having the highest number of appearances.
  • Find the number of minimum delete operations.

Code:

def countFreq(arr):
    count = dict()
    
    for ele in arr:
        freq = count.get(ele, 0)
        if freq:
            count[ele] += 1
        else:
            count[ele] = 1
    
    return count

def findMax(count):
    return (max(count.values())) 

def minDelete(count, arr):
    numElements = len(arr)
    maxElement = findMax(count)
    
    return (numElements - maxElement)


arr = list(map(int, input("Enter your array: ").split()))
count = countFreq(arr)
print ("The minimum number of delete operations is", minDelete(count, arr))

Execution:

Enter your array: 9 8 6 5 7 9 6 2 9 9
The minimum number of delete operations is 6

More:

Please share this blog post if you enjoyed reading it!

Leave a Reply

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