Minimum number of distinct elements after removing M items | Set 2 - GeeksforGeeks

19 May, 2021
Given an array of items, an ith index element denotes the item id’s, and given a number m, the task is to remove m elements such that there should be minimum distinct id’s left. Print the number of distinct id’s.
Examples:
Input: arr[] = { 2, 2, 1, 3, 3, 3} m = 3Output: 1Explanation:Remove 1 and both 2’s.So, only 3 will be left, hence distinct number of element is 1.
Input: arr[] = { 2, 4, 1, 5, 3, 5, 1, 3} m = 2Output: 3Explanation:Remove 2 and 4 completely. So, remaining 1, 3 and 5 i.e. 3 elements.
For O(N*log N) approach please refer to the previous article.
Efficient Approach: The idea is to store the occurrence of each element in a Hash and count the occurrence of each frequency in a hash again. Below are the steps:
Traverse the given array elements and count the occurrences of each number and store it into the hash.Now instead of sorting the frequency, count the occurrences of the frequency into another array say fre_arr[].Calculate the total unique numbers(say ans) as the number of distinct id’s.Now, traverse the freq_arr[] array and if freq_arr[i] > 0 then remove the minimum of m/i and freq_arr[i](say t) from ans and subtract i*t from m to remove the occurrence of any number i from m.
Traverse the given array elements and count the occurrences of each number and store it into the hash.
Now instead of sorting the frequency, count the occurrences of the frequency into another array say fre_arr[].
Calculate the total unique numbers(say ans) as the number of distinct id’s.
Now, traverse the freq_arr[] array and if freq_arr[i] > 0 then remove the minimum of m/i and freq_arr[i](say t) from ans and subtract i*t from m to remove the occurrence of any number i from m.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to return minimum distinct// character after M removalsint distinctNumbers(int arr[], int m,                    int n){    unordered_map<int, int> count;     // Count the occurences of number    // and store in count    for (int i = 0; i < n; i++)        count[arr[i]]++;     // Count the occurences of the    // frequencies    vector<int> fre_arr(n + 1, 0);    for (auto it : count) {        fre_arr[it.second]++;    }     // Take answer as total unique numbers    // and remove the frequency and    // subtract the answer    int ans = count.size();     for (int i = 1; i <= n; i++) {        int temp = fre_arr[i];        if (temp == 0)            continue;         // Remove the minimum number        // of times        int t = min(temp, m / i);        ans -= t;        m -= i * t;    }     // Return the answer    return ans;} // Driver Codeint main(){    // Initialize array    int arr[] = { 2, 4, 1, 5, 3, 5, 1, 3 };     // Size of array    int n = sizeof(arr) / sizeof(arr[0]);    int m = 2;     // Function call    cout << distinctNumbers(arr, m, n);    return 0;}
// Java program to implement the// above approachimport java.util.*; class GFG{ // Function to return minimum distinct// character after M removalsstatic int distinctNumbers(int arr[], int m,                                      int n){    Map<Integer,        Integer> count = new HashMap<Integer,                                     Integer>();     // Count the occurences of number    // and store in count    for (int i = 0; i < n; i++)    count.put(arr[i],              count.getOrDefault(arr[i], 0) + 1);         // Count the occurences of the    // frequencies    int[] fre_arr = new int[n + 1];    for(Integer it : count.values())    {        fre_arr[it]++;    }     // Take answer as total unique numbers    // and remove the frequency and    // subtract the answer    int ans = count.size();     for(int i = 1; i <= n; i++)    {        int temp = fre_arr[i];        if (temp == 0)            continue;         // Remove the minimum number        // of times        int t = Math.min(temp, m / i);        ans -= t;        m -= i * t;    }     // Return the answer    return ans;} // Driver codepublic static void main(String[] args){         // Initialize array    int arr[] = { 2, 4, 1, 5, 3, 5, 1, 3 };         // Size of array    int n = arr.length;    int m = 2;         // Function call    System.out.println(distinctNumbers(arr, m, n));}} // This code is contributed by offbeat
# Python3 program for the above approach # Function to return minimum distinct# character after M removalsdef distinctNumbers(arr, m, n):     count = {}     # Count the occurences of number    # and store in count    for i in range(n):        count[arr[i]] = count.get(arr[i], 0) + 1     # Count the occurences of the    # frequencies    fre_arr = [0] * (n + 1)    for it in count:        fre_arr[count[it]] += 1     # Take answer as total unique numbers    # and remove the frequency and    # subtract the answer    ans = len(count)     for i in range(1, n + 1):        temp = fre_arr[i]        if (temp == 0):            continue                     # Remove the minimum number        # of times        t = min(temp, m // i)        ans -= t        m -= i * t     # Return the answer    return ans # Driver Codeif __name__ == '__main__':     # Initialize array    arr = [ 2, 4, 1, 5, 3, 5, 1, 3 ]     # Size of array    n = len(arr)    m = 2     # Function call    print(distinctNumbers(arr, m, n)) # This code is contributed by mohit kumar 29
// C# program to implement the// above approachusing System;using System.Collections.Generic;class GFG{ // Function to return minimum distinct// character after M removalsstatic int distinctNumbers(int []arr,                           int m, int n){  Dictionary<int,             int> count = new Dictionary<int,                                         int>();     // Count the occurences of number  // and store in count  for (int i = 0; i < n; i++)    if(count.ContainsKey(arr[i]))    {      count[arr[i]] = count[arr[i]] + 1;    }  else  {    count.Add(arr[i], 1);  }   // Count the occurences of the  // frequencies  int[] fre_arr = new int[n + 1];  foreach(int it in count.Values)  {    fre_arr[it]++;  }   // Take answer as total unique numbers  // and remove the frequency and  // subtract the answer  int ans = count.Count;   for(int i = 1; i <= n; i++)  {    int temp = fre_arr[i];    if (temp == 0)      continue;     // Remove the minimum number    // of times    int t = Math.Min(temp, m / i);    ans -= t;    m -= i * t;  }   // Return the answer  return ans;} // Driver codepublic static void Main(String[] args){  // Initialize array  int []arr = {2, 4, 1, 5, 3, 5, 1, 3};   // Size of array  int n = arr.Length;  int m = 2;   // Function call  Console.WriteLine(distinctNumbers(arr, m, n));}} // This code is contributed by Princi Singh
<script>   // Javascript program for the above approach // Function to return minimum distinct// character after M removalsfunction distinctNumbers(arr, m, n){    var count = new Map();     // Count the occurences of number    // and store in count    for (var i = 0; i < n; i++)        if(count.has(arr[i]))            count.set(arr[i], count.get(arr[i])+1)        else            count.set(arr[i], 1)     // Count the occurences of the    // frequencies    var fre_arr = Array(n + 1).fill(0);     count.forEach((value, key) => {                 fre_arr[value]++;    });          // Take answer as total unique numbers    // and remove the frequency and    // subtract the answer    var ans = count.size;     for (var i = 1; i <= n; i++) {        var temp = fre_arr[i];        if (temp == 0)            continue;         // Remove the minimum number        // of times        var t = Math.min(temp, parseInt(m / i));        ans -= t;        m -= i * t;    }     // Return the answer    return ans;} // Driver Code// Initialize arrayvar arr = [2, 4, 1, 5, 3, 5, 1, 3];// Size of arrayvar n = arr.length;var m = 2;// Function calldocument.write( distinctNumbers(arr, m, n)); </script>
3
 
Time Complexity: O(N)Auxiliary Space: O(N)
mohit kumar 29
offbeat
princi singh
famously
frequency-counting
Hash
Arrays
Greedy
Hash
Arrays
Hash
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Multidimensional Arrays in Java
Queue | Set 1 (Introduction and Array Implementation)
Linear Search
Python | Using 2D arrays/lists the right way
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Write a program to print all permutations of a given string
Huffman Coding | Greedy Algo-3