Minimize deletion or insertions of Array elements such that arr[i] have frequency as its value
Given an array arr[] of length N, the task is to find the minimum number of operations to change the array such that each arr[i] occurs arr[i] times where in each operation either one element can be deleted from the array or one element can be inserted in the array.
Examples:
Input: N = 4, arr[ ] = {1, 1, 3, 3}
Output: 2
Explanation: Delete one occurrence of 1 from the array in one operation.
In another operation, insert element 3 in the array.
The final array will be [ 1, 3, 3, 3 ] where 1 occurs 1 time and 3 occurs 3 times.
Minimum 2 operations are needed. It cannot be reconstructed in less than 2 moves.Input: N = 6, arr[ ] = {3, 3, 5,, 3, 2, 4}
Output: 3
Approach: The solution to the problem is based on the following idea:
For each array element (arr[i]), there are two choices: either delete all the occurrences of arr[i] or insert arr[i] such that number of occurrences is not same as its value.
Choose the minimum among the required number of deletions and insertions to minimize the total number of operations.
Follow the steps mentioned below to implement the idea:
- Store the frequency of all the elements
- Check if the frequency of the element is higher or greater than its value:
- If the frequency is higher then the best choice is to remove the element until the frequency becomes same as the current element.
- Else there are two choices:
- Delete all the occurrences of the element.
- Insert the element such that the frequency is same as its value.
- Add the minimum of these two in the final count of operations.
- Return the final count as the answer.
Below is the implementation for the above approach:
C++
// C++ code to implement the approach #include <bits/stdc++.h>using namespace std; // Function to find out minimum// number of operationint minOperations(int N, vector<int>& a){ // Map for storing frequency // of the array elements unordered_map<int, int> mp; for (auto x : a) { mp[x]++; } // Variable to store the answer int operations = 0; for (auto x : mp) { int occurences = x.second; // If the occurence is greater // than nunmber then the greedy // move is to remove extra occurences if (occurences > x.first) { operations += (occurences - x.first); } // Else you can remove all the // occurences of the number or // add the number sometimes until // the occurences of the number are // not equal to the number itself so // you have to take the minimum of // all the occurences else if (occurences < x.first) { operations += min(occurences, x.first - occurences); } } // Return the operations return operations;} // Driver codeint main(){ int N = 6; vector<int> arr = { 3, 3, 5, 3, 2, 4 }; // Function call cout << minOperations(N, arr) << endl; return 0;} |
3
Time Complexity: O(N)
Auxiliary Space: O(N)

