Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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 <bits/stdc++.h>
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<Integer,Integer> mp = new HashMap<Integer,Integer>();

    // 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<Integer> Freq = new Vector<Integer>();

    // Traverse the map
    for (Map.Entry<Integer,Integer> 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 
Python
# 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
<script>

// Javascript 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
function min_elements(arr, N, K) 
{
    
    // Store the frequency of each
    // distinct element of the array
    let mp = new Map();

    // Traverse the array
    for(let i = 0; i < N; i++) 
    {
        
        // Update frequency
        // of arr[i]
        if (mp.has(arr[i]))
        {
            mp.set(arr[i], mp.get(arr[i]) + 1)
        } else
        {
            mp.set(arr[i], 1)
        }
    }

    // Store frequency of each distinct
    // element of the array
    let Freq = [];

    // Traverse the map
    for(let it of mp) 
    {
        
        // Stores key of the map
        let i = it[0];

        // Insert mp[i] into Freq[]
        Freq.push(mp.get(i));
    }

    // Sort Freq[] in descending order
    Freq.sort((a, b) => b - a);

    // Stores size of Freq[]
    let len = Freq.length;

    // 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
    let cntMin = 0;

    // Iterate over the range [K, len]
    for(let i = K; i < len; i++)
    {
        
        // Update cntMin
        cntMin += Freq[i];
    }
    return cntMin;
}

// Driver Code
let arr = [ 5, 1, 3, 2, 4, 
            1, 1, 2, 3, 4 ];
let N = arr.length;
let K = 3;

document.write(min_elements(arr, N, K));

// This code contributed by _saurabh_jaiswal

</script>

Output
3

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

Approach#2: Using heapq

The idea is to count the frequency of each element in the array and keep track of the number of distinct elements in the array. Then we can find the number of elements to replace such that we have at most K distinct elements in the array. To do this, we can use a min-heap to keep track of the counts of the distinct elements in the array. We will pop the smallest count from the heap and replace that many elements until we have at most K distinct elements.

Algorithm

1. Count the frequency of each element in the array and keep track of the number of distinct elements in the array.
2. If the number of distinct elements is less than or equal to K, return 0.
3. Create a min-heap and insert the counts of the distinct elements in the array.
4. Find the number of elements to replace: num_to_replace = (number of distinct elements) – K
5. Pop the smallest count from the heap and add it to replacements.
6. Decrement num_to_replace by the count of the popped element.
7. If num_to_replace is greater than 0, go to step 5.
8. Return replacements.

C++
#include <iostream>
#include <vector>
#include <map>
#include <queue>

// Function to calculate minimum replacements
int minReplacements(std::vector<int> arr, int K) {
    // Create a frequency map
    std::map<int, int> freq;
    for (int num : arr) {
        freq[num]++;
    }

    // Calculate the number of unique numbers to replace
    int numToReplace = freq.size() - K;
    if (numToReplace <= 0) {
        return 0;
    }

    // Create a min heap based on the frequency of numbers
    std::priority_queue<int, std::vector<int>, std::greater<int>> pq;
    for (auto it : freq) {
        pq.push(it.second);
    }

    // Replace the least frequent numbers until we have only K unique numbers
    int replacements = 0;
    for (int i = 0; i < numToReplace; i++) {
        int count = pq.top();
        pq.pop();
        replacements += count;
    }

    return replacements;
}

int main() {
    std::vector<int> arr = {1, 1, 2, 2, 5};
    int K = 2;
    std::cout << minReplacements(arr, K) << std::endl; // Output: 1
    return 0;
}
Java
import java.util.*;

public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 1, 2, 2, 5};
        int K = 2;
        System.out.println(minReplacements(arr, K)); // Output: 1
    }

    public static int minReplacements(int[] arr, int K) {
        // Create a frequency map
        Map<Integer, Integer> freq = new HashMap<>();
        for (int num : arr) {
            freq.put(num, freq.getOrDefault(num, 0) + 1);
        }

        // Calculate the number of unique numbers to replace
        int numToReplace = freq.size() - K;
        if (numToReplace <= 0) {
            return 0;
        }

        // Create a min heap based on the frequency of numbers
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        for (int count : freq.values()) {
            pq.add(count);
        }

        // Replace the least frequent numbers until we have only K unique numbers
        int replacements = 0;
        for (int i = 0; i < numToReplace; i++) {
            int count = pq.poll();
            replacements += count;
        }

        return replacements;
    }
}
Python
import heapq

def min_replacements(arr, K):
    freq = {}
    for num in arr:
        freq[num] = freq.get(num, 0) + 1
    
    num_to_replace = len(freq) - K
    if num_to_replace <= 0:
        return 0
    
    pq = []
    for num, count in freq.items():
        heapq.heappush(pq, count)
    
    replacements = 0
    for i in range(num_to_replace):
        count = heapq.heappop(pq)
        replacements += count
    
    return replacements

arr = [1, 1, 2, 2, 5]
K = 2
print(min_replacements(arr, K)) # Output: 1
JavaScript
function minReplacements(arr, K) {
    // Create a frequency map
    let freq = {};
    for (let num of arr) {
        freq[num] = (freq[num] || 0) + 1;
    }

    // Calculate the number of unique elements to replace
    let numToReplace = Object.keys(freq).length - K;
    if (numToReplace <= 0) {
        return 0;
    }

    // Create a priority queue (min heap) from the frequency map
    let pq = Object.values(freq).sort((a, b) => a - b);

    // Pop the smallest frequencies from the queue until we have replaced enough elements
    let replacements = 0;
    for (let i = 0; i < numToReplace; i++) {
        replacements += pq.shift();
    }

    return replacements;
}

let arr = [1, 1, 2, 2, 5];
let K = 2;
console.log(minReplacements(arr, K));

Output
1

Time complexity: O(N) time where N is the length of the array. Inserting and popping elements from a min-heap takes O(log N) time. We do this for each distinct element in the array, so the overall time complexity is O(N log D) where D is the number of distinct elements in the array.

Space complexity: We use a dictionary to store the frequency of each element in the array, so the space complexity is O(N). We also use a min-heap to keep track of the counts of the distinct elements in the array, so the space complexity is O(D) where D is the number of distinct elements in the array. Overall, the space complexity is O(N).



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