Minimum removals required to make frequency of all remaining array elements equal
Last Updated :
23 Jul, 2025
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++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to get minimum removals required
// to make frequency of all remaining elements equal
int minDelete(int arr[], int n)
{
// Create an hash map and store frequencies of all
// array elements in it using element as key and
// frequency as value
unordered_map<int, int> freq;
for (int i = 0; i < n; i++)
freq[arr[i]]++;
// Initialize the result to store the minimum deletions
int tempans, res = INT_MAX;
// Find deletions required for each element and store
// the minimum deletions in result
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;
}
// Driver program to run the case
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;
// Java program for the above approach
class Main
{
// Function to get minimum removals required
// to make frequency of all remaining elements equal
static int minDelete(int arr[], int n)
{
// Create an hash map and store frequencies of all
// array elements in it using element as key and
// frequency as value
Map<Integer, Integer> freq = new HashMap<>();
for (int i = 0; i < n; i++)
freq.put(arr[i], freq.getOrDefault(arr[i], 0) + 1);
// Initialize the result to store the minimum deletions
int tempans, res = Integer.MAX_VALUE;
// Find deletions required for each element and store
// the minimum deletions in result
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;
}
// Driver program to run the case
public static void main(String args[])
{
int arr[] = { 2, 4, 3, 2, 5, 3 };
int n = arr.length;
System.out.println(minDelete(arr, n));
}
}
// This code is contributed by phasing17.
Python3
# Python program for the above approach
# Function to get minimum removals required
# to make frequency of all remaining elements equal
import sys
def minDelete(arr, n):
# Create an hash map and store frequencies of all
# array elements in it using element as key and
# frequency as value
freq = {}
for i in range(n):
if(arr[i] in freq):
freq[arr[i]] = freq[arr[i]]+1
else:
freq[arr[i]] = 1
# Initialize the result to store the minimum deletions
tempans, res = sys.maxsize,sys.maxsize
# Find deletions required for each element and store
# the minimum deletions in result
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
# Driver program to run the case
arr = [2, 4, 3, 2, 5, 3]
n = len(arr)
print(minDelete(arr, n))
# This code is contributed by shinjanpatra.
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to get minimum removals required
// to make frequency of all remaining elements equal
static int MinDelete(int[] arr, int n)
{
// Create a dictionary and store frequencies of all
// array elements in it using element as key and
// frequency as value
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;
}
}
// Initialize the result to store the minimum deletions
int tempans, res = int.MaxValue;
// Find deletions required for each element and store
// the minimum deletions in result
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;
}
// Driver program to run the case
static void Main(string[] args)
{
int[] arr = { 2, 4, 3, 2, 5, 3 };
int n = arr.Length;
Console.WriteLine(MinDelete(arr, n));
}
}
// This code is contributed by phasing17
JavaScript
<script>
// JavaScript program for the above approach
// Function to get minimum removals required
// to make frequency of all remaining elements equal
function minDelete(arr, n)
{
// Create an hash map and store frequencies of all
// array elements in it using element as key and
// frequency as value
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);
}
// Initialize the result to store the minimum deletions
let tempans, res = Number.MAX_VALUE;
// Find deletions required for each element and store
// the minimum deletions in result
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;
}
// Driver program to run the case
let arr = [2, 4, 3, 2, 5, 3];
let n = arr.length;
document.write(minDelete(arr, n));
// This code is contributed by shinjanpatra.
</script>
Efficient Approach: Follow the steps below to solve the problem:
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to count the minimum
// removals required to make frequency
// of all array elements equal
int minDeletions(int arr[], int N)
{
// Stores frequency of
// all array elements
map<int, int> freq;
// Traverse the array
for (int i = 0; i < N; i++) {
freq[arr[i]]++;
}
// Stores all the frequencies
vector<int> v;
// Traverse the map
for (auto z : freq) {
v.push_back(z.second);
}
// Sort the frequencies
sort(v.begin(), v.end());
// Count of frequencies
int size = v.size();
// Stores the final count
int ans = N - (v[0] * size);
// Traverse the vector
for (int i = 1; i < v.size(); i++) {
// Count the number of removals
// for each frequency and update
// the minimum removals required
if (v[i] != v[i - 1]) {
int safe = v[i] * (size - i);
ans = min(ans, N - safe);
}
}
// Print the final count
cout << ans;
}
// Driver Code
int main()
{
// Given array
int arr[] = { 2, 4, 3, 2, 5, 3 };
// Size of the array
int N = sizeof(arr) / sizeof(arr[0]);
// Function call to print the minimum
// number of removals required
minDeletions(arr, N);
}
Java
/*package whatever //do not write package name here */
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)
{
// Stores frequency of
// all array elements
HashMap<Integer, Integer> map = new HashMap<>();
;
// Traverse the array
for (int i = 0; i < N; i++) {
Integer k = map.get(arr[i]);
map.put(arr[i], (k == null) ? 1 : k + 1);
}
// Stores all the frequencies
ArrayList<Integer> v = new ArrayList<>();
// Traverse the map
for (Map.Entry<Integer, Integer> e :
map.entrySet()) {
v.add(e.getValue());
}
// Sort the frequencies
Collections.sort(v);
// Count of frequencies
int size = v.size();
// Stores the final count
int ans = N - (v.get(0) * size);
// Traverse the vector
for (int i = 1; i < v.size(); i++) {
// Count the number of removals
// for each frequency and update
// the minimum removals required
if (v.get(i) != v.get(i - 1)) {
int safe = v.get(i) * (size - i);
ans = Math.min(ans, N - safe);
}
}
// Print the final count
System.out.println(ans);
}
// Driver code
public static void main(String[] args)
{
// Given array
int arr[] = { 2, 4, 3, 2, 5, 3 };
// Size of the array
int N = 6;
// Function call to print the minimum
// number of removals required
minDeletions(arr, N);
}
}
// This code is contributed by aditya7409.
Python3
# Python 3 program for the above approach
from collections import defaultdict
# Function to count the minimum
# removals required to make frequency
# of all array elements equal
def minDeletions(arr, N):
# Stores frequency of
# all array elements
freq = defaultdict(int)
# Traverse the array
for i in range(N):
freq[arr[i]] += 1
# Stores all the frequencies
v = []
# Traverse the map
for z in freq.keys():
v.append(freq[z])
# Sort the frequencies
v.sort()
# Count of frequencies
size = len(v)
# Stores the final count
ans = N - (v[0] * size)
# Traverse the vector
for i in range(1, len(v)):
# Count the number of removals
# for each frequency and update
# the minimum removals required
if (v[i] != v[i - 1]):
safe = v[i] * (size - i)
ans = min(ans, N - safe)
# Print the final count
print(ans)
# Driver Code
if __name__ == "__main__":
# Given array
arr = [2, 4, 3, 2, 5, 3]
# Size of the array
N = len(arr)
# Function call to print the minimum
# number of removals required
minDeletions(arr, N)
# This code is contributed by chitranayal.
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to count the minimum
// removals required to make frequency
// of all array elements equal
static void minDeletions(int []arr, int N)
{
// Stores frequency of
// all array elements
Dictionary<int,int> freq = new Dictionary<int,int>();
// Traverse the array
for (int i = 0; i < N; i++)
{
if(freq.ContainsKey(arr[i]))
freq[arr[i]]++;
else
freq[arr[i]] = 1;
}
// Stores all the frequencies
List<int> v = new List<int>();
// Traverse the map
foreach (var z in freq) {
v.Add(z.Value);
}
// Sort the frequencies
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];
// Count of frequencies
int size = v.Count;
// Stores the final count
int ans = N - (v[0] * size);
// Traverse the vector
for (int i = 1; i < v.Count; i++) {
// Count the number of removals
// for each frequency and update
// the minimum removals required
if (v[i] != v[i - 1]) {
int safe = v[i] * (size - i);
ans = Math.Min(ans, N - safe);
}
}
// Print the final count
Console.WriteLine(ans);
}
// Driver Code
public static void Main()
{
// Given array
int []arr = { 2, 4, 3, 2, 5, 3 };
// Size of the array
int N = arr.Length;
// Function call to print the minimum
// number of removals required
minDeletions(arr, N);
}
}
// This code is contributed by SURENDRA_GANGWAR.
JavaScript
<script>
// Javascript program for the above approach
// Function to count the minimum
// removals required to make frequency
// of all array elements equal
function minDeletions(arr, N)
{
// Stores frequency of
// all array elements
var freq = new Map();
// Traverse the array
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);
}
}
// Stores all the frequencies
var v = [];
// Traverse the map
freq.forEach((value, key) => {
v.push(value);
});
// Sort the frequencies
v.sort();
// Count of frequencies
var size = v.length;
// Stores the final count
var ans = N - (v[0] * size);
// Traverse the vector
for (var i = 1; i < v.length; i++) {
// Count the number of removals
// for each frequency and update
// the minimum removals required
if (v[i] != v[i - 1]) {
var safe = v[i] * (size - i);
ans = Math.min(ans, N - safe);
}
}
// Print the final count
document.write( ans);
}
// Driver Code
// Given array
var arr = [ 2, 4, 3, 2, 5, 3 ];
// Size of the array
var N = arr.length;
// Function call to print the minimum
// number of removals required
minDeletions(arr, N);
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem