# Minimum replacements required to have at most K distinct elements in the array

• Last Updated : 15 Jun, 2021

Given an array arr[] consisting of N positive integers and an integer K, the task is to find the minimum number of array elements required to be replaced by the other array elements such that the array contains at most K distinct elements.

Input: arr[] = { 1, 1, 2, 2, 5 }, K = 2
Output:
Explanation:
Replacing arr[4] with arr[0] modifies arr[] to { 1, 1, 2, 2, 1 }
Distinct array elements of the array arr[] are { 1, 2 }
Therefore, the required output is 1.

Input: arr[] = { 5, 1, 3, 2, 4, 1, 1, 2, 3, 4 }, K = 3
Output:
Explanation:
Replacing arr[0] with arr[1] modifies arr[] to { 1, 1, 3, 2, 4, 1, 1, 2, 3, 4 }
Replacing arr[2] with arr[0] modifies arr[] to { 1, 1, 1, 2, 4, 1, 1, 2, 3, 4 }
Replacing arr[8] with arr[0] modifies arr[] to { 1, 1, 1, 2, 4, 1, 1, 2, 1, 4 }
Distinct array elements of the array arr[] are { 1, 2, 4 }
Therefore, the required output is 3.

Approach:The problem can be solved using Greedy technique. The idea is to replace the smaller frequency array elements with the higher frequency array elements. Follow the steps below to solve the problem:

Below is the implementation of the above approach:

## C++

 `// C++ program to implement``// the above approach``#include ``using` `namespace` `std;` `// Function to find minimum count of array``// elements required to be replaced such that``// count of distinct elements is at most K``int` `min_elements(``int` `arr[], ``int` `N, ``int` `K)``{` `    ``// Store the frequency of each``    ``// distinct element of the array``    ``map<``int``, ``int``> mp;` `    ``// Traverse the array``    ``for` `(``int` `i = 0; i < N; i++) {` `        ``// Update frequency``        ``// of arr[i]``        ``mp[arr[i]]++;``    ``}` `    ``// Store frequency of each distinct``    ``// element of the array``    ``vector<``int``> Freq;` `    ``// Traverse the map``    ``for` `(``auto` `it : mp) {` `        ``// Stores key of the map``        ``int` `i = it.first;` `        ``// Insert mp[i] into Freq[]``        ``Freq.push_back(mp[i]);``    ``}` `    ``// Sort Freq[] in descending order``    ``sort(Freq.rbegin(), Freq.rend());` `    ``// Stores size of Freq[]``    ``int` `len = Freq.size();` `    ``// If len is less than``    ``// or equal to K``    ``if` `(len <= K) {` `        ``return` `0;``    ``}` `    ``// Stores minimum count of array elements``    ``// required to be replaced such that``    ``// count of distinct elements is at most K``    ``int` `cntMin = 0;` `    ``// Iterate over the range [K, len]``    ``for` `(``int` `i = K; i < len; i++) {` `        ``// Update cntMin``        ``cntMin += Freq[i];``    ``}` `    ``return` `cntMin;``}` `// Driver Code``int` `main()``{``    ``int` `arr[] = { 5, 1, 3, 2, 4, 1, 1, 2, 3, 4 };` `    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr[0]);` `    ``int` `K = 3;``    ``cout << min_elements(arr, N, K);``    ``return` `0;``}`

## Java

 `// Java program to implement``// the above approach``import` `java.util.*;``class` `GFG``{` `  ``// Function to find minimum count of array``  ``// elements required to be replaced such that``  ``// count of distinct elements is at most K``  ``static` `int` `min_elements(``int` `arr[], ``int` `N, ``int` `K)``  ``{` `    ``// Store the frequency of each``    ``// distinct element of the array``    ``HashMap mp = ``new` `HashMap();` `    ``// Traverse the array``    ``for` `(``int` `i = ``0``; i < N; i++)``    ``{` `      ``// Update frequency``      ``// of arr[i]``      ``if``(mp.containsKey(arr[i]))``      ``{``        ``mp.put(arr[i], mp.get(arr[i])+``1``);``      ``}``      ``else``      ``{``        ``mp.put(arr[i], ``1``);``      ``}``    ``}` `    ``// Store frequency of each distinct``    ``// element of the array``    ``Vector Freq = ``new` `Vector();` `    ``// Traverse the map``    ``for` `(Map.Entry it : mp.entrySet())``    ``{` `      ``// Stores key of the map``      ``int` `i = it.getKey();` `      ``// Insert mp[i] into Freq[]``      ``Freq.add(mp.get(i));``    ``}` `    ``// Sort Freq[] in descending order``    ``Collections.sort(Freq,Collections.reverseOrder());` `    ``// Stores size of Freq[]``    ``int` `len = Freq.size();` `    ``// If len is less than``    ``// or equal to K``    ``if` `(len <= K)``    ``{``      ``return` `0``;``    ``}` `    ``// Stores minimum count of array elements``    ``// required to be replaced such that``    ``// count of distinct elements is at most K``    ``int` `cntMin = ``0``;` `    ``// Iterate over the range [K, len]``    ``for` `(``int` `i = K; i < len; i++)``    ``{` `      ``// Update cntMin``      ``cntMin += Freq.get(i);``    ``}``    ``return` `cntMin;``  ``}` `  ``// Driver Code``  ``public` `static` `void` `main(String[] args)``  ``{``    ``int` `arr[] = { ``5``, ``1``, ``3``, ``2``, ``4``, ``1``, ``1``, ``2``, ``3``, ``4` `};``    ``int` `N = arr.length;``    ``int` `K = ``3``;``    ``System.out.print(min_elements(arr, N, K));``  ``}``}` `// This code is contributed by shikhasingrajput`

