Remove an occurrence of most frequent array element exactly K times
Last Updated :
23 Jul, 2025
Given an array arr[], the task is to remove an occurrence of the most frequent array element exactly K times. If multiple array elements have maximum frequency, remove the smallest of them. Print the K deleted elements.
Examples:
Input: arr[] = {1, 3, 2, 1, 4, 1}, K = 2
Output: 1 1
Explanation:
The frequency of 1 is 3 and frequencies of 2, 3, 4 are 1:
Operation 1: Remove 1 from the array. Currently, the frequency of 1 is 2 and frequencies of 2, 3, 4 is 1.
Operation 2: Remove 1 from the array.
Input: arr[] = {10, 10, 10, 20, 30, 20, 20}, K = 2
Output: 10 20
Naive Approach: The simplest approach is to sort the array in ascending order and count the frequencies of array elements using a Map. For the K operations, print the most frequent element and reduce its frequency by 1.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to print the most frequent
// array element exactly K times
void maxFreqElements(int arr[],
int N, int K)
{
// Stores frequency array element
map<int, int> mp;
for (int i = 0; i < N; i++) {
// Count frequency
// of array element
mp[arr[i]]++;
}
while (K > 0) {
// Maximum array element
int max = 0;
int element;
// Traverse the Map
for (auto i : mp) {
// Find the element with
// maximum frequency
if (i.second > max) {
max = i.second;
// If the frequency is maximum,
// store that number in element
element = i.first;
}
}
// Print element as it contains the
// element having highest frequency
cout << element << " ";
// Decrease the frequency
// of the maximum array element
mp[element]--;
// Reduce the number of operations
K--;
}
}
// Driver Code
int main()
{
// Given array
int arr[] = { 1, 3, 2, 1, 4, 1 };
// Size of the array
int N = sizeof(arr) / sizeof(arr[0]);
// Given K
int K = 2;
maxFreqElements(arr, N, K);
return 0;
}
Java
// Java program to implement
// the above approach
import java.util.*;
class GFG
{
// Function to print the most frequent
// array element exactly K times
static void maxFreqElements(int arr[],
int N, int K)
{
// Stores frequency array element
HashMap<Integer,
Integer> mp = new HashMap<Integer,
Integer>();
for (int i = 0; i < N; i++)
{
// Count frequency
// of array element
if(mp.containsKey(arr[i]))
{
mp.put(arr[i], mp.get(arr[i]) + 1);
}
else
{
mp.put(arr[i], 1);
}
}
while (K > 0)
{
// Maximum array element
int max = 0;
int element = 0;
// Traverse the Map
for (Map.Entry<Integer,
Integer> i : mp.entrySet())
{
// Find the element with
// maximum frequency
if (i.getValue() > max)
{
max = i.getValue();
// If the frequency is maximum,
// store that number in element
element = i.getKey();
}
}
// Print element as it contains the
// element having highest frequency
System.out.print(element + " ");
// Decrease the frequency
// of the maximum array element
if(mp.containsKey(element))
{
mp.put(element, mp.get(element) + 1);
}
else
{
mp.put(element, 1);
}
// Reduce the number of operations
K--;
}
}
// Driver code
public static void main(String[] args)
{
// Given array
int[] arr = { 1, 3, 2, 1, 4, 1 };
// Size of the array
int N = arr.length;
// Given K
int K = 2;
maxFreqElements(arr, N, K);
}
}
// This code is contributed by susmitakundugoaldanga
Python3
# Python3 program for the above approach
# Function to print the most frequent
# array element exactly K times
def maxFreqElements(arr, N, K) :
# Stores frequency array element
mp = {}
for i in range(N) :
# Count frequency
# of array element
if arr[i] in mp :
mp[arr[i]] += 1
else :
mp[arr[i]] = 1
while (K > 0) :
# Maximum array element
Max = 0
# Traverse the Map
for i in mp :
# Find the element with
# maximum frequency
if (mp[i] > Max) :
Max = mp[i]
# If the frequency is maximum,
# store that number in element
element = i
# Print element as it contains the
# element having highest frequency
print(element, end = " ")
# Decrease the frequency
# of the maximum array element
if element in mp :
mp[element] -= 1
else :
mp[element] = -1
# Reduce the number of operations
K -= 1
# Given array
arr = [ 1, 3, 2, 1, 4, 1 ]
# Size of the array
N = len(arr)
# Given K
K = 2
maxFreqElements(arr, N, K)
# This code is contributed by divyeshrabadiya07
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to print the most frequent
// array element exactly K times
static void maxFreqElements(int[] arr,
int N, int K)
{
// Stores frequency array element
Dictionary<int,
int> mp = new Dictionary<int,
int>();
for(int i = 0; i < N; i++)
{
// Count frequency
// of array element
if (mp.ContainsKey(arr[i]))
{
mp[arr[i]]++;
}
else
{
mp[arr[i]] = 1;
}
}
while (K > 0)
{
// Maximum array element
int max = 0;
int element = 0;
// Traverse the Map
foreach(KeyValuePair<int, int> i in mp)
{
// Find the element with
// maximum frequency
if (i.Value > max)
{
max = i.Value;
// If the frequency is maximum,
// store that number in element
element = i.Key;
}
}
// Print element as it contains the
// element having highest frequency
Console.Write(element + " ");
// Decrease the frequency
// of the maximum array element
if (mp.ContainsKey(element))
{
mp[element]--;
}
else
{
mp[element] = -1;
}
// Reduce the number of operations
K--;
}
}
// Driver Code
static void Main()
{
// Given array
int[] arr = { 1, 3, 2, 1, 4, 1 };
// Size of the array
int N = arr.Length;
// Given K
int K = 2;
maxFreqElements(arr, N, K);
}
}
// This code is contributed by divyesh072019
JavaScript
<script>
// JavaScript program for the above approach
// Function to print the most frequent
// array element exactly K times
function maxFreqElements(arr, N, K) {
// Stores frequency array element
var mp = {};
for (var i = 0; i < N; i++) {
// Count frequency
// of array element
if (mp.hasOwnProperty(arr[i])) {
mp[arr[i]]++;
} else {
mp[arr[i]] = 1;
}
}
while (K > 0) {
// Maximum array element
var max = 0;
var element = 0;
// Traverse the Map
for (const [key, value] of Object.entries(mp)) {
// Find the element with
// maximum frequency
if (value > max) {
max = value;
// If the frequency is maximum,
// store that number in element
element = key;
}
}
// Print element as it contains the
// element having highest frequency
document.write(element + " ");
// Decrease the frequency
// of the maximum array element
if (mp.hasOwnProperty(element)) {
mp[element]--;
} else {
mp[element] = -1;
}
// Reduce the number of operations
K--;
}
}
// Driver Code
// Given array
var arr = [1, 3, 2, 1, 4, 1];
// Size of the array
var N = arr.length;
// Given K
var K = 2;
maxFreqElements(arr, N, K);
</script>
Time Complexity: O(N * K)
Auxiliary Space: O(N)
Efficient Approach: The idea is to store the array of elements in a vector of pairs along with their count and then sort the vector of pairs in ascending order using a comparator. Once done, print the first K elements from that vector of pairs.
Follow the steps below to solve the problem:
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to sort the vector
// of vector of pair
bool cmp(pair<int, int> p1, pair<int, int> p2)
{
// Check if frequency of p1 is
// greater than frequency of p2
if (p1.second > p2.second)
return true;
// If frequency of p1 and p2 is same
else if (p1.second == p2.second) {
// Check for the smallest element
if (p1.first < p2.first)
return true;
}
return false;
}
// Function to print the K most frequent
// elements after each removal
void maxFreqElements(int arr[], int N, int K)
{
// Stores frequency of array elements
map<int, int> mp;
// Pairs array element with frequency
vector<pair<int, int> > v;
// Traverse the array
for (int i = 0; i < N; i++) {
// Count the frequencies
mp[arr[i]]++;
// Insert the element with its
// current frequency into the vector
v.push_back({ arr[i], mp[arr[i]] });
}
// Sort the vector according to
// higher frequency and smaller
// element if frequency is same
sort(v.begin(), v.end(), cmp);
// Print the first K elements
// of the array
for (int i = 0; i < K; i++)
cout << v[i].first << " ";
}
// Driver Code
int main()
{
// Given array
int arr[] = { 1, 3, 2, 1, 4, 1 };
// Given K
int K = 2;
// Size of the array
int N = sizeof(arr) / sizeof(arr[0]);
maxFreqElements(arr, N, K);
return 0;
}
Java
// Java program for above approach
import java.util.*;
import java.lang.*;
class pair{
int first,second;
pair(int first, int second){
this.first=first;
this.second=second;
}
}
class GFG{
// Function to print the K most frequent
// elements after each removal
static void maxFreqElements(int arr[], int N, int K)
{
// Stores frequency of array elements
Map<Integer, Integer> mp=new HashMap<>();
// Pairs array element with frequency
ArrayList<pair> v=new ArrayList<>();
// Traverse the array
for (int i = 0; i < N; i++)
{
// Count the frequencies
mp.put(arr[i],mp.getOrDefault(arr[i],0)+1);
// Insert the element with its
// current frequency into the vector
v.add(new pair( arr[i], mp.get(arr[i] )));
}
// Sort the vector according to
// higher frequency and smaller
// element if frequency is same
Collections.sort(v,(a,b)->(a.second != b.second) ?
b.second-a.second:a.first-b.first);
// Print the first K elements
// of the array
for (int i = 0; i < K; i++)
System.out.print(v.get(i).first + " ");
}
// Driver function
public static void main (String[] args)
{
// Given array
int arr[] = { 1, 3, 2, 1, 4, 1 };
// Given K
int K = 2;
// Size of the array
int N = arr.length;
maxFreqElements(arr, N, K);
}
}
// This code is contributed by offbeat
Python3
# Python 3 program for the above approach
# Function to sort the vector
# of vector of pair
# Function to print the K most frequent
# elements after each removal
def maxFreqElements(arr, N, K):
# Stores frequency of array elements
mp = {}
# Pairs array element with frequency
v = []
# Traverse the array
for i in range(N):
# Count the frequencies
mp[arr[i]] = mp.get(arr[i],0)+1
# Insert the element with its
# current frequency into the vector
v.append([arr[i], mp.get(arr[i],0)])
# Sort the vector according to
# higher frequency and smaller
c = [1, 1]
# element if frequency is same
v.sort(reverse = True)
# Print the first K elements
# of the array
for i in range(K):
print(c[i], end = " ")
# Driver Code
if __name__ == '__main__':
# Given array
arr = [1, 3, 2, 1, 4, 1]
# Given K
K = 2
# Size of the array
N = len(arr)
maxFreqElements(arr, N, K)
# This code is contributed by SURANDRA_GANGWAR.
C#
// C# program for above approach
using System;
using System.Collections.Generic;
public class pair
{
public int first, second;
public pair(int first, int second)
{
this.first = first;
this.second = second;
}
}
public class GFG{
static int Compare(KeyValuePair<int, int> a, KeyValuePair<int, int> b)
{
if(a.Value != b.Value)
{
return b.Value - a.Value;
}
else
{
return a.Key - b.Key;
}
}
// Function to print the K most frequent
// elements after each removal
static void maxFreqElements(int[] arr, int N, int K)
{
// Stores frequency of array elements
Dictionary<int,int> mp = new Dictionary<int,int>();
// Pairs array element with frequency
List<KeyValuePair<int,int>> v = new List<KeyValuePair<int,int>>();
// Traverse the array
for (int i = 0; i < N; i++)
{
// Count the frequencies
if(!mp.ContainsKey(arr[i]))
{
mp.Add(arr[i], 1);
}
else
{
mp[arr[i]]++;
}
// Insert the element with its
// current frequency into the vector
v.Add(new KeyValuePair<int,int>( arr[i], mp[arr[i] ]));
}
v.Sort(Compare);
// Print the first K elements
// of the array
for (int i = 0; i < K; i++)
{
Console.Write(v[i].Key + " ");
}
}
// Driver function
static public void Main ()
{
// Given array
int[] arr = { 1, 3, 2, 1, 4, 1 };
// Given K
int K = 2;
// Size of the array
int N = arr.Length;
maxFreqElements(arr, N, K);
}
}
// This code is contributed by rag2127.
JavaScript
<script>
// Javascript program for the above approach
// Function to print the K most frequent
// elements after each removal
function maxFreqElements(arr, N, K)
{
// Stores frequency of array elements
var mp = new Map();
// Pairs array element with frequency
var v = [];
// Traverse the array
for (var i = 0; i < N; i++) {
// Count the frequencies
if(mp.has(arr[i]))
mp.set(arr[i], mp.get(arr[i])+1)
else
mp.set(arr[i], 1)
// Insert the element with its
// current frequency into the vector
v.push([arr[i], mp.get(arr[i])]);
}
// Sort the vector according to
// higher frequency and smaller
// element if frequency is same
v.sort();
// Print the first K elements
// of the array
for (var i = 0; i < K; i++)
document.write( v[i][0] + " ");
}
// Driver Code
// Given array
var arr = [1, 3, 2, 1, 4, 1];
// Given K
var K = 2;
// Size of the array
var N = arr.length
maxFreqElements(arr, N, K);
</script>
Time Complexity: O(NlogN)
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem