Minimum delete operations to make all elements of array same
Last Updated :
23 Jul, 2025
Given an array of n elements such that elements may repeat. We can delete any number of elements from the array. The task is to find a minimum number of elements to be deleted from the array to make it equal.
Examples:
Input: arr[] = {4, 3, 4, 4, 2, 4}
Output: 2
After deleting 2 and 3 from array, array becomes
arr[] = {4, 4, 4, 4}
Input: arr[] = {1, 2, 3, 4, 5}
Output: 4
We can delete any four elements from array.
In this problem, we need to minimize the delete operations. The approach is simple, we count the frequency of each element in an array, then find the frequency of the most frequent elements in count array. Let this frequency be max_freq. To get the minimum number of elements to be deleted from the array calculate n - max_freq where n is a number of elements in the given array.
C++
// C++ program to find minimum
// number of deletes required
// to make all elements same.
#include <bits/stdc++.h>
using namespace std;
// Function to get minimum number of elements to be deleted
// from array to make array 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]]++;
// Find maximum frequency among all frequencies.
int max_freq = INT_MIN;
for (auto itr = freq.begin(); itr != freq.end(); itr++)
max_freq = max(max_freq, itr->second);
// To minimize delete operations, we remove all
// elements but the most frequent element.
return n - max_freq;
}
// Driver program to run the case
int main()
{
int arr[] = { 4, 3, 4, 4, 2, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << minDelete(arr, n);
return 0;
}
Java
// Java program to find minimum number
// of deletes required to make all
// elements same.
import java.util.*;
class GFG{
// Function to get minimum number of
// elements to be deleted from array
// to make array 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
HashMap<Integer, Integer> freq = new HashMap<>();
for(int i = 0; i < n; i++)
freq.put(arr[i], freq.getOrDefault(arr[i], 0) + 1);
// Find maximum frequency among all frequencies.
int max_freq = Integer.MIN_VALUE;
for(Map.Entry<Integer,
Integer> entry : freq.entrySet())
max_freq = Math.max(max_freq,
entry.getValue());
// To minimize delete operations,
// we remove all elements but the
// most frequent element.
return n - max_freq ;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 4, 3, 4, 4, 2, 4 };
int n = arr.length;
System.out.print(minDelete(arr, n));
}
}
// This code is contributed by amal kumar choubey and corrected by Leela Kotte
Python3
# Python3 program to find minimum
# number of deletes required to
# make all elements same.
# Function to get minimum number
# of elements to be deleted from
# array to make array elements equal
def minDelete(arr, n):
# Create an dictionary 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]] += 1
else:
freq[arr[i]] = 1;
# Find maximum frequency
# among all frequencies.
max_freq = 0;
for i, j in freq.items():
max_freq = max(max_freq, j);
# To minimize delete operations,
# we remove all elements but the
# most frequent element.
return n - max_freq;
# Driver code
arr = [ 4, 3, 4, 4, 2, 4 ];
n = len(arr)
print(minDelete(arr, n));
# This code is contributed by grand_master
C#
// C# program to find minimum number
// of deletes required to make all
// elements same.
using System;
using System.Collections.Generic;
class GFG {
// Function to get minimum number of
// elements to be deleted from array
// to make array 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
Dictionary<int, int> freq
= new Dictionary<int, int>();
for (int i = 0; i < n; i++)
if (freq.ContainsKey(arr[i]))
{
freq[arr[i]] = freq[arr[i]] + 1;
}
else
{
freq.Add(arr[i], 1);
}
// Find maximum frequency among all frequencies.
int max_freq = int.MinValue;
foreach(KeyValuePair<int, int> entry in freq)
max_freq = Math.Max(max_freq, entry.Value);
// To minimize delete operations,
// we remove all elements but the
// most frequent element.
return n - max_freq + 1;
}
// Driver code
public static void Main(String[] args)
{
int[] arr = {4, 3, 4, 4, 2, 4};
int n = arr.Length;
Console.Write(minDelete(arr, n));
}
}
// This code is contributed by Amit Katiyar
JavaScript
<script>
// Javascript program to find minimum number
// of deletes required to make all
// elements same.
// Function to get minimum number of
// elements to be deleted from array
// to make array 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)
}
}
// Find maximum frequency among all frequencies.
let max_freq = Number.MIN_SAFE_INTEGER;
for(let entry of freq)
max_freq = Math.max(max_freq, entry[1]);
// To minimize delete operations,
// we remove all elements but the
// most frequent element.
return n - max_freq ;
}
// Driver code
let arr = [4, 3, 4, 4, 2, 4 ];
let n = arr.length;
document.write(minDelete(arr, n));
// This code is contributed by _saurabh_jaiswal.
</script>
Output:
2
Time complexity: O(n)
Auxiliary Space: O(n)
Another Approach Using binary search :
- .First , we will sort the array for binary search function . Then we can find frequency of all array elements using lower_bound and upper bound .
- Then our answer will be n - max_frequency .
- Then return final answer
Below is the implementation of the above approach:
C++
// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find minimum operation required to
// make all array elements equal
int minDelete(int arr[], int n)
{
int max_freq = 1;
sort(arr,arr+n);//sort array for binary search
// Iterating the whole array
for(int i = 0 ; i < n ;i++)
{
//index of first and last occ of arr[i]
int first_index = lower_bound(arr,arr+n,arr[i])- arr;
int last_index = upper_bound(arr,arr+n,arr[i])- arr-1;
i = last_index; // assign i to last_index to avoid
// same element multiple time
int fre = last_index-first_index+1;//finding frequency
// Finding maximum frequency from all array elements
max_freq = max( max_freq , fre );
}
return n-max_freq;// return answer
}
// Drive code
int main()
{
int arr[] = { 4, 3, 4, 4, 2, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
// Function call
cout << minDelete(arr, n);
return 0;
}
// This Approach is contributed by nikhilsainiofficial546
Java
import java.util.Arrays;
public class Main {
// Function to find minimum operation required to make all
// array elements equal
public static int minDelete(int[] arr) {
int n = arr.length;
int max_freq = 1;
Arrays.sort(arr); // sort array for binary search
// Iterating the whole array
for (int i = 0; i < n; i++) {
// index of first and last occurrence of arr[i]
int first_index = Arrays.binarySearch(arr, arr[i]);
int last_index = first_index;
while (last_index < n - 1 && arr[last_index + 1] == arr[i]) {
last_index++;
}
i = last_index; // assign i to last_index to avoid same element multiple times
int fre = last_index - first_index + 1; // finding frequency
// Finding maximum frequency from all array elements
max_freq = Math.max(max_freq, fre);
}
return n - max_freq; // return answer
}
public static void main(String[] args) {
int[] arr = {4, 3, 4, 4, 2, 4};
System.out.println(minDelete(arr));
}
}
Python3
# Function to find minimum operation required to
# make all array elements equal
def minDelete(arr, n):
max_freq = 1
arr.sort() # sort array for binary search
# Iterating the whole array
i = 0
while i < n:
# index of first occ of arr[i]
first_index = arr.index(arr[i])
# find the last occ of arr[i]
j = n - 1
while j >= 0 and arr[j] != arr[i]:
j -= 1
last_index = j
fre = last_index - first_index + 1 # finding frequency
# Finding maximum frequency from all array elements
max_freq = max(max_freq, fre)
i = last_index + 1 # assign i to next index
return n - max_freq # return answer
# Drive code
arr = [4, 3, 4, 4, 2, 4]
n = len(arr)
# Function call
print(minDelete(arr, n))
C#
using System;
class Program {
// Function to find minimum operation required to
// make all array elements equal
static int minDelete(int[] arr, int n)
{
int max_freq = 1;
Array.Sort(arr); // sort array for binary search
// Iterating the whole array
for (int i = 0; i < n; i++) {
// index of first and last occ of arr[i]
int first_index
= Array.BinarySearch(arr, arr[i]);
int last_index = Array.LastIndexOf(arr, arr[i]);
i = last_index; // assign i to last_index to
// avoid same element multiple
// time
int fre = last_index - first_index
+ 1; // finding frequency
// Finding maximum frequency from all array
// elements
max_freq = Math.Max(max_freq, fre);
}
return n - max_freq; // return answer
}
static void Main(string[] args)
{
int[] arr = { 4, 3, 4, 4, 2, 4 };
int n = arr.Length;
// Function call
Console.WriteLine(minDelete(arr, n));
}
}
// This code is contributed by sarojmcy2e
JavaScript
// Function to find minimum operation required to
// make all array elements equal
function minDelete(arr, n) {
let max_freq = 1;
arr.sort((a, b) => a - b); // sort array for binary search
// Iterating the whole array
for (let i = 0; i < n; i++) {
// index of first and last occ of arr[i]
let first_index = arr.indexOf(arr[i]);
let last_index = arr.lastIndexOf(arr[i]);
i = last_index; // assign i to last_index to avoid
// same element multiple time
let fre = last_index - first_index + 1; // finding frequency
// Finding maximum frequency from all array elements
max_freq = Math.max(max_freq, fre);
}
return n - max_freq; // return answer
}
// Drive code
let arr = [4, 3, 4, 4, 2, 4];
let n = arr.length;
// Function call
console.log(minDelete(arr, n));
Time Complexity: O(N*Log2N), where N is the size of the input array
Auxiliary Space: O(1)
Note: Here we can optimize the extra space to count the frequency of each element to O(1) but for this, we have to modify our original array. See this article.
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 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