Minimum deletions required such that any number X will occur exactly X times

Given an array arr[] of N integers, the task is to find the minimum deletions required such that frequency of arr[i] is exactly arr[i] in the array for all possible values of i.
Examples:Â
Â
Input: arr[] = {1, 2, 2, 3, 3}Â
Output: 2Â
Frequency(1) = 1Â
Frequency(2) = 2Â
Frequency(3) = 2, frequency can’t be increasedÂ
So, delete every occurrence of 3.
Input: arr[] = {2, 3, 2, 3, 4, 4, 4, 4, 5}Â
Output: 3Â
Â
Â
Approach: There are two cases:Â
Â
- If frequency of X is greater than or equal o X then we delete extra frequencies of X to get exactly X elements of value X.
- If frequency of X is less than X then we delete all of the occurrences of X as it is impossible to get extra element of value X.
Below is the implementation of the above approach:Â
Â
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;Â
// Function to return the minimum// deletions requiredint MinDeletion(int a[], int n){Â
    // To store the frequency of    // the array elements    unordered_map<int, int> map;Â
    // Store frequency of each element    for (int i = 0; i < n; i++)        map[a[i]]++;Â
    // To store the minimum deletions required    int ans = 0;Â
    for (auto i : map) {Â
        // Value        int x = i.first;Â
        // It's frequency        int frequency = i.second;Â
        // If number less than or equal        // to it's frequency        if (x <= frequency) {Â
            // Delete extra occurrences            ans += (frequency - x);        }Â
        // Delete every occurrence of x        else            ans += frequency;    }Â
    return ans;}Â
// Driver codeint main(){Â Â Â Â int a[] = { 2, 3, 2, 3, 4, 4, 4, 4, 5 };Â Â Â Â int n = sizeof(a) / sizeof(a[0]);Â
    cout << MinDeletion(a, n);Â
    return 0;} |
Java
// Java Implementation of above approach import java.util.*;Â
class GFG {Â Â Â Â Â // Function to return the minimum// deletions requiredstatic int MinDeletion(int a[], int n){Â
    // To store the frequency of    // the array elements    Map<Integer,Integer> mp = new HashMap<>();Â
    // Store frequency of each element    for (int i = 0 ; i < n; i++)    {        if(mp.containsKey(a[i]))        {            mp.put(a[i], mp.get(a[i])+1);        }        else        {            mp.put(a[i], 1);        }    }    // To store the minimum deletions required    int ans = 0;Â
    for (Map.Entry<Integer,Integer> i : mp.entrySet())     {Â
        // Value        int x = i.getKey();Â
        // It's frequency        int frequency = i.getValue();Â
        // If number less than or equal        // to it's frequency        if (x <= frequency)         {Â
            // Delete extra occurrences            ans += (frequency - x);        }Â
        // Delete every occurrence of x        else            ans += frequency;    }Â
    return ans;}Â
// Driver codepublic static void main(String[] args){Â Â Â Â int a[] = { 2, 3, 2, 3, 4, 4, 4, 4, 5 };Â Â Â Â int n = a.length;Â
    System.out.println(MinDeletion(a, n));}}Â
// This code is contributed by Rajput-Ji |
Python3
# Python3 implementation of the approach Â
# Function to return the minimum # deletions required def MinDeletion(a, n) :Â
    # To store the frequency of     # the array elements     map = dict.fromkeys(a, 0); Â
    # Store frequency of each element     for i in range(n) :         map[a[i]] += 1; Â
    # To store the minimum deletions required     ans = 0; Â
    for key,value in map.items() :Â
        # Value         x = key; Â
        # It's frequency         frequency = value; Â
        # If number less than or equal         # to it's frequency         if (x <= frequency) :Â
            # Delete extra occurrences             ans += (frequency - x); Â
        # Delete every occurrence of x         else :            ans += frequency; Â
    return ans; Â
Â
# Driver code if __name__ == "__main__" : Â
    a = [ 2, 3, 2, 3, 4, 4, 4, 4, 5 ];    n = len(a); Â
    print(MinDeletion(a, n)); Â
# This code is contributed by AnkitRai01 |
C#
// C# Implementation of above approachusing System;using System.Collections.Generic; Â
class GFG {Â Â Â Â Â // Function to return the minimum// deletions requiredstatic int MinDeletion(int []a, int n){Â
    // To store the frequency of    // the array elements    Dictionary<int,               int> mp = new Dictionary<int,                                        int>();Â
    // Store frequency of each element    for (int i = 0 ; i < n; i++)    {        if(mp.ContainsKey(a[i]))        {            var val = mp[a[i]];            mp.Remove(a[i]);            mp.Add(a[i], val + 1);         }        else        {            mp.Add(a[i], 1);        }    }         // To store the minimum deletions required    int ans = 0;Â
    foreach(KeyValuePair<int, int> i in mp)    {Â
        // Value        int x = i.Key;Â
        // It's frequency        int frequency = i.Value;Â
        // If number less than or equal        // to it's frequency        if (x <= frequency)         {Â
            // Delete extra occurrences            ans += (frequency - x);        }Â
        // Delete every occurrence of x        else            ans += frequency;    }Â
    return ans;}Â
// Driver codepublic static void Main(String[] args){Â Â Â Â int []a = { 2, 3, 2, 3, 4, 4, 4, 4, 5 };Â Â Â Â int n = a.Length;Â
    Console.WriteLine(MinDeletion(a, n));}}Â
// This code is contributed by PrinciRaj1992 |
Javascript
<script>// javaScript implementation of the approachÂ
// Function to return the minimum// deletions requiredfunction MinDeletion( a, n){    // To store the frequency of    // the array elements    let map = new Map();         // Store frequency of each element    for (let i = 0; i < n; i++){        if(map[a[i]])            map[a[i]]++;        else            map[a[i]] = 1     }Â
    // To store the minimum deletions required    let ans = 0;    for(var m in map){                 // Value        let x = m;Â
        // It's frequency        let frequency = map[m];Â
        // If number less than or equal        // to it's frequency        if (x <= frequency) {Â
            // Delete extra occurrences            ans += (frequency - x);        }Â
        // Delete every occurrence of x        else            ans += frequency;    };Â
    return ans;}Â
// Driver codelet a = [ 2, 3, 2, 3, 4, 4, 4, 4, 5 ];let n = a.length;document.write( MinDeletion(a, n));Â
// This code is contributed by rohitsingh07052.</script> |
Output:Â
3
Â
Time Complexity: O(n), where n is the size of the given array.
Auxiliary Space: O(n), where n is the size of the given array.
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



