Open In App

Minimize insertions or deletions to make frequency of each array element equal to its value

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of N integers, the task is to find the minimum insertion or deletion operations required to make the frequency of each element equal to its value.

Example:

Input: arr = {3, 2, 3, 1, 2}
Output: 1
Explanation: Initially, the frequency of integers in the array is freq[3] = 2, freq[2]  = 2 and freq[1] = 1. In the 1st operation, insert 3 into the array. Hence the array becomes arr[] = {3, 2, 3, 1, 2, 3} having frequency of each element equal to its value. 

Input: [3, 3, 4, 3, 1, 2]
Output: 2
Explanation: In 1st operation, delete 4 from the array. In 2nd operation, insert 2 into the array. Hence the array becomes arr[] = {3, 3, 3, 1, 2, 2} having frequency of each element equal to its value.  

Approach: The given problem can be solved using a Greedy Approach. Follow the steps below to solve the given problem:

  • Create a hash map freq, to store the frequency of all elements of the array.
  • Iterate over all the values of the map using a variable key. If freq[key] > key, it will contribute (freq[key] – key) to the total operation count, otherwise, it will contribute min(freq[key], key – freq[key]) to the total operation count.
  • Create a variable count which stores the operation count of all the possible key values which will be the required answer.

Below is the implementation of the above approach:

C++




// C++ implementation of above approach
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
 
// Function to find minimum insertions or
// deletions required to make frequency
// of each element equal to its value
int minOperations(int arr[], int n)
{
   
    // Initializing Hash Map for making
    // frequency map
    map<int, int> mp;
 
    // Making frequency map
    for (int i = 0; i < n; i++) {
        mp[arr[i]]++;
    }
 
    // Stores the final count of operations
    int count = 0;
 
    // Traversing Hash Map
    for (auto it : mp) {
 
        // Updating the operation count
        if (it.second >= it.first)
            count += (it.second - it.first);
        else
            count += min(it.first - it.second, it.second);
    }
 
    // Return Answer
    return count;
}
 
// Driver Code
int main()
{
    int arr[] = { 3, 3, 4, 3, 1, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int count = minOperations(arr, n);
    cout << count;
    return 0;
}
 
// This code is contributed by kdheraj.


Java




// Java implementation of the above approach
 
import java.util.*;
 
class GFG {
 
    // Function to find minimum insertions or
    // deletions required to make frequency
    // of each element equal to its value
    public static int minOperations(int[] arr, int n)
    {
        // Initializing Hash Map for making
        // frequency map
        Map<Integer, Integer> freq = new HashMap<>();
 
        // Making frequency map
        for (int val : arr)
            freq.put(val, freq.getOrDefault(val, 0) + 1);
 
        // Stores the final count of operations
        int count = 0;
 
        // Traversing Hash Map
        for (Map.Entry mp : freq.entrySet()) {
 
            int key = (int)mp.getKey();
            int val = (int)mp.getValue();
 
            // Updating the operation count
            if (val >= key)
                count += val - key;
            else
                count += Math.min(key - val, val);
        }
 
        // Return Answer
        return count;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int[] arr = { 3, 3, 4, 3, 1, 2 };
        int n = arr.length;
        System.out.println(minOperations(arr, n));
    }
}


Python3




# Python 3 implementation of above approach
from collections import defaultdict
 
# Function to find minimum insertions or
# deletions required to make frequency
# of each element equal to its value
def minOperations(arr, n):
 
    # Initializing Hash Map for making
    # frequency map
    mp = defaultdict(int)
 
    # Making frequency map
    for i in range(n):
        mp[arr[i]] += 1
 
    # Stores the final count of operations
    count = 0
 
    # Traversing Hash Map
    for it in mp:
 
        # Updating the operation count
        if (mp[it] >= it):
            count += (mp[it] - it)
 
        else:
            count += min(it - mp[it], mp[it])
 
    # Return Answer
    return count
 
# Driver Code
if __name__ == "__main__":
 
    arr = [3, 3, 4, 3, 1, 2]
    n = len(arr)
    count = minOperations(arr, n)
    print(count)
 
    # This code is contributed by ukasp.


C#




// C# implementation of the above approach
 
using System;
using System.Collections;
using System.Collections.Generic;
 
class GFG {
 
// Function to find minimum insertions or
// deletions required to make frequency
// of each element equal to its value
static int minOperations(int []arr, int n)
{
   
    // Initializing Hash Map for making
    // frequency map
    Dictionary<int, int> mp =
          new Dictionary<int, int>();
  
 
    // Making frequency map
    for (int i = 0; i < n; i++) {
        if (mp.ContainsKey(arr[i])) {
              int val = mp[arr[i]];
              mp.Remove(arr[i]);
              mp.Add(arr[i], val + 1);
        }
        else {
          mp.Add(arr[i], 1);
        }
    }
 
    // Stores the final count of operations
    int count = 0;
 
    // Traversing Hash Map
    foreach(KeyValuePair<int, int> it in mp) {
 
        // Updating the operation count
        if (it.Value >= it.Key)
            count += (it.Value - it.Key);
        else
            count += Math.Min(it.Key - it.Value, it.Value);
    }
 
    // Return Answer
    return count;
}
 
 
// Driver code
public static void Main()
{
    int[] arr = { 3, 3, 4, 3, 1, 2 };
    int n = arr.Length;
    Console.Write(minOperations(arr, n));
}
}
// This code is contributed by Samim Hossain Mondal.


Javascript




<script>
// Javascript implementation of above approach
 
// Function to find minimum insertions or
// deletions required to make frequency
// of each element equal to its value
function minOperations(arr, n)
{
   
    // Initializing Hash Map for making
    // frequency map
    var mp = new Map();
  
    // Traverse through array elements and
    // count frequencies
    for (var i = 0; i < n; i++)
    {
        if(mp.has(arr[i]))
            mp.set(arr[i], mp.get(arr[i])+1)
        else
            mp.set(arr[i], 1)
    }
 
    // Stores the final count of operations
    var count = 0;
    var keys = [];
     
    mp.forEach((value, key) => {
        keys.push(key);
    });
    // Traversing Hash Map
    keys.forEach((key) => {
 
        // Updating the operation count
        if (mp.get(key) >= key)
            count += (mp.get(key) - key);
        else
            count += Math.min(key - mp.get(key), mp.get(key));
    });
 
    // Return Answer
    return count;
}
 
// Driver Code
var arr = [ 3, 3, 4, 3, 1, 2 ];
var n = arr.length;
var count = minOperations(arr, n);
document.write(count);
 
// This code is contributed by Samim Hossain Mondal.
</script>


Output

2

Time complexity: O(N)
Auxiliary Space: O(N)



Last Updated : 23 Mar, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads