Remove array elements to reduce frequency of each array element to at most K
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++
#include <bits/stdc++.h>
using namespace std;
vector< int > RemoveElemArr(vector< int >& arr,
int n, int k)
{
if (n == 0 || n == 1)
return arr;
int j = 0;
for ( int i = 0; i < n; i++) {
if (j < k || arr[i] > arr[j - k]) {
arr[j++] = arr[i];
}
}
while (arr.size() > j) {
arr.pop_back();
}
return arr;
}
void printArray(vector< int >& arr)
{
for ( int i = 0; i < arr.size();
i++) {
cout << arr[i] << " " ;
}
}
void UtilRemov(vector< int >& arr, int n, int k)
{
arr = RemoveElemArr(arr, n, k);
printArray(arr);
}
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
import java.util.*;
class GFG
{
static int [] RemoveElemArr( int []arr,
int n, int k)
{
if (n == 0 || n == 1 )
return arr;
int j = 0 ;
for ( int i = 0 ; i < n; i++)
{
if (j < k || arr[i] > arr[j - k])
{
arr[j++] = arr[i];
}
}
while (arr.length > j)
{
arr = Arrays.copyOfRange(arr, 0 , arr.length- 1 );
}
return arr;
}
static void printArray( int [] arr)
{
for ( int i = 0 ; i < arr.length;
i++)
{
System.out.print(arr[i]+ " " );
}
}
static void UtilRemov( int []arr, int n, int k)
{
arr = RemoveElemArr(arr, n, k);
printArray(arr);
}
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);
}
}
|
Python3
def RemoveElemArr(arr, n, k):
if (n = = 0 or n = = 1 ):
return arr
j = 0
for i in range (n):
if (j < k or arr[i] > arr[j - k]):
arr[j], j = arr[i], j + 1
while ( len (arr) > j):
del arr[ - 1 ]
return arr
def printArray(arr):
for i in arr:
print (i, end = " " )
def UtilRemov(arr, n, k):
arr = RemoveElemArr(arr, n, k)
printArray(arr)
if __name__ = = '__main__' :
arr = [ 1 , 2 , 2 , 3 , 4 , 4 , 4 , 5 , 5 ]
k = 2
n = len (arr)
UtilRemov(arr, n, k)
|
C#
using System;
using System.Linq;
class GFG
{
static int [] RemoveElemArr( int []arr,
int n, int k)
{
if (n == 0 || n == 1)
return arr;
int j = 0;
for ( int i = 0; i < n; i++)
{
if (j < k || arr[i] > arr[j - k])
{
arr[j++] = arr[i];
}
}
while (arr.Length > j)
{
arr = arr.Take(arr.Length - 1).ToArray();
}
return arr;
}
static void printArray( int [] arr)
{
for ( int i = 0; i < arr.Length;
i++)
{
Console.Write(arr[i] + " " );
}
}
static void UtilRemov( int []arr, int n, int k)
{
arr = RemoveElemArr(arr, n, k);
printArray(arr);
}
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);
}
}
|
Javascript
<script>
function RemoveElemArr(arr, n, k)
{
if (n == 0 || n == 1)
return arr;
var j = 0;
for ( var i = 0; i < n; i++) {
if (j < k || arr[i] > arr[j - k]) {
arr[j++] = arr[i];
}
}
while (arr.length > j) {
arr.pop();
}
return arr;
}
function printArray(arr)
{
for ( var i = 0; i < arr.length;
i++) {
document.write(arr[i] + " " );
}
}
function UtilRemov(arr, n, k)
{
arr = RemoveElemArr(arr, n, k);
printArray(arr);
}
var arr = [ 1, 2, 2, 3, 4, 4, 4, 5, 5 ];
var k = 2;
var n = arr.length;
UtilRemov(arr, n, k);
</script>
|
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;
vector< int > reduceFrequency( const vector< int >& arr, int k)
{
unordered_map< int , int > freq;
for ( int i : arr)
{
if (freq.find(i) != freq.end())
{
freq[i]++;
}
else
{
freq[i] = 1;
}
}
vector< int > new_arr;
for ( int i : arr)
{
if (freq[i] <= k)
{
new_arr.push_back(i);
}
freq[i] -= 2;
}
return new_arr;
}
int main()
{
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;
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 {
public static List<Integer> reduceFrequency(List<Integer> arr, int k) {
Map<Integer, Integer> freq = new HashMap<>();
for ( int i : arr) {
freq.put(i, freq.getOrDefault(i, 0 ) + 1 );
}
List<Integer> new_arr = new ArrayList<>();
for ( int i : arr) {
if (freq.get(i) <= k) {
new_arr.add(i);
}
freq.put(i, freq.getOrDefault(i, 0 ) - 2 );
}
return new_arr;
}
public static void main(String[] args) {
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();
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();
}
}
|
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
arr1 = [ 1 , 1 , 1 , 1 , 2 , 2 , 2 , 3 , 4 , 4 , 4 , 4 , 5 ]
k1 = 3
print (reduce_frequency(arr1, k1))
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
{
static List< int > ReduceFrequency(List< int > arr, int k)
{
Dictionary< int , int > freq = new Dictionary< int , int >();
foreach ( int i in arr)
{
if (freq.ContainsKey(i))
{
freq[i]++;
}
else
{
freq[i] = 1;
}
}
List< int > new_arr = new List< int >();
foreach ( int i in arr)
{
if (freq[i] <= k)
{
new_arr.Add(i);
}
freq[i] -= 2;
}
return new_arr;
}
static void Main( string [] args)
{
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();
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 reduceFrequency(arr, k) {
const freq = {};
for (let i of arr) {
if (freq[i] !== undefined) {
freq[i]++;
} else {
freq[i] = 1;
}
}
const new_arr = [];
for (let i of arr) {
if (freq[i] <= k) {
new_arr.push(i);
}
freq[i] -= 2;
}
return new_arr;
}
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( ' ' ));
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)
Last Updated :
20 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...