Minimum removals required to make frequency of all remaining array elements equal
Given an array arr[] of size N, the task is to find the minimum number of array elements required to be removed such that the frequency of the remaining array elements become equal.
Examples :
Input: arr[] = {2, 4, 3, 2, 5, 3}
Output: 2
Explanation: Following two possibilities exists:
1) Either remove an occurrence of 2 and 3. The array arr[] modifies to {2, 4, 3, 5}. Therefore, frequency of all the elements become equal.
2) Or, remove an occurrence of 4 and 5. The array arr[] modifies to {2, 3, 2, 3}. Therefore, frequency of all the elements become equal.
Input: arr[] = {1, 1, 2, 1}
Output: 1
Naive Approach: We count the frequency of each element in an array. Then for each value v in frequency map, we traverse the frequency map and check whether this current value is less than v, if it is true then we add this current value to our result and if it is false then we add the difference between the current value and v to our result. After each traversal, store minimum of current result and previous result.
Algorithm:
Step 1: Create a function called “minDelete” that accepts the arguments arr, an integer array of size n, and the function name.
Step 2: Create an unordered map called “freq” to keep track of each element’s frequency in the input array. Set each element’s frequency to 0 at the beginning.
Step 3: Increase the frequency of each element in the “freq” map as you traverse the input array.
Step 4: Set two variables, “tempans” and “res,” to their respective initial values of 0 and INT MAX.
Step 5: Use the iterator “itr” to navigate the “freq” map. Repeat the traversal of the map for each element using an additional iterator called “j”.
a. Increase “tempans” by the frequency of the element pointed by “j” if its frequency is lower than that of the element pointed by “itr”.
b. If the frequency of the element pointed by “j” is greater than or equal to that of the element pointed by “itr”, increment “tempans” by the difference between the frequency of the element pointed by “j” and that of the element pointed by “itr”.
Step 6: Update “res” with the minimum value between “res” and “tempans”.
Step 7: Return res.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minDelete( int arr[], int n)
{
unordered_map< int , int > freq;
for ( int i = 0; i < n; i++)
freq[arr[i]]++;
int tempans, res = INT_MAX;
for ( auto itr = freq.begin(); itr != freq.end();
itr++) {
tempans = 0;
for ( auto j = freq.begin(); j != freq.end(); j++) {
if (j->second < itr->second) {
tempans = tempans + j->second;
}
else {
tempans
= tempans + (j->second - itr->second);
}
}
res = min(res, tempans);
}
return res;
}
int main()
{
int arr[] = {2, 4, 3, 2, 5, 3};
int n = sizeof (arr) / sizeof (arr[0]);
cout << minDelete(arr, n);
return 0;
}
|
Java
import java.util.HashMap;
import java.util.Map;
class Main
{
static int minDelete( int arr[], int n)
{
Map<Integer, Integer> freq = new HashMap<>();
for ( int i = 0 ; i < n; i++)
freq.put(arr[i], freq.getOrDefault(arr[i], 0 ) + 1 );
int tempans, res = Integer.MAX_VALUE;
for (Map.Entry<Integer, Integer> itr : freq.entrySet()) {
tempans = 0 ;
for (Map.Entry<Integer, Integer> j : freq.entrySet()) {
if (j.getValue() < itr.getValue()) {
tempans = tempans + j.getValue();
}
else {
tempans = tempans + (j.getValue() - itr.getValue());
}
}
res = Math.min(res, tempans);
}
return res;
}
public static void main(String args[])
{
int arr[] = { 2 , 4 , 3 , 2 , 5 , 3 };
int n = arr.length;
System.out.println(minDelete(arr, n));
}
}
|
Python3
import sys
def minDelete(arr, n):
freq = {}
for i in range (n):
if (arr[i] in freq):
freq[arr[i]] = freq[arr[i]] + 1
else :
freq[arr[i]] = 1
tempans, res = sys.maxsize,sys.maxsize
for [key,value] in freq.items():
tempans = 0
for [key1,value1] in freq.items():
if (value1 < value):
tempans = tempans + value1
else :
tempans = tempans + (value1 - value)
res = min (res, tempans)
return res
arr = [ 2 , 4 , 3 , 2 , 5 , 3 ]
n = len (arr)
print (minDelete(arr, n))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int MinDelete( int [] arr, int n)
{
Dictionary< int , int > freq = new Dictionary< int , int >();
for ( int i = 0; i < n; i++)
{
if (freq.ContainsKey(arr[i]))
{
freq[arr[i]]++;
}
else
{
freq[arr[i]] = 1;
}
}
int tempans, res = int .MaxValue;
foreach (KeyValuePair< int , int > itr in freq)
{
tempans = 0;
foreach (KeyValuePair< int , int > j in freq)
{
if (j.Value < itr.Value)
{
tempans = tempans + j.Value;
}
else
{
tempans = tempans + (j.Value - itr.Value);
}
}
res = Math.Min(res, tempans);
}
return res;
}
static void Main( string [] args)
{
int [] arr = { 2, 4, 3, 2, 5, 3 };
int n = arr.Length;
Console.WriteLine(MinDelete(arr, n));
}
}
|
Javascript
<script>
function minDelete(arr, n)
{
let freq = new Map();
for (let i = 0; i < n; i++){
if (freq.has(arr[i])){
freq.set(arr[i],freq.get(arr[i])+1);
}
else freq.set(arr[i],1);
}
let tempans, res = Number.MAX_VALUE;
for (let [key,value] of freq){
let tempans = 0;
for (let [key1,value1] of freq) {
if (value1 < value) {
tempans = tempans + value1;
}
else {
tempans = tempans + (value1 - value);
}
}
res = Math.min(res, tempans);
}
return res;
}
let arr = [2, 4, 3, 2, 5, 3];
let n = arr.length;
document.write(minDelete(arr, n));
</script>
|
Efficient Approach: Follow the steps below to solve the problem:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minDeletions( int arr[], int N)
{
map< int , int > freq;
for ( int i = 0; i < N; i++) {
freq[arr[i]]++;
}
vector< int > v;
for ( auto z : freq) {
v.push_back(z.second);
}
sort(v.begin(), v.end());
int size = v.size();
int ans = N - (v[0] * size);
for ( int i = 1; i < v.size(); i++) {
if (v[i] != v[i - 1]) {
int safe = v[i] * (size - i);
ans = min(ans, N - safe);
}
}
cout << ans;
}
int main()
{
int arr[] = { 2, 4, 3, 2, 5, 3 };
int N = sizeof (arr) / sizeof (arr[0]);
minDeletions(arr, N);
}
|
Java
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.Collections;
class GFG {
public static void minDeletions( int arr[], int N)
{
HashMap<Integer, Integer> map = new HashMap<>();
;
for ( int i = 0 ; i < N; i++) {
Integer k = map.get(arr[i]);
map.put(arr[i], (k == null ) ? 1 : k + 1 );
}
ArrayList<Integer> v = new ArrayList<>();
for (Map.Entry<Integer, Integer> e :
map.entrySet()) {
v.add(e.getValue());
}
Collections.sort(v);
int size = v.size();
int ans = N - (v.get( 0 ) * size);
for ( int i = 1 ; i < v.size(); i++) {
if (v.get(i) != v.get(i - 1 )) {
int safe = v.get(i) * (size - i);
ans = Math.min(ans, N - safe);
}
}
System.out.println(ans);
}
public static void main(String[] args)
{
int arr[] = { 2 , 4 , 3 , 2 , 5 , 3 };
int N = 6 ;
minDeletions(arr, N);
}
}
|
Python3
from collections import defaultdict
def minDeletions(arr, N):
freq = defaultdict( int )
for i in range (N):
freq[arr[i]] + = 1
v = []
for z in freq.keys():
v.append(freq[z])
v.sort()
size = len (v)
ans = N - (v[ 0 ] * size)
for i in range ( 1 , len (v)):
if (v[i] ! = v[i - 1 ]):
safe = v[i] * (size - i)
ans = min (ans, N - safe)
print (ans)
if __name__ = = "__main__" :
arr = [ 2 , 4 , 3 , 2 , 5 , 3 ]
N = len (arr)
minDeletions(arr, N)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void minDeletions( int []arr, int N)
{
Dictionary< int , int > freq = new Dictionary< int , int >();
for ( int i = 0; i < N; i++)
{
if (freq.ContainsKey(arr[i]))
freq[arr[i]]++;
else
freq[arr[i]] = 1;
}
List< int > v = new List< int >();
foreach ( var z in freq) {
v.Add(z.Value);
}
int sz = v.Count;
int []temp = new int [sz];
for ( int i = 0; i < v.Count; i++)
temp[i] = v[i];
Array.Sort(temp);
for ( int i = 0; i < v.Count; i++)
v[i] = temp[i];
int size = v.Count;
int ans = N - (v[0] * size);
for ( int i = 1; i < v.Count; i++) {
if (v[i] != v[i - 1]) {
int safe = v[i] * (size - i);
ans = Math.Min(ans, N - safe);
}
}
Console.WriteLine(ans);
}
public static void Main()
{
int []arr = { 2, 4, 3, 2, 5, 3 };
int N = arr.Length;
minDeletions(arr, N);
}
}
|
Javascript
<script>
function minDeletions(arr, N)
{
var freq = new Map();
for ( var i = 0; i < N; i++) {
if (freq.has(arr[i]))
{
freq.set(arr[i], freq.get(arr[i])+1);
}
else
{
freq.set(arr[i], 1);
}
}
var v = [];
freq.forEach((value, key) => {
v.push(value);
});
v.sort();
var size = v.length;
var ans = N - (v[0] * size);
for ( var i = 1; i < v.length; i++) {
if (v[i] != v[i - 1]) {
var safe = v[i] * (size - i);
ans = Math.min(ans, N - safe);
}
}
document.write( ans);
}
var arr = [ 2, 4, 3, 2, 5, 3 ];
var N = arr.length;
minDeletions(arr, N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Last Updated :
09 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...