The Wayback Machine - https://web.archive.org/web/20240624032253/https://www.geeksforgeeks.org/minimum-delete-operations-make-elements-array/
Open In App

Minimum delete operations to make all elements of array same

Last Updated : 11 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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));


Output

2

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

Bitwise XOR of same indexed array elements after rearranging an array to make XOR of same indexed elements of two arrays equal
Given two arrays A[] and B[] consisting of N positive integers, the task is to the Bitwise XOR of same indexed array elements after rearranging the array B[] such that the Bitwise XOR of the same indexed elements of the arrays A[] becomes equal. Examples: Input: A[] = {1, 2, 3}, B[] = {4, 6, 7}Output: 5Explanation:Below are the possible arrangement
14 min read
Minimum number of operations required to delete all elements of the array
Given an integer array arr, the task is to print the minimum number of operations required to delete all elements of the array. In an operation, any element from the array can be chosen at random and every element divisible by it can be removed from the array. Examples: Input: arr[] = {2, 4, 6, 3, 5, 10} Output: 3 Choosing 2 as the first element wi
9 min read
Minimum increments to make all array elements equal with sum same as the given array after exactly one removal
Given an array arr[] of size N and an integer K, the task is to check if all array elements can be made equal by removing an array element and incrementing the value of all other array elements such that the total sum of the array elements remains the same. If found to be true, then print "YES". Otherwise, print "NO". Examples : Input: arr[] = { 2,
7 min read
Make parity of elements same using minimum operations
Given an array A[] of length N along with an integer X, the task is to make the parity of all the elements in A[] the same by using either of the given functions on two distinct indexed elements C and D, the minimum number of times. Operation 1: (C | D) ^ XOperation 2: (C ^ D) | X Note: It is not allowed to use both functions. Examples: Input: N =
15+ min read
Minimum operations to make counts of remainders same in an array
Given an array arr[] of N integers and an integer M where N % M = 0. The task is to find the minimum number of operations that need to be performed on the array to make c0 = c1 = ..... = cM - 1 = N / M where cr is the number of elements in the given array having remainder r when divided by M. In each operation, any array element can be incremented
7 min read
Minimum gcd operations to make all array elements one
Given an array A[] of size N. You can replace any number in the array with the gcd of that element with any of its adjacent elements. Find the minimum number of such operation to make the element of whole array equal to 1. If its not possible print -1. Examples: Input : A[] = {4, 8, 9} Output : 3 Explanation: In the first move we choose (8, 9) gcd(
8 min read
Minimum operations required to make all the elements distinct in an array
Given an array of N integers. If a number occurs more than once, choose any number y from the array and replace the x in the array to x+y such that x+y is not in the array. The task is to find the minimum number of operations to make the array a distinct one. Examples: Input: a[] = {2, 1, 2} Output: 1 Let x = 2, y = 1 then replace 2 by 3. Performin
5 min read
Minimum operations required to make all Array elements divisible by K
Given an array a[], integer K and an integer X (which is initially initialized to 0). Our task is to find the minimum number of moves required to update the array such that each of its elements is divisible by K by performing the following operations: Choose one index i from 1 to N and increase ai by X and then increase X by 1. This operation canno
9 min read
Minimum no. of operations required to make all Array Elements Zero
Given an array of N elements and each element is either 1 or 0. You need to make all the elements of the array equal to 0 by performing the below operations: If an element is 1, You can change it's value equal to 0 then, if the next consecutive element is 1, it will automatically get converted to 0.if the next consecutive element is already 0, noth
12 min read
Minimum operations required to make all the array elements equal
Given an array arr[] of n integer and an integer k. The task is to count the minimum number of times the given operation is required to make all the array elements equal. In a single operation, the kth element of the array is appended at the end of the array and the first element of the array gets deleted (the size of the array remains same). If th
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg