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

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 = 3
Output: 1
Explanation:
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 = 2
Output: 3
Explanation:
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:

  1. Traverse the given array elements and count the occurrences of each number and store it into the hash.
  2. Now instead of sorting the frequency, count the occurrences of the frequency into another array say fre_arr[].
  3. Calculate the total unique numbers(say ans) as the number of distinct id’s.
  4. 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return minimum distinct
// character after M removals
int 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 Code
int 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement the
// above approach
import java.util.*;
 
class GFG{
 
// Function to return minimum distinct
// character after M removals
static 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 code
public 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
 
# Function to return minimum distinct
# character after M removals
def 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 Code
if __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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement the
// above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to return minimum distinct
// character after M removals
static 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 code
public 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

chevron_right


Output: 

3


 

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.