Minimum delete operations to make all elements of array same in C++.


Problem statement

Given an array of n elements such that elements may repeat. We can delete any number of elements from array. The task is to find a minimum number of elements to be deleted from array to make it equal.

arr[] = {10, 8, 10, 7, 10, -1, -4, 12}

We have to delete highlighted 5 elements to make all array elements the same.

Algorithm

1. Count frequency of each element
2. Find maximum frequecy among the frequencies. Let us call this as maxFrequncy
3. Elements to be deleted: n – maxFrequecy where n is size of an array

Example

#include <iostream>
#include <unordered_map>
#include <climits>
#define SIZE(arr) (sizeof(arr)/sizeof(arr[0]))
using namespace std;
int minDeleteOperations(int *arr, int n){
   unordered_map<int, int> frequecy;
   int maxFrequency = INT_MIN;
   for (int i = 0; i < n; ++i) {
      frequecy[arr[i]]++;
   }
   for (auto it = frequecy.begin(); it != frequecy.end(); ++it) {
      maxFrequency = max(maxFrequency, it->second);
   }
   return (n - maxFrequency);
}
int main(){
   int arr[] = {10, 8, 10, 7, 10, -1, 9, 4};
   cout << "Required deletes: " << minDeleteOperations(arr, SIZE(arr)) << "\n";
   return 0;
}

Output

When you compile and execute the above program. It generates the following output −

Required deletes: 5

Updated on: 23-Sep-2019

128 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements