Open In App

Remove array elements to reduce frequency of each array element to at most K

Last Updated : 20 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a sorted array arr[] of size N and an integer K, the task is to print the array by removing the minimum number of array elements to make frequency of each element at most K.

Examples:

Input: arr[] = { 1, 1, 1, 1, 2, 2, 2, 3, 4, 4, 4, 4, 5 }, K = 3 
Output: { 1, 1, 1, 2, 2, 2, 3, 4, 4, 4, 5 } 
Explanation: 
Removing arr[0], arr[8] modifies arr[] to { 1, 1, 1, 2, 2, 2, 3, 4, 4, 4, 5 }. 
The frequency of each distinct array element is at most K(=3). 
Therefore, the required output is { 1, 1, 1, 2, 2, 2, 3, 4, 4, 4, 5 }.

Input: arr[] = { 1, 2, 2, 3, 4, 4, 4, 5, 5 }, K = 2 
Output: { 1, 2, 2, 3, 4, 4, 5, 5 }

Naive Approach: The simplest approach to solve this problem is to traverse the array and check if the frequency of the array elements is greater than K or not. If found to be true, then remove the current element from the array. Otherwise, increment the frequency of the array element and print the array element. 

Time Complexity: O(N2) 
Auxiliary Space: O(1)

Efficient Approach: Follow the steps below to solve the problem:

  • Initialize a variable, say j = 0 to store the index of any array element by removing the array elements such that the frequency of each distinct element is at most K.
  • Traverse the array and check if j < K or arr[i] > arr[j – K] is true or not. If found to be true, then update arr[j++] = arr[i].
  • Finally, print the array by removing all the array elements whose index is greater than or equal to j.

Below is the implementation of the above approach.

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to remove array elements
// such that frequency of each distinct
// array element is at most K
vector<int> RemoveElemArr(vector<int>& arr,
                        int n, int k)
{
    // Base Case
    if (n == 0 || n == 1)
        return arr;
 
    // Stores index of array element by removing
    // the array element such that the frequency
    // of array elements is at most K
    int j = 0;
 
    // Traverse the array
    for (int i = 0; i < n; i++) {
 
        // If j < k or arr[i] > arr[j - k]
        if (j < k || arr[i] > arr[j - k]) {
 
            // Update arr[j]
            arr[j++] = arr[i];
        }
    }
 
    // Remove array elements
    while (arr.size() > j) {
        arr.pop_back();
    }
 
    return arr;
}
 
// Function to print the array
void printArray(vector<int>& arr)
{
 
    // Traverse the array
    for (int i = 0; i < arr.size();
        i++) {
        cout << arr[i] << " ";
    }
}
 
// Utility Function to remove array elements
// such that frequency of each distinct
// array element is at most K
void UtilRemov(vector<int>& arr, int n, int k)
{
    arr = RemoveElemArr(arr, n, k);
 
    // Print updated array
    printArray(arr);
}
 
// Driver Code
int main()
{
 
    vector<int> arr
        = { 1, 2, 2, 3, 4, 4, 4, 5, 5 };
 
    int k = 2;
    int n = arr.size();
 
    UtilRemov(arr, n, k);
 
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG
{
 
// Function to remove array elements
// such that frequency of each distinct
// array element is at most K
static int [] RemoveElemArr(int []arr,
                        int n, int k)
{
   
    // Base Case
    if (n == 0 || n == 1)
        return arr;
 
    // Stores index of array element by removing
    // the array element such that the frequency
    // of array elements is at most K
    int j = 0;
 
    // Traverse the array
    for (int i = 0; i < n; i++)
    {
 
        // If j < k or arr[i] > arr[j - k]
        if (j < k || arr[i] > arr[j - k])
        {
 
            // Update arr[j]
            arr[j++] = arr[i];
        }
    }
 
    // Remove array elements
    while (arr.length > j)
    {
        arr = Arrays.copyOfRange(arr, 0, arr.length-1);
    }
 
    return arr;
}
 
// Function to print the array
static void printArray(int [] arr)
{
 
    // Traverse the array
    for (int i = 0; i < arr.length;
        i++)
    {
        System.out.print(arr[i]+ " ");
    }
}
 
// Utility Function to remove array elements
// such that frequency of each distinct
// array element is at most K
static void UtilRemov(int []arr, int n, int k)
{
    arr = RemoveElemArr(arr, n, k);
 
    // Print updated array
    printArray(arr);
}
 
// Driver Code
public static void main(String[] args)
{
 
    int []arr
        = { 1, 2, 2, 3, 4, 4, 4, 5, 5 };
    int k = 2;
    int n = arr.length;
    UtilRemov(arr, n, k);
}
}
 
// This code is contributed by Amit Katiyar


Python3




# Python3 program for the above approach
 
# Function to remove array elements
# such that frequency of each distinct
# array element is at most K
def RemoveElemArr(arr, n, k):
     
    # Base Case
    if (n == 0 or n == 1):
        return arr
 
    # Stores index of array element by
    # removing the array element such
    # that the frequency of array
    # elements is at most K
    j = 0
 
    # Traverse the array
    for i in range(n):
         
        # If j < k or arr[i] > arr[j - k]
        if (j < k or arr[i] > arr[j - k]):
             
            # Update arr[j]
            arr[j], j = arr[i], j + 1
             
    # Remove array elements
    while (len(arr) > j):
        del arr[-1]
 
    return arr
 
# Function to print the array
def printArray(arr):
     
    # Traverse the array
    for i in arr:
        print(i, end = " ")
         
# Utility Function to remove array elements
# such that frequency of each distinct
# array element is at most K
def UtilRemov(arr, n, k):
     
    arr = RemoveElemArr(arr, n, k)
 
    # Print updated array
    printArray(arr)
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 1, 2, 2, 3, 4, 4, 4, 5, 5 ]
 
    k = 2
    n = len(arr)
 
    UtilRemov(arr, n, k)
 
# This code is contributed by mohit kumar 29


C#




// C# program to implement
// the above approach 
using System;
using System.Linq;
 
class GFG
{
 
  // Function to remove array elements
  // such that frequency of each distinct
  // array element is at most K
  static int [] RemoveElemArr(int []arr,
                              int n, int k)
  {
 
    // Base Case
    if (n == 0 || n == 1)
      return arr;
 
    // Stores index of array element by removing
    // the array element such that the frequency
    // of array elements is at most K
    int j = 0;
 
    // Traverse the array
    for (int i = 0; i < n; i++)
    {
 
      // If j < k or arr[i] > arr[j - k]
      if (j < k || arr[i] > arr[j - k])
      {
 
        // Update arr[j]
        arr[j++] = arr[i];
      }
    }
 
    // Remove array elements
    while (arr.Length > j)
    {
      arr = arr.Take(arr.Length - 1).ToArray();
    }
 
    return arr;
  }
 
  // Function to print the array
  static void printArray(int [] arr)
  {
 
    // Traverse the array
    for (int i = 0; i < arr.Length;
         i++)
    {
      Console.Write(arr[i] + " ");
    }
  }
 
  // Utility Function to remove array elements
  // such that frequency of each distinct
  // array element is at most K
  static void UtilRemov(int []arr, int n, int k)
  {
    arr = RemoveElemArr(arr, n, k);
 
    // Print updated array
    printArray(arr);
  }
 
  // Driver code
  public static void Main()
  {
    int []arr
      = { 1, 2, 2, 3, 4, 4, 4, 5, 5 };
    int k = 2;
    int n = arr.Length;
    UtilRemov(arr, n, k);
  }
}
 
// This code is contributed by sanjoy_62.


Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to remove array elements
// such that frequency of each distinct
// array element is at most K
function RemoveElemArr(arr, n, k)
{
    // Base Case
    if (n == 0 || n == 1)
        return arr;
 
    // Stores index of array element by removing
    // the array element such that the frequency
    // of array elements is at most K
    var j = 0;
 
    // Traverse the array
    for (var i = 0; i < n; i++) {
 
        // If j < k or arr[i] > arr[j - k]
        if (j < k || arr[i] > arr[j - k]) {
 
            // Update arr[j]
            arr[j++] = arr[i];
        }
    }
 
    // Remove array elements
    while (arr.length > j) {
        arr.pop();
    }
 
    return arr;
}
 
// Function to print the array
function printArray(arr)
{
 
    // Traverse the array
    for (var i = 0; i < arr.length;
        i++) {
        document.write(arr[i] + " ");
    }
}
 
// Utility Function to remove array elements
// such that frequency of each distinct
// array element is at most K
function UtilRemov(arr, n, k)
{
    arr = RemoveElemArr(arr, n, k);
 
    // Print updated array
    printArray(arr);
}
 
var arr = [ 1, 2, 2, 3, 4, 4, 4, 5, 5 ];
 
    var k = 2;
    var n = arr.length;
 
    UtilRemov(arr, n, k);
     
    // This code is contributed by SoumikMondal
     
</script>


Output

1 2 2 3 4 4 5 5








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

Using dictionary to count frequency in python:

Approach:

Create a dictionary to store the frequency of each element in the array.
Iterate over the array and check the frequency of each element. If the frequency of an element is less than or equal to K, add it to a new array and decrement its frequency in the dictionary.
Return the new array.

C++




#include <iostream>
#include <vector>
#include <unordered_map>
 
using namespace std;
 
// Function to reduce the frequency of elements in the array
// such that no element appears more than k times
vector<int> reduceFrequency(const vector<int>& arr, int k)
{
    // Create an unordered_map to store the frequency of each element
    unordered_map<int, int> freq;
    for (int i : arr)
    {
        // Increase the frequency count of element i
        if (freq.find(i) != freq.end())
        {
            freq[i]++;
        }
        else
        {
            // If i is not in the map, initialize its frequency to 1
            freq[i] = 1;
        }
    }
 
    // Create a new vector to store the reduced array
    vector<int> new_arr;
    for (int i : arr)
    {
        // If the frequency of element i is less than or equal to k, include it in the new array
        if (freq[i] <= k)
        {
            new_arr.push_back(i);
        }
        // Decrease the frequency count of element i by 2
        freq[i] -= 2;
    }
 
    return new_arr;
}
 
int main()
{
    // Example 1
    vector<int> arr1 = {1, 1, 1, 1, 2, 2, 2, 3, 4, 4, 4, 4, 5};
    int k1 = 3;
    vector<int> result1 = reduceFrequency(arr1, k1);
    cout << "Reduced Array 1: ";
    for (int i : result1)
    {
        cout << i << " ";
    }
    cout << endl;
 
    // Example 2
    vector<int> arr2 = {1, 2, 2, 3, 4, 4, 4, 5, 5};
    int k2 = 2;
    vector<int> result2 = reduceFrequency(arr2, k2);
    cout << "Reduced Array 2: ";
    for (int i : result2)
    {
        cout << i << " ";
    }
    cout << endl;
 
    return 0;
}


Java




import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
public class Main {
    // Function to reduce the frequency of elements in the array
    // such that no element appears more than k times
    public static List<Integer> reduceFrequency(List<Integer> arr, int k) {
        // Create a HashMap to store the frequency of each element
        Map<Integer, Integer> freq = new HashMap<>();
        for (int i : arr) {
            // Increase the frequency count of element i
            freq.put(i, freq.getOrDefault(i, 0) + 1);
        }
 
        // Create a new ArrayList to store the reduced array
        List<Integer> new_arr = new ArrayList<>();
        for (int i : arr) {
            // If the frequency of element i is less than or equal to k, include it in the new array
            if (freq.get(i) <= k) {
                new_arr.add(i);
            }
            // Decrease the frequency count of element i by 2
            freq.put(i, freq.getOrDefault(i, 0) - 2);
        }
 
        return new_arr;
    }
 
    public static void main(String[] args) {
        // Example 1
        List<Integer> arr1 = List.of(1, 1, 1, 1, 2, 2, 2, 3, 4, 4, 4, 4, 5);
        int k1 = 3;
        List<Integer> result1 = reduceFrequency(arr1, k1);
        System.out.print("Reduced Array 1: ");
        for (int i : result1) {
            System.out.print(i + " ");
        }
        System.out.println();
 
        // Example 2
        List<Integer> arr2 = List.of(1, 2, 2, 3, 4, 4, 4, 5, 5);
        int k2 = 2;
        List<Integer> result2 = reduceFrequency(arr2, k2);
        System.out.print("Reduced Array 2: ");
        for (int i : result2) {
            System.out.print(i + " ");
        }
        System.out.println();
    }
}
 
// This code is contributed by rambabuguphka


Python3




def reduce_frequency(arr, k):
    freq = {}
    for i in arr:
        if i in freq:
            freq[i] += 1
        else:
            freq[i] = 1
     
    new_arr = []
    for i in arr:
        if freq[i] <= k:
            new_arr.append(i)
        freq[i] -= 2
     
    return new_arr
 
# Example 1
arr1 = [1, 1, 1, 1, 2, 2, 2, 3, 4, 4, 4, 4, 5]
k1 = 3
print(reduce_frequency(arr1, k1))
 
# Example 2
arr2 = [1, 2, 2, 3, 4, 4, 4, 5, 5]
k2 = 2
print(reduce_frequency(arr2, k2))


C#




using System;
using System.Collections.Generic;
 
class Program
{
    // Function to reduce the frequency of elements in the array
    // such that no element appears more than k times
    static List<int> ReduceFrequency(List<int> arr, int k)
    {
        // Create a dictionary to store the frequency of each element
        Dictionary<int, int> freq = new Dictionary<int, int>();
        foreach (int i in arr)
        {
            // Increase the frequency count of element i
            if (freq.ContainsKey(i))
            {
                freq[i]++;
            }
            else
            {
                // If i is not in the dictionary, initialize its frequency to 1
                freq[i] = 1;
            }
        }
 
        // Create a new list to store the reduced array
        List<int> new_arr = new List<int>();
        foreach (int i in arr)
        {
            // If the frequency of element i is less than or equal to k, include it in the new list
            if (freq[i] <= k)
            {
                new_arr.Add(i);
            }
            // Decrease the frequency count of element i by 2
            freq[i] -= 2;
        }
 
        return new_arr;
    }
 
    static void Main(string[] args)
    {
        // Example 1
        List<int> arr1 = new List<int> { 1, 1, 1, 1, 2, 2, 2, 3, 4, 4, 4, 4, 5 };
        int k1 = 3;
        List<int> result1 = ReduceFrequency(arr1, k1);
        Console.Write("Reduced Array 1: ");
        foreach (int i in result1)
        {
            Console.Write(i + " ");
        }
        Console.WriteLine();
 
        // Example 2
        List<int> arr2 = new List<int> { 1, 2, 2, 3, 4, 4, 4, 5, 5 };
        int k2 = 2;
        List<int> result2 = ReduceFrequency(arr2, k2);
        Console.Write("Reduced Array 2: ");
        foreach (int i in result2)
        {
            Console.Write(i + " ");
        }
        Console.WriteLine();
    }
}


Javascript




// Function to reduce the frequency of elements in the array
// such that no element appears more than k times
function reduceFrequency(arr, k) {
    // Create an object to store the frequency of each element
    const freq = {};
     
    for (let i of arr) {
        // Increase the frequency count of element i
        if (freq[i] !== undefined) {
            freq[i]++;
        } else {
            // If i is not in the object, initialize its frequency to 1
            freq[i] = 1;
        }
    }
 
    // Create a new array to store the reduced elements
    const new_arr = [];
    for (let i of arr) {
        // If the frequency of element i is less than or equal to k, include it in the new array
        if (freq[i] <= k) {
            new_arr.push(i);
        }
        // Decrease the frequency count of element i by 2
        freq[i] -= 2;
    }
 
    return new_arr;
}
 
// Example 1
const arr1 = [1, 1, 1, 1, 2, 2, 2, 3, 4, 4, 4, 4, 5];
const k1 = 3;
const result1 = reduceFrequency(arr1, k1);
console.log(result1.join(' '));
 
// Example 2
const arr2 = [1, 2, 2, 3, 4, 4, 4, 5, 5];
const k2 = 2;
const result2 = reduceFrequency(arr2, k2);
console.log(result2.join(' '));


Output

[1, 1, 1, 2, 2, 2, 3, 4, 4, 4, 5]
[1, 2, 2, 3, 4, 4, 5, 5]









Time Complexity: O(n)
Space Complexity: O(n)



Similar Reads

Reduce the array such that each element appears at most K times
Given a sorted array arr of size N, the task is to reduce the array such that each element can appear at most K times.Examples: Input: arr[] = {1, 2, 2, 2, 3}, K = 2 Output: {1, 2, 2, 3} Explanation: Remove 2 once, as it occurs more than 2 times.Input: arr[] = {3, 3, 3}, K = 1 Output: {3} Explanation: Remove 3 twice, as it occurs more than 1 times.
10 min read
Reduce the array such that each element appears at most 2 times
Given a sorted array arr of size N, the task is to reduce the array such that each element can appear at most two times. Examples: Input: arr[] = {1, 2, 2, 2, 3} Output: {1, 2, 2, 3} Explanation: Remove 2 once, as it occurs more than 2 times. Input: arr[] = {3, 3, 3} Output: {3, 3} Explanation: Remove 3 once, as it occurs more than 2 times. Approac
15 min read
Reduce an array to a single element by repeatedly removing larger element from a pair with absolute difference at most K
Given an array arr[] consisting of N integers and a positive integer K, the task is to check if the given array can be reduced to a single element by repeatedly removing the larger of the two elements present in a pair whose absolute difference is at most K. If the array can be reduced to a single element, then print "Yes". Otherwise, print "No". E
11 min read
Form an array of distinct elements with each element as sum of an element from each array
Given two arrays, arr1[] and arr2[] of equal size, which contain distinct elements, the task is to find another array with distinct elements such that elements of the third array are formed by the addition of the one-one element of the arr1[] and arr2[]. Examples: Input: arr[] = {1, 7, 8, 3}, arr2[] = {6, 5, 10, 2} Output: 3 8 13 18 Explanation: In
6 min read
Reduce the Array to 0 by decreasing elements by 1 or replacing at most K elements by 0
Given an array arr[] of N integers and a positive integer K, the task is to find the minimum number of operations required to reduce all array elements to 0 such that in each operation reduce any array element by 1 and independently at most K array element can be reduced to 0. Examples: Input: arr[] = {4, 1, 5}, K = 1Output: 5Explanation: Following
6 min read
Maximum difference between frequency of two elements such that element having greater frequency is also greater
Given an array of n positive integers with many repeating elements. The task is to find the maximum difference between the frequency of any two different elements, such that the element with greater frequency is also greater in value than the second integer. Examples: Input : arr[] = { 3, 1, 3, 2, 3, 2 }. Output : 2 Frequency of 3 = 3. Frequency of
12 min read
Replace each element by the difference of the total size of the array and frequency of that element
Given an array of integers, the task is to replace every element by the difference of the total size of the array and its frequency. Examples: Input: arr[] = { 1, 2, 5, 2, 2, 5, 4 }Output: 6 4 5 4 4 5 6Explanation:Size of the array is 7.The frequency of 1 is 1. So replace it by 7-1 = 6The frequency of 2 is 3. So replace it by 7-3 = 4 Input: arr[] =
9 min read
Maximize frequency of an element by at most one increment or decrement of all array elements
Given an array arr[] of size N, the task is to find the maximum frequency of any array element by incrementing or decrementing each array element by 1 at most once. Examples: Input: arr[] = { 3, 1, 4, 1, 5, 9, 2 } Output: 4 Explanation: Decrementing the value of arr[0] by 1 modifies arr[] to { 2, 1, 4, 1, 5, 9, 2 } Incrementing the value of arr[1]
8 min read
Maximize frequency of an element by at most one increment or decrement of all array elements | Set 2
Given an array arr[] of size N, the task is to find the maximum frequency of any array element by incrementing or decrementing each array element by 1 at most once. Examples: Input: arr[] = { 3, 1, 4, 1, 5, 9, 2 } Output: 4 Explanation: Decrementing the value of arr[0] by 1 modifies arr[] to { 2, 1, 4, 1, 5, 9, 2 } Incrementing the value of arr[1]
6 min read
Generate a number such that the frequency of each digit is digit times the frequency in given number
Given a number N containing digits from 1 to 9 only. The task is to generate a new number using the number N such that the frequency of each digit in the new number is equal to the frequency of that digit in N multiplied by the digit itself.Note: The digits in the new number must be in increasing order.Examples: Input : N = 312 Output : 122333 Expl
8 min read