## Python3

 `# Python3 program to implement``# the above approach` `# Function to find minimum count of array``# elements required to be replaced such that``# count of distinct elements is at most K``def` `min_elements(arr, N, K) :`` ` `    ``# Store the frequency of each``    ``# distinct element of the array``    ``mp ``=` `{}`` ` `    ``# Traverse the array``    ``for` `i ``in` `range``(N) :`` ` `        ``# Update frequency``        ``# of arr[i]``        ``if` `arr[i] ``in` `mp :``            ``mp[arr[i]] ``+``=` `1``        ``else` `:``            ``mp[arr[i]] ``=` `1`` ` `    ``# Store frequency of each distinct``    ``# element of the array``    ``Freq ``=` `[]`` ` `    ``# Traverse the map``    ``for` `it ``in` `mp :`` ` `        ``# Stores key of the map``        ``i ``=` `it`` ` `        ``# Insert mp[i] into Freq[]``        ``Freq.append(mp[i])`` ` `    ``# Sort Freq[] in descending order``    ``Freq.sort()``    ``Freq.reverse()`` ` `    ``# Stores size of Freq[]``    ``Len` `=` `len``(Freq)`` ` `    ``# If len is less than``    ``# or equal to K``    ``if` `(``Len` `<``=` `K) :``        ``return` `0`` ` `    ``# Stores minimum count of array elements``    ``# required to be replaced such that``    ``# count of distinct elements is at most K``    ``cntMin ``=` `0`` ` `    ``# Iterate over the range [K, len]``    ``for` `i ``in` `range``(K, ``Len``) :`` ` `        ``# Update cntMin``        ``cntMin ``+``=` `Freq[i]`` ` `    ``return` `cntMin``    ` `  ``# Driver code``arr ``=` `[ ``5``, ``1``, ``3``, ``2``, ``4``, ``1``, ``1``, ``2``, ``3``, ``4` `]``N ``=` `len``(arr)``K ``=` `3``;``print``(min_elements(arr, N, K))` `# This code is contributed by divyesh072019.`

## C#

 `// C# program to implement``// the above approach``using` `System;``using` `System.Collections.Generic;` `class` `GFG{` `// Function to find minimum count of array``// elements required to be replaced such that``// count of distinct elements is at most K``static` `int` `min_elements(``int` `[]arr, ``int` `N, ``int` `K)``{``    ` `    ``// Store the frequency of each``    ``// distinct element of the array``    ``Dictionary<``int``,``               ``int``> mp = ``new` `Dictionary<``int``,``                                        ``int``>();``    ` `    ``// Traverse the array``    ``for``(``int` `i = 0; i < N; i++)``    ``{``        ` `        ``// Update frequency``        ``// of arr[i]``        ``if` `(mp.ContainsKey(arr[i]))``        ``{``            ``mp[arr[i]] = mp[arr[i]] + 1;``        ``}``        ``else``        ``{``            ``mp.Add(arr[i], 1);``        ``}``    ``}``    ` `    ``// Store frequency of each distinct``    ``// element of the array``    ``List<``int``> Freq = ``new` `List<``int``>();``    ` `    ``// Traverse the map``    ``foreach` `(KeyValuePair<``int``, ``int``> it ``in` `mp)``    ``{``        ` `        ``// Stores key of the map``        ``int` `i = it.Key;``        ` `        ``// Insert mp[i] into Freq[]``        ``Freq.Add(mp[i]);``    ``}``    ` `    ``// Sort Freq[] in descending order``    ``Freq.Sort();``    ``Freq.Reverse();``    ` `    ``// Stores size of Freq[]``    ``int` `len = Freq.Count;``    ` `    ``// If len is less than``    ``// or equal to K``    ``if` `(len <= K)``    ``{``        ``return` `0;``    ``}``    ` `    ``// Stores minimum count of array elements``    ``// required to be replaced such that``    ``// count of distinct elements is at most K``    ``int` `cntMin = 0;``    ` `    ``// Iterate over the range [K, len]``    ``for``(``int` `i = K; i < len; i++)``    ``{``        ` `        ``// Update cntMin``        ``cntMin += Freq[i];``    ``}``    ``return` `cntMin;``}` `// Driver Code``public` `static` `void` `Main(String[] args)``{``    ``int` `[]arr = { 5, 1, 3, 2, 4, 1, 1, 2, 3, 4 };``    ``int` `N = arr.Length;``    ``int` `K = 3;``    ` `    ``Console.Write(min_elements(arr, N, K));``}``}` `// This code is contributed by gauravrajput1`

## Javascript

 ``

Output:

`3`

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

My Personal Notes arrow_drop_up